Skip to content

feat: Run convergence off the writer lease and unify the daemon loops - #5228

Merged
Sinity merged 4 commits into
masterfrom
feat/stage-engine
Sep 16, 2026
Merged

Sinity merged 4 commits into
masterfrom
feat/stage-engine

Conversation

@Sinity

@Sinity Sinity commented Sep 16, 2026 •

Copy link
Copy Markdown
Owner

Summary

The convergence stage engine runs off the daemon writer lease (polylogue-ssplv), the daemon's seventeen hand-rolled periodic loops are one observable runner (polylogue-74wvj), and the event bus has its first real producer/consumer pair (polylogue-14t7).

Problem

converge_batch ran entirely inside DaemonWriteCoordinator.run_sync, so Drive downloads, archive-wide materializers and the debt-drain's stage construction all held the sole writer; in a synthetic five-stage pass the writer was held 99.6% of the time. Seventeen loops each carried their own sleep/jitter/error handling, eight of them with cadences that had drifted from the registry. Nothing consumed the event bus.

Solution

  • ConvergenceStage.writer_admission is a typed field: bridged stages compute outside admission and bracket only their publication with admit_stage_write (polylogue/core/stage_admission.py); whole_execute names the residual. Converted: attachment_bytes, claude_workflow, delegation_work_evidence, sinex_publication. Residual: raw_authority_verdict_cache, standing_queries. Callers defer the pass through defer_convergence and run it after their coordinated region releases the writer.
  • polylogue/daemon/periodic.py: one runner with declared intervals, jitter, run-first vs sleep-first, recorded skips and failures, per-loop last-run/next-run/last-error surfaced through the status payload. Deleted loops: cli.py ×11 (schema_preflight_recheck, fts_merge, wal_checkpoint, status_snapshot_refresh, drive_source_catchup, heartbeat, lifecycle_heartbeat, db_optimize, convergence_check, raw_observation_convergence, health_check), blob_gc_periodic ×2, embedding_backlog ×2, secret_scan_sweep ×1. judgment_automation stays hand-rolled (async failure receipt on config reload) with a test asserting the exemption. A test holds registry cadences and loop bodies together.
  • announce_ingest_committed publishes IngestCommitted post-commit; the embedding backlog loop waits on the event or its interval, whichever first.

Measured (synthetic, 200 ms compute + 10 ms publish × 5 stages): writer held 1.050 s of 1.054 s before, 0.050 s of 1.050 s after.

Closure

write_effects.py and core/stage_admission.py are IN the derived-schema closure; the identity moves. Lands before the rebuild, never during one.

Verification

  • agentctl ... verify_quick → job 2550 succeeded (after the closure-baseline declaration 5b57142)
  • agentctl ... pytest_focused -- <touched test files + daemon cli, live watcher, live batch> → job 2545: 487 passed, 2 failed (both the master-red test_daemon_cli tests fixed forward in fix: Name hook-carrier watch sources apart from their session source #5229)
  • Worker: daemon selection 484 passed / 1 inherited failure; revision_backfill 105 passed; new test modules green; gate layering 0 violations; gate atlas green; ruff/mypy clean.

Residuals

  • Inherited at base, not touched: test_embedding_readiness.py::test_readiness_failure_branch_counts_error_message_rows, test_codex_state_live_ingest.py::test_codex_goal_materials_do_not_cross_supersede_source_roots.
  • daemon/status.py: one added key and one import (PR fix: Refuse and report unmeasured daemon HTTP and status observations #5220 overlap kept minimal); daemon/http.py untouched.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Sx3uCnEiY7MXtLt4FDEYfw

Sinity and others added 3 commits September 16, 2026 08:27
The generic stage walk ran entirely inside the writer lease: its callers
wrapped converge_batch in the write coordinator's run_sync, so a Drive
attachment download, two archive-wide graph materializations, the Sinex
transport drain and the standing-query pass all executed with the sole
archive writer held and every other writer queued behind them.

The engine now runs off the lease. ConvergenceStage.writer_admission names
how each stage reaches the writer: "bridged" stages compute, download and
drain outside admission and bracket only their short publication with
admit_stage_write; "whole_execute" is the named residual for a stage whose
compute and publication are not split yet, and the engine brackets that
stage alone. The residual is a typed field a reader can enumerate rather
than a property of the caller's control flow.

Converted to bridged: attachment_bytes (its writable connection pair now
opens inside the admitted section, because opening one requires the lease),
claude_workflow and delegation_work_evidence (both were already
compute-then-one-replacement), and sinex_publication (its lease and
persist-outcome writes are admitted separately, with the transport call
between them outside both). raw_authority_verdict_cache and standing
queries remain whole_execute.

The live-ingest and catch-up callers defer the pass with the existing
defer_convergence route and run it after their coordinated region releases
the writer, then record convergence outcomes through a separate short
admission. The pass's own writes -- hook paste enrichment and its
convergence-debt rows -- take the writer for themselves rather than
assuming one, since opening any write connection requires the lease.

Synthetic five-stage pass, 200ms compute + 10ms publish per stage:
writer held 1.050s of 1.054s before, 0.050s of 1.050s after.

polylogue-ssplv

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Sx3uCnEiY7MXtLt4FDEYfw
Sixteen declared PERIODIC services each carried their own `while True`,
and each re-implemented the same five decisions: sleep before or after the
work, how a missing archive file is skipped, how an exception is
classified, how a startup gate is awaited, and what the cadence is. They
did not agree. The visible cost was that a frozen loop and an idle one
looked identical from outside the process: nothing recorded when a loop
last ran, when it was next due, or what its last failure was.

PeriodicRunner owns those decisions once. `run_first` keeps the split
between loops that must publish before their first sleep (status snapshot,
convergence retry) and loops whose first tick is deliberately one interval
away (WAL checkpoint, daily optimize). A false `precondition` is a recorded
skip instead of a silent `continue`. An exception is recorded against the
loop and the cadence continues, except where a loop declares
`on_error="propagate"` because its failure is a signal the supervisor must
see (schema-preflight recovery). Each tick is jittered so sixteen loops
registered in one composition tick do not stay phase-locked, which means a
declared cadence is now the floor of a wait rather than its exact value.
PeriodicGate records which loops are waiting on a startup gate and since
when, so "waiting for catch-up" reads differently from "stalled".

Deleted loops (17 total): schema_preflight_recheck, fts_merge,
wal_checkpoint, status_snapshot_refresh, drive_source_catchup, heartbeat,
lifecycle_heartbeat, db_optimize, convergence_check,
raw_observation_convergence and health_check in daemon/cli.py; blob_gc and
blob_publication_reconciliation in blob_gc_periodic.py; embedding_backlog
and embedding_orphan_reconcile in embedding_backlog.py; secret_scan_sweep.
judgment_automation is not converted and stays a hand-rolled loop: it
reloads config before its sleep and writes an async failure receipt when
that reload fails, which the runner's synchronous interval contract cannot
host. A test names that exemption so it cannot be forgotten silently.

Eight PERIODIC specs had cadences that disagreed with the loop bodies they
described (fts_merge, heartbeat, db_optimize, embedding_orphan_reconcile,
blob_gc, blob_publication_reconciliation, secret_scan_sweep,
lifecycle_heartbeat). The registry now carries each loop's real interval
and a test holds the two sides together.

Per-loop last-run, next-due, last-error, skip and wakeup counts are served
through the existing status payload and as Prometheus gauges.

The `wakeup` parameter threaded through cli.py and embedding_backlog.py
here is the consumer half of the event-bus wiring that lands next.

polylogue-74wvj

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Sx3uCnEiY7MXtLt4FDEYfw
The typed in-process bus landed with full coverage of its pub/sub core but
nothing in the daemon published to it or subscribed from it, so its
ergonomics claim was untested against a live loop.

The producer is a declared post-commit write effect: an archive write that
changed sessions announces one IngestCommitted carrying the committed
session refs. Post-commit and not earlier, because a consumer woken by an
uncommitted write could read rows that still roll back; and
log-and-continue, because an announcement that fails must never fail a
committed write. A write that changed nothing announces nothing.

The consumer is the embedding backlog loop. It now waits on the event or
its declared interval, whichever comes first, and the interval stays as
its reconciliation tick: in-process delivery can be missed (no subscriber
yet, a handler that raised), so the event removes latency, never the poll
that establishes correctness. A dropped event still converges on the next
tick, and the per-loop `wakeups` counter makes a producer that never
reaches its consumer visible -- which polling alone could not show.

polylogue-14t7

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

coderabbitai Bot commented Sep 16, 2026

Copy link
Copy Markdown

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true

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.

`devtools gate schema-closure` is a ratchet over a checked-in inventory of
the modules feeding the derived schema identity, and this branch grows it
from 558 to 560.

`polylogue/core/stage_admission.py` enters because the write sections it
brackets belong to the analysis materializers, the Sinex publication
service and the live batch processor, all of which are already closure
members. `polylogue/daemon/event_bus.py` enters because the archive write
choke point now announces a committed ingest through it.

Both are load-bearing, not incidental: the seam has to be importable from
the write path it admits, and the producer has to reach the bus from the
commit it announces.

Consequence, stated plainly: the derived schema identity moves, so the
archive must reconverge through the production daemon before this is
treated as settled, and this must land before a rebuild starts rather than
during one.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Sx3uCnEiY7MXtLt4FDEYfw
@Sinity
Sinity marked this pull request as ready for review September 16, 2026 06:49
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@Sinity
Sinity merged commit 89618f9 into master Sep 16, 2026
3 checks passed
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 16, 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
🔒 Security Review ✅ Completed 2026-09-16T07:00:57.881858Z 5b57142 Draft marked ready
ℹ️ 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 deleted the feat/stage-engine branch September 16, 2026 06:49
Sinity added a commit that referenced this pull request Sep 16, 2026
#5228 added polylogue_daemon_periodic_loop_{age,due_in}_seconds, whose samples
are filtered on last_run_completed_at / next_run_at being set. `_emit_metric`
renders an empty sample list as `<name> 0`, so a daemon where no loop has
completed a pass yet publishes an age of 0s -- which reads as "just ran". The
metric added to prove a loop has not silently stopped ticking would report
perfect freshness in exactly that case.

The unlabeled zero is honest for a count and wrong for a gauge filtered on
having been measured, so omitting it is opt-out per call site rather than
changed for every caller.

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

Archive-bound writer ownership becomes total (polylogue-8qm4k): a
writable open of any archive tier without the in-process write lease is
refused at `sqlite3.connect` itself, and one write coordinator exists
per event loop.

## Problem

Lease enforcement was per connection factory. Every declared factory
asserted the lease, but ~70 direct `sqlite3.connect` sites could
reintroduce an unserialized writer invisibly (the 2026-09-05 rehearsal
death: a concurrent writer held source.db past DB_TIMEOUT during the
Drive catch-up). The standalone HTTP write runtime also built a
`DaemonWriteCoordinator` outside the per-loop registry, so a second
serialization queue could be minted on the same loop.

## Solution

- `polylogue/storage/sqlite/write_guard.py`:
`install_archive_write_guard` wraps `sqlite3.connect`; a writable open
of one of the six tier files asserts `require_write_lease`, with
`declared_unguarded_write(reason)` as the single thread-local seam for
bootstrap/test authorities. Armed inside `run_daemon_services`'
writer-boundary block.
- `register_write_coordinator`: one coordinator per loop; the standalone
runtime registers the one it builds.
- The guard's first integration run caught a real census miss: startup
durable-change-train reconciliation opened every durable tier read-write
inside `run_daemon_services` outside the lease (`daemon/cli.py` →
`durable_change_train._open_existing_tier`, 14 call sites); it now runs
under `write_lease("daemon.durable_change_train.startup")`. Three
test-side writable opens became read-only and one genuine test authority
declares itself.
- Census of every writable tier open at 89618f9 (table in the worker
report, condensed in the commit): every production daemon route already
reached the lease (via `require_write_lease`, `admit_stage_write`,
bridged stages or the HTTP write gate); CLI maintenance, MCP telemetry
and the offline generation builder are cross-process authorities outside
any in-process lease by construction.
- The #4683 locked-chunk guard still holds after #5228; a new test
reproduces the lock race with two synthetic writers on a scratch
archive.
- `docs/sqlite-connection-policy.md` gains the writable-open boundary
section.

## Closure

`daemon/write_coordinator.py` is IN the derived-schema closure; the
identity moves. Lands before the rebuild.

## Verification

- `agentctl ... verify_quick` → job 2605 **succeeded** (2591 failed on
layering/consumer-reachability/closure for the new module; fixed in
afbd03f)
- `agentctl ... pytest_focused -- <write lease/guard, convergence,
coordinator, watcher, http, daemon cli, ingest batch>` → job 2606: 511
passed, 2 failed (both the master-red test_daemon_cli tests fixed
forward in #5229)
- Worker: 240 + 137 passed over the affected files; ruff/mypy clean.

## Residuals

- The guard is armed only in the daemon writer boundary; the standalone
HTTP write runtime and MCP server do not arm it.
- `storage/index_generation.py`'s three writable generation opens are
not explicitly leased; if a daemon-side generation build reaches them
they will now be refused. Smoke this at the start of the fresh build
(polylogue-i3i5k owns the full-scale proof; 8qm4k stays open as that
gate).
- `daemon/http.py`: two lines (PR #5220 overlap).

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

https://claude.ai/code/session_01Sx3uCnEiY7MXtLt4FDEYfw


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **New Features**
- Added connection-level protection for archive SQLite databases,
requiring an active write lease before writable connections are opened.
- Added safe handling for declared administrative or maintenance writes.
- Extended daemon startup recovery so durable changes occur within the
single-writer boundary.
- Registered standalone HTTP writers with their write coordinator to
improve coordination.

- **Bug Fixes**
- Prevented uncoordinated archive writes while leaving read-only,
in-memory, and non-archive connections unaffected.

- **Documentation**
- Documented writable SQLite connection boundaries, lease requirements,
and approved bypass behavior.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Fable 5.1 <[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