Skip to content

fix: Refuse and report unmeasured daemon HTTP and status observations - #5220

Merged
Sinity merged 5 commits into
masterfrom
fix/daemon-http-status-honesty
Sep 18, 2026
Merged

Sinity merged 5 commits into
masterfrom
fix/daemon-http-status-honesty

Conversation

@Sinity

@Sinity Sinity commented Sep 16, 2026

Copy link
Copy Markdown
Owner

Summary

Five daemon HTTP/status beads where the surface reported a value it had not
measured, or refused nothing when it could do nothing.

Problem and solution, per bead

gqdfx — readiness started from True. fts_ready was initialized True,
so an absent index tier probed ready. It is now the named index_tier_missing
503 with the path in the message, added to the probe's closed taxonomy.

peo7o — reset claimed mutations it never performed. Every scope outside
RESET_SUPPORTED_SCOPES = {"session"} now refuses 400 unsupported_scope with
supported_scopes; session_id is required; Content-Length parses
defensively (400, not a 500 through daemon_safe_handler). The dead
{"ok": True} branch is gone, so no reset-all-all event can be emitted for an
unperformed mutation. _sync_run raises if a refused request ever reaches the
writer.

8r4zq (HTTP half) — unbounded mutation wait. _sync_run's mutating branch
carries _MUTATION_WAIT_TIMEOUT_S = 60 (shortenable via
X-Polylogue-Deadline-Ms, clamped) and raises DaemonMutationIndeterminate →
503 mutation_indeterminate + Retry-After. Deliberately indeterminate, not
cancelled: the submitted write may still land.

gmskd — two HTTP status lines in one SSE body. A stray
@daemon_safe_handler (left where a deleted section header had been) let
_send_json(503) write a second status line into a text/event-stream body.
_stream_events now ends the stream with an SSE error frame. Tests assert
decorator depth is exactly 1 and validate the actual bytes: exactly one
HTTP/1. line, every body line valid SSE framing.

31h8l — evidence summary had no outcome. The route carries an outcome
envelope via decide_outcome; an unreadable session_links yields
degraded/lineage_refs_unreadable plus lineage_refs_authoritative: false.

xvwpi — fabricated zeros across the status surface. blob_dir_size_bytes
literal 0 → None in all three producers; disk_free 0-on-OSError → None;
metrics.py all({}) → no series plus polylogue_probe_unmeasured{probe=...},
same for failed convergence_debt and hook_flow probes; build_info dirty
false-for-unread → "unknown"; LiveCursorSummary all-zero on sqlite3.Error
→ typed available=false/unavailable_reason; missing
progress_classification → unknown, not healthy. The suppressed
_check_daemon_liveness publishes daemon_liveness_state and folds
measured/unmeasured into the ETag, so a 304 cannot hide a failed probe.

Executed mutation

Both restorations, on the fixed tree:

E       assert <HTTPStatus.OK: 200> == <HTTPStatus.SERVICE_UNAVAILABLE: 503>
E       assert 'polylogue_f...ll_present 1' not in '# HELP poly...issing"} 0\n'
FAILED tests/unit/daemon/test_health_contract.py::...::test_readiness_refuses_when_index_tier_is_absent
FAILED tests/unit/daemon/test_unmeasured_observations.py::test_uninspected_fts_triggers_do_not_report_all_present
======================== 2 failed, 1 warning in 13.43s =========================

Both reverted; files byte-identical to the committed versions.

Verification

  • Focused run across all ten touched selectors — 313 passed, exit 0
    (receipt 20260916T015503Z-focused-test-1950537-34f34cca)
  • devtools test tests/unit/daemon/ tests/unit/operations/test_daemon_status.py
    — 2281 passed after fixes; rerun of the affected set 299 passed, exit 0
  • devtools verify --quick — exit 0, 21 gates ok
  • devtools render all --check — exit 0, grep -c "out of sync" = 0

devtools schema closure reports out for every changed file — confirmed,
not assumed. Nothing here is a rebuild-boundary hazard.

Residuals, stated honestly

  • q54dt is partial. The honest-total half is done: a truncated page now
    publishes total: null, total_is_exact: false, total_lower_bound: n
    instead of its own page size. The performance half needs declared operations
    for /api/paste-browser and /api/attachments, outside this write scope.
  • 7mgx is not done. The bypass is real and current —
    envelope_paste_spans(text, has_paste) ignores has_paste at all four call
    sites and durable index.paste_spans still has zero read sites. Consuming
    the canonical table needs a storage read surface. Landed here:
    paste_span_localization(spans, has_paste) returning
    localized/none/unlocalized, so the "stored evidence says paste,
    derivation cannot place it" case is nameable; the four http.py payloads do
    not yet publish it.
  • xvwpi's _status_ok returning ok: true with
    include_archive_readiness=False is untouched. Flipping it changes the
    operator-facing meaning of ok on the default compact path for every
    surface, and the payload already publishes
    archive_readiness: {checked: false, reason: ...}. Owner decision.
  • 8r4zq's non-HTTP unbounded waits in convergence.py,
    embedding_owner.py, write_coordinator.py remain open.
  • tar1n's route-generation half is not done and feat: Enforce daemon route declaration completeness with proven examples #5189 is not regressed.
    DAEMON_ROUTE_DECLARATIONS holds 4 executable declarations against 76
    metadata-only contracts; each promotion needs a declared domain_operation
    plus contract models in operations/ and surfaces/payloads.py. No
    hand-written /api route was added.
  • docs/plans/sqlite-degradation-baseline.json: the live-cursor anchor digest
    moved (0d9b797… → e935097…) because its handler source changed. Same
    site, count unchanged at 243.

🤖 Generated with Claude Code

https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK

@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.

@coderabbitai

coderabbitai Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

Next included review available in 59 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: 94777898-0c60-466b-8cdf-5ee3800630f3

📥 Commits

Reviewing files that changed from the base of the PR and between 89618f9 and a0e9eec.

📒 Files selected for processing (15)
  • docs/daemon.md
  • docs/plans/sqlite-degradation-baseline.json
  • polylogue/daemon/events_http.py
  • polylogue/daemon/healthz.py
  • polylogue/daemon/http.py
  • polylogue/daemon/metrics.py
  • polylogue/daemon/status.py
  • polylogue/daemon/status_snapshot.py
  • polylogue/daemon/webui_data.py
  • polylogue/operations/daemon_status.py
  • tests/unit/daemon/test_daemon_http.py
  • tests/unit/daemon/test_events_sse_framing.py
  • tests/unit/daemon/test_health_contract.py
  • tests/unit/daemon/test_http_bounded_mutations.py
  • tests/unit/daemon/test_unmeasured_observations.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 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-16T02:06:26.307453Z e10bdf8 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 added a commit that referenced this pull request Sep 16, 2026
…#5228)

## 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 #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 #5220 overlap
kept minimal); `daemon/http.py` untouched.

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

https://claude.ai/code/session_01Sx3uCnEiY7MXtLt4FDEYfw

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Sinity and others added 4 commits September 16, 2026 08:50
The readiness probe left fts_ready at True and only reassigned it inside
'if dbf.exists()', so a fresh start, a wrong archive root, or a mid-rebuild
window answered 200 {'status': 'ready', 'fts': null} and orchestrators
routed traffic to a daemon with no archive. An unperformed measurement is
now reported as the named 'index_tier_missing' refusal.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
POST /api/reset defaulted scope to 'all' while only 'session' was
implemented, so the default body answered 200 with detail 'reset all - no
sessions matched' and emitted a reset event having touched nothing; a
malformed Content-Length raised into a 500. Both are now typed 400s.

_handle_events carried two @daemon_safe_handler decorators, and the JSON
error path wrote a second HTTP status line into an open text/event-stream
body. A mid-stream failure now terminates the stream with an SSE error
frame.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
Bounds every mutating HTTP route's wait on its writer future with the
request deadline and answers a typed mutation_indeterminate instead of
blocking forever behind a lease hold; carries an outcome envelope on the
session evidence-summary route so an unreadable session_links reports
degraded rather than an empty lineage; stops the paste-browser and
attachment-library walks from publishing their own page size as the archive
total; and replaces fabricated status literals (blob-dir size 0, disk-free 0
on OSError, all({}) FTS triggers present, dirty=false for an unread build,
an all-zero live-cursor summary after a read failure, a missing progress
classification rendered healthy, uninspected embedding counts) with explicit
unknowns, including in the status ETag material.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
The sqlite-degradation ratchet anchors each admitted site by the sha1 of
its normalized handler source, so making the live-cursor read failure
typed moved its digest. Same site, same count.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
#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
Sinity merged commit 569d7c4 into master Sep 18, 2026
3 checks passed
@Sinity
Sinity deleted the fix/daemon-http-status-honesty branch September 18, 2026 20:36
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]>
Sinity added a commit that referenced this pull request Sep 18, 2026
…ute (#5233)

## Summary

One intake route (polylogue-v4dcc, operator ruling 2026-09-16): the
fair-intake dispatcher admits whole pages as one live ingest batch, and
the watcher's chunk/catch-up/debounce/failed-retry route is deleted.
Measured 3.0x end-to-end on a synthetic 500-file corpus through the
production dispatcher.

## Problem

`polylogued run` has intaked through `FairIntakeDispatcher` one file per
`ingest_files` call since #4913, so every per-batch fixed cost
(retention scan, six-tier bootstrap, convergence pass, cursor
initialise, one writer hold) was paid per file, and the parse-stage
prefetch received one path at a time. The watcher's own 4-file chunk
route was still in the tree, exercised only by tests and the perf
harness, and every campaign number measured that dead route.

## Solution

- `FairIntakeDispatcher._service_class` plans a page against the class
deficit (bytes-aware, stops at the class share, never splits below one
file) and calls one `admit_page`; adapters without it still get per-item
`admit`.
- `FileIntakeAdapter.admit_page`: authority gate → `cursor.initialize` →
`select_ingest_candidates` → one `ingest_files` batch → one embedding
and one session-profile convergence for the page → one outcome per path
from `LiveBatchMetrics` (`succeeded_paths`, new
`excluded_paths`/`deferred_paths`, `failed_paths`), so deficit,
retry_after and isolation stay per item; `AdmissionOutcome.DEFERRED` is
new; `MultiplexIntakeAdapter` splits a page along source ownership;
`LiveParseStage` is warmed with the page.
- Deleted (ledger in the commit, pinned by
`tests/unit/architecture/test_one_intake_route.py`): `_catch_up` and its
planner/candidate/chunk/pledge helpers, `_periodic_catch_up`, the
debounce queue, the failed-retry scan, `_flush_convergence_off_writer`,
`_stage_write_admission`, `intake_hints_only`, `catch_up_active`,
`debounce_s`, the `_CATCH_UP_*` constants, and `run_live_watcher` (no
production caller). The unclaimed-file sweep moved into the dispatcher's
discovery walk; cursor comparison and reconciliation scope became
`LiveWatcher.select_ingest_candidates`.
- Kept deliberately: the writer hold around `_ingest_files`, now per
page rather than per file. Removing it refuses the daemon's own ingest
because `ingest_files`' ops-tier writes are not self-admitting
(follow-up bead filed).
- Discovery follows directory symlinks with cycle detection over
resolved real paths (polylogue-lu1dk, a regression since #4913 the
deleted scan had masked): a cycle or dangling link is a typed
`daemon.intake.discovery_failed` per path, a link into the archive root
is never followed, and source ownership matches the lexical path as well
as the resolved one (a second bug: linked files were discovered, then
disowned).
- New events: `daemon.intake.page_refused`,
`daemon.intake.item_retryable`.
- Harness: `/realm/tmp/work/perf-2026-09-15/real_ingest_driver.py`
gained `--dispatcher`, `--admit-per-item`, `--synthetic N`,
`--budget/--page-size`.

## Measured (500 synthetic claude-code files, 8.44 MB, same host, 17
dispatcher passes)

| shape | wall | end-to-end MB/s | files/s | peak RSS |
|---|---|---|---|---|
| per-item admission (base) | 155.28 s | 0.054 | 3.22 | 180 MB |
| page admission (after) | 51.66 s | 0.163 | 9.68 | 237 MB |

Receipts under `/realm/tmp/work/intake-route-perf/`. Run in the
foreground because host backpressure had frozen the bulk pool for ~50
min; rerunnable through the `scratch` operation.

## Closure

`sources/live/{watcher,batch,metrics,parse_prefetch}.py` are IN the
derived-schema closure; the identity moves. Lands before the rebuild,
never during one.

## Verification

- `agentctl ... verify_quick` → job 2637 **succeeded** (2634 failed on
two stale test typings, fixed in bd15f51)
- `agentctl ... pytest_focused -- <13 touched test files + fair intake +
daemon cli>` → job 2635: 518 passed, 3 failed (the two master-red
test_daemon_cli tests fixed in #5229 and the inherited codex
goal-materials test); the two fixed test files re-ran 92/92 green
- Worker: 518 passed / 3 inherited failures over the 13 touched files;
`gate atlas`, `gate layering`, `gate patterns` green; ruff/mypy clean.

## Residuals (filed as beads)

- Ops-tier writes inside `ingest_files` are not self-admitting (hold
stays per page).
- Dead `catch_up_cycle` readers, inert `--debounce-s`,
`catch_up_complete` now meaning "watcher ready", coarser
unreadable-subtree accounting, Claude sidecar forced reparse gone.
Sequenced after PR #5220 (daemon/status.py).

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

https://claude.ai/code/session_01Sx3uCnEiY7MXtLt4FDEYfw

---------

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