An open source, non-profit web search engine
Address review: clean text on the way in, and contain the failures
Daoud Clarkee3f73df5d42c
diff --git a/mwmbl/indexer/external_cache.py b/mwmbl/indexer/external_cache.pyindex 8ead0cd..8af54b4 100644--- a/mwmbl/indexer/external_cache.py+++ b/mwmbl/indexer/external_cache.py@@ -40,6 +40,7 @@ from typing import Optionalfrom django.conf import settingsfrom mwmbl.tinysearchengine.indexer import Document, DocumentSource, TinyIndex+from mwmbl.tokenizer import clean_unicodelogger = getLogger(__name__)@@ -292,11 +293,13 @@ def _entries_to_store(source: DocumentSource, term: str, documents: list[Documen)]+ # The providers' own text, cleaned: it arrives as JSON from outside, and a title or an+ # extract holding a character that cannot be stored would cost the whole cache page.return [Document(- title=document.title,+ title=clean_unicode(document.title),url=document.url,- extract=document.extract,+ extract=clean_unicode(document.extract),score=float(rank),term=term,state=document.state,diff --git a/mwmbl/indexer/index_batches.py b/mwmbl/indexer/index_batches.pyindex 6f4eaa6..cc1d1a2 100644--- a/mwmbl/indexer/index_batches.py+++ b/mwmbl/indexer/index_batches.py@@ -15,7 +15,14 @@ from mwmbl.indexer.batch_cache import BatchCachefrom mwmbl.indexer.blacklist_snapshot import get_snapshot_blacklistfrom mwmbl.indexer.index import prepare_url_for_tokenizing, tokenize_documentfrom mwmbl.indexer.indexdb import BatchStatus-from mwmbl.tinysearchengine.indexer import CURATED_STATES, Document, DocumentState, PageError, TinyIndex+from mwmbl.tinysearchengine.indexer import (+ CURATED_STATES,+ Document,+ DocumentState,+ PageError,+ TinyIndex,+ cleaned_document,+)from mwmbl.tinysearchengine.rank import HeuristicRankerfrom mwmbl.tokenizer import get_bigrams, tokenizefrom mwmbl.utils import get_domain@@ -83,7 +90,12 @@ def index_documents(documents, index_path):tens of megabytes and hold ~156 MB of domain strings for the process's life - seeblacklist_snapshot."""documents = filter_blacklisted_documents(documents)- page_documents = preprocess_documents(documents, index_path)+ # Cleaned here rather than at each of the paths above, for the same reason the+ # blacklist is: every one of them takes its text from somewhere outside, and a title or+ # an extract holding a character that cannot be stored costs the whole page it would be+ # written to - a page that is shared with documents from everywhere else.+ cleaned_documents = [cleaned_document(document) for document in documents]+ page_documents = preprocess_documents(cleaned_documents, index_path)new_page_doc_counts = index_pages(index_path, page_documents)end_time = datetime.now(timezone.utc)return end_time, new_page_doc_counts@@ -175,17 +187,19 @@ def index_results_against_query(documents: list[Document], query: str, index_patif not (doc.url and doc.title):continuedoc_tokens = _document_token_set(doc)+ # This path does not go through index_documents, so it cleans its own text.+ cleaned = cleaned_document(doc)for term, words in query_terms.items():if not (words <= doc_tokens):continuepage = indexer.get_key_page_index(term)page_documents[page].append(Document(- doc.title,- doc.url,- doc.extract,+ cleaned.title,+ cleaned.url,+ cleaned.extract,term=term,- last_crawled=doc.last_crawled,+ last_crawled=cleaned.last_crawled,))if page not in existing_keys:diff --git a/mwmbl/tinysearchengine/indexer.py b/mwmbl/tinysearchengine/indexer.pyindex e3aa19e..07fea42 100644--- a/mwmbl/tinysearchengine/indexer.py+++ b/mwmbl/tinysearchengine/indexer.py@@ -4,7 +4,7 @@ import jsonimport osimport structfrom contextlib import contextmanager-from dataclasses import asdict, dataclass, field+from dataclasses import asdict, dataclass, field, replacefrom enum import IntEnumfrom io import UnsupportedOperationfrom logging import getLogger@@ -12,6 +12,8 @@ from typing import Callable, Generic, List, Optional, TypeVarimport mmh3+from mwmbl.tokenizer import clean_unicode+# 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@@ -153,6 +155,21 @@ class Document:return tuple(values)+def cleaned_document(document: Document) -> Document:+ """The document with text that cannot be stored on a page taken out of it.++ A lone surrogate is the case that turns up: a title or an extract that a UTF-16 client+ truncated in the middle of an astral character, which arrives as a \\udXXX escape that+ json.loads accepts and no UTF-8 encoder will write. It has to go before the document+ reaches a page, or it costs the whole page the document would be stored on.++ clean_unicode is what tokenize already does to the same text, so the terms a document+ is indexed under do not change - only the text stored alongside them, which until now+ kept a character the reader could not render anyway.+ """+ return replace(document, title=clean_unicode(document.title), extract=clean_unicode(document.extract))++@dataclassclass TokenizedDocument(Document):tokens: List[str] = field(default_factory=list)@@ -273,9 +290,12 @@ class TinyIndex(Generic[T]):# 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:+ except (PageError, OSError):# 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.+ # read of it will very likely succeed. OSError as well as PageError: the read+ # is a syscall, and a device that failed on one page should cost a query that+ # page rather than answer the whole search with a 500. Writers do not swallow+ # either.logger.exception("Could not read index page %d", index)return []@@ -379,6 +399,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."""+ if not 0 <= i < self.num_pages:+ # Left to the extension, a negative page index is an OverflowError converting+ # the offset and one past the end is a short read; both are this, and callers+ # only handle PageError.+ raise PageError(f"Page {i} is not in an index of {self.num_pages} pages")offset = i * self.page_size + METADATA_SIZEtry:return read_index_page(self.index_file.fileno(), offset, self.page_size, term)diff --git a/mwmbl_rank/src/index.rs b/mwmbl_rank/src/index.rsindex a007258..1cc5354 100644--- a/mwmbl_rank/src/index.rs+++ b/mwmbl_rank/src/index.rs@@ -66,19 +66,24 @@ fn borrow_file(fd: i32) -> ManuallyDrop<File> {ManuallyDrop::new(unsafe { File::from_raw_fd(fd) })}+/// A read that came up short is a page that is not there rather than a failed syscall: a+/// positioned read stops at the end of the file, so it 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.+fn read_error(error: std::io::Error) -> PageIoError {+ if error.kind() == std::io::ErrorKind::UnexpectedEof {+ return PageIoError::Unreadable(format!("could not read a whole page: {error}"));+ }+ PageIoError::Io(error)+}+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}"- )));- }+ // read_exact_at rather than read_at: it reads until it has the whole page, and it+ // retries a read the kernel interrupted with a signal, which is what os.pread does+ // since PEP 475 and what a bare read_at does not.+ file.read_exact_at(&mut page, offset).map_err(read_error)?;Ok(page)}@@ -244,6 +249,22 @@ fn py_to_value(object: &Bound<'_, PyAny>) -> PyResult<Value> {)))}+/// The items to store, as JSON values.+///+/// Anything that will not convert is a PageError rather than the TypeError or ValueError it+/// arrives as: a score that has come out NaN, a string holding an unpaired surrogate, a+/// type with no JSON form. json.dumps wrote all three without complaint, so they can reach+/// here, and a caller that catches PageError loses the one page it could not write. Letting+/// the raw exception out instead would abort the whole run - see index_pages, which catches+/// PageError for exactly that reason.+fn py_items_to_values(items: &Bound<'_, PyList>) -> PyResult<Vec<Value>> {+ items+ .iter()+ .map(|item| py_to_value(&item))+ .collect::<PyResult<Vec<Value>>>()+ .map_err(|e| PageError::new_err(format!("Cannot store these documents on a page: {e}")))+}+fn compress_prefix(serialised: &[String], count: usize) -> Result<Vec<u8>, PageIoError> {let mut json = String::from("[");for (position, item) in serialised[..count].iter().enumerate() {@@ -330,22 +351,16 @@ pub fn write_index_page(page_size: usize,items: &Bound<'_, PyList>,) -> PyResult<usize> {- let values: Vec<Value> = items- .iter()- .map(|item| py_to_value(&item))- .collect::<PyResult<_>>()?;+ let values = py_items_to_values(items)?;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()- )));- }+ // write_all_at rather than write_at: a short write would leave the page half old+ // and half new, which is the torn page every reader and writer here is guarding+ // against, so it writes the rest rather than reporting it - and, like the read, it+ // retries a write a signal interrupted. What is left is a real failure of the+ // device, which is an OSError as it has always been.+ file.write_all_at(&page, offset).map_err(PageIoError::Io)?;Ok(num_stored)})?;Ok(num_stored)@@ -359,10 +374,7 @@ pub fn pack_index_page(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 values = py_items_to_values(items)?;let (page, num_stored) = py.allow_threads(|| pack_page(page_size, &values))?;Ok((PyBytes::new_bound(py, &page).unbind(), num_stored))}diff --git a/scripts/benchmark_index_reads.py b/scripts/benchmark_index_reads.pyindex 2e64ec5..d55019c 100644--- a/scripts/benchmark_index_reads.py+++ b/scripts/benchmark_index_reads.py@@ -69,7 +69,10 @@ def report_memory(label: str):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:+ # Exclusive: this file is created, sized and then deleted, so it must be this run's own.+ # The flag is one letter from `reads --index-path`, and an index passed here by mistake+ # would be truncated to nothing and then removed.+ with open(path, "xb") 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")@@ -198,7 +201,11 @@ def main():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(+ "--sparse-file",+ default="/tmp/benchmark-index-sparse",+ help="the sparse file to create for the measurement, which must not exist and is deleted afterwards",+ )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")@@ -213,7 +220,7 @@ def main():args = parser.parse_args()if args.measurement == "pagetables":- measure_page_tables(args.path, args.num_pages)+ measure_page_tables(args.sparse_file, args.num_pages)else:measure_reads(args.index_path, args.num_reads, args.num_threads, args.decode)diff --git a/test/test_external_cache.py b/test/test_external_cache.pyindex eaca04a..4e2dbea 100644--- a/test/test_external_cache.py+++ b/test/test_external_cache.py@@ -144,6 +144,17 @@ def test_results_come_back_from_the_index(cache_index):assert all(document.state == DocumentState.FROM_WIKI for document in cached)+def test_a_providers_text_is_cleaned_before_it_is_stored(cache_index):+ """The providers answer with JSON from outside, and a lone surrogate in it cannot be+ stored on a page - it would cost the whole cache page rather than the one entry."""+ broken = Document(title="Monty \ud83d", url="https://example.com/monty", extract="half \ud83d")++ store_external_results(DocumentSource.WIKIPEDIA, "python", [broken])++ cached = get_cached_external_results(DocumentSource.WIKIPEDIA, "python")+ assert [(document.title, document.extract) for document in cached] == [("Monty ", "half ")]++def test_the_providers_order_is_what_comes_back(cache_index):"""The cache stores the rank the provider gave, not the score it was handed. Storingthe score would make an entry mean different things to callers asking for differentdiff --git a/test/test_index_batches.py b/test/test_index_batches.pyindex 79dce14..8a4784e 100644--- a/test/test_index_batches.py+++ b/test/test_index_batches.py@@ -272,3 +272,37 @@ def test_index_documents_keeps_everything_when_nothing_blacklisted(index_path):index_documents(documents, index_path)assert "https://example.com/y" in _all_urls(index_path)+++def test_index_documents_cleans_text_that_cannot_be_stored(index_path):+ """A UTF-16 client that truncates a title mid-emoji sends half of one, which arrives as+ a lone surrogate. Stored on a page it would cost the whole page, so it is dropped at the+ choke point and the document is indexed like any other."""+ documents = [+ Document(title="Half an emoji \ud83d", url="https://example.com/y", extract="also half \udc00"),+ Document(title="Whole", url="https://example.com/z", extract="a good page"),+ ]++ with patch(PATCH_TARGET, return_value=snapshot_blacklist(set())):+ index_documents(documents, index_path)++ stored = []+ with TinyIndex(item_factory=Document, index_path=index_path, mode="r") as index:+ for page_index in range(10):+ stored += [document for document in index.get_page(page_index) if document.url.endswith("/y")]++ assert stored, "the document was not indexed"+ assert {(document.title, document.extract) for document in stored} == {("Half an emoji ", "also half ")}+ assert "https://example.com/z" in _all_urls(index_path), "the rest of the page was lost"+++def test_index_results_against_query_cleans_text_that_cannot_be_stored(index_path):+ """It builds its own documents rather than going through index_documents, so it has to+ clean them itself or lose the page."""+ document = Document(title="Rust \ud83d", url="https://example.com/rust", extract="async \ud83d")++ assert index_results_against_query([document], "rust", index_path) == 1++ with TinyIndex(item_factory=Document, index_path=index_path, mode="r") as index:+ stored = index.retrieve("rust")+ assert [d.title for d in stored] == ["Rust "]diff --git a/test/test_index_page_writes.py b/test/test_index_page_writes.pyindex 9749783..d5e9651 100644--- a/test/test_index_page_writes.py+++ b/test/test_index_page_writes.py@@ -317,3 +317,50 @@ def test_damage_that_gets_past_zstd_still_degrades_to_no_results(index_path):with pytest.raises(PageError):indexer.get_page(page_index)assert indexer.retrieve("zebra") == []+++ "document",+ [+ pytest.param(Document("Title", "https://example.com", "extract", float("nan"), "a"), id="nan-score"),+ pytest.param(Document("Title \ud800", "https://example.com", "extract", 1.0, "a"), id="lone-surrogate"),+ ],+)+def test_a_document_that_cannot_be_written_costs_its_page_and_no_more(index_path, document):+ """json.dumps wrote both of these - NaN as a bare word no other reader accepts, and an+ unpaired surrogate as an escape - so either can reach a write today. They are refused+ now, and the refusal has to be a PageError: index_pages catches that and skips the one+ page, where anything else aborts the run and 500s POST /crawler/results."""+ with TinyIndex(Document, index_path, "w") as indexer:+ with pytest.raises(PageError):+ indexer.store_in_page(3, [document])++ counts = index_pages(index_path, {3: [document], 4: [_doc(2, "b")]})++ with TinyIndex(Document, index_path, "r") as indexer:+ assert indexer.get_page(3) == [], "the page was written with a document it cannot hold"+ assert len(indexer.get_page(4)) == 1, "a later page was skipped"+ assert counts["b"] == 1+++def test_a_page_outside_the_index_is_a_page_error(index_path):+ """The offset is arithmetic on the page number, so a negative one overflows converting+ it and one past the end reads nothing. Callers only handle PageError."""+ with TinyIndex(Document, index_path, "r") as indexer:+ with pytest.raises(PageError):+ indexer.get_page(NUM_PAGES)+ with pytest.raises(PageError):+ indexer.get_page(-1)+++def test_a_failed_read_degrades_to_no_results(index_path, monkeypatch):+ """A read is a syscall now, so a device that fails on one page raises OSError where it+ used to raise nothing at all. It costs a query that page's term, like an unreadable+ page does, rather than 500ing the whole search."""++ def fail(*args, **kwargs):+ raise OSError(errno.EIO, "Input/output error")++ with TinyIndex(Document, index_path, "r") as indexer:+ monkeypatch.setattr("mwmbl.tinysearchengine.indexer.read_index_page", fail)+ assert indexer.retrieve("zebra") == []diff --git a/test/test_indexer.py b/test/test_indexer.pyindex 05e4c0f..2abdbae 100644--- a/test/test_indexer.py+++ b/test/test_indexer.py@@ -182,8 +182,9 @@ def test_a_page_claiming_more_than_it_could_hold_is_unreadable():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)+ # Compresses to a few hundred bytes, and its header says it is 4 MiB and a byte -+ # one past the 1024 pages' worth that a page is allowed to claim.+ overlarge = ZstdCompressor().compress(b"a" * (4 * 1024 * 1024 + 1))with open(index_path, "r+b") as index_file:index_file.seek(METADATA_SIZE)index_file.write(_pad_to_page_size(overlarge, 4096))