Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Contain an unreadable page to that page

Daoud Clarke1165e03451cd
diff --git a/mwmbl/count_urls.py b/mwmbl/count_urls.py
index abed08e..0705a01 100644
--- a/mwmbl/count_urls.py
+++ b/mwmbl/count_urls.py
@@ -10,7 +10,7 @@ from django.conf import settings
from pydistinct.stats_estimators import smoothed_jackknife_estimator
from redis import Redis
-from mwmbl.tinysearchengine.indexer import TinyIndex, Document
+from mwmbl.tinysearchengine.indexer import Document, PageError, TinyIndex
from mwmbl.utils import parse_url
INDEX_RESULT_COUNT_KEY = "index-result-count-{date}"
@@ -57,7 +57,14 @@ def count_urls():
domain_counts = Counter()
total_docs = 0
for i in page_sample:
- page = index.get_page(i)
+ try:
+ page = index.get_page(i)
+ except PageError:
+ # An unlocked read while the indexer is writing, so most of these are torn
+ # rather than damaged. Count the page as empty, as retrieve() does, rather
+ # than abandoning the sample.
+ logger.warning("Could not read index page %d while counting URLs", i)
+ continue
url_counts.update({doc.url for doc in page})
domains = [parse_url(doc.url).netloc for doc in page]
domain_counts.update(domains)
diff --git a/mwmbl/indexer/index_batches.py b/mwmbl/indexer/index_batches.py
index ca77843..2aaf142 100644
--- a/mwmbl/indexer/index_batches.py
+++ b/mwmbl/indexer/index_batches.py
@@ -16,7 +16,8 @@ from mwmbl.indexer.batch_cache import BatchCache
from mwmbl.indexer.blacklist_snapshot import get_snapshot_blacklist
from mwmbl.indexer.index import tokenize_document, prepare_url_for_tokenizing
from mwmbl.indexer.indexdb import BatchStatus
-from mwmbl.tinysearchengine.indexer import Document, TinyIndex, DocumentState, CURATED_STATES
+from mwmbl.tinysearchengine.indexer import (
+ CURATED_STATES, Document, DocumentState, PageError, TinyIndex)
from mwmbl.tinysearchengine.rank import score_result, DOCUMENT_FREQUENCIES, N_DOCUMENTS, HeuristicRanker
from mwmbl.tokenizer import tokenize, get_bigrams
from mwmbl.utils import add_term_infos, get_domain
@@ -115,11 +116,19 @@ def index_pages(index_path: str, page_documents: dict[int, list[Document]], mark
with TinyIndex(Document, index_path, 'w') as indexer:
ranker = HeuristicRanker(indexer, None, score_threshold=float('-inf'))
for page_index, documents in page_documents.items():
- with indexer.page(page_index) as page:
- combined_documents = combine_documents(page.documents, documents, mark_synced, ranker)
- num_stored = page.store(combined_documents)
- logger.info(f"Storing {num_stored} of {len(combined_documents)} documents for "
- f"page {page_index}, originally {len(page.documents)}")
+ try:
+ with indexer.page(page_index) as page:
+ combined_documents = combine_documents(page.documents, documents, mark_synced, ranker)
+ num_stored = page.store(combined_documents)
+ logger.info(f"Storing {num_stored} of {len(combined_documents)} documents for "
+ f"page {page_index}, originally {len(page.documents)}")
+ except PageError:
+ # One page we cannot safely write costs the documents bound for it, not the
+ # rest of the batch. Letting it propagate would abort every remaining page,
+ # and this runs inside POST /crawler/results and the batch indexer, where
+ # that means a 500 or a batch that is never marked done and retries forever.
+ logger.exception("Skipping index page %d", page_index)
+ continue
term_new_doc_counts.update(document.term for document in combined_documents[:num_stored]
if document.state != DocumentState.SYNCED_WITH_MAIN_INDEX)
@@ -174,7 +183,14 @@ def index_results_against_query(documents: list[Document], query: str, index_pat
term=term, last_crawled=doc.last_crawled,
))
if page not in existing_keys:
- existing_keys[page] = {(d.term, d.url) for d in indexer.get_page(page)}
+ try:
+ existing_keys[page] = {(d.term, d.url) for d in indexer.get_page(page)}
+ except PageError:
+ # An unlocked read, so most likely another writer mid-store. It only
+ # decides whether a URL counts as new; the write below takes the
+ # page's lock and reads it properly.
+ logger.warning("Could not read index page %d while counting new URLs", page)
+ existing_keys[page] = set()
if (term, doc.url) not in existing_keys[page]:
new_urls.add(doc.url)
diff --git a/mwmbl/indexer/purge_blacklisted.py b/mwmbl/indexer/purge_blacklisted.py
index e09b678..ea3b6bf 100644
--- a/mwmbl/indexer/purge_blacklisted.py
+++ b/mwmbl/indexer/purge_blacklisted.py
@@ -24,7 +24,7 @@ from logging import getLogger
from typing import Callable, Iterable, Optional
from mwmbl.indexer.index import tokenize_document
-from mwmbl.tinysearchengine.indexer import Document, TinyIndex
+from mwmbl.tinysearchengine.indexer import Document, PageError, TinyIndex
from mwmbl.utils import get_domain
logger = getLogger(__name__)
@@ -79,19 +79,29 @@ def purge_documents(index: TinyIndex, documents: Iterable[Document],
# pages, so counting each removal would report an order of magnitude too many.
removed_urls_by_domain: dict[str, set[str]] = defaultdict(set)
for page_index, urls in pages_to_urls.items():
- with index.page(page_index) as page:
- kept = [d for d in page.documents if d.url not in urls]
- if len(kept) == len(page.documents):
- # Nothing to remove here, so leave the page alone rather than rewriting it.
- continue
-
- for document in page.documents:
- if document.url in urls:
- try:
- removed_urls_by_domain[get_domain(document.url)].add(document.url)
- except ValueError:
- removed_urls_by_domain[document.url].add(document.url)
- page.store(kept)
+ try:
+ with index.page(page_index) as page:
+ kept = [d for d in page.documents if d.url not in urls]
+ if len(kept) == len(page.documents):
+ # Nothing to remove here, so leave the page alone rather than rewriting it.
+ continue
+
+ for document in page.documents:
+ if document.url in urls:
+ try:
+ removed_urls_by_domain[get_domain(document.url)].add(document.url)
+ except ValueError:
+ removed_urls_by_domain[document.url].add(document.url)
+ num_stored = page.store(kept)
+ if num_stored < len(kept):
+ logger.warning("Page %d only held %d of %d documents kept after purging",
+ page_index, num_stored, len(kept))
+ except PageError:
+ # The caller has already drained these documents out of the purge queue, so
+ # letting one unreadable page propagate would lose the whole batch - including
+ # every page that purged cleanly - and it would do so on every run.
+ logger.exception("Skipping index page %d while purging", page_index)
+ continue
removed_by_domain = {domain: len(urls) for domain, urls in removed_urls_by_domain.items()}
if removed_by_domain:
diff --git a/mwmbl/tinysearchengine/copy_index.py b/mwmbl/tinysearchengine/copy_index.py
index b8146c4..04f9ed3 100644
--- a/mwmbl/tinysearchengine/copy_index.py
+++ b/mwmbl/tinysearchengine/copy_index.py
@@ -5,7 +5,7 @@ from collections import defaultdict
from logging import getLogger
from mwmbl.indexer.index_batches import index_pages, get_url_score
-from mwmbl.tinysearchengine.indexer import TinyIndex, Document
+from mwmbl.tinysearchengine.indexer import Document, PageError, TinyIndex
from mwmbl.utils import add_term_infos
logger = getLogger(__name__)
@@ -25,7 +25,13 @@ def copy_pages(old_index_path: str, new_index_path: str, start_page: int, num_pa
if page_index >= old_index.num_pages:
break
- documents = old_index.get_page(page_index)
+ try:
+ documents = old_index.get_page(page_index)
+ except PageError:
+ # A whole-index scan meets every damaged page there is. Losing one
+ # page's documents is the cost of the copy finishing at all.
+ logger.warning("Skipping unreadable page %d of %s", page_index, old_index_path)
+ continue
documents_with_terms = add_term_infos(documents, old_index, page_index)
documents_with_scores = [Document(
document.title,
diff --git a/mwmbl/tinysearchengine/indexer.py b/mwmbl/tinysearchengine/indexer.py
index eedb150..1605885 100644
--- a/mwmbl/tinysearchengine/indexer.py
+++ b/mwmbl/tinysearchengine/indexer.py
@@ -7,6 +7,7 @@ from contextlib import contextmanager
from dataclasses import dataclass, asdict, field
from enum import IntEnum
from io import UnsupportedOperation
+from json import JSONDecodeError
from logging import getLogger
from mmap import mmap, PROT_READ, PROT_WRITE
from typing import TypeVar, Generic, Callable, List, Optional
@@ -34,6 +35,9 @@ logger = getLogger(__name__)
F_OFD_SETLKW = 38
# struct flock { short l_type; short l_whence; off_t l_start; off_t l_len; pid_t l_pid; }
# Padded to the native 32 bytes so nothing past our buffer is read. l_pid must be 0 for OFD.
+# The q's assume a 64-bit off_t, i.e. an LP64 build - true of every platform this runs on.
+# On a 32-bit build the buffer would be the wrong shape and fcntl would answer EINVAL,
+# which UNSUPPORTED_LOCK_ERRNOS reads as "this kernel cannot lock" and latches locking off.
_FLOCK_STRUCT = "hhqqi4x"
# Errnos that mean this kernel or filesystem cannot do the lock at all, as opposed to a
@@ -212,10 +216,27 @@ def _pad_to_page_size(data: bytes, page_size: int):
class _OpenPage(Generic[T]):
"""One page of the index, open for a read-modify-write. See TinyIndex.page."""
- def __init__(self, index: 'TinyIndex[T]', page_index: int):
+ def __init__(self, index: 'TinyIndex[T]', page_index: int, locked: bool):
self._index = index
self._page_index = page_index
- self.documents: List[T] = index.get_page(page_index)
+ self.reset = False
+ try:
+ 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
+ # progress, and merging onto an empty list would store over whatever it
+ # is writing. Refuse; the caller skips this page.
+ raise
+ # Holding the page's exclusive lock, no other writer that takes the lock can
+ # be part-way through it, so this is real damage - a bad block, or a write
+ # from before locking existed - rather than a torn read. Nothing else will
+ # ever repair it, because every reader treats it as empty and every writer
+ # would refuse it, so this write resets the page. That costs whatever was on
+ # it, which is already unreadable.
+ logger.error("Index page %d is corrupt; resetting it", page_index)
+ self.documents = []
+ self.reset = True
def store(self, values: List[T]) -> int:
"""Write these values to the page, returning how many of them actually fit.
@@ -325,7 +346,7 @@ class TinyIndex(Generic[T]):
logger.warning("Could not lock index page %d (%s); writing it unlocked",
i, e)
try:
- yield
+ yield locked
finally:
if locked:
try:
@@ -366,9 +387,13 @@ class TinyIndex(Generic[T]):
decompressor = ZstdDecompressor()
try:
decompressed_data = decompressor.decompress(page_data)
- except ZstdError as e:
- raise PageError(f"Could not decompress page {i}: {e}") from e
- return json.loads(decompressed_data.decode('utf8'))
+ 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.
+ raise PageError(f"Could not read page {i}: {e}") from e
def store_in_page(self, page_index: int, values: list[T]) -> int:
"""Overwrite a page, returning how many of `values` actually fit on it.
@@ -411,9 +436,16 @@ class TinyIndex(Generic[T]):
Not calling store() writes nothing, which is what a caller that finds nothing to
change should do.
+
+ Raises PageError if the page will not decode and the lock was not taken, since a
+ page that is merely being written by someone else looks exactly the same and must
+ not be merged onto. A caller looping over pages should catch that and skip the
+ page rather than abandon the rest of them. Holding the lock, an unreadable page is
+ real damage instead, and the block runs with `documents` empty and `reset` set -
+ see _OpenPage.
"""
- with self._locked_page(i):
- yield _OpenPage(self, i)
+ with self._locked_page(i) as locked:
+ yield _OpenPage(self, i, locked)
@staticmethod
def create(item_factory: Callable[..., T], index_path: str, num_pages: int, page_size: int):
diff --git a/mwmbl/views.py b/mwmbl/views.py
index b4e18dc..1cc295f 100644
--- a/mwmbl/views.py
+++ b/mwmbl/views.py
@@ -299,9 +299,13 @@ def _revert_curation(curation):
term = " ".join(tokenize(curation.query))
documents = [Document(**doc) for doc in curation.original_index_results]
- with indexer.page(indexer.get_key_page_index(term)) as page:
+ page_index = indexer.get_key_page_index(term)
+ with indexer.page(page_index) as page:
# Replace all existing documents for the term with the original documents
- page.store(documents + [doc for doc in page.documents if doc.term != term])
+ all_documents = documents + [doc for doc in page.documents if doc.term != term]
+ num_stored = page.store(all_documents)
+ logger.info(f"Reverted to {num_stored} of {len(all_documents)} documents "
+ f"at page {page_index}")
def _get_curation(request, query, documents, reranked_documents):
diff --git a/test/test_index_page_writes.py b/test/test_index_page_writes.py
index 8d81aa4..4f375d0 100644
--- a/test/test_index_page_writes.py
+++ b/test/test_index_page_writes.py
@@ -17,8 +17,10 @@ from tempfile import TemporaryDirectory
import pytest
-from mwmbl.indexer.index_batches import index_results_against_query
-from mwmbl.tinysearchengine.indexer import METADATA_SIZE, Document, DocumentState, TinyIndex
+from mwmbl.indexer.index_batches import index_pages, index_results_against_query
+from mwmbl.indexer.purge_blacklisted import purge_documents
+from mwmbl.tinysearchengine.indexer import (
+ METADATA_SIZE, Document, DocumentState, PageError, TinyIndex)
NUM_PAGES = 64
@@ -201,3 +203,113 @@ def test_concurrent_writers_leave_the_page_readable(index_path):
assert page, "the page was left empty"
assert all(document.title and document.url for document in page)
+
+
+# ---------------------------------------------------------------------------
+# A page that will not decode
+# ---------------------------------------------------------------------------
+
+def _doc(i: int, term: str) -> Document:
+ return Document(f"Title {i}", f"https://example.com/{i}", "extract", 1.0, term)
+
+
+def _corrupt(index_path: str, page_index: int):
+ """Damage a page that has real content on it.
+
+ It has to be written first: a freshly created page is a few bytes of compressed `[]`
+ followed by zero padding, so overwriting the padding with zeros changes nothing.
+ """
+ with TinyIndex(Document, index_path, 'w') as indexer:
+ indexer.store_in_page(page_index, [_doc(i, "seeded") for i in range(5)])
+
+ with open(index_path, "r+b") as index_file:
+ index_file.seek(METADATA_SIZE + page_index * 4096 + 16)
+ index_file.write(b"\0" * 64)
+
+ with TinyIndex(Document, index_path, 'r') as indexer:
+ with pytest.raises(PageError):
+ indexer.get_page(page_index)
+
+
+def test_one_unreadable_page_does_not_abandon_the_rest_of_the_batch(index_path):
+ """index_pages runs inside POST /crawler/results and the batch indexer.
+
+ Letting a single page propagate would 500 the submission, or leave a batch unmarked
+ and retried forever, and would skip every page after it in the same call.
+ """
+ _corrupt(index_path, 3)
+
+ counts = index_pages(index_path, {3: [_doc(1, "a")], 4: [_doc(2, "b")], 5: [_doc(3, "c")]})
+
+ with TinyIndex(Document, index_path, 'r') as indexer:
+ assert len(indexer.get_page(4)) == 1, "a later page was skipped"
+ assert len(indexer.get_page(5)) == 1, "a later page was skipped"
+ assert counts["b"] == 1 and counts["c"] == 1
+
+
+def test_a_corrupt_page_is_reset_by_a_writer_holding_its_lock(index_path):
+ """Holding the page's exclusive lock, no other locked writer can be mid-write on it,
+ so an unreadable page is real damage rather than a torn read - and nothing else will
+ ever repair it, since readers treat it as empty and writers refuse it."""
+ _corrupt(index_path, 3)
+
+ index_pages(index_path, {3: [_doc(1, "a")]})
+
+ with TinyIndex(Document, index_path, 'r') as indexer:
+ assert [d.url for d in indexer.get_page(3)] == ["https://example.com/1"]
+
+
+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.
+ 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"))
+
+ index_pages(index_path, {3: [_doc(1, "a")], 4: [_doc(2, "b")]})
+
+ with TinyIndex(Document, index_path, 'r') as indexer:
+ assert len(indexer.get_page(4)) == 1, "a later page was skipped"
+ with pytest.raises(PageError):
+ indexer.get_page(3) # left alone, not reset and not merged onto
+
+
+def test_purging_skips_a_page_it_cannot_read(index_path):
+ """purge_documents' caller has already drained these documents out of the purge queue,
+ so one propagating page would lose the whole batch on every run."""
+ blacklisted = Document("Spam", "https://spam.example.com/1", "extract", 1.0, None)
+ with TinyIndex(Document, index_path, 'w') as indexer:
+ pages = {indexer.get_key_page_index(term)
+ for term in ("spam", "extract", "spam example com")}
+ assert len(pages) > 1, "expected the document to be filed under several terms"
+
+ with TinyIndex(Document, index_path, 'w') as indexer:
+ for page_index in pages:
+ indexer.store_in_page(page_index, [blacklisted])
+ _corrupt(index_path, sorted(pages)[0])
+
+ with TinyIndex(Document, index_path, 'w') as indexer:
+ removed = purge_documents(indexer, [blacklisted], lambda domain: True)
+
+ assert removed == {"spam.example.com": 1}, "the readable pages were not purged"
+
+
+def test_damage_that_gets_past_zstd_still_degrades_to_no_results(index_path):
+ """retrieve() catches PageError and nothing else, so a page that decompresses into
+ something that is not JSON has to arrive as one too - or it 500s a search."""
+ from zstandard import ZstdCompressor
+
+ from mwmbl.tinysearchengine.indexer import _pad_to_page_size
+
+ with TinyIndex(Document, index_path, 'r') as indexer:
+ page_index = indexer.get_key_page_index("zebra")
+
+ payload = ZstdCompressor().compress(b"\xff\xfe definitely not json")
+ with open(index_path, "r+b") as index_file:
+ index_file.seek(METADATA_SIZE + page_index * 4096)
+ index_file.write(_pad_to_page_size(payload, 4096))
+
+ with TinyIndex(Document, index_path, 'r') as indexer:
+ with pytest.raises(PageError):
+ indexer.get_page(page_index)
+ assert indexer.retrieve("zebra") == []