Skip to content

perf(live): Share one ops connection per ingest publication - #5388

Merged
Sinity merged 4 commits into
masterfrom
perf/parse-cursor-superlinear
Sep 22, 2026
Merged

Sinity merged 4 commits into
masterfrom
perf/parse-cursor-superlinear

Conversation

@Sinity

@Sinity Sinity commented Sep 22, 2026

Copy link
Copy Markdown
Owner

Summary

polylogue-s8x8s claims super-linear work in parse and cursor commit. It does not reproduce — both are linear at head. What does reproduce is gross per-file redundancy at constant cost, and fixing that gives a measured 2.4–2.6× speedup on cold ingest.

The bead's premise is refuted, measured

Synthetic claude-code corpora through the real LiveBatchProcessor.ingest_files route with DaemonConverger(make_default_convergence_stages(...)):

N files cold total cold/file
100 19.78 s 197.8 ms
500 93.50 s 187.0 ms
2000 354.85 s 177.4 ms

Per-file cost falls slightly with N. A fixed 5-file chunk ingested into an archive holding 100/500/2000 files issued identical statement counts (ops.db 983, index.db 973) at every size. Parse cost within one file is flat at 110–115 µs/record from 4k to 64k records.

The bead's next_ordinal O(n²) is genuinely gone (base_support.py:53 is return self._counts.get(unit, 0)), and jsonl_complete_prefix already validates tail-first.

What is real: 16.5 SQLite connections for one 8-message session

Attribution by call site over a 50-file cold ingest. Three fixed here:

  1. Per-operation ops.db open/commit/close inside each _run_ops_write (~10.1/file) — _record_full_cursor, _record_convergence_outcome, _record_failed_cursor, attempt progress each opened their own.
  2. _append_plan → CursorStore.get_record (1.0/file) re-asking for a record _ingest_files already read in one get_records.
  3. _record_raw_retention_outcome (1.0/file) opening per scoped path.

Fix is one scope plus a cursor_is_known flag:

def publish(*scoped_args: P.args, **scoped_kwargs: P.kwargs) -> T:
    with self._cursor.ops_write_scope():
        return function(*scoped_args, **scoped_kwargs)

Total connections 553 → 454 per 50 files; ops.db write connections 10.1 → 2.1 per file.

Result, measured under contention

The host was heavily loaded (load 31.7, ~20 queued pytest jobs from sibling lanes), so this is an interleaved 3-round A/B at N=300, alternating base and head back to back:

round base ms/file head ms/file speedup
1 305.8 120.9 2.53×
2 317.0 121.7 2.60×
3 418.5 173.1 2.42×

Connects/file 16.55 → 8.51 in every round.

Correctness: commit boundaries are unchanged

ops_write_scope shares a connection; each _connect_ops block still commits on success and rolls back on failure. The proof is that commits/file is byte-identical before and after at every size — 15.32 / 15.18 / 15.17 both ways, 30,332 commits at N=2000 either way. A crash at any point leaves the same durable prefix. No hashing, lowering or DDL is touched.

Anti-vacuity executed — including two refutations

Mutation 1, remove the scope: ingest opened 64 ops.db write connections for 6 files (10.67 per file); an ops publication must share one connection.
Mutation 2, restore the per-path re-read: 4.83 per file, assert 4.833 <= 4.0, plus the batch already read every offered path's cursor in one query.

Two further assertions I drafted stayed GREEN under their own mutation and were deleted rather than kept:

  • An ops.db commit floor. Mutation deferred _connect_ops's commit to scope exit; result was connections=25 commits=73 with and without it — every writer commits explicitly inside its own block, so no commit depends on the scope. Refuted.
  • An append-route assertion against a lost cursor snapshot. Mutation passed cursor=None, cursor_is_known=True; the test still passed, because _append_plan resynthesizes an equivalent cursor from source.db. The route cannot witness the defect. Refuted.

Both refutations are recorded in the module docstring so the next reader doesn't re-derive them.

Verification

devtools test <12 live/ingest/cursor selections>  exit 1  353 passed, 2 failed
  base ba2c63c47, same selection in this worktree  exit 1  351 passed, 2 failed
    -> exactly the two inherited failures, no new red
devtools test tests/unit/sources/test_live_ingest_ops_work.py  exit 0, 2 passed
devtools verify --quick     exit 0, 25 gates
devtools render all --check exit 0, 'out of sync' count 0
devtools gate mypy          Success: no issues found in 2971 source files

Schema identity

polylogue/sources/live/batch.py is closure IN: INDEX moves dba2f05e… → e2282952…, OPS unchanged. Membership unchanged, gate schema-closure passed with no --update. Must land before a rebuild starts, never during one.

Residual redundancy left unfixed, with reasons

Six further per-file sites sit outside this file's scope. The largest is filed separately: origin_specs._source_signature stats every closure source file on every _fingerprint_sources call — 232,981 calls / 239,459 posix.stat for 200 files (~1,165 stats per ingested file), ~5% of cold wall. Also: hermes_state and hermes_verification each open every ingested .jsonl as a SQLite database (2 opens/file); the cheap guard is a header check in sqlite_export.logical_source_shape, but that is a detection-boundary change needing origin specs + real fixtures + replay parity.

Bead ACs 1 and 4 need the real-data corpus rather than a synthetic driver and are not addressed; s8x8s stays open on those.

🤖 Generated with Claude Code

https://claude.ai/code/session_01ToWqpkXotr573DiQex5vcy

Sinity and others added 4 commits September 22, 2026 06:43
Live ingest publishes its ops-tier bookkeeping one publication at a time
through _run_ops_write. A publication is rarely one statement: a full
cursor commit reads the record, upserts it and resets its failure
counters; a convergence outcome clears stale debt for the source path and
for every session the file touched before recording the new rows; a
retention pass records or clears debt for every path it scoped. Each of
those opened, committed and closed its own ops.db connection, and closing
a WAL connection checkpoints it -- so the churn, not the statements, was
the cost.

Measured on a synthetic claude-code corpus through the real
LiveBatchProcessor.ingest_files route (2000 files, 8 messages each):
ops.db connection opens fell from 20,235 to 4,169 and cold ingest from
354.8 s to 191.9 s (177.4 ms -> 95.9 ms per file). The ops.db COMMIT
count is unchanged at exactly 30,332 -- the scope shares a connection, it
does not merge transactions, so the durable prefix after a crash at any
point is exactly what it was.

Two redundant reads go with it. _append_plan asked ingest_cursor for a
record per path even though _ingest_files had already read every offered
path in one query, so a path the batch knew had no cursor cost one more
ops.db connection to re-learn it; the batch now says it looked.
_record_raw_retention_outcome opened a connection per scoped path for a
loop that runs once per compaction pass.

Growth is linear in corpus size before and after: per-file cold cost at
100/500/2000 files was 197.8/187.0/177.4 ms before and 83.4/82.1/95.9 ms
after, and a fixed 5-file chunk issues the same ops.db statement count
against a 100-, 500- and 2000-file archive. The bead's super-linearity
claim does not reproduce at the corpus level.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01ToWqpkXotr573DiQex5vcy
Two of the four assertions drafted for this file stayed green under the
mutation they existed to catch, so they were evidence of nothing:

- an ops.db commit floor, against folding the publications into one
  transaction. Deferring _connect_ops's commit to scope exit changed the
  count by zero (73 commits for six files either way) because every
  writer commits explicitly inside its own block.
- an append-route assertion, against a wrong cursor snapshot. Passing
  cursor=None, cursor_is_known=True still left all six files on the
  append route, because _append_plan resynthesizes an equivalent cursor
  from source.db when it is told there is none.

Both are recorded in the module docstring so the next reader does not
re-derive them. What remains is executed: removing the publication scope
from _run_ops_write puts the connection budget at 10.67 per file against
a 4.0 ceiling, and restoring _append_plan's per-path cursor re-read puts
it at 4.83 and names the six repeated reads.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01ToWqpkXotr573DiQex5vcy
Both fakes replace ``_append_plan`` with an explicit keyword-only
signature, so ``plan_append``'s new ``cursor_is_known`` argument reached
them as an unexpected keyword rather than being absorbed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01ToWqpkXotr573DiQex5vcy
``cursor.py`` binds ``open_connection`` by name, so patching that binding
is what isolates the store's own ops-tier writes; the counter calls the
factory's own module to reach the unpatched implementation instead of
reading a re-export mypy does not consider public.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01ToWqpkXotr573DiQex5vcy
@coderabbitai

coderabbitai Bot commented Sep 22, 2026

Copy link
Copy Markdown

Warning

Review limit reached

Next included review available in 15 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Advanced

Run ID: 386f9d03-bffe-4286-9a56-0db92971ddba

📥 Commits

Reviewing files that changed from the base of the PR and between 6fa8440 and 1938204.

📒 Files selected for processing (3)
  • polylogue/sources/live/batch.py
  • tests/unit/sources/test_live_batch_support.py
  • tests/unit/sources/test_live_ingest_ops_work.py

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-22T04:49:28.811218Z 1938204 PR opened
🔒 Security Review ✅ Completed 2026-09-22T04:52:54.703526Z 1938204 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Sinity
Sinity enabled auto-merge (squash) September 22, 2026 04:44
@Sinity
Sinity merged commit d082601 into master Sep 22, 2026
3 checks passed
@Sinity
Sinity deleted the perf/parse-cursor-superlinear branch September 22, 2026 04:55
Sinity added a commit that referenced this pull request Sep 22, 2026
#5389)

## Summary

`polylogue-rk0it`. A cold build was paying WAL checkpoint and fsync cost
on `ops.db` — the **disposable** tier — on every write. Holding those
checkpoints for the build's lifetime cuts disposable-tier syncs by 90%
and halves the ingest window, with **zero change to any durable tier**.

## Measured, by strace between in-process ingest markers

Synthetic 16-file codex-shaped page through
`LiveBatchProcessor.ingest_files` under a registered
`ColdBuildGeneration`. Identical across two repeats each.

| path | before | after |
|---|---|---|
| `ops.db` | 61 | **5** |
| `ops.db-wal` | 122 | **11** |
| archive dir | 63 | **8** |
| `source.db` | 2 | 2 |
| `source.db-wal` | 4 | 4 |
| blob file+dir | 32 | 32 |
| **total** | **284** | **62** |

Disposable-tier syncs **246 → 24** (15.4 → 1.5 per file). Durable-tier
and blob syncs **unchanged**. Transaction counts unchanged on both sides
(source 65 BEGIN/65 COMMIT, ops 81, index 32).

cProfile, median of 3 warm runs: `Connection.commit` 0.600 s → 0.057 s,
`Connection.close` 0.748 s → 0.105 s. **Ingest window 2.27 s → 1.03 s**
on an idle machine.

## Why this is safe, stated as a durability argument

`ops.db` is the disposable tier — cursors, attempts, convergence debt,
telemetry. The deferral is scoped to `ColdBuildGeneration`'s lifetime:
`_retain_ops_checkpoints` in `open_writer` (i.e. per dispatcher page),
released at promote/discard. It only delays *cursor durability*; it can
never advance a cursor earlier than its durability boundary.
`test_settling_the_build_drains_the_wal` proves the widened window does
not leak onto a settled archive.

No new write mode (AC6): the candidate index keeps
`BULK_BUILD_WRITE_CONNECTION_PROFILE`, the ops holder uses the ordinary
`WRITE_CONNECTION_PROFILE` that `CursorStore._connect_ops` already uses.
The only new keyword is `check_same_thread`, a connection-lifetime flag.

## AC4 should be closed as "no evidence", not implemented

The bead asks to re-cut governance commit boundaries, citing 13.1 s of
66 s in source `Connection.__exit__`. **That premise has evaporated.**
It was measured when `source.db` was in DELETE/FULL mode. At head,
source is WAL + `synchronous=NORMAL`:

- 4.06 source-tier commits per ingested file, costing **0.059 s of a
2.195 s window**
- **6 `fdatasync` calls per 8 files** — a commit does not fsync under
WAL+NORMAL
- **zero** of the 0.586 s of `Connection.commit` in the profile is
attributable to a source-tier writer

So re-cutting the durable tier's transaction boundaries would buy ~2.7%
and spend the one atomicity contract a rebuild cannot reconstruct. That
work was deliberately not done. The bead needs amending rather than
leaving a P0 criterion pointing at a premise that no longer holds.

## Anti-vacuity — four mutations executed

1. Delete `_retain_ops_checkpoints()` → 3 FAILED, `assert not
exists(.../ops.db-wal)`.
2. Delete `_release_ops_checkpoint_holder()` from `discard` → FAILED,
WAL survives the build.
3. Add `BEGIN` before the holder's attachment read → FAILED, `assert 1
== 0`, `wal_checkpoint(TRUNCATE)` answers busy — proves the holder
defers checkpoints *without* blocking the recurring checkpoint the
argument depends on.
4. Bare `sqlite3.connect` in `_ensure_source_conn` → FAILED, `('wal', 2,
5000, 0) == ('wal', 1, 30000, 1)` — synchronous FULL, 5 s timeout,
foreign keys off.

## A real bug the layering ratchet caught that no test did

The holder's first version swallowed `sqlite3.Error`, and `gate
layering`'s `sqlite_degradation_site_added` ratchet refused it. Removing
the swallow exposed a genuine cross-thread defect: `open_writer()` runs
on different write-coordinator threads, so the attachment read raised
`ProgrammingError`, silently replaced the holder and **leaked the
previous connection on every cross-thread pass**. The ratchet, not any
test, is what found it.

## Verification

```
devtools test <9 connection-policy/lease/coordinator selections>  exit 0, 134 passed
devtools test <cold-build durability + generation>                exit 0, 17 passed
devtools verify --quick        exit 0   (base control also exit 0 — no inherited red)
devtools render all --check    exit 0, 'out of sync' count 0
```

Schema closure: `sources/live/cold_build.py` and `connection_profile.py`
are both **IN**. INDEX `dba2f05e… → 9bd28b3a…`, OPS unchanged.
Membership unchanged, `gate schema-closure` green with no `--update`.
**Must land before a rebuild starts.**

## Residuals

- **97 `ops.db` opens for a 16-file page, 94 outside the held scope** —
the remaining cost is connection *creation*, not durability. Traced to
`batch._record_full_cursor` (2/file), `_record_convergence_outcome`,
`_record_raw_retention_outcome`, `_record_attempt_progress`
(~1.25/file), `_append_plan`. They run in separate
`_run_sync`/`asyncio.to_thread` calls so the thread-local scope doesn't
reach them. That is a live-ingest change, not cold-build; needs its own
bead. (Note #5388 fixes the in-scope half of this on the live route.)
- **AC5's blob half untouched**: 1 file + 1 directory fsync per blob,
unchanged. Batching to one pass per dispatcher page is a
durable-material change needing its own crash-window argument.
- AC3 has no tier-by-tier durability document; AC7 needs real-data
stratified samples through `FairIntakeDispatcher`; ADDENDUM-1 wants the
instrumentation committed (working driver exists in scratch,
`tests/benchmarks/` is its in-tree home).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01ToWqpkXotr573DiQex5vcy

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Sinity added a commit that referenced this pull request Sep 22, 2026
polylogue-ol2fc. Two `test_schema_preflight.py` cases failed with `expected
at least N completed ops write scope(s), saw 0`. The assertion pinned a
contract that no longer exists: #5265 replaced the one-scope-per-batch
`ops_write_scope` with one admitted section per ops write, and #5388 put the
scope inside that section. A degraded batch performs no ops write at all --
`ingest_files` returns synthetic skip metrics before `begin_ingest_attempt`
-- so demanding a completed scope demanded exactly the ops bookkeeping #1003
exists to suppress.

`assert_no_ops_bookkeeping` asserts what the degraded path does guarantee:
zero scopes entered, zero stage events published, nothing left open or
buffered. `assert_scopes_balanced` stays for the structural-error case,
which does reach ops publication and passes unchanged.

Anti-vacuity, executed: moving the degraded return to after the
`attempt_start` ops write (leaving every other assertion satisfiable) makes
both cases red -- `degraded ingest entered 1 ops write scope(s)` and
`... entered 5 ops write scope(s); it must not reach ops bookkeeping` --
and restoring the gate makes them green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01ToWqpkXotr573DiQex5vcy
Sinity added a commit that referenced this pull request Sep 22, 2026
polylogue-ol2fc. Two `test_schema_preflight.py` cases failed with `expected
at least N completed ops write scope(s), saw 0`. The assertion pinned a
contract that no longer exists: #5265 replaced the one-scope-per-batch
`ops_write_scope` with one admitted section per ops write, and #5388 put the
scope inside that section. A degraded batch performs no ops write at all --
`ingest_files` returns synthetic skip metrics before `begin_ingest_attempt`
-- so demanding a completed scope demanded exactly the ops bookkeeping #1003
exists to suppress.

`assert_no_ops_bookkeeping` asserts what the degraded path does guarantee:
zero scopes entered, zero stage events published, nothing left open or
buffered. `assert_scopes_balanced` stays for the structural-error case,
which does reach ops publication and passes unchanged.

Anti-vacuity, executed: moving the degraded return to after the
`attempt_start` ops write (leaving every other assertion satisfiable) makes
both cases red -- `degraded ingest entered 1 ops write scope(s)` and
`... entered 5 ops write scope(s); it must not reach ops bookkeeping` --
and restoring the gate makes them green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01ToWqpkXotr573DiQex5vcy
Sinity added a commit that referenced this pull request Sep 22, 2026
…5409)

## Summary

A real `polylogued run` ingests nothing. Four sites on its own ingest
path open a write-mode archive connection with no lease held — or bound
to the wrong archive root — and the armed single-writer boundary raises
`UnleasedWriteError`, which refuses the whole intake page. Live ingest
has been broken since 2026-09-16.

## Problem

This was filed as a cluster of 16 failing tests with two candidate
explanations. **Both are refuted**, and the defect is production-only.

- *"Startup never converges"* — no. `daemon.started` fires, the watcher
binds all 16 source roots, the API answers, and per-publication ops
writes succeed under their own lease in the same log.
- *"A writer lease is never released"* — no. Every
`daemon.writer.released … status=success` line shows holds of 1–800 ms.
The defect is a lease never **taken**.

Reproduced outside pytest with the installed `polylogued` console script
against a synthetic 3-session corpus — no fixture, no harness. The line
that decides the diagnosis, from the real daemon's stderr at base:

```
daemon.intake.page_refused ... error_detail=open_connection(<root>/ops.db) requires the daemon
write lease; open it inside write_lease(...) ... error_type=UnleasedWriteError files=3
outcome=degraded reason=page_admission_failed
```

Bisected on the real binary: `OK messages=50` at `342cf9e20` (#5221),
`TIMEOUT last=0` at `1c1895098` (#5263) and every later point. The
window opens at `d7d3ddae5` (#5224, 2026-09-16), which added
`require_write_lease` to `CursorStore.ops_write_scope`; #5265 moved the
raise site to `get_records` but did not introduce it.

**#5382 is not the cause**, despite the differential that pointed there:
the cluster was already failing in the 09-21 corpus run, and #5382
landed 09-22 02:54 UTC.

The four sites, each proven by stack capture at the raise:

| Site | Route |
|---|---|
| `sources/live/batch.py:963` | `get_records` → `_connect_ops` →
`open_connection(ops.db)` on the event loop |
| `daemon/cli.py` | `_drain_convergence_debt_once` → `CursorStore(db)` →
`initialize_archive_database(ops.db)` |
| `sources/live/batch.py:1515` | inline `self._event_emitter(...)` →
`open_daemon_connection(ops.db)` |
| `archive.py:1435` | `_ensure_source_conn` bound to the candidate
generation dir, not the declared root |

## Verification

Production route, the real binary, no pytest:

| | base `0df0f6a00` | head |
|---|---|---|
| result | `TIMEOUT last=0` | **`OK messages=50`** |
| `UnleasedWriteError` lines | 81 | **0** |
| `convergence_debt.pass.error` | present | **0** |

Re-run after rebasing onto current master `17566b048`: **`OK messages=50
after 27.3s`, 0 unleased errors** — the fix holds on the current tree,
not only on the base it was written against.

- `devtools verify --quick` → **21/25 gates green at time of writing,
with the single failure being `gate atlas`, which is already red on
master** (`docs/atlas/daemon.md`, hook-carrier anchor). Reproduced in a
clean detached worktree at `17566b048` carrying none of these changes.
PR #5408 fixes it.
- `devtools render all --check` → exit 0, `grep -c 'out of sync'` =
**0**.
- `devtools test` over `test_daemon_resilience.py`,
`test_schema_preflight.py`, `test_daemon_ops_lease_boundary.py`,
`test_daemon_operation_route.py`, `test_inferred_corpus_loop.py` →
**exit 0, 72 selected, 72 passed**. No timeout, mark or wait bound was
changed anywhere, so the resilience tests reach their own
`_wait_for_messages` assertions with real nonzero counts.
- `test_daemon_cli.py` at head: 106/112. At base: 100/107. Delta is one
test **fixed**; the remaining 6 are byte-identical inherited red.
Baseline established by detaching at the base SHA and running the same
selection.

### Anti-vacuity, executed

Four production reverts, one at a time, each restored:

- revert `_connect_ops_read` → `UnleasedWriteError:
open_connection(…/ops.db) requires the daemon write lease`, from two
independent tests
- revert the `_run_sync` wrapper on the batch emitter →
`UnleasedWriteError: live batch event ledger requires the daemon write
lease`
- revert `admit_stage_write` on the `CursorStore` construction →
`UnleasedWriteError: open_connection(…/ops.db)`
- revert `_ensure_source_conn` to `archive_root=self.archive_root` →
`UnleasedWriteError:
open_source_tier_write_connection(…/gen-1790055341112-6db616a2/source.db)
is outside the archive bound to writer test.cold_build`

Opposite direction pinned:
`test_ops_tier_writes_still_require_the_write_lease` fails if `ops.db`
is made lease-free wholesale.

## The cluster was three causes, not one

- **12 of 16** are the production defect above.
- **2** are a stale test contract: they assert
`assert_scopes_balanced(at_least=N)` on the degraded short-circuit path,
but #5265 retired the one-scope-per-batch contract and #5388 put the
scope inside each admitted publication. A degraded batch returns
synthetic skip metrics before `begin_ingest_attempt`, so it correctly
performs zero ops writes and can never satisfy `at_least>=1`. Retargeted
to `assert_no_ops_bookkeeping`.
- **1** is a harness more restrictive than production — a phantom.
`test_fresh_runtime_prepares_tier_journals…` died in its own `seed`:
`SessionBuilder.save` writes through the thread-local cache in
`storage/sqlite/connection.py`, whose `index.db` connection ATTACHes the
sibling durable tiers and is never closed, so `PRAGMA
journal_mode=DELETE` on `source.db` hit the seeding thread's own lock.
Isolated proof: `source LOCKED database is locked` / `user ok` / `audit
ok`. A fresh `polylogued` process has no such cached connection, so
**production cannot exhibit this one at all**.
- **1 more** was fixed by #5388 landing on master during the lane; it
passes at base untouched.

The harness was **under**-reporting, never over-reporting, for the real
cause.

## Still red, handed back

The 4
`test_daemon_watcher_hints_wake_fair_intake_and_canonical_derivation`
params are a **fourth, distinct cause** that only became visible once
the daemon started ingesting. They are no longer `CancelledError`; the
fix carries them past ingest (`ingested_session_count=1`) into
`test_daemon_cli.py:2747`, where `sum(report.done == 1 …) ==
expected_versions` sees `[(…, 0), (…, 2)]` — the canonical derivation
kernel reported done=0 then done=2 instead of one per version. That is a
derivation-batching question and needs its own bead. Confirmed
inherited-red at base by the same nodeids.

Two further inherited reds, failing identically at base and head:
`test_raw_observation_publication_holds_writer_lease_through_replay`
(`AttributeError: 'FakeArchive' object has no attribute 'archive_root'`
— a test double that never gained an attribute production now reads) and
`test_run_daemon_services_parks_operation_recovery_on_audit_schema_mismatch`.

The 2 `test_inferred_corpus_loop.py` property tests pass at head, but
**no code cause was established** for their corpus-run timeouts and they
do not arm the write lease. The honest reading is host-load starvation,
not a fix — do not credit them here.

## Behaviour change worth a reviewer's eye

The 7 SELECT-only `CursorStore` readers now open read-only when no
`ops_write_scope` connection is held. On a fresh archive with no
`ops.db` they raise `sqlite3.OperationalError: unable to open database
file` instead of silently bootstrapping it through a write-mode open.
The daemon bootstraps the archive root before any of these run, and
`cli.py:1584` already documents this exact `initialize=False` read-probe
pattern — its `get_record` call was a fifth latent `UnleasedWriteError`
site that this change also removes — so the typed failure is judged
correct rather than adding an unexercised guard.

## Schema closure

IN: `sources/live/batch.py`, `sources/live/cursor.py`,
`archive_tiers/archive.py`. out: `daemon/cli.py` and all three test
files.

- `DerivedTier.index`: `8a971a53…` (base, measured in a detached
worktree) → `abb040da…`
- `DerivedTier.ops`: unchanged

A closure move on ordinary code — no DDL, no lowering or materializer
semantics, no durable migration. Needs reconvergence, and **must land
before a fresh rebuild starts, never during one**. Re-measure at merge;
other lanes are moving this value concurrently.

## Follow-ups, same defect class, left unlanded

- `archive.py:5599` `ArchiveStore.delete_sessions` still binds
`require_write_lease(archive_root=self.archive_root)` instead of
`_write_lease_archive_root`, so a delete on a generation-rooted store
fails exactly as `_ensure_source_conn` did.
- `daemon/cli.py:487`
`_mark_interrupted_live_ingest_attempts_on_shutdown` constructs
`CursorStore(initialize=True)` on the shutdown path — an unleased ops
write. Currently unreached because signal termination logs
`daemon.shutdown.ingest_recovery_deferred`, but a non-signal graceful
stop would hit it.

Neither was fixed because neither could be exercised.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01ToWqpkXotr573DiQex5vcy

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
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