An open source, non-profit web search engine
Read and write index pages in the Rust extension
Claude12872c0dbcdb
diff --git a/mwmbl/tinysearchengine/indexer.py b/mwmbl/tinysearchengine/indexer.pyindex b091865..e3aa19e 100644--- a/mwmbl/tinysearchengine/indexer.py+++ b/mwmbl/tinysearchengine/indexer.py@@ -7,12 +7,16 @@ from contextlib import contextmanagerfrom dataclasses import asdict, dataclass, fieldfrom enum import IntEnumfrom io import UnsupportedOperation-from json import JSONDecodeErrorfrom logging import getLoggerfrom typing import Callable, Generic, List, Optional, TypeVarimport mmh3-from zstandard import ZstdCompressor, ZstdDecompressor, ZstdError++# Pages are read, packed and written by the Rust extension, which does the positioned+# read, the zstd and the JSON with the GIL released - see mwmbl_rank/src/index.rs.+# PageError is raised from there and imported by the rest of the codebase from here, as+# it always was: a page that will not decode, or data that will not fit on one.+from mwmbl_rank import PageError, pack_index_page, read_index_page, write_index_pageVERSION = 1METADATA_CONSTANT = b"mwmbl-tiny-search"@@ -157,10 +161,6 @@ class TokenizedDocument(Document):T = TypeVar("T")-class PageError(Exception):- pass--@dataclassclass TinyIndexMetadata:version: int@@ -184,49 +184,6 @@ class TinyIndexMetadata:return TinyIndexMetadata(**values)-# Find the optimal amount of data that fits onto a page-# We do this by leveraging binary search to quickly find the index where:-# - index+1 cannot fit onto a page-# - <=index can fit on a page-def _binary_search_fitting_size(compressor: ZstdCompressor, page_size: int, items: list[T], lo: int, hi: int):- # Base case: our binary search has gone too far- if lo > hi:- return -1, None- # Check the midpoint to see if it will fit onto a page- mid = (lo + hi) // 2- compressed_data = compressor.compress(json.dumps(items[:mid]).encode("utf8"))- size = len(compressed_data)- if size > page_size:- # We cannot fit this much data into a page- # Reduce the hi boundary, and try again- return _binary_search_fitting_size(compressor, page_size, items, lo, mid - 1)- else:- # We can fit this data into a page, but maybe we can fit more data- # Try to see if we have a better match- potential_target, potential_data = _binary_search_fitting_size(compressor, page_size, items, mid + 1, hi)- if potential_target != -1:- # We found a larger index that can still fit onto a page, so use that- return potential_target, potential_data- else:- # No better match, use our index- return mid, compressed_data---def _trim_items_to_page(compressor: ZstdCompressor, page_size: int, items: list[T]):- # Find max number of items that fit on a page- return _binary_search_fitting_size(compressor, page_size, items, 0, len(items))---def _get_page_data(page_size: int, items: list[T]):- """The padded page bytes, and how many of `items` actually fit on it."""- compressor = ZstdCompressor()- num_fitting, serialised_data = _trim_items_to_page(compressor, page_size, items)-- compressed_data = compressor.compress(json.dumps(items[:num_fitting]).encode("utf8"))- assert len(compressed_data) <= page_size, "The data shouldn't get bigger"- return _pad_to_page_size(compressed_data, page_size), num_fitting--def _pad_to_page_size(data: bytes, page_size: int):page_length = len(data)if page_length > page_size:@@ -297,9 +254,9 @@ class TinyIndex(Generic[T]):self.index_file = Nonedef __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+ # Pages are read and written positionally on this descriptor, in the extension,+ # 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.@@ -313,13 +270,14 @@ class TinyIndex(Generic[T]):index = self.get_key_page_index(key)logger.debug(f"Retrieving index {index}")try:- page = self.get_page(index)+ # Passing the term drops the documents that another term put on this page+ # before any of them is built into a Document.+ return self.get_page(index, term=key)except PageError:# One unreadable page costs this query the results for one term, and the next# read of it will very likely succeed. Writers do not swallow this.logger.exception("Could not read index page %d", index)return []- return [item for item in page if item.term is None or item.term == key]def get_key_page_index(self, key) -> int:key_hash = mmh3.hash(key, signed=False)@@ -383,11 +341,14 @@ class TinyIndex(Generic[T]):# Dropped on close anyway; failing here would mask the caller's own error.logger.warning("Could not release the lock on index page %d", i)- def get_page(self, i) -> list[T]:+ def get_page(self, i, term: Optional[str] = None) -> list[T]:"""- Get the page at index i, decompress and deserialise it using JSON+ Get the page at index i, decompress and deserialise it using JSON.++ Pass `term` to keep only the documents that belong to it - the ones whose term is+ that term, or which have none, exactly as retrieve() needs them."""- results = self._get_page_tuples(i)+ results = self._get_page_tuples(i, term)items = []for item in results:try:@@ -409,7 +370,7 @@ class TinyIndex(Generic[T]):logger.error(f"Could not recover item in index page {i}, skipping: {e2}. Item: {item}")return items- def _get_page_tuples(self, i):+ def _get_page_tuples(self, i, term: Optional[str] = None):"""The raw tuples on page i. Raises PageError if the page will not decode.It deliberately does not fall back to an empty page. A page that fails to@@ -418,22 +379,11 @@ class TinyIndex(Generic[T]):over everything that was on the page. Readers that would rather have no resultsthan an error catch this - see retrieve."""- 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()+ offset = i * self.page_size + METADATA_SIZEtry:- decompressed_data = decompressor.decompress(page_data)- return json.loads(decompressed_data.decode("utf8"))- except (ZstdError, UnicodeDecodeError, JSONDecodeError) as e:- # Damage that gets past zstd's checksum lands on the decode or the parse- # instead, and it is the same kind of unreadable. Callers catch PageError and- # nothing else, so anything raised from here that is not one would escape- # them - retrieve() would 500 a search rather than degrading to no results.+ return read_index_page(self.index_file.fileno(), offset, self.page_size, term)+ except PageError as e:+ # The extension knows the offset it read, not which page that was.raise PageError(f"Could not read page {i}: {e}") from edef store_in_page(self, page_index: int, values: list[T]) -> int:@@ -445,7 +395,7 @@ class TinyIndex(Generic[T]):value_tuples = [value.as_tuple() for value in values]return self._write_page(value_tuples, page_index)- def _write_page(self, data, i: int) -> int:+ def _write_page(self, data: list, i: int) -> int:"""Serialise the data using JSON, compress it and store it at index i.If the data is too big, it will store the first items in the list and discard the@@ -454,14 +404,11 @@ class TinyIndex(Generic[T]):if self.mode != "w":raise UnsupportedOperation("The file is open in read mode, you cannot write")- page_data, num_stored = _get_page_data(self.page_size, data)- logger.debug(f"Got page data of length {len(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+ offset = i * self.page_size + METADATA_SIZE+ try:+ return write_index_page(self.index_file.fileno(), offset, self.page_size, data)+ except PageError as e:+ raise PageError(f"Could not write page {i}: {e}") from e@contextmanagerdef page(self, i: int):@@ -501,7 +448,7 @@ class TinyIndex(Generic[T]):metadata_bytes = metadata.to_bytes()metadata_padded = _pad_to_page_size(metadata_bytes, METADATA_SIZE)- page_bytes, _ = _get_page_data(page_size, [])+ page_bytes, _ = pack_index_page(page_size, [])with open(index_path, "wb") as index_file:index_file.write(metadata_padded)diff --git a/mwmbl_rank/Cargo.lock b/mwmbl_rank/Cargo.lockindex 6cc0123..cfd046a 100644--- a/mwmbl_rank/Cargo.lock+++ b/mwmbl_rank/Cargo.lock@@ -80,6 +80,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b7a4d3ec6524d28a329fc53654bbadc9bdd7b0431f5d65f1a56ffb28a1ee5283"dependencies = ["find-msvc-tools",+ "jobserver",+ "libc","shlex",]@@ -706,6 +708,16 @@ version = "1.0.18"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"+[[package]]+name = "jobserver"+version = "0.1.35"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"+dependencies = [+ "getrandom 0.4.2",+ "libc",+]+[[package]]name = "js-sys"version = "0.3.94"@@ -816,6 +828,7 @@ dependencies = ["serde_json","url","xgb",+ "zstd",][[package]]@@ -2054,3 +2067,31 @@ name = "zmij"version = "1.0.21"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"++[[package]]+name = "zstd"+version = "0.13.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a"+dependencies = [+ "zstd-safe",+]++[[package]]+name = "zstd-safe"+version = "7.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "64d80649ab6db9d9f6f9c80a40becd948eda4714a0a5ac8c4d157a32231c7882"+dependencies = [+ "zstd-sys",+]++[[package]]+name = "zstd-sys"+version = "2.1.0+zstd.1.5.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ef0a8027ec3ee71300ab3bcbcd0393f434aa72b91ca6d635a39941deae8eea0"+dependencies = [+ "cc",+ "pkg-config",+]diff --git a/mwmbl_rank/Cargo.toml b/mwmbl_rank/Cargo.tomlindex cf2f01d..f454f80 100644--- a/mwmbl_rank/Cargo.toml+++ b/mwmbl_rank/Cargo.toml@@ -12,9 +12,10 @@ pyo3 = { version = "0.21", features = ["extension-module"] }xgb = { version = "3.0.5", features = ["use_prebuilt_xgb"] }regex = "1"serde = { version = "1", features = ["derive"] }-serde_json = "1"+serde_json = { version = "1", features = ["float_roundtrip"] }once_cell = "1"url = "2"+zstd = "0.13"[profile.release]lto = truediff --git a/mwmbl_rank/src/index.rs b/mwmbl_rank/src/index.rsnew file mode 100644index 0000000..a007258--- /dev/null+++ b/mwmbl_rank/src/index.rs@@ -0,0 +1,368 @@+//! TinyIndex page I/O.+//!+//! A page of the index is a zstd frame holding a JSON array of document tuples, padded+//! with zeros to the page size. Reading one is a positioned read, a decompress and a+//! parse, and writing one is a serialise, a compress and a positioned write. All of that+//! happens here with the GIL released, so worker threads overlap their page reads instead+//! of queueing for the interpreter - which is what a pread in Python cannot do, because it+//! releases the GIL for the syscall and then has to win it back for the decompress and the+//! parse.+//!+//! Python keeps everything else: it opens the file and passes the descriptor in, holds the+//! metadata and the page locks, and turns the tuples that come back into Documents.++use std::cell::RefCell;+use std::fs::File;+use std::mem::ManuallyDrop;+use std::os::unix::fs::FileExt;+use std::os::unix::io::FromRawFd;++use pyo3::create_exception;+use pyo3::exceptions::{PyException, PyOSError, PyTypeError, PyValueError};+use pyo3::prelude::*;+use pyo3::types::{PyBool, PyBytes, PyDict, PyFloat, PyList, PyLong, PyString, PyTuple};+use serde_json::{Map, Number, Value};+use zstd::bulk::{Compressor, Decompressor};+use zstd::zstd_safe;++create_exception!(+ mwmbl_rank,+ PageError,+ PyException,+ "A page that will not decode, or data that will not fit on one."+);++/// Where `term` sits in Document.as_tuple(). as_tuple truncates trailing Nones, so a+/// document with no term may have nothing at that position at all.+const TERM_INDEX: usize = 4;++/// python-zstandard's default level, which is what wrote every page in the index today.+const COMPRESSION_LEVEL: i32 = 3;++/// How much bigger than the page itself its contents are allowed to claim to be. See+/// decompress_page: it bounds what a corrupt frame header can make this allocate.+const MAX_PAGE_EXPANSION: usize = 1024;++/// Everything that can go wrong away from the GIL, split by what Python should see: a+/// failed syscall is an OSError as it has always been, and a page that will not decode is+/// a PageError, which every caller of the index already handles.+enum PageIoError {+ Io(std::io::Error),+ Unreadable(String),+}++impl From<PageIoError> for PyErr {+ fn from(error: PageIoError) -> PyErr {+ match error {+ PageIoError::Io(e) => PyOSError::new_err(e.to_string()),+ PageIoError::Unreadable(message) => PageError::new_err(message),+ }+ }+}++/// The descriptor belongs to the Python file object that opened it, so wrap it without+/// taking ownership - a plain File would close it when this returns.+fn borrow_file(fd: i32) -> ManuallyDrop<File> {+ ManuallyDrop::new(unsafe { File::from_raw_fd(fd) })+}++fn read_page_bytes(fd: i32, offset: u64, page_size: usize) -> Result<Vec<u8>, PageIoError> {+ let file = borrow_file(fd);+ let mut page = vec![0u8; page_size];+ let num_read = file.read_at(&mut page, offset).map_err(PageIoError::Io)?;+ if num_read != page_size {+ // A positioned read 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.+ return Err(PageIoError::Unreadable(format!(+ "got {num_read} bytes, expected {page_size}"+ )));+ }+ Ok(page)+}++thread_local! {+ /// One decompression context per thread, reused for every page it reads. Building one+ /// allocates a working buffer and costs about as much as decompressing a page, and+ /// each call decompresses a whole frame on its own, so there is no state to carry+ /// between reads and a failed page cannot poison the next one.+ static DECOMPRESSOR: RefCell<Decompressor<'static>> =+ RefCell::new(Decompressor::new().expect("Could not create a zstd decompression context"));++ /// And one compression context, for the same reason. Packing a page compresses about+ /// a dozen prefixes of the documents to find the ones that fit, so building a context+ /// per compression cost more than the compression did.+ static COMPRESSOR: RefCell<Compressor<'static>> = RefCell::new(+ Compressor::new(COMPRESSION_LEVEL).expect("Could not create a zstd compression context"));+}++/// Decompress the one zstd frame at the start of the page, ignoring whatever follows it -+/// which is the zero padding that brings the page up to its fixed size.+fn decompress_page(page: &[u8]) -> Result<Vec<u8>, PageIoError> {+ let unreadable = |e: std::io::Error| PageIoError::Unreadable(e.to_string());+ let frame_size = zstd_safe::find_frame_compressed_size(page).map_err(zstd_error)?;+ let frame = &page[..frame_size];+ // Every frame the index writes carries its content size, so this is the exact size of+ // the buffer to decompress into rather than a guess.+ let contents_size = zstd_safe::get_frame_content_size(frame)+ .map_err(|e| PageIoError::Unreadable(e.to_string()))?+ .ok_or_else(|| PageIoError::Unreadable("The frame has no content size".to_string()))?+ as usize;+ // That size is data like anything else on the page, and the buffer is allocated before+ // a byte is decompressed, so a corrupt header must not be able to ask for a gigabyte.+ // Real pages expand by well under ten times; this is far past that and still bounded.+ let largest_readable = page.len() * MAX_PAGE_EXPANSION;+ if contents_size > largest_readable {+ return Err(PageIoError::Unreadable(format!(+ "The frame claims {contents_size} bytes, more than the {largest_readable} a page can hold"+ )));+ }+ DECOMPRESSOR.with_borrow_mut(|decompressor| {+ decompressor+ .decompress(frame, contents_size)+ .map_err(unreadable)+ })+}++/// zstd reports a failure as an error code, and the text for it is all there is to say.+fn zstd_error(code: usize) -> PageIoError {+ PageIoError::Unreadable(zstd_safe::get_error_name(code).to_string())+}++fn decode_page(page: &[u8], term: Option<&str>) -> Result<Vec<Value>, PageIoError> {+ let contents = decompress_page(page)?;+ // Damage that gets past zstd lands on the parse instead, and it is the same kind of+ // unreadable. Invalid UTF-8 fails here too, as the decode in Python did.+ let items: Vec<Value> =+ serde_json::from_slice(&contents).map_err(|e| PageIoError::Unreadable(e.to_string()))?;+ match term {+ None => Ok(items),+ Some(term) => Ok(items+ .into_iter()+ .filter(|item| has_term(item, term))+ .collect()),+ }+}++/// Whether a document tuple belongs to this term: its own, or no term at all. Filtering+/// here rather than in Python means a page's documents that another term put there are+/// never built into Python objects.+fn has_term(item: &Value, term: &str) -> bool {+ match item.get(TERM_INDEX) {+ None | Some(Value::Null) => true,+ Some(Value::String(item_term)) => item_term == term,+ Some(_) => false,+ }+}++fn value_to_py(py: Python<'_>, value: Value) -> PyResult<PyObject> {+ let object = match value {+ Value::Null => py.None(),+ Value::Bool(boolean) => boolean.into_py(py),+ Value::Number(number) => match (number.as_i64(), number.as_u64(), number.as_f64()) {+ (Some(integer), _, _) => integer.into_py(py),+ (_, Some(unsigned), _) => unsigned.into_py(py),+ (_, _, Some(float)) => float.into_py(py),+ // A JSON number is an i64, a u64 or an f64, so nothing reaches this.+ _ => return Err(PageError::new_err(format!("Unreadable number {number}"))),+ },+ Value::String(string) => string.into_py(py),+ Value::Array(items) => values_to_py(py, items)?.into(),+ Value::Object(fields) => {+ let dict = PyDict::new_bound(py);+ for (key, field) in fields {+ dict.set_item(key, value_to_py(py, field)?)?;+ }+ dict.into()+ }+ };+ Ok(object)+}++/// A JSON array as the list json.loads would have returned.+fn values_to_py<'py>(py: Python<'py>, values: Vec<Value>) -> PyResult<Bound<'py, PyList>> {+ let items = values+ .into_iter()+ .map(|value| value_to_py(py, value))+ .collect::<PyResult<Vec<PyObject>>>()?;+ Ok(PyList::new_bound(py, items))+}++fn py_to_value(object: &Bound<'_, PyAny>) -> PyResult<Value> {+ if object.is_none() {+ return Ok(Value::Null);+ }+ // Before the integer check, not after: a Python bool is an int.+ if let Ok(boolean) = object.downcast::<PyBool>() {+ return Ok(Value::Bool(boolean.is_true()));+ }+ if let Ok(integer) = object.downcast::<PyLong>() {+ return Ok(Value::Number(Number::from(integer.extract::<i64>()?)));+ }+ if let Ok(float) = object.downcast::<PyFloat>() {+ let value = float.value();+ // JSON has no NaN or infinity. Python's json module writes them anyway, as words+ // no other reader accepts, so a score that has gone wrong is caught here rather+ // than written to a page that will not parse again.+ let number = Number::from_f64(value).ok_or_else(|| {+ PyValueError::new_err(format!("{value} cannot be stored in an index page"))+ })?;+ return Ok(Value::Number(number));+ }+ if let Ok(string) = object.downcast::<PyString>() {+ return Ok(Value::String(string.to_str()?.to_owned()));+ }+ if let Ok(list) = object.downcast::<PyList>() {+ return Ok(Value::Array(+ list.iter()+ .map(|item| py_to_value(&item))+ .collect::<PyResult<_>>()?,+ ));+ }+ if let Ok(tuple) = object.downcast::<PyTuple>() {+ return Ok(Value::Array(+ tuple+ .iter()+ .map(|item| py_to_value(&item))+ .collect::<PyResult<_>>()?,+ ));+ }+ if let Ok(dict) = object.downcast::<PyDict>() {+ let mut fields = Map::with_capacity(dict.len());+ for (key, value) in dict.iter() {+ let name = key.downcast::<PyString>().map_err(|_| {+ PyTypeError::new_err("Only string keys can be stored in an index page")+ })?;+ fields.insert(name.to_str()?.to_owned(), py_to_value(&value)?);+ }+ return Ok(Value::Object(fields));+ }+ Err(PyTypeError::new_err(format!(+ "Cannot store {} in an index page",+ object.get_type().name()?+ )))+}++fn compress_prefix(serialised: &[String], count: usize) -> Result<Vec<u8>, PageIoError> {+ let mut json = String::from("[");+ for (position, item) in serialised[..count].iter().enumerate() {+ if position > 0 {+ json.push(',');+ }+ json.push_str(item);+ }+ json.push(']');+ COMPRESSOR.with_borrow_mut(|compressor| {+ compressor+ .compress(json.as_bytes())+ .map_err(PageIoError::Io)+ })+}++/// The padded page bytes, and how many of `items` actually fit on them.+///+/// A page holds a fixed number of bytes, and how many documents that is depends on how+/// well they compress, so the largest prefix that fits is found by binary search over the+/// compressed size. The tail that does not fit is dropped, which is why callers pass their+/// documents best-first.+fn pack_page(page_size: usize, items: &[Value]) -> Result<(Vec<u8>, usize), PageIoError> {+ let serialised: Vec<String> = items.iter().map(|item| item.to_string()).collect();+ // One compression context for the whole search: the binary search compresses a dozen+ // prefixes, and building a context each time would cost more than the compression.+ let mut low = 0;+ let mut high = items.len();+ let mut best = (0, compress_prefix(&serialised, 0)?);+ while low <= high {+ let count = (low + high) / 2;+ let compressed = compress_prefix(&serialised, count)?;+ if compressed.len() > page_size {+ if count == 0 {+ break;+ }+ high = count - 1;+ } else {+ best = (count, compressed);+ low = count + 1;+ }+ }++ let (num_stored, mut page) = best;+ if page.len() > page_size {+ return Err(PageIoError::Unreadable(format!(+ "Data is too big ({}) for page size ({page_size})",+ page.len()+ )));+ }+ page.resize(page_size, 0);+ Ok((page, num_stored))+}++/// Read the page at `offset`, returning its document tuples as lists.+///+/// Pass `term` to keep only the documents that belong to it - the ones whose term is that+/// term, or which have none. Raises PageError if the page will not decode, which means it+/// is corrupt or was caught half-written; it deliberately does not fall back to an empty+/// page, because a writer that merged onto one would store its result over everything that+/// was there.+#[pyfunction]+#[pyo3(signature = (fd, offset, page_size, term=None))]+pub fn read_index_page(+ py: Python<'_>,+ fd: i32,+ offset: u64,+ page_size: usize,+ term: Option<String>,+) -> PyResult<Py<PyList>> {+ let items = py.allow_threads(|| {+ let page = read_page_bytes(fd, offset, page_size)?;+ decode_page(&page, term.as_deref())+ })?;+ Ok(values_to_py(py, items)?.unbind())+}++/// Write `items` over the page at `offset`, returning how many of them fitted.+#[pyfunction]+pub fn write_index_page(+ py: Python<'_>,+ fd: i32,+ offset: u64,+ page_size: usize,+ items: &Bound<'_, PyList>,+) -> PyResult<usize> {+ let values: Vec<Value> = items+ .iter()+ .map(|item| py_to_value(&item))+ .collect::<PyResult<_>>()?;+ let num_stored = py.allow_threads(|| -> Result<usize, PageIoError> {+ let (page, num_stored) = pack_page(page_size, &values)?;+ let file = borrow_file(fd);+ let num_written = file.write_at(&page, offset).map_err(PageIoError::Io)?;+ if num_written != page.len() {+ // 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.+ return Err(PageIoError::Unreadable(format!(+ "wrote {num_written} bytes of {}",+ page.len()+ )));+ }+ Ok(num_stored)+ })?;+ Ok(num_stored)+}++/// The bytes of a page holding `items`, and how many of them fitted, without writing it.+/// TinyIndex.create uses this to lay down the empty pages of a new index.+#[pyfunction]+pub fn pack_index_page(+ py: Python<'_>,+ page_size: usize,+ items: &Bound<'_, PyList>,+) -> PyResult<(Py<PyBytes>, usize)> {+ let values: Vec<Value> = items+ .iter()+ .map(|item| py_to_value(&item))+ .collect::<PyResult<_>>()?;+ let (page, num_stored) = py.allow_threads(|| pack_page(page_size, &values))?;+ Ok((PyBytes::new_bound(py, &page).unbind(), num_stored))+}diff --git a/mwmbl_rank/src/lib.rs b/mwmbl_rank/src/lib.rsindex 75da1d4..8589b0c 100644--- a/mwmbl_rank/src/lib.rs+++ b/mwmbl_rank/src/lib.rs@@ -6,6 +6,7 @@mod domain;mod features;mod idf;+mod index;mod pipeline;mod text;mod wiki;@@ -199,6 +200,10 @@ fn get_features_py(fn mwmbl_rank(m: &Bound<'_, PyModule>) -> PyResult<()> {m.add_class::<PyXGBPipeline>()?;m.add_function(wrap_pyfunction!(get_features_py, m)?)?;+ m.add_function(wrap_pyfunction!(index::read_index_page, m)?)?;+ m.add_function(wrap_pyfunction!(index::write_index_page, m)?)?;+ m.add_function(wrap_pyfunction!(index::pack_index_page, m)?)?;+ m.add("PageError", m.py().get_type_bound::<index::PageError>())?;m.add("NUM_FEATURES", features::NUM_FEATURES)?;m.add("FEATURE_NAMES", features::FEATURE_NAMES.to_vec())?;Ok(())diff --git a/scripts/benchmark_index_reads.py b/scripts/benchmark_index_reads.pyindex 0604fab..2e64ec5 100644--- a/scripts/benchmark_index_reads.py+++ b/scripts/benchmark_index_reads.py@@ -1,8 +1,8 @@"""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.+Standard library only unless `--decode` is passed, 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:@@ -23,6 +23,11 @@ has to win it back, which a mapped read never does, so ten threads doing nothingpages 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 theJSON parse; that work dwarfs the handoff and is the number to judge the change on.++`--decode` also times the extension, which does the read, the decompress and the parse in+Rust with the GIL released. That is what buys the threaded throughput back: Python holds+the interpreter for the decompress and the parse, so its threads queue behind each other+whichever way they read the page."""import argparse@@ -120,14 +125,12 @@ def report_timings(label: str, timings: list[float], elapsed: float):)-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+def decode_page(zstandard, page_data: bytes):+ """What reading a page in Python costs once the bytes are in hand.+ A fresh decompressor per page, as the Python version did - sharing one across threads+ corrupts its buffer.+ """return json.loads(zstandard.ZstdDecompressor().decompress(page_data).decode("utf8"))@@ -150,11 +153,26 @@ def measure_reads(path: str, num_reads: int, num_threads: int, decode: bool):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))+ readers = [("mmap", read_mapped), ("pread", read_pread)]+ if decode:+ # 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 and the extension.+ import zstandard++ import mwmbl_rank++ def with_decode(read_page):+ return lambda page_index: decode_page(zstandard, read_page(page_index))++ def read_rust(page_index: int):+ return mwmbl_rank.read_index_page(fileno, METADATA_SIZE + page_index * PAGE_SIZE, PAGE_SIZE)++ # There is no raw mode for the extension: the read, the decompress and the parse+ # are one call with the GIL released, which is the whole point of it.+ readers = [(label, with_decode(read_page)) for label, read_page in readers] + [("rust", read_rust)]- for label, read_raw in (("mmap", read_mapped), ("pread", read_pread)):- read_page = with_decode(read_raw) if decode else read_raw+ for label, read_page in readers:# 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.diff --git a/test/test_indexer.py b/test/test_indexer.pyindex a2a9155..05e4c0f 100644--- a/test/test_indexer.py+++ b/test/test_indexer.py@@ -1,8 +1,9 @@+import jsonfrom pathlib import Pathfrom tempfile import TemporaryDirectoryimport pytest-from zstandard import ZstdCompressor+from zstandard import ZstdCompressor, ZstdDecompressorfrom mwmbl.tinysearchengine.indexer import (METADATA_SIZE,@@ -12,11 +13,9 @@ from mwmbl.tinysearchengine.indexer import (DocumentState,PageError,TinyIndex,- _binary_search_fitting_size,- _get_page_data,_pad_to_page_size,- _trim_items_to_page,)+from mwmbl_rank import pack_index_pagedef test_create_index():@@ -31,112 +30,53 @@ def test_create_index():assert page == []-def test_binary_search_fitting_size_all_fit():- items = [1, 2, 3, 4, 5, 6, 7, 8, 9]- compressor = ZstdCompressor()- page_size = 4096- count_fit, data = _binary_search_fitting_size(compressor, page_size, items, 0, len(items))-- # We should fit everything- assert count_fit == len(items)---def test_binary_search_fitting_size_subset_fit():- items = [1, 2, 3, 4, 5, 6, 7, 8, 9]- compressor = ZstdCompressor()- page_size = 15- count_fit, data = _binary_search_fitting_size(compressor, page_size, items, 0, len(items))-- # We should not fit everything- assert count_fit < len(items)+def _documents(count: int) -> list[tuple]:+ return [Document(title=f"text{i}", url=f"text{i}", extract=f"text{i}", score=i).as_tuple() for i in range(count)]-def test_binary_search_fitting_size_none_fit():- items = [1, 2, 3, 4, 5, 6, 7, 8, 9]- compressor = ZstdCompressor()- page_size = 5- count_fit, data = _binary_search_fitting_size(compressor, page_size, items, 0, len(items))+def test_pack_page_fits_everything_that_fits():+ items = _documents(10)- # We should not fit anything- assert count_fit == -1- assert data is None+ page, num_stored = pack_index_page(4096, items)+ assert num_stored == len(items)+ assert len(page) == 4096-def test_get_page_data_single_doc():- document1 = Document(title="title1", url="url1", extract="extract1", score=1.0)- items = [document1.as_tuple()]- compressor = ZstdCompressor()- page_size = 4096-- # Trim data- num_fitting, trimmed_data = _trim_items_to_page(compressor, 4096, items)-- # We should be able to fit the 1 item into a page- assert num_fitting == 1+def test_pack_page_drops_the_tail_that_does_not_fit():+ """A page holds a fixed number of bytes, so the count that comes back is what store()+ reports to its caller and has to be what was actually kept."""+ items = _documents(5000)- # Compare the trimmed data to the actual data we're persisting- # We need to pad the trimmmed data, then it should be equal to the data we persist- padded_trimmed_data = _pad_to_page_size(trimmed_data, page_size)- serialized_data, num_stored = _get_page_data(page_size, items)- assert serialized_data == padded_trimmed_data- assert num_stored == num_fitting+ page, num_stored = pack_index_page(4096, items)+ assert 1 < num_stored < len(items)+ assert json.loads(ZstdDecompressor().decompress(page)) == [list(item) for item in items[:num_stored]]-def test_get_page_data_many_docs_all_fit():- # Build giant documents item- documents = []- documents_len = 500- page_size = 4096- for x in range(documents_len):- txt = "text{}".format(x)- document = Document(title=txt, url=txt, extract=txt, score=x)- documents.append(document)- items = [document.as_tuple() for document in documents]-- # Trim the items- compressor = ZstdCompressor()- num_fitting, trimmed_data = _trim_items_to_page(compressor, page_size, items)- # We should be able to fit all items- assert num_fitting == documents_len+def test_pack_page_raises_when_nothing_fits():+ """Not even an empty page fits in five bytes. Returning a page that is too big would+ have it written over the start of the next one."""+ with pytest.raises(PageError):+ pack_index_page(5, _documents(9))- # Compare the trimmed data to the actual data we're persisting- # We need to pad the trimmed data, then it should be equal to the data we persist- serialized_data, num_stored = _get_page_data(page_size, items)- padded_trimmed_data = _pad_to_page_size(trimmed_data, page_size)- assert serialized_data == padded_trimmed_data- assert num_stored == num_fitting---def test_get_page_data_many_docs_subset_fit():- # Build giant documents item- documents = []- documents_len = 5000- page_size = 4096- for x in range(documents_len):- txt = "text{}".format(x)- document = Document(title=txt, url=txt, extract=txt, score=x)- documents.append(document)- items = [document.as_tuple() for document in documents]-- # Trim the items- compressor = ZstdCompressor()- num_fitting, trimmed_data = _trim_items_to_page(compressor, page_size, items)+def test_a_written_page_is_readable_by_python_zstandard():+ """The extension writes the pages, and an older container reading the same index maps+ it and decompresses with python-zstandard. The frames have to stay interchangeable."""+ 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")- # We should be able to fit a subset of the items onto the page- assert num_fitting > 1- assert num_fitting < documents_len+ with TinyIndex(Document, index_path, "w") as index:+ page_index = index.get_key_page_index("term")+ index.store_in_page(page_index, [document])- # Compare the trimmed data to the actual data we're persisting- # We need to pad the trimmed data, then it should be equal to the data we persist- serialized_data, num_stored = _get_page_data(page_size, items)- padded_trimmed_data = _pad_to_page_size(trimmed_data, page_size)+ with open(index_path, "rb") as index_file:+ page = index_file.read()[METADATA_SIZE + page_index * 4096 :][:4096]- assert serialized_data == padded_trimmed_data- # The count is what store() reports back, so it has to match what was actually kept.- assert num_stored == num_fitting+ assert json.loads(ZstdDecompressor().decompress(page)) == [list(document.as_tuple())]def test_constructing_document_removes_none():@@ -235,6 +175,45 @@ def test_a_write_through_another_handle_is_visible_without_reopening():assert [item.url for item in documents] == ["https://example.com"]+def test_a_page_claiming_more_than_it_could_hold_is_unreadable():+ """The decompressed size comes out of the page's own header, and the buffer for it is+ allocated before a byte is read. A page that says it holds megabytes is damage, and+ reading it would be the allocation that finishes off a worker already short of memory."""+ 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)+ # Compresses to a few hundred bytes, and its header says it is 4 MB.+ overlarge = ZstdCompressor().compress(b"a" * 4 * 1024 * 1024)+ with open(index_path, "r+b") as index_file:+ index_file.seek(METADATA_SIZE)+ index_file.write(_pad_to_page_size(overlarge, 4096))++ with TinyIndex(Document, index_path, "r") as index:+ with pytest.raises(PageError):+ index.get_page(0)+++def test_retrieve_keeps_only_the_documents_for_its_term():+ """Terms whose hashes collide share a page. The filtering happens in the extension, so+ the documents another term left there are never built into Document objects at all."""+ 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)+ wanted = Document("Wanted", "https://wanted.example.com", "Extract", 1.0, "term")+ other = Document("Other", "https://other.example.com", "Extract", 1.0, "another term")+ untermed = Document("Untermed", "https://untermed.example.com", "Extract", 1.0)++ with TinyIndex(Document, index_path, "w") as index:+ index.store_in_page(index.get_key_page_index("term"), [wanted, other, untermed])++ with TinyIndex(Document, index_path, "r") as index:+ retrieved = index.retrieve("term")+ whole_page = index.get_page(index.get_key_page_index("term"))++ assert [item.url for item in retrieved] == [wanted.url, untermed.url]+ assert [item.url for item in whole_page] == [wanted.url, other.url, untermed.url]++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. Silentlydecoding whatever came back would let a writer merge onto it and store the result."""