Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
cfc414d
perf(lexical): keep per-class statistics and score in one statement
ascalva Nov 12, 2026
8d3789b
perf(attestation): index the ledger by output hash
ascalva Nov 12, 2026
907286f
feat(eval): a stress battery for the stores on a copy-on-write clone
ascalva Nov 12, 2026
a630708
perf(lexical): read the paths' units by their own index
ascalva Nov 12, 2026
9ab5b21
fix(attestation): take the hashes asked for as they come
ascalva Nov 12, 2026
99b2486
perf(lexical): sum with filtered aggregates, past SQLite's depth outside
ascalva Nov 12, 2026
7423da7
test(eval): the stress battery reads clones and keeps texts out
ascalva Nov 12, 2026
de7cbbd
docs(experiments): keyword search and ledger lookups, before and after
ascalva Nov 12, 2026
e5d6d0f
docs(paper): keyword search and ledger lookups at corpus scale
ascalva Nov 12, 2026
57e0c96
docs(readme): the tests badge counts the statistics and ledger tests
ascalva Nov 12, 2026
d4c92cd
test(lexical): kill a write after its unit rows, and land in batches
ascalva Nov 12, 2026
722d5dc
fix(lexical): count without waiting for the lock; roll back early fails
ascalva Nov 12, 2026
88daf48
fix(attestation): migrate the ledger without waiting; scan until then
ascalva Nov 12, 2026
b60805e
feat(eval): a prepared source, a replacing batch and a concurrent open
ascalva Nov 12, 2026
dd04108
docs(runbook): reverting the kept lexical statistics, with its test
ascalva Nov 12, 2026
b3e4c0e
docs(design): name the store lines the kept statistics moved
ascalva Nov 12, 2026
6f23598
test(lexical): the reference fixture says what it keeps verbatim
ascalva Nov 12, 2026
7a4119d
docs(experiments): the keyword and ledger record, measured again
ascalva Nov 12, 2026
7db5c7e
docs(paper): the keyword and ledger article on the runs that replace it
ascalva Nov 12, 2026
9328ac4
docs(readme): the tests badge and count are the tier's 3,658
ascalva Nov 12, 2026
7ad053b
docs: the lexical migrations' range and the earlier loads, exactly
ascalva Nov 12, 2026
78626a0
docs: the call that finds the lock free counts the statistics
ascalva Nov 12, 2026
b4a3b59
fix(lexical): a failed count leaves the store answering from its units
ascalva Nov 12, 2026
34b35d9
fix(attestation): a failed migration leaves the lookups on the records
ascalva Nov 12, 2026
75c887c
docs(runbook): end every process of the change before the revert step
ascalva Nov 12, 2026
c414618
docs: a failed migration and the revert step in the record and article
ascalva Nov 12, 2026
8ea8c09
docs(readme): the tests badge and count are the tier's 3,662
ascalva Nov 12, 2026
8257a33
docs: the migrations' docstrings say which errors never reach a reader
ascalva Nov 12, 2026
e20be81
test(adversarial): the guest's lexical spy wraps the ranking that sco…
ascalva Nov 14, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
[![sorry](https://img.shields.io/badge/sorry-0-brightgreen)](formal/sorry-budget)
[![kernels](https://img.shields.io/badge/kernel_replay-6_checkers-6f42c1)](formal/check.sh)
[![attacks](https://img.shields.io/badge/attacks-232_with_controls-blue)](formal/PalaceTest)
[![tests](https://img.shields.io/badge/tests-3721-brightgreen)](docs/runbook.md)
[![tests](https://img.shields.io/badge/tests-3750-brightgreen)](docs/runbook.md)
[![coverage](https://img.shields.io/badge/coverage-77%25-green)](pyproject.toml)
[![mypy](https://img.shields.io/badge/mypy-0_errors_in_core-brightgreen)](pyproject.toml)
[![sealed core](https://img.shields.io/badge/sealed_core-zero_egress-6f42c1)](scripts/check_imports.py)
Expand Down Expand Up @@ -177,7 +177,7 @@ The build's own history is a dataset. Every commit's structure is snapshotted in

```sh
uv sync --extra dev
uv run pytest -q -m 'not live and not podman and not needs_vault and not needs_restic' # the deterministic tier: 3,721 tests
uv run pytest -q -m 'not live and not podman and not needs_vault and not needs_restic' # the deterministic tier: 3,750 tests
uv run mypy # strict core: 0 errors (the 67 in tests/ are pinned)
uv run python scripts/check_imports.py # the sealed core names no network module
uv run python -m ops.type_gate # every core-reaching package is type-checked
Expand Down
132 changes: 111 additions & 21 deletions core/attestation/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,20 @@
Thread-safety mirrors the JobQueue fix (PROGRESS 2026-06-27): the vault watcher emits ingest
attestations from a spawned thread, so the connection is opened `check_same_thread=False` and
every method is guarded by a reentrant lock.

The producer lookups (which attestations name a hash among their outputs) read a side table of
the ledger, one row for each element of each record's `output_hashes` with the record's id and
action, keyed by the hash: a lookup is an index seek, where it was a decode of every record. The
table is written by a trigger on the ledger, so every append writes its rows in its own statement
and transaction, whatever process appends, and a rolled-back append leaves none. A ledger written
before the table existed gets it on its first open, filled from the records in one transaction.
No open or lookup fails because of that migration. It does not wait for the file's write lock: a
process that opens the ledger while another holds the lock opens at once and answers the lookups
by one pass over the records, as the ledger answered them before the table, until a lookup finds
the lock free and makes the table. A migration that fails for any other reason (a file the
process cannot write, a full disk) is rolled back, and the lookups pass over the records until
the ledger is opened again. The table is derived from the records and changes no record: the
ledger stays append-only.
"""

from __future__ import annotations
Expand Down Expand Up @@ -36,6 +50,25 @@
CREATE INDEX IF NOT EXISTS att_role_ts ON attestations(agent_role, timestamp);
"""

# The output-hash side table: created, filled from the records and given its trigger in one
# transaction (`AttestationStore._migrate`), so its presence means it is complete. `pos` is the
# element's place in the record's `output_hashes`, so a record that names a hash twice has two
# rows, as the records do.
_OUTPUTS = (
"CREATE TABLE output_hashes (hash TEXT NOT NULL, att_id TEXT NOT NULL, action TEXT NOT NULL, "
"pos INTEGER NOT NULL, PRIMARY KEY (hash, att_id, pos)) WITHOUT ROWID",
"INSERT INTO output_hashes (hash, att_id, action, pos) "
"SELECT j.value, a.id, a.action, j.key FROM attestations a, "
"json_each(a.payload_json, '$.output_hashes') j",
"CREATE TRIGGER attestation_outputs AFTER INSERT ON attestations BEGIN "
"INSERT INTO output_hashes (hash, att_id, action, pos) "
"SELECT j.value, NEW.id, NEW.action, j.key FROM json_each(NEW.payload_json, "
"'$.output_hashes') j; END",
)
_BATCH = 400
_TIMEOUT_S = 5.0 # how long a statement waits for another connection's lock
_LOCKED = (sqlite3.SQLITE_BUSY, sqlite3.SQLITE_LOCKED) # a lock another connection holds


@dataclass(frozen=True)
class AttestationChain:
Expand Down Expand Up @@ -81,11 +114,54 @@ def __post_init__(self) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True)
self._lock = threading.RLock()
self._defer = False
self._conn = sqlite3.connect(str(self.path), check_same_thread=False)
self._conn = sqlite3.connect(str(self.path), timeout=_TIMEOUT_S,
check_same_thread=False)
self._conn.row_factory = sqlite3.Row
with self._lock:
self._conn.executescript(_DDL)
self._conn.commit()
self._migration_failed = False # failed but for the lock: not tried again here
self._indexed = self._migrate()

def _has_outputs(self) -> bool:
return self._conn.execute("SELECT 1 FROM sqlite_master WHERE type = 'table' "
"AND name = 'output_hashes'").fetchone() is not None

def _migrate(self) -> bool:
"""Give a ledger written before the output-hash side table its table, its rows and its
trigger, in one transaction (another process may have done it first: checked again
inside); True once the table exists. Only the open and the lookups call it, and no SQLite
error of the migration reaches them. The migration does not wait for the write lock: while
another connection holds it nothing is written, the answer is False, and the lookups pass
over the records until a later lookup finds the table or makes it. Any other failure (a
file this process cannot write, a full disk, an I/O error) is rolled back and answers
False, and this store does not try again; its next open does. A crash midway leaves the
ledger as it was, to be migrated at the next open."""
if self._has_outputs():
return True
conn = self._conn
if conn.in_transaction: # inside a deferred block: its appends are not ours to end
return False
if self._migration_failed:
return False
try:
conn.execute("PRAGMA busy_timeout = 0")
try:
conn.execute("BEGIN IMMEDIATE")
finally:
conn.execute(f"PRAGMA busy_timeout = {int(_TIMEOUT_S * 1000)}")
if not self._has_outputs():
for statement in _OUTPUTS:
conn.execute(statement)
conn.commit()
except sqlite3.Error as exc:
conn.rollback()
self._migration_failed = (getattr(exc, "sqlite_errorcode", 0) & 0xFF) not in _LOCKED
return False
except BaseException:
conn.rollback()
raise
return True

def append(self, att: Attestation) -> Attestation:
"""Insert one attestation. Append-only: an id already present is left untouched
Expand Down Expand Up @@ -135,34 +211,48 @@ def by_role(self, role: str) -> list[Attestation]:
return [a for a in self.all() if a.agent_role == role]

def producers_by_output(self, hashes: set[str]) -> dict[str, list[tuple[str, str]]]:
"""Each hash's producers, (action, id), for many hashes in one pass the database makes
over the ledger (SQLite's JSON functions, no record decoded in Python): what a batch of
landings asks once instead of `producers_of` per landing."""
"""Each hash's producers, (action, id), sorted, an attestation once for each time its
outputs name the hash: what a batch of landings asks once instead of `producers_of` per
landing, a seek of the output-hash table a hash."""
out: dict[str, list[tuple[str, str]]] = {h: [] for h in hashes}
if not hashes:
return out
with self._lock:
self._conn.execute("CREATE TEMP TABLE IF NOT EXISTS wanted_hashes "
"(h TEXT PRIMARY KEY)")
self._conn.execute("DELETE FROM wanted_hashes")
self._conn.executemany("INSERT OR IGNORE INTO wanted_hashes VALUES (?)",
[(h,) for h in hashes])
rows = self._conn.execute(
"SELECT j.value, a.action, a.id FROM attestations a, "
"json_each(a.payload_json, '$.output_hashes') j "
"WHERE j.value IN (SELECT h FROM wanted_hashes)").fetchall()
self._conn.execute("DELETE FROM wanted_hashes")
for h, action, att_id in rows:
for h, action, att_id in self._outputs(hashes, "hash, action, att_id"):
out[str(h)].append((str(action), str(att_id)))
return {h: sorted(ps) for h, ps in out.items()}

def _outputs(self, hashes: set[str], columns: str) -> list[sqlite3.Row]:
"""The output-hash table's rows for the hashes (`columns` of `hash`, `att_id`, `action`),
by seeks of its key, a statement a few hundred hashes; while the ledger has no table yet
(`_migrate`), the same rows from one pass over the records. Reads alone: no transaction is
opened, so no lock outlives the call."""
wanted = list(hashes)
rows: list[sqlite3.Row] = []
with self._lock:
if not self._indexed:
self._indexed = self._migrate()
if not self._indexed:
return self._scanned(wanted, columns) if wanted else []
for i in range(0, len(wanted), _BATCH):
batch = wanted[i:i + _BATCH]
rows += self._conn.execute(
f"SELECT {columns} FROM output_hashes WHERE hash IN "
f"({', '.join('?' for _ in batch)})", batch).fetchall()
return rows

def _scanned(self, wanted: list[str], columns: str) -> list[sqlite3.Row]:
"""`_outputs`'s rows from the records themselves, for a ledger without the table: one
pass of SQLite's JSON functions over every record, the hashes asked for given as one JSON
array (no temporary table, so no transaction)."""
names = {"hash": "j.value", "att_id": "a.id", "action": "a.action"}
select = ", ".join(f"{names[c.strip()]} AS {c.strip()}" for c in columns.split(","))
return self._conn.execute(
f"SELECT {select} FROM attestations a, json_each(a.payload_json, '$.output_hashes') j "
"WHERE j.value IN (SELECT value FROM json_each(?))", [json.dumps(wanted)]).fetchall()

def producers_of(self, hashes: set[str]) -> set[str]:
"""Ids of attestations whose `output_hashes` intersect `hashes` — the attestations that
PRODUCED any of those outputs. This is the chain-linking lookup: an action consuming
hash h derives from whatever attested producing h (attestation-layer.md §2)."""
if not hashes:
return set()
return {a.id for a in self.all() if hashes & set(a.output_hashes)}
return {str(r[0]) for r in self._outputs(hashes, "att_id")}

def chain_for(self, att_id: str) -> AttestationChain:
"""Assemble the transitive closure following `derived_from_ids`. `complete` is False if
Expand Down
23 changes: 14 additions & 9 deletions core/ingest/landing.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@
attest twice. A rename is the one event the digest cannot show: the same bytes under a new path
are a version event by the identity design (bp-031), and `sync_path` tells it from a re-run by
the catalog, where the old path still binds the identity until the pass tombstones it. The
attestation check scans the store; an index by output hash is the efficiency item if it ever
shows in a profile.
attestation check reads the ledger's output-hash table (`AttestationStore.producers_by_output`),
a seek a digest, where it was a pass over every record: at a few hundred thousand records the pass
took seconds and an item landed effect by effect asked it three times.
"""

from __future__ import annotations
Expand All @@ -37,11 +38,15 @@ def record_version_if_new(versions: VersionStore, doc_id: str, digest: str) -> V


def attested_by(attestor: Attestor | None, action: str, digest: str) -> list[str]:
"""The ids of the attestations of `action` that name `digest` among their outputs, through
the store's producer lookup (`producers_of`, a pass over the ledger)."""
"""The ids of the attestations of `action` that name `digest` among their outputs, sorted,
each once: from the store's producers by output (their actions with them) where it has them,
else from its producer ids, each record read for its action."""
store: Any = getattr(attestor, "store", None)
if store is None or not digest:
return []
if hasattr(store, "producers_by_output"):
pairs = store.producers_by_output({digest}).get(digest, [])
return sorted({str(att_id) for act, att_id in pairs if act == action})
out = []
for att_id in sorted(store.producers_of({digest})):
att = store.get(att_id)
Expand All @@ -52,11 +57,11 @@ def attested_by(attestor: Attestor | None, action: str, digest: str) -> list[str

def attested_batch(attestor: Attestor | None,
digests: set[str]) -> dict[str, list[tuple[str, str]]]:
"""For many digests in one pass over the ledger, each digest's producers: the attestations,
of any action, whose outputs name it, as (action, id). `attested_by` is the producers of one
action, and an attestation's parents (`StoreAttestor.emit`'s auto-link) the producers of its
inputs; the batched landing reads both off this one pass a batch (`Writer.land_batch`), where
asking per store is two passes a store, which grow with the ledger."""
"""For many digests in one read of the ledger's output-hash table, each digest's producers:
the attestations, of any action, whose outputs name it, as (action, id). `attested_by` is the
producers of one action, and an attestation's parents (`StoreAttestor.emit`'s auto-link) the
producers of its inputs; the batched landing reads both off this one read a batch
(`Writer.land_batch`) rather than asking per store."""
store: Any = getattr(attestor, "store", None)
out: dict[str, list[tuple[str, str]]] = {d: [] for d in digests}
if store is None or not digests:
Expand Down
Loading
Loading