Skip to content

Keyword search on kept statistics, and the attestation ledger indexed by output hash - #93

Merged
ascalva merged 29 commits into
mainfrom
perf/keyword-and-ledger
Nov 14, 2026
Merged

ascalva merged 29 commits into
mainfrom
perf/keyword-and-ledger

Conversation

@ascalva

@ascalva ascalva commented Nov 12, 2026 •

Copy link
Copy Markdown
Owner

This is the first change of a stress-testing programme that uses the corpus instance (400,274
items, 1,369,944 lexical units, 117,975,818 postings, 387,838 attestations) as its load. It takes
the two reads that were furthest past budget there, a keyword query and the attestation ledger's
producer lookup, and removes their cost without changing an answer: every answer of the battery
before the change is the answer after it, bit for bit. The price is on the landing, 7 to 11% a
batch. It ships the battery that measured it (eval/stress_battery.py), the record
(docs/experiments/keyword-and-ledger-2026-11-11.md) and the article
(papers/2026-11-11-keyword-and-ledger/).

Abstract

A knowledge store answers keyword queries from a BM25 index kept in SQLite and links every
attestation of its append-only ledger to the attestations that produced its inputs. On the corpus
instance a title query under the class filter the store always applies took a warm median of
14.4 s and up to 34.1 s, the store's own query shape (a class and 400 paths) 5.41 s, and the
producers of one digest 2.43 s, a lookup an item landed on its own asks three times. Neither cost
is in the data: with no planner statistics SQLite counted each query term's document frequency by
visiting every unit, and the ledger was decoded record by record in Python. The statistics are
now kept instead of counted: per class, the current units and their total length, and per class
and term the current units holding the term, moved in the transaction of every write that changes
which units are current, so a reader's statistics remain the sums of its cleared classes' rows
and a filtered read remains a function of the cleared rows alone. Scoring is one statement that
starts from the query terms' postings or from the given paths' units and writes the sum over the
terms out in their order, since SQLite's own sum() compensates its rounding: the scores are the
old statements' to the last bit. The ledger gains a table from each output hash to its record and
action, written by a trigger in the append's own statement. On the same clone the warm medians
become 1.20 s, 5.9 ms and 8 µs, items landed one at a time go from 7.6 s to 0.16 s an item, a
batch of 2,000 items lands 7 to 11% slower, and every answer compared is identical to the one
before. Property tests check the identity, the statistics against a recount after any sequence of
writes, the clearance rule, and the ledger table against a scan.

What changes

  • core/stores/lexical.py
    • class_stats(provenance, units, tokens) and term_stats(term, provenance, df), moved by the
      net currency changes of each transaction (land, land_many, retire, reset), once a
      batch, a version's deleted units leaving them before their postings go; statistics() gives
      a reader's sums.
    • A store from before them counts them on its first open, in one transaction (one pass over the
      postings a class, in key order); a stale store (another tokenizer's units) is counted by its
      reset instead. The count takes the file's write lock without waiting: a process that opens
      the store while another holds it (counting, or writing) opens at once and, until the
      statistics are counted, counts each query's statistics from the units as every query did
      before (the same integers, so the same scores); a later open or query counts them once the
      lock is free, in that call (two minutes on the corpus). A writer waits for the lock as any
      write does. A count that fails for any other reason (a file the process cannot write, a full
      disk, an I/O error) is rolled back, and the store answers the same way until it is opened
      again: no SQLite error of the count reaches an open or a query, and only the lock is tried
      again by a later query. The counting transaction creates the two tables, so opening an old
      store writes nothing unless it counts.
    • Once counted, three triggers refuse a write to the units from outside the store's own
      transactions (which hold a key in meta while they run), so an older process cannot leave
      the statistics wrong without a sign. Every write begins inside its try, so a failure of its
      first statements rolls the transaction back.
    • search and scores are one statement: postings first (CROSS JOIN), or the paths' units
      first (INDEXED BY units_path), the per-posting weight as core/ingest/lexical.py computes it,
      the sum written out in the sorted terms' order with filtered aggregates, the top k and ties by
      unit id in SQL. A query of more than 500 distinct terms (past SQLite's expression depth) has
      the same weights summed in Python in the same order.
  • core/attestation/store.py: output_hashes(hash, att_id, action, pos), keyed by hash, record
    and position, filled from the records by a migration on first open and kept by an AFTER INSERT
    trigger; producers_of and producers_by_output read it by seeks and only read. The migration
    takes the write lock without waiting, and not inside a transaction already open on the
    connection; a migration that fails for another reason (a ledger this process cannot write, a
    full disk) is rolled back and waits for the next open. Until the table exists the lookups
    answer from one pass over the records, the hashes given as one JSON array.
  • core/ingest/landing.py: attested_by (and so already_attested) reads the producers by output
    where the store has that lookup; a store without it (a test's scan-only stand-in) is asked the
    old way. No caller changes; nothing of core/ingest/writer.py or the other files of A read-only guest principal: the grant, its MCP surface, and the leaks it closed #89 and A palace without vectors: lexical code ingestion for a coding agent #90
    is touched.
  • eval/stress_battery.py: the battery, on cp -c clones of an instance's stores. It prepares a
    source of its own first (the lexical index and the ledger opened once by the code under test,
    the migration timed), so every part of every code starts on files the cache has not read; load
    averages, warm (each pass's wall and processor time) and fresh-process timings, resident memory,
    a memory watchdog, answers kept as digests (no query text or item content in the record). The
    landing ends with a batch that replaces the versions of the batch before it, and the statistics'
    upkeep is timed on its own; a concurrent part opens an old lexical file in two processes at
    once. The three places it does not run are named in the record with their reasons.
  • Tests: tests/fixtures/lexical_reference.py keeps the old statements as the reference;
    tests/property/test_lexical_statistics.py (bit identity, both sum paths, ties, the control
    that sum() is not the reference sum, recount after any sequence including batched landings
    that land a path more than once, the clearance rule), tests/property/test_ledger_outputs.py
    (table equals a scan, the four lookups against the scan and the replaced statement, the
    migration of an old ledger, other writers, a dying append, a ledger opened while another
    connection holds its lock, a ledger this process cannot write, a full one),
    tests/unit/test_lexical_index.py (migration, stale store, the guard, a transaction that dies
    after its unit rows, a process killed there for a landing and for a retire, a store opened while
    another connection holds its lock, one whose count fails on a read-only file and on a full one,
    a write whose writer key fails, the runbook's revert step, and a store of the change left
    running through it), tests/unit/test_stress_battery.py (clones only, no text in the record,
    the thread cap).
  • Docs: the experiment record (md and json), a note in dn-two-phase-ingestion §7.1, the ledger
    row, §5.3 and names for the moved lines in dn-temporal-snapshot, the runbook's step for
    reverting the change and the processes to end before it, the article, the README's test count.

Measurements, before and after

Clones of the corpus instance's data at stage 1: run 4 on main at f969904, run 5 on the branch at
b61c0ca0 (the later commits change code only on a path no run took, a migration that fails for a
reason other than the lock), the same command, each part of each code starting on a clone of a
prepared source the cache has not read. Apple M2 Pro, 12 cores, 32 GB, shared with
other work; BLAS at four threads; every process ends itself above 3.8 GB resident; Python 3.15.2,
SQLite 3.54.1; the corpus's lexical file opened with LEGACY's tokenizer, which made it.

measure (warm medians of five passes; range over queries) before after load (1 min), before / after
title query, class filter, 16 queries 14.4 s (1.49-34.1 s) 1.20 s (0.08 ms-6.17 s) 3.0-5.6 / 2.7-3.8
title query, no filter, 16 queries 9.58 s (0.97-23.3 s) 1.16 s (0.07 ms-5.78 s) 2.2-5.0 / 2.7-3.7
scores, class + 400 paths, 5 queries 5.41 s (1.19-15.1 s) 5.9 ms (1.9-12.4 ms) 2.2-3.0 / 2.8
search, class + 400 paths, 5 queries 5.39 s (1.20-15.0 s) 4.7 ms (1.8-11.5 ms) 1.9-2.6 / 2.8
fresh process, 14-term title, class filter 24.0-24.2 s, 469 MB 4.03-4.04 s, 73 MB 2.5-3.1 / 2.7-2.8
fresh process, 14-term title, scores with paths 15.0-15.1 s 14.1-14.3 ms 2.5-3.0 / 3.0
producers_of, one digest 2.43 s 8.2 µs 1.9-2.7 / 2.9
attested_by through the landing 2.42 s 8.1 µs 2.6-3.4 / 2.9
producers_by_output, 2,050 digests 292 ms 6.4 ms (first call 295 ms) 3.1 / 2.9
landing 2,000 new items, batches 1-2, 3 processes 10.45 s (9.41-11.50) 11.13 s (9.75-12.15) 2.3-2.9 / 2.7-3.8
its upkeep (LexicalStore._keep) 0.39 s (0.30-0.53)
landing 2,000 replacing versions, 3 processes 9.88 s (8.95-10.19) 10.93 s (10.81-11.61) 2.1-2.8 / 3.3-3.8
its upkeep 0.76 s (0.74-0.85)
three items landed one at a time 22.8 s 0.48 s 2.3 / 3.9
derive.pending (control, untouched) 2.19 s 2.22 s 2.1-2.3 / 3.6-3.8
migration on first open: statistics / ledger table 126.0 s, +29.6 MB / 2.68 s, +64.4 MB after: 2.0 / 3.0
a second process, 5 s into the first's open: its query 16.7 s (nothing to count; file cold) 1.37 s (opened at once) 2.3-2.5 / 3.7-3.8

Answers: the 65 the battery keeps (top tens with scores, path scores, producer sets and lists),
the 18 fresh processes' answers and the concurrent part's are identical before and after, scores
compared as the bits of their doubles; all five runs, the three earlier ones too, gave the same
65. Of the before run's warm passes, ten under the class filter took up to 1.75 times their
processor time at loads of 3.1 to 5.6, so the medians of L20 and L23 there (26.1 s and 32.3 s)
carry waits (their processor times' medians are 18.9 s and 26.8 s); no pass of the after run
waited.

Gates

  • uv run ruff check .: all checks passed.
  • uv run python scripts/check_imports.py: the core firewall and the worker boundary OK.
  • uv run mypy core agents eval ops scheduler scripts: no issues in 370 files; uv run mypy:
    67 errors, the tests/ baseline exactly.
  • uv run python -m ops.type_gate: exit 0 (the pre-existing non-fatal finding-0223 line only).
  • The deterministic tier as CI runs it (-m 'not live and not podman and not needs_vault and not needs_restic' --deselect tests/unit/test_core_self_containment.py::test_core_imports_nothing_outside_core --cov):
    3,662 passed, 11 skipped, 21 deselected, exit 0 (3 min 50 s, one-minute load 2.9 at its start
    and 2.4 at its end); line and branch coverage 77%, as before. The README's tests badge and
    count say 3,662.
  • The same tier on a trial rebase onto main at 0a5fba2 (without coverage): 3,680 passed, 11
    skipped, 21 deselected.
  • On the head rebased onto ab67880, after the landing log (The temporal snapshot, stage SN-1: the landing log, and the two forms of removal #92) merged: this pull request's
    store tests, the stress battery's tests, the lite palace's tests and the landing log's property
    tests pass (90 tests). CI on the pushed head runs the rest.
  • The six property tests at 1,000 examples each (a copy of the two files with max_examples
    raised, not committed): passed, 49.5 s (load 2.9 to 3.5).
  • scripts/build_papers.sh papers/2026-11-11-keyword-and-ledger: built, 9 pages, no undefined
    reference, no overfull or underfull box.
  • formal/: unchanged (and docs/LAWS.md unchanged, so formal/check.sh was not needed).

Notes

  • Bit identity needs the sum written out. SQLite 3.54.1's sum() and total() compensate
    their rounding (Kahan-Babuska-Neumaier): over 1, 2^-53, 2^-53 in order they give 1 + 2^-52 where
    the store's loop gives 1. That, with the order SQLite adds a unit's terms in, is why the
    statistics-in-SQL candidate of an earlier, unpublished study of the stores matched the store's
    scores on 7 of its 26 queries. The statement writes the sum out in the sorted terms' order, each
    missing term adding 0.0 (exact for a positive double), with max(c) FILTER (WHERE i = j) per
    term. An interleaved comparison on one clone (14 queries, five rounds, the order alternating,
    load 2.7-4.3) measured it 17 to 28% faster than the same sum with CASE on the titles of seven
    terms or more, 16 to 25% on those of three to five and 8 to 9% on two, with identical answers.
    Its cost against a compensated sum() was not measured.

  • The paths shape needed its index named. Without planner statistics SQLite drove it from
    units_current (current, provenance), every current unit of the class for each path given.

  • SQLite's expression depth (1,000) refuses a written-out sum of about 1,000 terms; above 500
    distinct terms the weights are read out of the statement in order and summed in Python.

  • The replaced producers_by_output left a transaction open. Filling its temporary table, in
    the ledger connection's legacy transaction mode, began a transaction that kept a shared lock on
    the ledger file (rollback-journal mode) after the call returned, so another connection's write
    failed until the ledger's connection next committed. The new lookups only read.

  • Duplicates in output_hashes. Attestation.create sorts the hashes but keeps repeats; the
    side table keys on the element's position, so producers_by_output still lists a record once a
    time it names a hash, and attested_by lists each id once, as before.

  • Upkeep by triggers was measured and rejected. On a scratch store of 100,000 synthetic units
    (a scratch script, not committed; one run each, load 2.7-2.9), a batch of 7,044 units took 52%
    longer with a trigger on the currency and 162% longer with one on each posting as well, against
    8% for the batched upkeep. Only the guard is a trigger on the units.

  • The migrations do not wait for the lock. The first version counted the lexical statistics in
    the constructor under BEGIN IMMEDIATE, so every other process that opened the store during the
    count (two minutes on the corpus) waited out the 30 s busy timeout and failed, readers included;
    the ledger's migration ran the same way under Python's 5 s default (2.6 s on the corpus, so other
    openers waited there rather than failed), and a ledger the process could not write no longer
    opened. Each migration now tries the write lock without waiting. A reader
    opens at once and answers from the units (the lexical index) or from one pass over the records
    (the ledger) until the migration is done, with the same answers; a writer waits for the lock as
    any write does and fails past the store's timeout. On the corpus a second process that opened
    the lexical file 5 s into another's count opened in 0.47 ms and answered its query in 1.37 s,
    the keyword part's answer. That repair at first caught only the lock and a read-only file: any
    other failure of a migration, a full disk (SQLITE_FULL) or an I/O error, made the open and every
    query or lookup raise, where main's reader answers. Every failure is now rolled back and the
    store answers as above; only the lock is tried again by a later query, and any other failure
    waits for the next open, so a file that cannot take the count (two minutes on the corpus) is not
    read through again at every query. A lexical file this process cannot write, or a full one
    (SQLite's page limit at the file's size), opens and answers as the old statements do, and so
    does a full ledger; the full files' tests fail on the earlier repair (which raised), and the
    read-only file's on its trying the count again at every query. As on main, a lexical file in a
    read-only directory does not open (WAL mode needs its shared-memory file).

  • The battery and the landing log. eval/stress_battery.py opens the catalog of a clone and
    lands through the writer. Since The temporal snapshot, stage SN-1: the landing log, and the two forms of removal #92, the first open of a catalog that has rows and no landing log
    writes the log's genesis, and a landing that appends to the log needs the instance's
    landing-log-key. In the suite the fixture sets a test value, and the battery's child processes
    inherit it. A hand run on a clone of the corpus instance now needs that item, a test value, in
    its environment.

  • A failed migration is silent. After a failure other than the lock (a full disk that is
    later freed, for instance), a long-lived process such as the daemon keeps answering from the
    units or the records, at the speed from before this change, until it is restarted, and nothing
    is logged. The answers are right; an operator cannot tell that the kept statistics or the
    ledger's table are missing. The second review left this open as a note.

  • The guard is a behaviour change, and one way until it is dropped. Once a store's statistics
    are counted, a process running the code from before this change (for instance a runner in an
    older worktree) gets an error on its first write to the units instead of desynchronizing them.
    A revert of this change therefore needs a step once it is deployed and no process of the change
    is left, now in the runbook (Deploy):

    sqlite3 <data dir>/lexical.sqlite "DROP TRIGGER IF EXISTS units_kept_insert;
      DROP TRIGGER IF EXISTS units_kept_update; DROP TRIGGER IF EXISTS units_kept_delete;
      DELETE FROM meta WHERE key = 'statistics';"

    The reverted code reads neither class_stats nor term_stats; deleting the record makes the
    change, if it lands again, count them anew. The change counts them again, and installs the
    triggers, whenever an open or a query finds the record gone, and a process keeps the code it
    started with, while the deploy restarts only the daemon: an MCP server, a query or a runner of
    the change still running undoes the step at its next query, and the reverted code's writes
    raise again (a test shows it). So the runbook says to end, before the step, every process that
    opens the stores and started before the deploy or runs from a checkout that still holds the
    change, how to find the ones holding the file open (lsof, ps), and how to check, after the
    step and again later, that the triggers stay dropped. A test runs the step's statements against
    the old landing. A stale store (another tokenizer's units) is not counted on open and keeps no
    guard until its reset. The ledger's table needs nothing: its trigger keeps it on every append,
    whoever appends.

  • Migration costs differ from the unpublished study's: the statistics took 114.5 to 126.0 s on
    clones the cache had not read (eight opens, one-minute loads 1.96 to 4.86; the study's build,
    130.5 s), one pass over the postings a class in key order with no sort; the ledger's table 1.8
    to 2.7 s (seven opens, loads 2.65 to 4.86; the study's 0.52 to 0.93 s), a WITHOUT ROWID table
    keyed by hash, record and position, filled in record order with its trigger in the same
    transaction; it takes 166 B a record (the study's 213 to 227 B for a rowid table and an index).

  • The landing's price. A batch of 2,000 new items takes 11.13 s against 10.45 s at the median
    (7%), a batch replacing 2,000 versions 10.93 s against 9.88 s (11%), at a one-minute load 0.5 to
    1 higher. The upkeep, timed on its own, is 0.39 s and 0.76 s of it (3.1 to 4.8% and 6.9 to 7.3%
    of the batch); the trigger's rows add 28 to 43 µs an append; the ledger's batch lookup saves 0.2
    to 0.5 s; the rest of the lexical stage's rise is not attributed (the upkeep's timer does not
    cover the commit that writes the pages it changed). The first version called a batched landing
    unchanged within its spread: its after run landed on files the migration had just read, timed no
    upkeep and replaced no versions.

  • Free queries stay linear in their postings, under 1 µs a posting (6.17 s for the 6.5 million
    of the longest title). Posting arrays in segments are the next step; a free query's memory in a
    fresh process fell from 469 MB to 73 MB with the dictionary of every scored unit.

  • The corpus holds one class, so its readers sum one row; the property tests hold four, and each
    of the six properties passed 1,000 examples in a longer run (60 or 80 in the suite). The
    corpus's lexical file is LEGACY's, so it was measured under LEGACY; under the current tokenizer
    the store refuses it until it is re-derived, as main does.

  • Not run, each named in the record with its reason: the whole-stratum load of a sentence admitting
    the dialogue stratum (tens of GB on the whole corpus), the test that a commit's cut holds a
    citation edge (the corpus has no citation store) and the pending mask of a sentence's nodes
    (nothing is pending on the corpus).

  • Earlier runs. The first version of this pull request rested on three runs of an earlier
    battery (three passes, no processor time, no prepared source). Its before figures for search
    with paths (8.43 s) and the class-filtered L3 (5.69 s) did not reproduce: in main's code
    search and scores with paths are the same computation, and run 4 gives 5.39 s and 2.92 s with
    every pass of those queries within 2% of its median. Its landing ran on files the migration had
    just read and did not time the upkeep; its figure for the filtered aggregate (6 to 27%) traced to
    no record; some of its load ranges mixed the five- and fifteen-minute fields into the one-minute
    figure; it compared the control's first call with a 7.2 s the stage-1 record does not hold; and
    it said the landings reached no line changed between its runs 2 and 3, when the ledger's lookups
    had stopped sorting the hashes they are asked for (0.24 ms for 2,050; no answer can change). The
    record lists each, and the JSON keeps those runs under earlier_runs.

Merge order

#90, #92 and #89 have merged (main is 8d4dff3), and this pull request is rebased onto it. In
content it is independent of #89: the only file both change is README.md, where this one changes
only the tests badge and the sentence with the test count. Every commit but the README's replays
without a conflict, the landing log's edits to docs/design-notes/dn-temporal-snapshot.md and
docs/runbook.md included: this one's edits to that note (the ledger's rows, section 5.3 and the
names of the store lines it moved) apply over #92's text as they are. The count is set by
arithmetic: main's 3,721 plus the 29 tests this pull request adds, 3,750. The instance lifecycle
and the cut algebra, not yet opened, may merge first; whichever merges later is rebased.

One test of #89's needed a change on this base: the guest's noninterference test wrapped
LexicalStore._score_units to record the classes of every lexical score, and this pull request
scores through _ranked instead, so the wrapper now wraps _ranked with the same assertions.

Main's code, #90's with it, reaches the lexical store through land, land_many, retire and
holds_current (the writer, core/ingest/writer.py), land_many, reset, stale,
landed_versions and empty_versions (the backfill and the drain, core/ingest/derive.py),
search and scores (a near text's lexical seeds and the pending nodes' lexical scores,
core/sentence/universe.py, scores and one of the two search calls with a class and a list
of paths) and count (the MCP server's status, agents/ambassador/mcp.py); its tests also reach
units_of and recorded_tokenizer. They keep their signatures and answers; retire and reset
now also move the kept statistics in their own transaction, and the class #90 adds (code) is
kept like any other. Nothing in #90 writes the lexical tables or reads the ledger's tables
directly.

🤖 Generated with Claude Code

ascalva and others added 28 commits November 13, 2026 19:18
LexicalStore.search counted every query term's document frequency by
visiting all current units, and the class filter turned the row
statement the same way; on the corpus instance (1.37 million units) a
title query took 13.6 s warm, 40 s for long titles. The statistics are
now kept, not counted: per class the current units and their total
length (class_stats), per class and term the units holding the term
(term_stats), moved in the transaction of every write that changes
which units are current (land, land_many, retire, reset), from the
units whose currency changed, once a batch. A reader's statistics are
its cleared classes' rows summed, so a filtered read stays a function
of the cleared rows alone.

The rows are read from the query terms' postings, or from the given
paths' units, and the arithmetic, the sum over the terms and the top k
are one statement. SQLite's sum() compensates its rounding, so the sum
is written out in the sorted terms' order; the scores are the old
statements' to the bit (property-tested against the old statements,
kept in tests/fixtures/lexical_reference.py).

A store from before the statistics counts them on its first open, in
one transaction; a stale store (another tokenizer's units) is counted
by its reset instead. Once counted, triggers refuse a write to the
units from outside this class's transactions, so a process of the old
code cannot leave the statistics wrong without a sign.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
producers_of decoded every record in Python (2.4 s a call at 387,838
records) and an item landed effect by effect asked it three times. A
side table holds one row for each element of each record's
output_hashes with the record's id and action, keyed by the hash, and
producers_of, producers_by_output, and attested_by and
already_attested through core/ingest/landing.py read it by seeks.

A trigger on the ledger writes the rows, so every append writes them
in its own statement and transaction, whatever process appends, and a
rolled-back append leaves none. A ledger written before the table gets
it on its first open, filled from the records in one transaction. The
lookups only read, so no transaction or lock outlives a call (the old
producers_by_output left one open through its temporary table).

Property-tested: the table equals a scan of the ledger after any
sequence of appends, and the four lookups answer what the scan and the
replaced json_each statement answer, before and after the migration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
eval/stress_battery.py runs a fixed battery against clones of an
instance's stores (cp -c, never the source): keyword queries free and
in the palace's call shape (a class and a list of paths), warm and a
fresh process each; ledger lookups one at a time and in a batch; a
landing of 2,000 synthetic items through the writer, batched and
lazy, and three effect by effect; the drain's pending set. Every
timing carries the load average, every process caps BLAS at four
threads and ends itself past a resident-memory cap. Query texts and
item content stay out of the record; answers go beside it as digests
so two runs compare bit for bit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With no planner statistics, SQLite drove the path shape from the
class's index (units_current) and visited every current unit of the
class for each path given; the statement now names units_path, so a
path's units are a seek.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The lookups sorted the hashes to batch them, which raises on a set
that mixes types; the old scan took any set. The batches need no order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A term's weight now enters the written-out sum as max(c) FILTER (WHERE
i = j) rather than max(CASE WHEN i = j THEN c END): a row no longer
calls every term's aggregate, so the corpus's long titles take less
time for the same doubles. SQLite parses a + b + ... as a tree as deep
as its terms and refuses one deeper than 1,000, so a query of more
than 500 distinct terms has the same weights read out of the
statement in the terms' order and summed in Python; the old statements
took any length, and the law is tested on both paths.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A small instance run through the battery's keyword, ledger and stratum
parts: the source's files are as they were, every shape answers the
same on every pass, and no title or text reaches the record. The
battery's arguments are parsed apart from its guard, and its ledger
draws no more digests than the ledger holds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The stress battery on clones of the corpus instance, main against the
branch: title queries under the class filter 14.2 s to 1.20 s warm
median, the store's own call shape (a class and 400 paths) 5.5 s to
5.5 ms, the producers of a digest 2.47 s to 7 us, a batch's 304 ms to
5.9 ms, three items landed one at a time 23.1 s to 0.082 s; the
batched landing unchanged within its spread, the drain's pending set
(untouched) the same, and every answer identical bit for bit. The
migrations cost 115 to 122 s and 29.6 MB for the lexical statistics,
1.8 to 2.7 s and 64.4 MB for the ledger's table, once a store.

The two design notes that described the statistics as counted at
query time and the producer lookup as a decode of every record now
say what the store does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The article for the change: why the two reads were slow on the corpus
instance (each term's document frequency counted by visiting every
unit, the ledger decoded record by record), the kept statistics and
the proofs that they are a recount after every committed transaction
and a reader's cleared classes' own, why the sum is written out
(IEEE addition of 0.0 is exact; SQLite's sum() compensates), the
statement, the guard and the ledger's table, and the measurements
before and after. Every reference was looked up on Crossref or
OpenAlex; where the registry's volume and pages disagree with the
usual citation they are left out and the DOI given.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The deterministic tier is 3,652 passed (11 skipped, 21 deselected) with
the kept statistics', the ledger table's and the stress battery's
tests. Coverage stays 77%.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The two tests of a transaction that dies between the unit rows and the
statistics replaced _keep for every call, so a landing died at its
version's own call, before any unit row of the batch was written. The
dying _keep now lets those calls through and dies at the batch's own,
after recording what the transaction holds then: b.md's unit written
and a.md's new version current for the landing, a.md's units no longer
current for the retire. The process-ending test does the same for a
retire as well as a landing.

The recount, identity and clearance properties gain a batched step:
one land_many of several versions with paths and digests drawn again,
so a unit's currency moves more than once before the batch's
statistics move, which is the path Writer.land_batch takes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The first open of a store from before the kept statistics counted them
under BEGIN IMMEDIATE, two minutes on the corpus, and every other
process that opened the store meanwhile tried the same count, waited
out the 30 s busy timeout and failed, readers included, where the code
before this change opened and searched.

The count now tries the write lock without waiting (busy timeout 0 for
its BEGIN). When another connection holds it, or the file cannot be
written, the store opens at once and counts a query's statistics from
the units, as every query did before they were kept: the same integers,
so the same scores. A later open or query counts them once the lock is
free; a write still waits for the lock as any write does. The
statistics' tables are created by the counting transaction, so opening
an old store writes nothing unless it counts.

_begin ran BEGIN IMMEDIATE and the writer key's insert before the
callers' try, so a failed insert left the transaction open, holding the
write lock. Every write now begins inside its try, and the rollback
ends a transaction only when one is open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The output-hash table's migration ran in the constructor under Python's
default 5 s timeout, so a ledger this process could not write (a
read-only copy) no longer opened at all, and a ledger whose migration
took longer than the timeout would fail every other opener, where the
code before opened and read either.

The migration now tries the write lock without waiting and, inside a
transaction already open on the connection (a deferred block), not at
all. Until the table exists the lookups answer from one pass of SQLite's
JSON functions over the records, the hashes given as one JSON array, so
no temporary table and no transaction: the answers the table gives. A
later lookup or open makes the table once it can.

The property test's copy of the replaced statement says what it changed
(its temporary table's name, and a commit the original lacked) instead
of calling itself verbatim.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The battery now prepares a source of its own before its parts: clones
of the stores, the lexical index and the ledger opened once by the code
under test, so a store from before a change is migrated there, once,
timed with the load beside it. Every part clones the prepared files
again, so each part of each code starts from files the cache has not
read; before, the code that migrated read the whole lexical file at
each part's first open and ran the part on a warm file.

The landing lands three batches of new items and then the third
batch's paths again with other bytes, which replaces every unit that
batch made current, and times the lexical index's upkeep of its
statistics (LexicalStore._keep) where the code has one; it checks the
kept class statistics against a count after the batches. A concurrent
part opens a lexical index from before the change in one process and,
seconds later, in a second that asks one query. Each warm pass keeps
its processor time beside its wall time.

The record names the two other places the scaling study found past
budget as not run, with the reason: the cut test needs a citation
store, the pending mask something pending. The thread cap now lowers a
larger count already set, and the docstring says the study is
unpublished and cites the public stage-1 record for the stratum's
memory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Once an instance's lexical statistics are counted, the units' three
guard triggers refuse every write from code that does not keep them, so
a revert deployed alone makes the reverted code's landings, retires and
resets raise. The runbook's deploy section now gives the step: after
the revert is deployed (not before, or the running code counts them
again and installs the triggers with them), drop the triggers and the
record that the statistics are counted. A test runs those statements
on a store, lands with the code from before the change, and opens it
with the change again, which counts the statistics anew.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
dn-temporal-snapshot pointed at lines of core/stores/lexical.py,
core/attestation/store.py and core/ingest/landing.py that this change
moved: the ledger's DDL and its ORDER BY, the lexical DDL, the currency
updates, retire, reset, the statistics and the landing's attestation
check. They are named now (`_DDL`, `AttestationStore.all`,
`attest_once`, `LexicalStore._land_one`, `retire`, `reset`,
`statistics`, `attested_by`, `attested_batch`), as section 5.3 already
was, and 5.3 no longer says the statistics are computed from the mask
"as they are today", which the same section says they are not.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The fixture's SQL is the old store's, word for word, but its code is
written as functions of a connection, and its scores() reads a unit's
path one at a time where the store read four hundred at once. It now
says so instead of calling the whole of it verbatim.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The record now rests on two runs of the battery as it stands (run 4 on
main at f969904, run 5 on the branch at b61c0ca0): a prepared source,
so each part of each code starts on files the cache has not read; five
warm passes with their processor time; a batch that replaces versions,
with the statistics' upkeep timed on its own; and a reader opening the
lexical file while another process migrates it. It adds an interleaved
comparison of the filtered aggregate against the CASE form it replaced.

What the new runs change in the text: the landing is slower after the
change (7% a batch of new items, 11% a replacing batch, at a higher
load), the upkeep 0.39 s and 0.76 s of it and the rest not attributed;
the before figures of search with paths (5.39 s, not 8.43 s) and of
the class-filtered L3 (2.92 s, not 5.69 s); the filtered aggregate is
17 to 28% faster on the titles of seven terms or more, a figure the
first version gave without a record; every load range is the
one-minute field.

The three earlier runs stay, in the JSON and in a section that lists
what did not hold: the figures above, the landing's warm files, the
sentence that the landings reached no changed line, the control's
first call, the ledger's three passes, the mixed load fields, and the
7.2 s set beside a record that does not hold it. All five runs gave the
same 65 answers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The evaluation now rests on runs 4 and 5: a prepared source, so each
part starts on files the cache has not read; five warm passes with their
processor time; a batch that replaces versions, with the upkeep timed;
and a reader opening the lexical file during another process's count.
The table, the results and the abstract carry their figures, among them
the landing's price (7 to 11% a batch, the upkeep 0.39 s and 0.76 s of
it, the rest not attributed), the waits in the before run's slowest
passes, and the filtered aggregate's 17 to 28% on the titles of seven
terms or more from an interleaved comparison, in place of a figure no
run recorded.

The implementation section says the count and the ledger's migration do
not wait for the lock and what a reader does meanwhile. It also
corrects four sentences: the output-hash table is keyed by hash, record
and position; the old lookup path serves a store without the lookup by
output, not a ledger without the table; the guard costs a primary-key
lookup in meta a unit written, changed or deleted; and the compensated
sum's case is the remark in section 3. The fresh-process sentence gives
the class-filtered query (24 s to 4.0 s, 469 MB to 73 MB) and the paths
shape (15 s to 14 ms) apart, and the tests paragraph the longer runs of
the properties (1,000 examples each).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The deterministic tier as CI runs it passes 3,658 tests on this branch
(11 skipped, 21 deselected): six more than the badge said, the tests
added for the migrations that do not wait (a lexical index and a ledger
opened while another connection holds the lock, and a ledger this
process cannot write), the writer key's failure, the revert step and
the battery's thread cap. The crash test killed by the process ending
was renamed, now that it kills a retire as well as a landing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The article gave the count of the lexical statistics as 115 to 126 s,
which rounds the measured 114.5 s up; it now gives 114.5 to 126.0 s.
The record gives the earlier migrations' one-minute loads to two
places (2.38 to 4.86 and 2.65 to 4.86) rather than rounded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A store opened while another process held its lock counts its
statistics at the first open or query that finds the lock free, inside
that call: on the corpus the two minutes of the count. The record's
section on a reader during the migration and the article's
implementation paragraph now say so, beside the reader that answers
from the units meanwhile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The count of the statistics is a write that the open and a reader's query make, where the code
before it wrote nothing at open. It caught only another connection's lock and a read-only file:
any other failure, a full disk (SQLITE_FULL) or an I/O error, propagated from the constructor and
from every query of a store not yet counted, so a reader that main's code serves raised instead.

Every sqlite3.Error of the count is now rolled back and leaves the store as it was; the store
answers from its units, as every query did before the statistics were kept. Only the lock is
tried again by a later query. Any other failure is not tried again until the store is opened
again, so a file that cannot take the count is not read through again at every query. Writes
(landing, retire, reset) raise as before.

The test opens a store from before the statistics as a read-only file and as a full one
(SQLite's page limit at the file's size), checks every answer against the old statements, that
no query begins the count again and that a landing fails, then counts at the next open. It
fails on the previous code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The ledger's migration (the output-hash table, its rows and its trigger) is a write that the open
and a lookup make, where the code before it wrote nothing at open. It caught only another
connection's lock and a read-only file: any other failure, a full disk (SQLITE_FULL) or an I/O
error, propagated from the constructor and from every lookup of a ledger without the table.

Every sqlite3.Error of the migration is now rolled back, and the lookups answer from one pass
over the records until the table exists. Only the lock is tried again by a later lookup; any
other failure waits for the next open. Appends raise as before.

The test opens a ledger the old code wrote as a full file (SQLite's page limit at the file's
size): the lookups answer what the scan and the replaced statement answer, none begins the
migration again, an append fails, and the next open makes the table. It fails on the previous
code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The step that drops the guard's triggers and the statistics' record said only to wait for the
deploy of the revert. The deploy restarts the daemon and no other process, and a process keeps the
code it started with: an MCP server, a query or a runner of the change still running counts the
statistics again at its next open or query, installs the triggers with them, and the reverted
code's landings, retires and resets raise again.

The step now waits until no process of the change is left (those started before the deploy, and
any run from a checkout or worktree that still holds the change), names them, says how to find
the ones holding the file open (lsof, ps), and gives a check that the triggers stay dropped, to
run after the step and again later, with what to do when it finds them back.

A test shows the hazard: a store of the change left open while the step runs counts the
statistics again at its next query, from the units as the reverted code left them, installs the
triggers, and the old landing is refused. The step's statements and its check are shared with the
step's existing test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The record said the branch's commits after run 5 change no code; they now change one path no run
took, a migration that fails for a reason other than another connection's lock, and the record
says so, and says what that path did at the measured commit (a full file made the open and every
query raise) and does now. The article's implementation paragraphs say what a failed count and a
failed ledger migration do, its tests paragraph adds the full and read-only files and the store
of the change that reinstalls the guard after the revert step, and its limits say the step waits
until no process of the change is left. The article builds to 9 pages, with no undefined reference
and no overfull or underfull box.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The four tests this round adds (a store whose count fails on a read-only file and on a full one,
a ledger whose migration fails on a full file, a store of the change left running through the
revert step) take the deterministic tier from 3,658 to 3,662 passed (11 skipped, 21 deselected),
as CI runs it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The docstrings of the two migrations said they never fail the open or a query. What the code
holds is narrower: no SQLite error of the count or of the ledger's migration reaches them (an
interrupt still does). The ledger tests' law 4 also names the full file the new test opens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ascalva
ascalva force-pushed the perf/keyword-and-ledger branch from 47194c1 to 8257a33 Compare November 14, 2026 00:19
…res now

The guest's noninterference test recorded the classes of every lexical
score by wrapping LexicalStore._score_units. This pull request scores in
one statement through _ranked, which search and scores both call, so the
wrapper moves there with its arguments; what it records and asserts is
unchanged. On main with the guest merged, CI failed on the missing
attribute (pytest) and on one mypy error over the tests' baseline of 67.
The guest's and the lexical index's tests pass (39), and mypy is at 67.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant