Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Read and write index pages with pread and pwrite instead of a mapping

Claude50f43e919c2b
diff --git a/mwmbl/indexer/blacklist_snapshot.py b/mwmbl/indexer/blacklist_snapshot.py
index a5de0a3..53ae446 100644
--- a/mwmbl/indexer/blacklist_snapshot.py
+++ b/mwmbl/indexer/blacklist_snapshot.py
@@ -18,7 +18,7 @@ So the query path never fetches, parses or holds the domain strings. A backgroun
a 64-bit integer, and publishes the sorted array to Redis as one ~11 MB blob. Workers
load the blob into a numpy array and answer membership with a vectorised binary search:
10.7 MB resident, and ~94 us to classify the ~200 distinct domains of a typical query -
-noise next to the mmap page reads and the Wikipedia call the same request already makes.
+noise next to the index page reads and the Wikipedia call the same request already makes.
Hashing rather than storing the domains is what buys the 15x memory saving. It costs
exactness in principle: two different domains could collide and a clean domain be treated
diff --git a/mwmbl/indexer/external_cache.py b/mwmbl/indexer/external_cache.py
index 7904eed..8ead0cd 100644
--- a/mwmbl/indexer/external_cache.py
+++ b/mwmbl/indexer/external_cache.py
@@ -67,7 +67,7 @@ _cache_index_path: Optional[Path] = None
def get_cache_index() -> TinyIndex:
"""The read handle for this process, opened once and left open.
- Same lifetime as the main index in search_setup - mmap'd read-only for the life of the
+ Same lifetime as the main index in search_setup - open read-only for the life of the
worker. Writers open their own short-lived 'w' handle instead, as every other writer in
the codebase does; see store_external_results.
@@ -82,9 +82,9 @@ def get_cache_index() -> TinyIndex:
_cache_index, _cache_index_path = None, None
# Both globals are assigned only once __enter__ has returned. Assigning the index
# first and the path after would, if __enter__ raised (the file removed between
- # __init__ and open, EMFILE, a failed mmap), leave a half-open index behind that
- # every later call would take the path-mismatch branch on and call __exit__ on -
- # an AttributeError on its None mmap, swallowed as a cache miss, for the life of
+ # __init__ and open, EMFILE), leave a half-open index behind that every later
+ # call would take the path-mismatch branch on and call __exit__ on - an
+ # AttributeError on its None index_file, swallowed as a cache miss, for the life of
# the worker. A failed open has to leave this exactly as it found it.
index = TinyIndex(item_factory=Document, index_path=path)
index.__enter__()
diff --git a/mwmbl/tinysearchengine/indexer.py b/mwmbl/tinysearchengine/indexer.py
index 1c25ea7..b091865 100644
--- a/mwmbl/tinysearchengine/indexer.py
+++ b/mwmbl/tinysearchengine/indexer.py
@@ -9,7 +9,6 @@ from enum import IntEnum
from io import UnsupportedOperation
from json import JSONDecodeError
from logging import getLogger
-from mmap import PROT_READ, PROT_WRITE, mmap
from typing import Callable, Generic, List, Optional, TypeVar
import mmh3
@@ -248,7 +247,7 @@ class _OpenPage(Generic[T]):
self.documents: List[T] = index.get_page(page_index)
except PageError:
if not locked:
- # Without the lock this could equally be another writer's memcpy in
+ # Without the lock this could equally be another writer's pwrite in
# progress, and merging onto an empty list would store over whatever it
# is writing. Refuse; the caller skips this page.
raise
@@ -296,16 +295,18 @@ class TinyIndex(Generic[T]):
self.page_size = metadata.page_size
logger.info(f"Loaded index with {self.num_pages} pages and {self.page_size} page size")
self.index_file = None
- self.mmap = None
def __enter__(self):
+ # Pages are read and written with os.pread/os.pwrite on this descriptor, never
+ # through the buffer. The file object is kept rather than a raw descriptor because
+ # fileno() feeds the OFD locks in _set_page_lock, and closing it closes the
+ # descriptor for us. Mapping the file instead would cost ~800 MiB of unreclaimable
+ # page tables per worker for a 390 GiB index, and buy nothing: reading a page
+ # copies it out of the mapping either way.
self.index_file = open(self.index_path, "r+b")
- prot = PROT_READ if self.mode == "r" else PROT_READ | PROT_WRITE
- self.mmap = mmap(self.index_file.fileno(), 0, prot=prot)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
- self.mmap.close()
self.index_file.close()
def retrieve(self, key: str) -> List[T]:
@@ -330,7 +331,7 @@ class TinyIndex(Generic[T]):
Storing a page is read -> merge -> write, with no atomicity of its own. Two writers
on the same page lose one writer's documents, which for a cache is tolerable. The
- serious case is a *torn* read: _write_page copies ~4 KB into the mmap, and a reader
+ serious case is a *torn* read: _write_page writes ~4 KB over the page, and a reader
that catches it half-written gets a ZstdError, which _get_page_tuples turns into an
empty page. A writer that reads empty then merges and stores wipes out everything
else on that page - permanent loss in a 400 GB index, not a transient blip. Since
@@ -417,7 +418,13 @@ class TinyIndex(Generic[T]):
over everything that was on the page. Readers that would rather have no results
than an error catch this - see retrieve.
"""
- page_data = self.mmap[i * self.page_size + METADATA_SIZE : (i + 1) * self.page_size + METADATA_SIZE]
+ page_data = os.pread(self.index_file.fileno(), self.page_size, i * self.page_size + METADATA_SIZE)
+ if len(page_data) != self.page_size:
+ # pread stops at the end of the file, so a short read means the file is not
+ # the shape the metadata says it is - truncated, or half-written by create.
+ # Decoding the fragment anyway is how a writer comes to merge onto a page it
+ # never actually read.
+ raise PageError(f"Could not read page {i}: got {len(page_data)} bytes, expected {self.page_size}")
decompressor = ZstdDecompressor()
try:
decompressed_data = decompressor.decompress(page_data)
@@ -449,7 +456,11 @@ class TinyIndex(Generic[T]):
page_data, num_stored = _get_page_data(self.page_size, data)
logger.debug(f"Got page data of length {len(page_data)}")
- self.mmap[i * self.page_size + METADATA_SIZE : (i + 1) * self.page_size + METADATA_SIZE] = page_data
+ num_written = os.pwrite(self.index_file.fileno(), page_data, i * self.page_size + METADATA_SIZE)
+ if num_written != len(page_data):
+ # A short write leaves the page half old and half new, which is exactly the
+ # torn page every reader and writer here is guarding against. Say so loudly.
+ raise PageError(f"Could not write page {i}: wrote {num_written} bytes of {len(page_data)}")
return num_stored
@contextmanager
@@ -457,7 +468,7 @@ class TinyIndex(Generic[T]):
"""Open page i for a read-modify-write, holding its lock throughout.
Changing a page is read -> merge -> write, and the three have to be atomic
- together. _write_page copies ~4 KB into the mmap; a reader catching it half-written
+ together. _write_page writes ~4 KB over the page; a reader catching it half-written
gets a page that will not decompress, and a writer that took that for an empty page
would store its result over everything else there.
diff --git a/scripts/benchmark_index_reads.py b/scripts/benchmark_index_reads.py
new file mode 100644
index 0000000..0604fab
--- /dev/null
+++ b/scripts/benchmark_index_reads.py
@@ -0,0 +1,204 @@
+"""Measure what dropping the index memory mapping buys, and what it costs.
+
+Standard library only, so it can be copied to the server and run with the system python
+against the production index - the point of the read-speed half is to measure real disk
+and a real page cache, which a sparse file cannot model.
+
+Two measurements, chosen separately:
+
+ python3 scripts/benchmark_index_reads.py pagetables
+ python3 scripts/benchmark_index_reads.py reads --index-path devdata/index-v2.tinysearch
+
+`pagetables` builds a production-sized sparse file, touches one page in each 2 MiB window
+both ways and reports VmPTE. That is the number the change exists for, and it needs no
+index: expect roughly 800 MiB mapped against a few MiB with pread.
+
+`reads` times random page reads both ways on a real index, single-threaded and across ten
+threads. A warm mapped read is a memcpy, ~200 ns; a warm pread adds a syscall, ~1 us. A
+query reads about ten pages, so ~10 us added per query against a zstd decompress and a JSON
+parse of each of those pages.
+
+Watch the threaded throughput rather than the threaded mean. A pread releases the GIL and
+has to win it back, which a mapped read never does, so ten threads doing nothing but read
+pages lose most of their throughput - far more than the syscall itself costs. Pass
+`--decode` to time what get_page really does, the read plus the zstd decompress and the
+JSON parse; that work dwarfs the handoff and is the number to judge the change on.
+"""
+
+import argparse
+import json
+import mmap
+import os
+import random
+import statistics
+import time
+from concurrent.futures import ThreadPoolExecutor
+
+PAGE_SIZE = 4096
+METADATA_SIZE = 4096
+
+# One page table page covers 512 file pages, so touching one page per 2 MiB window is
+# enough to allocate the whole table for that window - which is how a worker doing random
+# lookups saturates its page tables long before it has read much of the index.
+PAGE_TABLE_WINDOW = 2 * 1024 * 1024
+
+# The production index: 102,400,000 pages of 4 KiB, 390 GiB.
+PRODUCTION_NUM_PAGES = 102_400_000
+
+
+def read_status_field(field: str) -> int:
+ """The named /proc/self/status field in KiB."""
+ with open("/proc/self/status") as status_file:
+ for line in status_file:
+ if line.startswith(field + ":"):
+ return int(line.split()[1])
+ raise ValueError(f"No {field} in /proc/self/status")
+
+
+def report_memory(label: str):
+ print(
+ f" {label:<12} VmPTE {read_status_field('VmPTE') / 1024:8.1f} MiB VmRSS {read_status_field('VmRSS') / 1024:8.1f} MiB"
+ )
+
+
+def measure_page_tables(path: str, num_pages: int):
+ """Touch one page per 2 MiB window through a mapping and through pread."""
+ file_size = METADATA_SIZE + num_pages * PAGE_SIZE
+ with open(path, "wb") as index_file:
+ index_file.truncate(file_size)
+ offsets = list(range(METADATA_SIZE, file_size - PAGE_SIZE, PAGE_TABLE_WINDOW))
+ print(f"{file_size / 1024**3:.0f} GiB sparse file, {len(offsets)} windows touched")
+
+ index_file = open(path, "r+b")
+ report_memory("baseline")
+
+ mapping = mmap.mmap(index_file.fileno(), 0, prot=mmap.PROT_READ)
+ # Without this, a read fault maps 16 pages rather than one (fault-around), so the
+ # resident set is 32 times the page tables and the kernel reclaims it on any machine
+ # smaller than the server - and khugepaged then retracts the page tables the reclaim
+ # emptied, which is exactly the number being measured. MADV_RANDOM is also what the
+ # access pattern actually is: one page per lookup, nowhere near its neighbours.
+ mapping.madvise(mmap.MADV_RANDOM)
+ for offset in offsets:
+ mapping[offset : offset + PAGE_SIZE]
+ report_memory("mmap")
+ mapping.close()
+ report_memory("after close")
+
+ fileno = index_file.fileno()
+ for offset in offsets:
+ os.pread(fileno, PAGE_SIZE, offset)
+ report_memory("pread")
+ index_file.close()
+ os.remove(path)
+
+
+def time_reads(read_page, page_indices: list[int]) -> list[float]:
+ timings = []
+ for page_index in page_indices:
+ start = time.perf_counter()
+ read_page(page_index)
+ timings.append((time.perf_counter() - start) * 1e6)
+ return timings
+
+
+def report_timings(label: str, timings: list[float], elapsed: float):
+ """Per-read latency, and the throughput of the run it came from.
+
+ Both, because under threads they say different things. A pread releases the GIL and
+ then has to win it back, so its per-read mean counts time the thread spent waiting for
+ the interpreter rather than for the kernel. Throughput is what the worker actually
+ gets.
+ """
+ ordered = sorted(timings)
+ p50 = ordered[len(ordered) // 2]
+ p99 = ordered[int(len(ordered) * 0.99)]
+ rate = len(timings) / elapsed / 1000
+ print(
+ f" {label:<22} mean {statistics.mean(timings):8.2f} us p50 {p50:8.2f} us "
+ f"p99 {p99:8.2f} us {rate:7.1f}k reads/s"
+ )
+
+
+def decode_page(page_data: bytes):
+ """What get_page does with a page once it has it."""
+ # Not at the top of the file: everything else here is standard library so the script
+ # can run on the server with the system python, and only --decode needs zstandard.
+ # A fresh decompressor per page, as _get_page_tuples does - sharing one across threads
+ # corrupts its buffer.
+ import zstandard
+
+ return json.loads(zstandard.ZstdDecompressor().decompress(page_data).decode("utf8"))
+
+
+def measure_reads(path: str, num_reads: int, num_threads: int, decode: bool):
+ """Time random page reads on a real index, mapped and with pread."""
+ file_size = os.path.getsize(path)
+ num_pages = (file_size - METADATA_SIZE) // PAGE_SIZE
+ generator = random.Random(2)
+ page_indices = [generator.randrange(num_pages) for _ in range(num_reads)]
+ print(f"{path}: {num_pages} pages, {num_reads} random reads, {num_threads} threads")
+
+ index_file = open(path, "rb")
+ fileno = index_file.fileno()
+ mapping = mmap.mmap(fileno, 0, prot=mmap.PROT_READ)
+
+ def read_mapped(page_index: int):
+ offset = METADATA_SIZE + page_index * PAGE_SIZE
+ return mapping[offset : offset + PAGE_SIZE]
+
+ def read_pread(page_index: int):
+ return os.pread(fileno, PAGE_SIZE, METADATA_SIZE + page_index * PAGE_SIZE)
+
+ def with_decode(read_page):
+ return lambda page_index: decode_page(read_page(page_index))
+
+ for label, read_raw in (("mmap", read_mapped), ("pread", read_pread)):
+ read_page = with_decode(read_raw) if decode else read_raw
+ # Warm the page cache for this set of pages, so the single-threaded numbers are
+ # about the read itself rather than about disk. Cold reads are dominated by the
+ # disk either way; measure those on the server with the cache dropped.
+ time_reads(read_page, page_indices)
+ start = time.perf_counter()
+ timings = time_reads(read_page, page_indices)
+ report_timings(f"{label} single-threaded", timings, time.perf_counter() - start)
+
+ chunk_size = num_reads // num_threads
+ chunks = [page_indices[i : i + chunk_size] for i in range(0, num_reads, chunk_size)]
+ start = time.perf_counter()
+ with ThreadPoolExecutor(max_workers=num_threads) as pool:
+ results = list(pool.map(lambda chunk: time_reads(read_page, chunk), chunks))
+ elapsed = time.perf_counter() - start
+ report_timings(f"{label} {num_threads} threads", [t for chunk in results for t in chunk], elapsed)
+
+ mapping.close()
+ index_file.close()
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ subparsers = parser.add_subparsers(dest="measurement", required=True)
+
+ page_tables_parser = subparsers.add_parser("pagetables", help="page tables for a production-sized mapping")
+ page_tables_parser.add_argument("--path", default="/tmp/benchmark-index-sparse")
+ page_tables_parser.add_argument("--num-pages", type=int, default=PRODUCTION_NUM_PAGES)
+
+ reads_parser = subparsers.add_parser("reads", help="read speed against a real index")
+ reads_parser.add_argument("--index-path", required=True)
+ reads_parser.add_argument("--num-reads", type=int, default=100_000)
+ reads_parser.add_argument("--num-threads", type=int, default=10)
+ reads_parser.add_argument(
+ "--decode",
+ action="store_true",
+ help="time the whole of get_page - read, zstd decompress, JSON parse - which needs zstandard",
+ )
+
+ args = parser.parse_args()
+ if args.measurement == "pagetables":
+ measure_page_tables(args.path, args.num_pages)
+ else:
+ measure_reads(args.index_path, args.num_reads, args.num_threads, args.decode)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/test/test_index_page_writes.py b/test/test_index_page_writes.py
index 44581ef..9749783 100644
--- a/test/test_index_page_writes.py
+++ b/test/test_index_page_writes.py
@@ -1,6 +1,6 @@
"""Changing an index page is read -> merge -> write, and has to be atomic.
-_write_page copies ~4 KB into the mmap, and a reader catching it half-written gets a page
+_write_page writes ~4 KB over the page, and a reader catching it half-written gets a page
that will not decompress. Every read-modify-write goes through TinyIndex.page(), which
holds the page's lock for the whole block, so no caller has to know locking exists.
"""
@@ -59,7 +59,7 @@ def test_page_holds_the_lock_across_the_read_and_the_write(index_path):
"""The lock must be held for as long as the block runs, and no longer.
It asserts the exclusion property directly rather than trying to win the race: the
- window is a single memcpy, so a racing test passes with the lock removed and guards
+ window is a single pwrite, so a racing test passes with the lock removed and guards
nothing.
"""
context = multiprocessing.get_context("fork")
@@ -266,7 +266,7 @@ def test_a_corrupt_page_is_reset_by_a_writer_holding_its_lock(index_path):
def test_an_unlocked_writer_refuses_a_page_it_could_not_read(index_path, monkeypatch):
"""Without the lock, a page that will not decode is just as likely to be another
- writer's memcpy in progress, and resetting it would store over what they are writing.
+ writer's pwrite in progress, and resetting it would store over what they are writing.
Skip it - and leave it for a writer that can take the lock."""
_corrupt(index_path, 3)
_fail_to_lock(monkeypatch, OSError(errno.ENOLCK, "no locks available"))
diff --git a/test/test_indexer.py b/test/test_indexer.py
index 1a092cd..a2a9155 100644
--- a/test/test_indexer.py
+++ b/test/test_indexer.py
@@ -1,13 +1,16 @@
from pathlib import Path
from tempfile import TemporaryDirectory
+import pytest
from zstandard import ZstdCompressor
from mwmbl.tinysearchengine.indexer import (
+ METADATA_SIZE,
STATE_INDEX,
Document,
DocumentSource,
DocumentState,
+ PageError,
TinyIndex,
_binary_search_fitting_size,
_get_page_data,
@@ -208,3 +211,41 @@ def test_a_document_with_an_unreadable_state_keeps_its_other_values():
assert documents[0].state is None
assert documents[0].source == DocumentSource.WIKIPEDIA
assert documents[0].last_crawled == 123
+
+
+def test_a_write_through_another_handle_is_visible_without_reopening():
+ """Search and the external cache keep one read handle open for the life of the worker
+ while writers come and go on short-lived 'w' handles, so a read has to see a write made
+ elsewhere with no flush and no reopen. Positioned reads and writes share the page cache,
+ which is what makes that hold."""
+ with TemporaryDirectory() as temp_dir:
+ index_path = str(Path(temp_dir) / "temp-index.tinysearch")
+ TinyIndex.create(Document, index_path, num_pages=4, page_size=4096)
+ document = Document("Title", "https://example.com", "Extract", 1.0, "term")
+
+ with TinyIndex(Document, index_path, "r") as reader:
+ page_index = reader.get_key_page_index("term")
+ assert reader.get_page(page_index) == []
+
+ with TinyIndex(Document, index_path, "w") as writer:
+ writer.store_in_page(page_index, [document])
+
+ documents = reader.get_page(page_index)
+
+ assert [item.url for item in documents] == ["https://example.com"]
+
+
+def test_a_truncated_page_raises_rather_than_reading_short():
+ """A read that stops at the end of the file must not pass for a page. Silently
+ decoding whatever came back would let a writer merge onto it and store the result."""
+ with TemporaryDirectory() as temp_dir:
+ index_path = str(Path(temp_dir) / "temp-index.tinysearch")
+ TinyIndex.create(Document, index_path, num_pages=4, page_size=4096)
+ page_size = 4096
+ with open(index_path, "r+b") as index_file:
+ index_file.truncate(METADATA_SIZE + 3 * page_size + page_size // 2)
+
+ with TinyIndex(Document, index_path, "r") as index:
+ assert index.get_page(2) == []
+ with pytest.raises(PageError):
+ index.get_page(3)