An open source, non-profit web search engine
Make index page writes safe
Daoud Clarke4cba6a69c6a1
diff --git a/mwmbl/indexer/index_batches.py b/mwmbl/indexer/index_batches.pyindex db0bb76..ca77843 100644--- a/mwmbl/indexer/index_batches.py+++ b/mwmbl/indexer/index_batches.py@@ -114,13 +114,14 @@ def index_pages(index_path: str, page_documents: dict[int, list[Document]], markterm_new_doc_counts = Counter()with TinyIndex(Document, index_path, 'w') as indexer:ranker = HeuristicRanker(indexer, None, score_threshold=float('-inf'))- for page, documents in page_documents.items():- existing_documents = indexer.get_page(page)- combined_documents = combine_documents(existing_documents, documents, mark_synced, ranker)- logger.info(f"Storing {len(combined_documents)} documents for page {page}, originally {len(existing_documents)}")- indexer.store_in_page(page, combined_documents)-- term_new_doc_counts.update(document.term for document in combined_documents+ 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)}")++ term_new_doc_counts.update(document.term for document in combined_documents[:num_stored]if document.state != DocumentState.SYNCED_WITH_MAIN_INDEX)return term_new_doc_countsdiff --git a/mwmbl/indexer/purge_blacklisted.py b/mwmbl/indexer/purge_blacklisted.pyindex a66f19c..e09b678 100644--- a/mwmbl/indexer/purge_blacklisted.py+++ b/mwmbl/indexer/purge_blacklisted.py@@ -79,18 +79,19 @@ 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():- page = index.get_page(page_index)- kept = [d for d in page if d.url not in urls]- if len(kept) == len(page):- continue-- for document in page:- 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)- index.store_in_page(page_index, kept)+ 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)removed_by_domain = {domain: len(urls) for domain, urls in removed_urls_by_domain.items()}if removed_by_domain:diff --git a/mwmbl/tinysearchengine/indexer.py b/mwmbl/tinysearchengine/indexer.pyindex ee1d431..eedb150 100644--- a/mwmbl/tinysearchengine/indexer.py+++ b/mwmbl/tinysearchengine/indexer.py@@ -1,5 +1,9 @@+import errno+import fcntlimport jsonimport os+import struct+from contextlib import contextmanagerfrom dataclasses import dataclass, asdict, fieldfrom enum import IntEnumfrom io import UnsupportedOperation@@ -20,6 +24,34 @@ PAGE_SIZE = 4096logger = getLogger(__name__)+# Open File Description locks (Linux 3.15+). Byte-range like POSIX record locks, but owned+# by the open file description like flock - which is the property that matters here.+# Ordinary fcntl/lockf record locks are owned by the *process* and are dropped as soon as+# any fd on the file is closed, and index_results_against_query opens and closes a read+# handle on the index on every store, so in a threaded worker a plain lockf would be+# released out from under whoever held it. Verified: with lockf, closing an unrelated fd+# lets another process take the "held" lock; with OFD locks it does not.+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.+_FLOCK_STRUCT = "hhqqi4x"++# Errnos that mean this kernel or filesystem cannot do the lock at all, as opposed to a+# one-off failure to take it: an old kernel rejects the F_OFD_SETLKW command with EINVAL,+# and a filesystem with no record-lock support answers ENOLCK/ENOSYS/ENOTSUP. Only these+# latch locking off for the process - see _locked_page.+UNSUPPORTED_LOCK_ERRNOS = frozenset({errno.EINVAL, errno.ENOLCK, errno.ENOSYS,+ errno.ENOTSUP, errno.EOPNOTSUPP})++# Set False the first time locking turns out to be unsupported here - see _locked_page.+_page_locking_supported = True+++def _set_page_lock(fileno: int, lock_type: int, start: int, length: int):+ fcntl.fcntl(fileno, F_OFD_SETLKW,+ struct.pack(_FLOCK_STRUCT, lock_type, os.SEEK_SET, start, length, 0))++class DocumentState(IntEnum):"""The state of the document in the index. A value of None indicates an organic search result.@@ -159,12 +191,13 @@ def _trim_items_to_page(compressor: ZstdCompressor, page_size: int, items:list[Tdef _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)+ return _pad_to_page_size(compressed_data, page_size), num_fittingdef _pad_to_page_size(data: bytes, page_size: int):@@ -176,6 +209,24 @@ def _pad_to_page_size(data: bytes, page_size: int):return page_data+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):+ self._index = index+ self._page_index = page_index+ self.documents: List[T] = index.get_page(page_index)++ def store(self, values: List[T]) -> int:+ """Write these values to the page, returning how many of them actually fit.++ A page holds a fixed number of bytes and the tail that does not fit is dropped, so+ pass them best-first. It is store() rather than an assignment to `documents`+ precisely because what you pass is not necessarily what ends up stored.+ """+ return self._index.store_in_page(self._page_index, values)++class TinyIndex(Generic[T]):def __init__(self, item_factory: Callable[..., T], index_path, mode='r'):if mode not in {'r', 'w'}:@@ -213,13 +264,76 @@ class TinyIndex(Generic[T]):def retrieve(self, key: str) -> List[T]:index = self.get_key_page_index(key)logger.debug(f"Retrieving index {index}")- page = self.get_page(index)+ try:+ page = self.get_page(index)+ 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)return key_hash % self.num_pages+ @contextmanager+ def _locked_page(self, i: int):+ """Hold an exclusive lock on page i for a read-modify-write.++ 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+ 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+ the wiki index cache writes from the request path, on a large fraction of searches+ and from every gunicorn worker, that stops being hypothetical.++ Private: every read-modify-write on the index goes through page(), so no+ caller has to know this exists. Readers deliberately do not take it - search would+ pay a syscall per retrieve on the hot path, and a torn read costs a reader only one+ query's results for one term, which the next read fixes.++ If the lock cannot be taken, carry on without one. Every indexing path here - batch+ indexing, curation, POST /crawler/results, copy_index, purge - ran with no lock at+ all before this existed, so turning a failure to lock into a hard failure of all of+ them would be a much worse regression than the race it is guarding. An errno that+ means this environment does not support the lock at all latches+ _page_locking_supported off, so the warning is said once rather than per page;+ anything else is treated as a one-off and locking is tried again next time.+ """+ global _page_locking_supported+ if self.mode != 'w':+ raise UnsupportedOperation("The file is open in read mode, you cannot lock a page")++ start = i * self.page_size + METADATA_SIZE+ fileno = self.index_file.fileno()+ locked = False+ if _page_locking_supported:+ try:+ _set_page_lock(fileno, fcntl.F_WRLCK, start, self.page_size)+ locked = True+ except OSError as e:+ if e.errno in UNSUPPORTED_LOCK_ERRNOS:+ _page_locking_supported = False+ logger.warning(+ "Index page locking is not available here (%s); index writes will "+ "race as they did before it was added. Concurrent writers to one "+ "page can lose documents.", e)+ else:+ logger.warning("Could not lock index page %d (%s); writing it unlocked",+ i, e)+ try:+ yield+ finally:+ if locked:+ try:+ _set_page_lock(fileno, fcntl.F_UNLCK, start, self.page_size)+ except OSError:+ # 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]:"""Get the page at index i, decompress and deserialise it using JSON@@ -240,30 +354,66 @@ class TinyIndex(Generic[T]):return itemsdef _get_page_tuples(self, i):+ """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+ decompress is either corrupt or caught mid-write, and treating that as "no+ documents here" is how a writer comes to merge onto nothing and store its result+ 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]decompressor = ZstdDecompressor()try:decompressed_data = decompressor.decompress(page_data)except ZstdError as e:- logger.exception(f"Error decompressing page {i}: {e}")- return []+ raise PageError(f"Could not decompress page {i}: {e}") from ereturn json.loads(decompressed_data.decode('utf8'))- def store_in_page(self, page_index: int, values: list[T]):+ def store_in_page(self, page_index: int, values: list[T]) -> int:+ """Overwrite a page, returning how many of `values` actually fit on it.++ A page holds a fixed number of bytes and the tail that does not fit is dropped, so+ pass the values best-first. To change a page based on what it already holds, use+ page() instead, which does the read and the write under one lock."""value_tuples = [value.as_tuple() for value in values]- self._write_page(value_tuples, page_index)+ return self._write_page(value_tuples, page_index)- def _write_page(self, data, i: int):+ def _write_page(self, data, 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 rest.+ If the data is too big, it will store the first items in the list and discard the+ rest; the number actually stored is returned."""if self.mode != 'w':raise UnsupportedOperation("The file is open in read mode, you cannot write")- page_data = _get_page_data(self.page_size, data)+ 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+ return num_stored++ @contextmanager+ def page(self, i: int):+ """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+ 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.++ Locking lives here rather than in the callers because "hold a lock across your read+ and your write" is the kind of rule that gets quietly forgotten. There is one way to+ change a page and it is already correct::++ with index.page(page_index) as page:+ page.store(merge(page.documents))++ Not calling store() writes nothing, which is what a caller that finds nothing to+ change should do.+ """+ with self._locked_page(i):+ yield _OpenPage(self, i)@staticmethoddef create(item_factory: Callable[..., T], index_path: str, num_pages: int, page_size: int):@@ -274,7 +424,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, _ = _get_page_data(page_size, [])with open(index_path, 'wb') as index_file:index_file.write(metadata_padded)diff --git a/mwmbl/views.py b/mwmbl/views.pyindex 247819b..b4e18dc 100644--- a/mwmbl/views.py+++ b/mwmbl/views.py@@ -299,14 +299,9 @@ def _revert_curation(curation):term = " ".join(tokenize(curation.query))documents = [Document(**doc) for doc in curation.original_index_results]- page_index = indexer.get_key_page_index(term)- existing_documents = indexer.get_page(page_index)- other_term_documents = [doc for doc in existing_documents if doc.term != term]-- # Replace all existing documents for the term with the original documents- all_documents = documents + other_term_documents-- indexer.store_in_page(page_index, all_documents)+ with indexer.page(indexer.get_key_page_index(term)) 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])def _get_curation(request, query, documents, reranked_documents):@@ -392,21 +387,22 @@ def _save_to_index(query: str, new_results: list[Document]):]page_index = indexer.get_key_page_index(term)- existing_documents_no_terms = indexer.get_page(page_index)- existing_documents = add_term_infos(existing_documents_no_terms, indexer, page_index)- new_urls = {doc.url for doc in documents}- other_documents = [doc for doc in existing_documents if doc.url not in new_urls]- logger.info(f"Found {len(other_documents)} other documents for term {term} at page {page_index} "- f"with terms { {doc.term for doc in other_documents} }")-- # Update state for other documents- states = {doc.url: doc.state for doc in new_results}- for doc in other_documents:- doc.state = states.get(doc.url, doc.state)-- all_documents = documents + other_documents- logger.info(f"Storing {len(all_documents)} documents at page {page_index}")- indexer.store_in_page(page_index, all_documents)++ with indexer.page(page_index) as page:+ existing_documents = add_term_infos(page.documents, indexer, page_index)+ new_urls = {doc.url for doc in documents}+ other_documents = [doc for doc in existing_documents if doc.url not in new_urls]+ logger.info(f"Found {len(other_documents)} other documents for term {term} at page {page_index} "+ f"with terms { {doc.term for doc in other_documents} }")++ # Update state for other documents+ states = {doc.url: doc.state for doc in new_results}+ for doc in other_documents:+ doc.state = states.get(doc.url, doc.state)++ all_documents = documents + other_documents+ num_stored = page.store(all_documents)+ logger.info(f"Stored {num_stored} of {len(all_documents)} documents at page {page_index}")return {"curation": "ok"}diff --git a/test/test_index_page_writes.py b/test/test_index_page_writes.pynew file mode 100644index 0000000..8d81aa4--- /dev/null+++ b/test/test_index_page_writes.py@@ -0,0 +1,203 @@+"""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+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.+"""+import errno+import fcntl+import multiprocessing+import os+import random+import string+import struct+from io import UnsupportedOperation+from pathlib import Path+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+++NUM_PAGES = 64++# The non-blocking form of the lock the index takes, for a child that wants to find out+# whether a page is free rather than wait for it.+F_OFD_SETLK = 37+++def index_path():+ with TemporaryDirectory() as temp_dir:+ path = str(Path(temp_dir) / "temp-index.tinysearch")+ with TinyIndex.create(Document, path, num_pages=NUM_PAGES, page_size=4096):+ pass+ yield path+++def _try_lock_in_child(index_path: str, page: int, queue):+ """Child process: report whether the page lock is free."""+ from mwmbl.tinysearchengine.indexer import _FLOCK_STRUCT++ with TinyIndex(Document, index_path, 'w') as indexer:+ start = page * indexer.page_size + METADATA_SIZE+ try:+ fcntl.fcntl(indexer.index_file.fileno(), F_OFD_SETLK,+ struct.pack(_FLOCK_STRUCT, fcntl.F_WRLCK, os.SEEK_SET,+ start, indexer.page_size, 0))+ queue.put(True)+ except OSError:+ queue.put(False)+++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+ nothing.+ """+ context = multiprocessing.get_context("fork")+ with TinyIndex(Document, index_path, 'r') as indexer:+ target = indexer.get_key_page_index("zebra")++ def child_can_lock(page_index=target):+ queue = context.Queue()+ child = context.Process(target=_try_lock_in_child, args=(index_path, page_index, queue))+ child.start()+ child.join(timeout=30)+ return queue.get(timeout=5)++ with TinyIndex(Document, index_path, 'w') as indexer:+ with indexer.page(target) as page:+ assert not child_can_lock(), "another process took a lock we were holding"++ # An ordinary POSIX record lock is owned by the *process* and is dropped the+ # moment any fd on the file is closed - and index_results_against_query opens+ # and closes a read handle on every store, so in a threaded worker that would+ # silently release the lock mid-write. OFD locks survive it.+ with TinyIndex(Document, index_path, 'r'):+ pass+ assert not child_can_lock(), \+ "closing an unrelated fd released the lock - this needs an OFD lock"++ assert child_can_lock((target + 1) % NUM_PAGES), "a different page was blocked"+ assert page.documents == []++ assert child_can_lock(), "the lock was not released"+++def test_page_writes_nothing_unless_store_is_called(index_path):+ seeded = [Document("Zebra", "https://en.wikipedia.org/wiki/Zebra", "", 3.0, "zebra",+ state=DocumentState.FROM_WIKI)]+ with TinyIndex(Document, index_path, 'w') as indexer:+ target = indexer.get_key_page_index("zebra")+ indexer.store_in_page(target, seeded)++ with indexer.page(target) as page:+ assert [d.url for d in page.documents] == [seeded[0].url] # read, then do nothing++ with TinyIndex(Document, index_path, 'r') as indexer:+ assert [d.url for d in indexer.get_page(target)] == [seeded[0].url]+++def test_store_reports_how_many_documents_actually_fit(index_path):+ """A page drops the tail that does not fit, which is why this is store() and not an+ assignment to `documents` - what you pass is not necessarily what is kept."""+ # Distinct, incompressible extracts - zstd would squeeze 500 identical ones onto a+ # single page and there would be nothing to truncate.+ filler = random.Random(0)+ many = [Document(f"Zebra {i}", f"https://en.wikipedia.org/wiki/Zebra_{i}",+ "".join(filler.choices(string.ascii_letters, k=400)),+ 3.0, "zebra", state=DocumentState.FROM_WIKI)+ for i in range(500)]+ with TinyIndex(Document, index_path, 'w') as indexer:+ with indexer.page(indexer.get_key_page_index("zebra")) as page:+ num_stored = page.store(many)++ assert 0 < num_stored < len(many), f"expected truncation, stored {num_stored}"++ with TinyIndex(Document, index_path, 'r') as indexer:+ assert len(indexer.get_page(indexer.get_key_page_index("zebra"))) == num_stored+++def test_page_needs_write_mode(index_path):+ with TinyIndex(Document, index_path, 'r') as indexer:+ with pytest.raises(UnsupportedOperation):+ with indexer.page(0):+ pass+++def _fail_to_lock(monkeypatch, err: OSError):+ from mwmbl.tinysearchengine import indexer as indexer_module++ monkeypatch.setattr(indexer_module, "_page_locking_supported", True)+ monkeypatch.setattr(indexer_module, "_set_page_lock",+ lambda *args: (_ for _ in ()).throw(err))+ return indexer_module+++def _store_one(index_path: str) -> Document:+ document = Document("Zebra", "https://en.wikipedia.org/wiki/Zebra", "", 3.0, None)+ assert index_results_against_query([document], "zebra", index_path) == 1++ with TinyIndex(Document, index_path, 'r') as indexer:+ assert {d.url for d in indexer.retrieve("zebra")} == {document.url}+ return document+++def test_writes_continue_when_page_locking_is_unsupported(index_path, monkeypatch):+ """A filesystem without record locks must not break indexing.++ Every path through index_pages ran with no lock at all before this existed, so an+ environment that cannot lock should degrade to that, not fail.+ """+ indexer_module = _fail_to_lock(monkeypatch, OSError(errno.ENOLCK, "no locks available"))++ _store_one(index_path)++ assert indexer_module._page_locking_supported is False+++def test_a_one_off_lock_failure_does_not_disable_locking(index_path, monkeypatch):+ """Only an errno meaning "this environment cannot lock" latches locking off.++ Anything else - a deadlock detection, an interrupted call - is a one-off. Latching on+ it would silently drop the lock for the rest of the process's life on a blip.+ """+ indexer_module = _fail_to_lock(monkeypatch, OSError(errno.EDEADLK, "resource deadlock"))++ _store_one(index_path)++ assert indexer_module._page_locking_supported is True+++def _store_repeatedly(index_path: str, term: str, url_prefix: str, count: int):+ """Child-process worker: store documents under `term`, over and over."""+ for i in range(count):+ # The title has to contain the term, or the containment rule stores nothing.+ index_results_against_query(+ [Document(f"Zebra {url_prefix} {i}", f"https://example.com/{url_prefix}/{i}", "",+ 3.0, None)],+ term, index_path)+++def test_concurrent_writers_leave_the_page_readable(index_path):+ """Smoke test: four processes hammering one page leave it decodable, not empty."""+ context = multiprocessing.get_context("fork")+ workers = [context.Process(target=_store_repeatedly,+ args=(index_path, "zebra", f"w{n}", 30))+ for n in range(4)]+ for worker in workers:+ worker.start()+ for worker in workers:+ worker.join(timeout=60)+ assert worker.exitcode == 0++ with TinyIndex(Document, index_path, 'r') as indexer:+ page = indexer.get_page(indexer.get_key_page_index("zebra"))++ assert page, "the page was left empty"+ assert all(document.title and document.url for document in page)diff --git a/test/test_indexer.py b/test/test_indexer.pyindex a409568..ad85626 100644--- a/test/test_indexer.py+++ b/test/test_indexer.py@@ -63,8 +63,9 @@ def test_get_page_data_single_doc():# 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 persistpadded_trimmed_data = _pad_to_page_size(trimmed_data, page_size)- serialized_data = _get_page_data(page_size, items)+ serialized_data, num_stored = _get_page_data(page_size, items)assert serialized_data == padded_trimmed_data+ assert num_stored == num_fittingdef test_get_page_data_many_docs_all_fit():@@ -87,10 +88,11 @@ def test_get_page_data_many_docs_all_fit():# 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 = _get_page_data(page_size, items)+ 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_fittingdef test_get_page_data_many_docs_subset_fit():@@ -114,10 +116,12 @@ def test_get_page_data_many_docs_subset_fit():# 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 = _get_page_data(page_size, items)+ 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+ # The count is what store() reports back, so it has to match what was actually kept.+ assert num_stored == num_fittingdef test_constructing_document_removes_none():