Skip to content

fix(daemon): Unblock live ingest refused by unleased ops-tier opens - #5409

Merged
Sinity merged 4 commits into
masterfrom
fix/daemon-under-test-ingests
Sep 22, 2026
Merged

Sinity merged 4 commits into
masterfrom
fix/daemon-under-test-ingests

Conversation

@Sinity

@Sinity Sinity commented Sep 22, 2026

Copy link
Copy Markdown
Owner

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 fix(storage): Close seventeen live P1 review findings in the storage tier #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 chore: Live ingest ops-tier writes are not self-admitting, so the write… #5265 retired the one-scope-per-batch contract and perf(live): Share one ops connection per ingest publication #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 perf(live): Share one ops connection per ingest publication #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.ai/code/session_01ToWqpkXotr573DiQex5vcy

@coderabbitai

coderabbitai Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

Next included review available in 41 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: 839fd4ce-858a-4d9e-ba74-75ee1f11f479

📥 Commits

Reviewing files that changed from the base of the PR and between 735f52f and ffb1650.

📒 Files selected for processing (7)
  • polylogue/daemon/cli.py
  • polylogue/sources/live/batch.py
  • polylogue/sources/live/cursor.py
  • polylogue/storage/sqlite/archive_tiers/archive.py
  • tests/unit/daemon/test_daemon_operation_route.py
  • tests/unit/daemon/test_daemon_ops_lease_boundary.py
  • tests/unit/daemon/test_schema_preflight.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-22T07:59:26.621768Z ffb1650 New commits
🔒 Security Review ✅ Completed 2026-09-22T08:02:55.749628Z 1d7020d 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 07:49
Sinity and others added 4 commits September 22, 2026 09:50
polylogue-ol2fc. A real `polylogued run` started, bound its API and watched
its sources, then ingested nothing: every intake page was refused with
`daemon.intake.page_refused ... reason=page_admission_failed` and the
`UnleasedWriteError` behind it, so the archive stayed empty forever.

Four sites on the daemon's own ingest path opened a write-mode archive
connection without holding the lease, or bound to the wrong archive root.
With the single-writer boundary armed -- which is exactly the state the
daemon runs in, and only the daemon -- each one aborts the whole page:

- `CursorStore.get_records` and six sibling SELECT-only ops readers went
  through `_connect_ops`, a write-mode open. `get_records` runs during batch
  planning on the event loop, outside the per-publication `_run_sync` hold
  that owns the lease. New `_connect_ops_read` reuses a held
  `ops_write_scope` connection and otherwise opens read-only.
- `LiveBatchProcessor` called its event emitter inline. The daemon's emitter
  appends to the ops-tier event ledger, so it is an ops publication and now
  takes the writer through `_run_sync` like every other one.
- `_drain_convergence_debt_once` constructed `CursorStore(db)`, whose
  bootstrap and interrupted-attempt rewrite are writes; it now passes
  `initialize=False` and leaves its ledger writes to `admit_stage_write`.
- `ArchiveStore._ensure_source_conn` bound the durable `source.db` open to
  the candidate directory. Under a cold-build generation that file is a
  read-through symlink to the declared archive's own tier, so the binding is
  `_write_lease_archive_root` -- the root the index-tier open already uses.

Verification: a synthetic archive with three 50-message claude-code JSONL
sessions, driven through the real `polylogued run` binary.
  base 0df0f6a: `TIMEOUT last=0`, 81 UnleasedWriteError lines
  head:           `OK messages=50 after 28.6s`, 0 UnleasedWriteError lines
The regression window opens at #5224 (2026-09-16): the same driver reports
`OK messages=50` at 342cf9e and `TIMEOUT last=0` from d7d3dda onward.

Anti-vacuity, executed: each of the four production edits was reverted and
the matching test in `tests/unit/daemon/test_daemon_ops_lease_boundary.py`
went red with the production failure text, e.g. `UnleasedWriteError:
open_connection(.../ops.db) requires the daemon write lease` and
`open_source_tier_write_connection(.../gen-.../source.db) is outside the
archive bound to writer test.cold_build`. The opposite direction is pinned
by `test_ops_tier_writes_still_require_the_write_lease`, which fails if
ops.db is made lease-free wholesale.

Schema closure: `batch.py`, `cursor.py` and `archive.py` are IN;
`daemon/cli.py` and the new test are out. Derived INDEX identity moves
8a971a5382afa46b0b08cfc35c98ab47a375802e3008f2ec883fe5b5c1267aa6 ->
abb040dad955a69ff876586e76e7557e1cba89a1cb53b1350903759804707003; OPS is
unchanged at 868662352a182527e6a561a0f7746a603cf2df17f3efda2da8190e6f1785104a.
No DDL, lowering or materializer semantics change -- this is a closure move
on ordinary code, and it must land before a fresh rebuild starts.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01ToWqpkXotr573DiQex5vcy
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
…ck starts

polylogue-ol2fc, split from the ingest-lease defect. `_seed_sessions` writes
through `SessionBuilder.save`, which uses the thread-local cached connection
in `storage/sqlite/connection.py`. That connection ATTACHes the sibling
durable tiers and is never closed, so `source.db` stays locked for the life
of the thread.

`test_fresh_runtime_prepares_tier_journals_before_first_snapshot_and_mutation`
seeds and then sets `PRAGMA journal_mode=DELETE` on source/user/audit to
present the daemon with untouched rollback-journal tiers. The PRAGMA hit the
seeding thread's own lock and raised `sqlite3.OperationalError: database is
locked` in *setup* -- before the route under test ran at all. A real
`polylogued` start has no such cached connection, so this was a harness that
is more restrictive than production: a phantom failure, not a defect in the
operation route.

Seeding is setup and must hand the stack an archive no other writer holds,
so `_seed_sessions` now clears the cache the way `tests/conftest.py` and
`test_corruption_recovery.py` already do.

Anti-vacuity, executed: with the clear removed, seeding a fresh archive and
then running the same PRAGMA loop reports `source LOCKED database is locked`
/ `user ok` / `audit ok`; with it, `source ok` / `user ok` / `audit ok`.

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

polylogue-ol2fc follow-up to 20ec976. That commit stopped
`_drain_convergence_debt_once` from constructing its `CursorStore` with
`initialize=True` outside a lease by passing `initialize=False`. The
construction is not incidental: `CursorStore.initialize` also migrates
retired convergence-debt stage names and rewinds interrupted attempts, and
`test_drain_convergence_debt_migrates_retired_insights_stage` proved the
drain depends on that migration -- it went red with
`assert 'insights' == 'derived'`.

The construction is a write section, so it is admitted as one:
`admit_stage_write("maintenance.convergence_debt.initialize", ...)`. Under
the daemon it runs on the writer; with no admission bound (a standalone pass
or a unit test) `admit_stage_write` falls through to a direct call, so the
recovery semantics are exactly what they were before either commit.

Anti-vacuity, executed: replacing the admitted construction with a bare
`CursorStore(db)` makes
`test_convergence_debt_drain_runs_under_its_stage_admission` red with
`UnleasedWriteError: open_connection(.../ops.db) requires the daemon write
lease`; restoring it makes it green. The test binds a real admission that
takes a lease, which is the shape `_daemon_stage_write_admission` provides.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01ToWqpkXotr573DiQex5vcy
@Sinity
Sinity force-pushed the fix/daemon-under-test-ingests branch from 1d7020d to ffb1650 Compare September 22, 2026 07:55
@Sinity

Sinity commented Sep 22, 2026

Copy link
Copy Markdown
Owner Author

Rebased onto master 735f52f14 (which now includes #5408).

The rebase independently confirmed this PR's diagnosis. The only conflict was in archive.py, where #5408 and this branch had made the identical fix — archive_root=self._write_lease_archive_root — reached from completely different evidence: #5408's storage lane from a code-review finding about lease roots, this lane from the real binary ingesting zero messages. Only the explanatory comments differed. I kept master's and added the production evidence #5408 did not have.

Re-verified on the new base:

Separately, the host-side cause of the exit 137 collection kills this lane reported is fixed and activated: agentctl-pytest-quick.slice was sized MemoryHigh = 5G while pytest-quick.parallel = 2, so two concurrent runs shared 2.5G each and memory.high reclaim tripped ManagedOOMMemoryPressure=kill. systemd-oomd killed 29 pytest jobs between 08:22 and 08:44. Resized to 9G/10G (Sinity/sinnix#65) and verified live. Zero kills in the 68 minutes since, under comparable load.

@Sinity
Sinity merged commit d8a52f5 into master Sep 22, 2026
3 checks passed
@Sinity
Sinity deleted the fix/daemon-under-test-ingests branch September 22, 2026 08:07
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