Repository navigation
feat(daemon): Declare event contracts and qualify route latency with drops - #5349
Conversation
… cursor Two halves of the same statement about the daemon event channel: an advertised topic now has a declared contract, and a replay gap is an explicit resync rather than a silently short answer. Topic contracts (polylogue-20d.13.5): EVENT_SPECS declares, per advertised kind, the object/source refs, the archive and ledger tiers those refs resolve against, the resume cursor, the wire frame, the producer transaction phase, the exhaustive payload projection, the audience, and the single production emitter. GRANULAR_EVENT_KINDS is derived from the registry so advertising a topic and declaring its contract are one act. Ledger bound and cursor refusal (polylogue-20d.13.6): prune_daemon_events is the named enforcement point, run inside every emit transaction. DaemonEventRetention declares no default bound on purpose -- no measurement of the real emission rate exists, so an unbounded ledger reports itself unbounded instead of carrying an invented number. query_events_since now returns a typed DaemonEventPage whose status is decided once, inside the reader, so a second caller cannot bypass the retained-minimum check; a cursor below the retained minimum, or ahead of a reset ledger, yields a snapshot-shaped resync envelope with a reason. The poll shape reports outcome "degraded" and the SSE shape writes one `event: snapshot` frame, reusing the existing backpressure envelope rather than teaching clients a second signal. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015WCh9YW3cRfsg3CZBKU7Fq
… drops Route latency had no declared contract and no honest denominator. Both are the same story about one file, so they land together. The contract (polylogue-jtwu.1): RouteObservationSpec names a route once -- surface, route, verb, declared phases, sampling disposition -- and RouteObservationReceipt carries the evidence for one invocation: build, archive and workload scope, request id plus run id and its parent, daemon-versus-direct, named phases with wall and CPU time, response size and status, evidence refs, and which measures were unavailable rather than zero. to_workload_receipt is the adapter onto WorkloadReceipt that polylogue-jtwu's DESIGN asks for, and route-observation now appears in the declared measurement-path inventory instead of being a private path. The receipt's projection rides in the existing route_observations row's attributes, so compute_latency_percentiles and `polylogue analyze latency` keep reading the same rows; the persisted row and the workload receipt join on the receipt's correlation refs. The denominator (polylogue-jtwu.2): every path that loses an observation -- no archive root, missing ops tier, a failed emit, the writer's own retention and row-cap prune, an unsampled spec -- now increments a counted reason instead of only logging. compute_latency_percentiles requires a RouteObservationDrops argument with no default and returns a RouteLatencyReport, so a p50/p95 cannot be produced without stating what the sample lost. Each bucket carries its own dropped_count and sample completeness, and a reader in a different process from the emitters reports its accounting as incomplete rather than as zero drops -- zero and unknown are different answers. `polylogue analyze latency` prints the drop line beside the percentiles in both output formats. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015WCh9YW3cRfsg3CZBKU7Fq
|
Warning Review limit reachedNext included review available in 47 minutes. View limit detailsLimit 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. Review configuration: ⚙️ Run configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Advanced Run ID: 📒 Files selected for processing (9)
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. Comment |
|
You have reached your Codex usage limits for security reviews. Please try again later. |
7a0c2f9 to
9f420bb
Compare
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Re-verified after a second rebase onto
Branch force-pushed |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9f420bb2b2
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
…#5785) ## Summary This PR salvages ChatGPT fleet worker 12's Codex-debt batch (beads `polylogue-1tyq5.55`, `.56`, `.60`, `.62`; 72 findings) and turns it into verified changes. Five fixes land with regression tests that fail on master. The worker's sixth fix (a negative completion cache) was dropped, and its health-check fix was replaced with a stricter version. ## Problem - **55.05** `health_check()` raises `SchemaSkew` when a tier is on another version. The tier probe opened the file with schema admission but caught only `sqlite3.Error`, so the probe crashed instead of reporting an error check. - **55.10** `list_assertion_candidate_reviews(limit=10)` computed `total` with a second, unbounded review read. That read ran the per-candidate judgment lookup (N+1) across the whole candidate history. - **60.01** `--stream --limit N` followed continuations with no limit. The final page could therefore fetch rows past N, and the resulting `result_too_large` refusal was re-raised for continuations instead of narrowing the page. - **60.20** `raw-authority-frontier` printed the all-state `plan_count` as `obligations=`, including terminal `superseded` plans. - **62.01** Named `analyze postmortem|portfolio|cost-outlook` computed the inherited root format but rendered from the local `None` format, so they printed text when JSON was requested. ## Solution - `_archive_tier_readiness_check` keeps admission, passes `tier=`, and reports any `SchemaRefusalError` as an ERROR check. The worker's `validate_schema=False` version was replaced because it compared only `user_version`, so a derived tier with a stale identity at the right version was reported OK. `test_health_check_reports_derived_identity_skew` fails on the worker's version. - `_archive_list_assertion_candidate_reviews` returns `(page, count)` from one read transaction. The count comes from `count_assertion_claims`, which now accepts `target_ref` and `statuses=None`. The count includes expired claims, matching the review read model. - `_read_session_windows` sends the remaining bound with every continuation. An oversized resumed page halves in place, and later pages keep the narrowed bound, because `session.read` refuses a continuation that widens its window. - The plain frontier line says `plans=` (the neutral label the finding offered). - `analyze_verb` renders every branch from the effective format: the local format if given, otherwise the root format, normalized with `normalize_output_dialect`. An explicit local `--format` still wins. - **62.16 dropped.** The deleted-candidate case was already fixed on master in 8cb1133 (#5722): each successful answer, empty or not, removes the cached matches for the refreshed prefix. The worker added a cache of empty answers that offline completion would treat as authoritative. Nothing invalidated it except a later contradicting daemon answer or the 24h TTL, and an offline reader cannot tell whether the archive changed without opening it. The cold-cache message on a miss is displayed rather than inserted, and it is accurate. - Two stale tests in `test_archive_query.py` expected `_emit_stats` to exit 0 over a converging archive. #5700 made that outcome degraded with a nonzero exit, so the tests now expect that. They failed on master before this PR. ## Verification - `agentctl job start polylogue verify_quick --workspace /realm/worktrees/salvage-w12 --wait` → job 2374: `verify: PASSED exit=0` (head 331a204ddd, pre-rebase; the rebase onto 4501f13 touched none of these files). Earlier job 2368 failed on format and mypy in the worker's commit; commit 3561647 fixes both. - `agentctl job start polylogue pytest_focused --workspace /realm/worktrees/salvage-w12 --wait -- tests/unit/api/test_archive_health_tier_skew.py tests/unit/api/test_assertion_candidate_review_count.py tests/unit/cli/test_analyze_named_projection_format.py tests/unit/cli/test_raw_authority_frontier_output.py tests/unit/cli/test_session_window_continuation_bounds.py tests/unit/cli/test_analyze_projections.py tests/unit/cli/test_archive_query.py tests/unit/cli/test_completion_daemon_boundary.py tests/unit/api/test_assertion_candidate_queue_health.py` → job 2405 at head 3561647: `devtools test: PASSED exit=0 diagnosis=pytest_passed`, 168 passed. - Anti-vacuity: the new tests were run on an origin/master checkout (job 2351). Every fix test failed there (11 failures, plus the 2 stale stats tests). The one exception is `test_named_analysis_local_format_overrides_inherited_json`, a precedence guard that should pass on both. Job 2355 ran the health tests against the worker's `validate_schema=False` variant, and the derived-identity case failed (status OK instead of ERROR). - Inherited, not addressed here: `tests/unit/api/test_facade_contracts.py::test_archive_facet_buckets_count_unique_sessions_for_duplicate_hits` and `::test_no_undiscovered_async_methods` fail identically on master 4501f13 (job 2401). ## Self-review - **Sibling sites.** The review count had one caller, and `judge.py` consumes the facade's `total`. The daemon health endpoint has its own tier checks and is out of scope. The other `validate_schema=False` opens are reset, paths and export tools, not health reporting. - **Cancellation and loops.** The window retry loop is bounded by halving to 1 and then re-raising. No new loop reads without a bound. - **Unbounded reads.** This PR removes one, the unbounded review read, and adds none. - **Fail-open fallbacks.** The health probe now reports refusals instead of hiding them. The dropped completion change would have turned a cache miss into an authoritative empty answer. - **Compatibility shims.** None. `count_assertion_claims` gained optional parameters, and its existing `annotations/join.py` callers are unchanged. - **Removed symbols.** No production symbol was removed. The `test_codex_debt_w12.py` files were renamed by behaviour. - **Production route.** The API tests go through `Polylogue.health_check` and `list_assertion_candidate_reviews` on bootstrapped archives. The CLI tests go through `cli` or the real command with a mocked transport (`dispatch_read`) and the real `lower_session_read`. ## Derived-identity closure `polylogue/storage/sqlite/archive_tiers/user_write.py` is a member of `docs/plans/schema-closure-baseline.json`, so this PR moves the candidate derived identity. Closure membership does not grow (the `schema-closure` gate passed). No other changed production file is a member. ## Per-finding dispositions Counts: 5 fixed, 60 fixed-already, 2 stale, 1 refuted, 4 not reached. The not-reached findings (55.18, 55.22, 60.12, 62.08) stay open on their beads. | key | disposition | evidence | test | | --- | --- | --- | --- | | 55.01 #4326 `polylogue/api/__init__.py:51` | refuted | `polylogue/api/parity.py:472–491`: The explicit context-pack exclusion includes topic_pack; composed builders do not own a separate operation identity under this contract. | — | | 55.02 #5381 `polylogue/api/archive.py:410` | fixed-already | `polylogue/api/archive.py::_read_session_transcript_page`: The normalized offset is used for both the read and returned page coordinates. | — | | 55.03 #4287 `polylogue/api/archive.py:818` | fixed-already | `polylogue/api/archive.py::_archive_list_summaries_with_post_filters`: Effective specification pagination is restored after content filtering. | — | | 55.04 #4295 `polylogue/api/archive.py:871` | fixed-already | `polylogue/api/archive.py::_archive_aggregate_facet_families / keyed`: Repeated facet bucket counts are added across chunks rather than overwritten. | — | | 55.05 #4871 `polylogue/api/archive.py:1114` | fixed | `_archive_tier_readiness_check` keeps admission and reports `SchemaRefusalError` as ERROR | `api/test_archive_health_tier_skew.py` | | 55.06 #4192 `polylogue/api/archive.py:1152` | fixed-already | `polylogue/api/archive.py::_archive_list_assertion_claims`: Uses _readable_user_tier rather than an index-backed query runner. | — | | 55.07 #4794 `polylogue/api/archive.py:1546` | fixed-already | `polylogue/storage/sqlite/connection_profile.py::_install_progress_handler`: Read frames install an expiry/cancellation-aware SQLite progress handler, including work using the bound connection. | — | | 55.08 #4552 `polylogue/api/archive.py:1691` | fixed-already | `polylogue/api/archive.py::_archive_list_assertion_candidates`: Calls the canonical actionable queue reader rather than the expiry-retaining review reader. | — | | 55.09 #4295 `polylogue/api/archive.py:3066` | fixed-already | `polylogue/api/archive.py::pathology_report`: replace(spec, limit=None, offset=0) removes query pagination from the scope denominator. | — | | 55.10 #4295 `polylogue/api/archive.py:3448` | fixed | one read transaction; scalar `count_assertion_claims` replaces the second unbounded review read | `api/test_assertion_candidate_review_count.py` | | 55.11 #4552 `polylogue/api/archive.py:3453` | fixed-already | `polylogue/api/archive.py::_readable_user_tier`: Missing/non-file and unreadable durable-tier failures retain typed unavailability rather than returning an empty list. | — | | 55.12 #4295 `polylogue/api/archive.py:3503` | fixed-already | `polylogue/cli/commands/judge.py::judge_command`: Preserves authoritative review totals; additional client-side time filtering reads the complete selection before recounting. | — | | 55.13 #5302 `polylogue/api/archive.py:4021` | fixed-already | `polylogue/operations/facade_writers.py::record_manual_continuation_product`: Invokes _resolve_session_graph before committing the manual link, refreshing topology projections. | — | | 55.14 #5302 `polylogue/api/archive.py:4021` | fixed-already | `polylogue/operations/facade_writers.py::record_manual_continuation_product`: Invokes the canonical cycle/quarantine pass instead of leaving the direct insert unchecked. | — | | 55.15 #4180 `polylogue/api/archive.py:5081` | fixed-already | `polylogue/api/archive.py::search_session_hits`: Passes unresolved spec.to_plan() to failure-classifying search_hits_for_plan. | — | | 55.16 #4180 `polylogue/api/archive.py:5512` | fixed-already | `polylogue/api/archive.py::filter`: Constructs SessionFilter without vector-provider initialization. | — | | 55.17 #5362 `polylogue/api/archive.py:5557` | fixed-already | `polylogue/api/archive.py::query_sessions`: Includes title_is_synthesized from display_label_source. | — | | 55.18 #5370 `polylogue/api/archive.py:5561` | not reached | `polylogue/api/archive.py::read_transcript_window`: Anchor lookup and transcript-window reading still have separate read lifetimes. Single-snapshot implementation remains necessary; no fix written. | — | | 55.19 #5370 `polylogue/api/archive.py:5563` | fixed-already | `polylogue/api/archive.py::read_transcript_window`: Explicitly rejects around combined with transcript filters. | — | | 55.20 #4357 `polylogue/api/archive.py:6330` | fixed-already | `polylogue/api/archive.py::get_effective_context`: Canonical ID resolution plus read_summary replaces full transcript hydration for the existence check. | — | | 55.21 #4261 `polylogue/api/insights.py:753` | fixed-already | `polylogue/api/insights.py::cost_outlook`: Restricts the cost query to the selected cycle's since/until rather than the whole archive. | — | | 55.22 #5007 `polylogue/api/insights.py:916` | not reached | `polylogue/api/insights.py::get_ancestors/get_descendants/get_siblings/get_thread/get_logical_session`: Exhaustive relationship helpers still consume the default topology page without exhaustion. No implementation written. | — | | 55.23 #5007 `polylogue/api/insights.py:927` | fixed-already | `polylogue/api/insights.py::_resolve_for_topology`: Uses canonical archive resolve_session_id, preserving native-ID resolution. | — | | 55.24 #4799 `polylogue/api/insights.py:1030` | fixed-already | `polylogue/api/insights.py::compact_lineage`: Both public page defaults use DEFAULT_LINEAGE_PAGE_LIMIT. | — | | 55.25 #4539 `polylogue/api/search_envelope_builder.py:138` | fixed-already | `polylogue/api/search_envelope_builder.py::build_search_envelope_for_spec; polylogue/operations/authority.py::authority_for_config`: The envelope delegates authority resolution to the owner that resolves the active archive root. | — | | 56.01 #4603 `polylogue/api/search_envelope_builder.py:148` | fixed-already | `polylogue/api/search_envelope_builder.py::build_search_envelope_for_spec`: Reports matched=total and analyzed=len(hits). | — | | 60.01 #5337 `polylogue/cli/archive_query.py:360` | fixed | continuations carry the remaining bound; resumed pages halve in place, never widen | `cli/test_session_window_continuation_bounds.py` | | 60.02 #4402 `polylogue/cli/archive_query.py:390` | fixed-already | `polylogue/surfaces/cursor_identity.py::search_cursor_request_identity`: Presentation-only parameters are excluded from cursor identity. | — | | 60.03 #4987 `polylogue/cli/archive_query.py:1913` | fixed-already | `polylogue/cli/render/rows.py::project_payload`: Outcome is preserved independently of selected result fields. | — | | 60.04 #5249 `polylogue/cli/click_app.py:479` | fixed-already | `polylogue/cli/query_contracts.py::QueryOutputSpec.from_params`: Explicit file destination and path retain typed FILE identity even for reserved-looking filenames. | — | | 60.05 #4337 `polylogue/cli/click_app.py:554` | fixed-already | `polylogue/cli/query_group.py::_asks_for_query_workflow_help`: The advertised find help route is handled while respecting option arity. | — | | 60.06 #4340 `polylogue/cli/click_app.py:628` | fixed-already | `polylogue/cli/click_app.py::main`: Runtime checks run inside guarded_entry passed to run_machine_entry. | — | | 60.07 #4651 `polylogue/cli/click_command_registration.py:192` | fixed-already | `polylogue/cli/commands/insights_alias.py`: The existing root group exposes only Fable, not the entire operational group. No alias is introduced by this batch. | — | | 60.08 #4580 `polylogue/cli/click_command_registration.py:192` | fixed-already | `polylogue/cli/commands/insights_alias.py`: The existing narrow route preserves the promised Fable-packet command. No alias is introduced by this batch. | — | | 60.09 #4550 `polylogue/cli/click_command_registration.py:192` | fixed-already | `polylogue/cli/commands/insights_alias.py::_register_fable_packet`: Registers only the intended Fable command rather than the entire operational group. | — | | 60.10 #4698 `polylogue/cli/commands/check.py:41` | fixed-already | `polylogue/scenarios/operational_surfaces.py`: Authored doctor scenarios use current routes without the retired repair flags. | — | | 60.11 #5349 `polylogue/cli/commands/diagnostics.py:992` | fixed-already | `polylogue/cli/commands/diagnostics.py::latency_command`: The empty-bucket branch still renders incomplete-drop accounting. | — | | 60.12 #5639 `polylogue/cli/commands/import_command.py:117` | not reached | `polylogue/cli/commands/import_command.py::_wait_for_demo_ingest`: Owner completion accounting improved, but a degraded receipt still causes immediate failure instead of waiting through the remaining convergence budget. No implementation written. | — | | 60.13 #5314 `polylogue/cli/commands/insights.py:147` | fixed-already | `polylogue/scenarios/insight_surfaces.py; tests/unit/cli/test_stdout_stderr_split.py`: Inventories use current rather than retired commands. | — | | 60.14 #4678 `polylogue/cli/commands/insights.py:224` | fixed-already | `polylogue/cli/commands/insights.py::_render_status_plain`: Plain output includes degraded counts and fallback reasons. | — | | 60.15 #4292 `polylogue/cli/commands/insights.py:450` | fixed-already | `polylogue/cli/commands/insights.py::_packet_json_document`: Dataclass tuples are lowered to JSON-native arrays. | — | | 60.16 #5311 `polylogue/cli/commands/judge.py:417` | fixed-already | `polylogue/cli/commands/judge.py::judge_command`: Interactive approval forwards the evidence digest and checks failed counts before printing success. | — | | 60.17 #4133 `polylogue/cli/commands/maintenance/_blob_gc.py:81` | fixed-already | `polylogue/cli/commands/maintenance/_blob_gc.py::blob_gc_command`: Blocked previews set ok=false and exit nonzero in both formats. | — | | 60.18 #4955 `polylogue/cli/commands/maintenance/_blob_gc.py:211` | stale | `polylogue/cli/commands/maintenance/_blob_gc.py`: gc_recover_command is gone; the remaining command is preview-only. | — | | 60.19 #5345 `polylogue/cli/commands/maintenance/_blob_integrity.py:52` | stale | `polylogue/cli/commands/maintenance/_blob_integrity.py`: _submit_replace_from_source and its cited relative-output forwarding route are gone. | — | | 60.20 #5350 `polylogue/cli/commands/maintenance/_raw_identity.py:47` | fixed | plain line labels the all-state count `plans=` | `cli/test_raw_authority_frontier_output.py` | | 60.21 #5301 `polylogue/cli/commands/maintenance/_raw_identity.py:59` | fixed-already | `polylogue/cli/commands/maintenance/_raw_identity.py::raw_authority_blockers_command`: Paginated public blocker inspection exposes expected/observed evidence. | — | | 60.22 #4955 `polylogue/cli/commands/maintenance/_raw_identity.py:247` | fixed-already | `polylogue/cli/commands/maintenance/_raw_identity.py::raw_authority_blocker_resolve_command`: Checks the affected count rather than presenting no-op resolution as an applied mutation. | — | | 60.23 #4824 `polylogue/cli/commands/maintenance/_verify_archive.py:85` | fixed-already | `polylogue/cli/commands/maintenance/_verify_archive.py::verify_archive_command`: Source-frontier construction is conditional on selected source-conservation work. | — | | 60.24 #5491 `polylogue/cli/commands/paths.py:75` | fixed-already | `polylogue/cli/commands/paths.py::_raw_materialization_readiness`: Propagates the selected index path through archive_debt_list(index_db_path=...). | — | | 60.25 #5353 `polylogue/cli/commands/status.py:342` | fixed-already | `polylogue/operations/daemon_status.py::produce_operation_status`: Merges runtime collection metadata into pinned readiness components. | — | | 62.01 #5422 `polylogue/cli/query_verbs.py:2434` | fixed | `analyze_verb` renders from the effective (normalized, inherited) format | `cli/test_analyze_named_projection_format.py` | | 62.02 #5007 `polylogue/cli/read_views/lineage.py:78` | fixed-already | `polylogue/cli/read_views/lineage.py`: The replacement operation-backed route uses the resolved target; the old _run path is gone. | — | | 62.03 #5407 `polylogue/cli/read_views/messages.py:226` | fixed-already | `polylogue/cli/read_views/messages.py::_write_messages_file`: Resolves symlink output before choosing the staging sibling. | — | | 62.04 #5407 `polylogue/cli/read_views/messages.py:227` | fixed-already | `polylogue/cli/read_views/messages.py::_write_messages_file`: Flushes and fsyncs the staged descriptor before replacement and synchronizes the directory. | — | | 62.05 #4291 `polylogue/cli/read_views/query_set.py:196` | fixed-already | `polylogue/cli/read_views/correlation.py::run_read_correlation`: Renders a string and delivers it through deliver_content instead of an uncaptured console-only renderer. | — | | 62.06 #5374 `polylogue/cli/read_views/session_evidence.py:180` | fixed-already | `polylogue/cli/read_views/session_evidence.py::_read_evidence_window`: Projection body coordinates take precedence before operation lowering. | — | | 62.07 #5520 `polylogue/cli/read_views/standard.py:99` | fixed-already | `polylogue/cli/query_output.py::deliver_query_output`: File delivery retains secret-candidate scanning. | — | | 62.08 #5520 `polylogue/cli/read_views/standard.py:99` | not reached | `polylogue/cli/read_views/standard.py::run_read_summary_or_transcript; polylogue/cli/archive_query.py::_read_session_windows`: The standard file path still accumulates the transcript and buffers its rendered document. End-to-end operation-backed streaming is not implemented. | — | | 62.09 #5520 `polylogue/cli/read_views/standard.py:99` | fixed-already | `polylogue/cli/read_views/standard.py::run_read_summary_or_transcript`: Forwards a typed FILE QueryDeliveryTarget, preserving reserved-looking filenames. | — | | 62.10 #5520 `polylogue/cli/read_views/standard.py:99` | fixed-already | `polylogue/operations/daemon_reads.py::_session_identity_projection; polylogue/cli/archive_query.py::_session_message_text`: The operation preserves tool_input; rendering includes structured tool input and omits reasoning blocks. | — | | 62.11 #5520 `polylogue/cli/read_views/standard.py:99` | fixed-already | `polylogue/cli/archive_query.py::_read_session_windows`: Initial oversized pages already halve their bound at the inspected base. This batch additionally fixes resumed-page narrowing under 60.01. | — | | 62.12 #5266 `polylogue/cli/session_rows.py:141` | fixed-already | `polylogue/cli/session_rows.py::_query_page_with_authority`: Synthetic missing-session selections explicitly include next_offset=None. | — | | 62.13 #5426 `polylogue/cli/shared/machine_errors.py:233` | fixed-already | `polylogue/cli/shared/machine_errors.py::error_archive_writer_ownership`: Undecidable ownership has a separate remedy that does not assert an observed resident daemon. | — | | 62.14 #5426 `polylogue/cli/shared/machine_errors.py:285` | fixed-already | `polylogue/cli/shared/machine_errors.py::extract_command`: Recognizes --output-format as a value-bearing option. | — | | 62.15 #5545 `polylogue/cli/shell_completion_values.py:117` | fixed-already | `polylogue/cli/shell_completion_values.py::_cached_value_matches`: Session IDs match native-ID and title substrings. | — | | 62.16 #5545 `polylogue/cli/shell_completion_values.py:135` | fixed-already | deleted-candidate case fixed by 8cb1133 (#5722): every successful answer prunes the refreshed prefix; negative-answer cache declined (see Solution) | — | | 62.17 #5545 `polylogue/cli/shell_completion_values.py:145` | fixed-already | `polylogue/cli/shell_completion_values.py::_remember_completion_values`: A per-archive map retains more than the most recent archive. | — | | 62.18 #5545 `polylogue/cli/shell_completion_values.py:157` | fixed-already | `polylogue/cli/shell_completion_values.py::_remember_completion_values`: Removes an existing value before reinsertion at the retention tail. | — | | 62.19 #5545 `polylogue/cli/shell_completion_values.py:178` | fixed-already | `polylogue/cli/shell_completion_values.py::_remember_completion_values`: Global serialized-byte eviction precedes publication. This batch includes new empty observations in that accounting. | — | | 62.20 #5545 `polylogue/cli/shell_completion_values.py:181` | fixed-already | `polylogue/cli/shell_completion_values.py::_remember_completion_values`: flock serializes the full cache read-modify-write sequence. | — | | 62.21 #5382 `polylogue/cli/write_authority.py:104` | fixed-already | `polylogue/storage/sqlite/write_lease.py::arm_write_lease_enforcement`: Locked process-wide user/suppressor counts make arming overlap-safe. | — | ## Residuals - The four not-reached findings remain open. - Changing `user_write.py` moves the derived identity, so this PR has to land before a rebuild starts. - The two `test_facade_contracts.py` failures are inherited from master. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_015pdKaZWyGe6Ngvsz468dzg --------- Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
|
Closing out open Codex review threads on this PR (evidence checked against master at ef10e59):
Resolving the fixed, stale and refuted threads; tracked threads stay open. |
|
Closing out open Codex review threads on this PR (evidence checked against master at 64a9bd0):
Resolving every thread listed; confirmed defects are fixed under the named bead. |
|
Closing out open Codex review threads on this PR (evidence checked against master at 0914f89):
Resolving every thread listed; confirmed defects are fixed under the named bead. |
|
Closing out open Codex review threads on this PR (evidence checked against master at f88b4a6):
Resolving every thread listed; confirmed defects are fixed under the named bead. |
#5843) ## Summary Daemon reads, events and observability residuals from the reindex-2026 daemon-reads group: - The SSE replay ledger `daemon_events` now has a production retention bound (a week, a 250,000-id span), enforced on every emit at O(expired rows) instead of a `COUNT(*)` scan (polylogue-20d.13.6 S2-2). - `analyze latency` computes percentiles over every sample in the lookback window instead of the newest 1,000 rows, and decides one terminal outcome (polylogue-jtwu.2). - One daemon run id is shared by the run's events, its `daemon_lifecycle` row, heartbeats and the status projection (polylogue-peo AC1). - The cold-status benchmark accepts the typed unavailable snapshot that status now returns without a daemon (polylogue-8s70). ## Problem - `DaemonEventRetention` defaulted to unbounded and nothing in production installed a bound, so the disposable ops-tier ledger grew with every `message.appended` (`polylogue/daemon/events.py`, `_RETENTION = _UNBOUNDED_RETENTION` at 633ec18). The row bound, once installed, ran `SELECT COUNT(*) FROM daemon_events` on every emit, and the age bound ran `MIN(id) ... WHERE ts_ms >= ?` over the `ts_ms` index, which visits every in-window row. - `analyze latency --limit` (default 1000) read the newest N rows per table and computed p50/p95 over them. A route with 1,200 samples whose oldest 200 were slow reported p95 = 10 ms instead of 5,000 ms. That is an arbitrary limit that changes the outcome. The command also decided no terminal outcome, although it is row-bearing and its drop accounting is never complete from a reader process. - `polylogued run` bound `run_id=uuid4().hex[:16]` into the logging context (`daemon/cli.py:4000`), while `DaemonLifecycle.start` minted a separate `uuid4()` for the lifecycle row (`daemon/lifecycle.py:86`). No event joined to its lifecycle row. `polylogued watch` bound no run id at all. - `tests/benchmarks/test_cli_cold_start.py` asserted exit 0, but `polylogue status` with no daemon now returns the typed unavailable snapshot and exits 1, so the lane could never produce a sample. ## Solution - `events.py`: `DEFAULT_DAEMON_EVENT_RETENTION` is the installed bound. `max_rows` bounds the retained id span (`DELETE ... WHERE id <= MAX(id) - max_rows`). Ids are AUTOINCREMENT and pruning only ever deletes a prefix, so the span is an upper bound on the row count. The age prune finds its boundary with a `NOT INDEXED` rowid walk that stops at the first in-window row. A cursor below the retained range still gets the typed `aged_out` resync envelope that #5349 added. - `route_observation.py`: `read_latency_report` streams both tables from the cursor over the whole window. The writers' own retention bounds the window, not the reader. `read_side_drops`, `READ_LIMIT_TRUNCATED` and the `--limit` option are deleted. `RouteLatencyReport.outcome` is `degraded` (`drop_accounting_incomplete`) when drops are not countable, `empty` when there are no buckets, and `ok` otherwise. The CLI prints the outcome and exits with its code. A missing `ops.db` is `degraded` (`ops_db_missing`). - `daemon/cli.py`: `daemon_run_id()` returns the run id already bound in the logging context, or binds one. `polylogued run` calls it before its first event, `run_daemon_services` calls it on entry (so `watch` and embedded callers are covered), and `DaemonLifecycle.start` now requires `run_id` and no longer mints its own. - `docs/atlas/daemon.md` documents the run id and the ledger bound. - `test_daemon_golden_parity.py`: deleted the unused `_strip_read_provenance` helper, which #5453 left behind when it removed the direct read leg. Retention value, decided rather than measured: the fresh archive's live `ops.db` holds 7 lifecycle events, so there is no emission rate to measure. The ledger is a resume buffer, not history. A subscriber that falls outside the bound receives a typed resync, never a short page. The age bound matches the ops tier's existing telemetry horizon (`ROUTE_OBSERVATION_RETENTION_MS`, 7 days). The id span keeps a cold build that emits one frame per session from growing the tier inside that week. Frames hold refs and counters, so the cap is tens of MB. Derived-identity closure: every changed production file is outside the closure (`devtools schema closure`: `out` for `polylogue/daemon/events.py`, `polylogue/daemon/cli.py`, `polylogue/daemon/lifecycle.py`, `polylogue/operations/route_observation.py`, `polylogue/cli/commands/diagnostics.py`). The derived schema identity does not move. ## Verification All runs went through AgentCTL on the exact head `4120d6ca461d` unless noted. - `agentctl job start --workspace /realm/worktrees/polylogue-daemon-reads polylogue verify_quick`: job 3506, `verify: PASSED exit=0` (receipt `20260929T182816Z-quick-3743796-0ab2b410`). - `agentctl job start --workspace ... polylogue pytest_focused -- <15 files>` (events endpoint, event cursor, route observation, diagnostics, lifecycle, golden parity, daemon CLI, queue health, health-check paths, perf floors, judgment automation, catch-up gate, browser pairing, HTTP security, cold-start bench): job 3509, 963 selected, 1 failed (receipt `20260929T182909Z-focused-test-3749815-bb3c5ba9`). The one failure is inherited: - `test_daemon_http_security.py::TestNoTokenLogging::test_no_token_in_log_or_print_calls` flags `polylogue/browser_capture/server.py:879`, a file this PR does not touch. The same test fails on detached master `633ec18ffc` with `--on-default-branch` (job 3481, `1 failed`). - `test_daemon_cli.py::test_cold_build_integrity_fault_stays_blocked_in_running_daemon` timed out once on an earlier head under host load (load average ~40). It also times out on detached master `633ec18ffc` (job 3499, `TimeoutError`). It passed in job 3509. - `devtools schema closure` reports `out` for every changed production file. ## Self-review Last pass over `git diff origin/master`, using the `docs/review/codex-review-guide.md` checklist: 1. ✓ Siblings and owners. `prune_daemon_events` remains the single enforcement point, called from both `emit_daemon_event` and `emit_daemon_events`. I grepped every reader of `daemon_events`. `api/archive.py:1934` and `judgment_automation.py` read the latest judgment event only as a fallback behind the typed `judgment_scheduler_receipts` row, which the same emit writes in the same transaction, so pruning cannot un-ack an outbox entry. `archive_verification.py:3172` reads `MAX(ts_ms)`, and the row just emitted always survives its own prune. The run id has one owner, `daemon_run_id`, and both entry points (`run`, and `watch` through `run_daemon_services`) go through it. 2. ✓ The fix itself. `DaemonLifecycle.start` now raises `ValueError` on an empty id. Its only production caller passes `daemon_run_id()`, which never returns empty. `_exit_with_outcome` raises `SystemExit` only for nonzero codes, and each early branch returns after it, so an `ok` JSON answer does not fall through into text rendering. 3. ✓ Memory and limits. The deleted `--limit` was a cap that changed the answer. `read_latency_report` iterates the cursors and keeps only the per-bucket samples that the percentile needs. The writers' retention (`ROUTE_OBSERVATION_RETENTION_MS` with its row cap, `MCP_CALL_LOG_RETENTION_MS`) bounds those samples. The ledger bound never refuses or shortens an answer: a cursor outside it gets the typed `aged_out` resync. 4. ✓ Cost per unit. A prune used to cost a `COUNT(*)` plus a `MIN(id)` over the `ts_ms` index on every emit. It now costs one `MAX(id)` probe plus a rowid walk over the rows that expired since the last emit. 5. N/A Interruption. No new loops or multi-step state. The prune runs inside the emit's existing transaction. 6. ✓ Ordering and races. The prune and the insert share one transaction and one connection. `query_events_since` keeps its single-snapshot `BEGIN`/`ROLLBACK`. 7. ✓ Failure classification. `analyze latency` without `ops.db` is `degraded` (`ops_db_missing`), not empty. 8. ✓ Silent outcomes. `analyze latency` now decides a terminal outcome (`surfaces/outcome.py`). An incomplete drop disposition is the named gap `drop_accounting_incomplete`, so the answer is `degraded` with or without rows, and the exit code follows it. 9. N/A Cleanup on failure. Nothing is acquired. 10. ✓ Identity and keys. One run id (`uuid4().hex`) now keys the lifecycle row and the logging context; before, two ids were minted independently. 11. N/A Lossless transforms. None. 12. ✓ Degenerate inputs. An empty ledger has `MAX(id)` NULL, so the row bound skips. An empty window gives `degraded`, or `empty` in a fully accounted in-memory report. Both cases are tested. 13. ✓ Consumers. Every `DaemonLifecycle.start` call site passes `run_id` (10 test sites, 1 production site). `read_side_drops` and `READ_LIMIT_TRUNCATED` had no other readers (grep). No docs or generated reference named `--limit` for latency. `docs/atlas/daemon.md` gained the run-id and bound statements. 14. ✓ Tests and stubs. The tests drive production routes: the real emit prunes against its own `observed_at_ms` without reading a clock, `read_latency_report` runs over rows written by `record_route_observation` and `record_mcp_call`, and the CLI JSON outcome is checked. Each test names its anti-vacuity mutation. Two judgment-automation tests replay 1970-dated outbox receipts next to real-time emits, so they now hold the ledger unbounded through the production injection point, with the reason stated in the fixture. The monkeypatch of `read_side_drops` went away with the function. 15. N/A Trust boundaries. No secrets or files are involved. Compatibility: no shim or alias. `--limit` is removed, not deprecated. ## Residuals - polylogue-8s70 stays open. Cold `polylogue status` measured 1.35-1.44 s on this host (load average 15-43), against a 500/800 ms budget. The import profile names the costs: `click_option_groups -> origin_filters -> origin_specs -> parsers.otel_genai -> parsers.base_models` (pydantic, about 0.9 s cumulative under load), `operation_kernel -> daemon_protocol` (0.39 s), `daemon_reads -> ... -> archive.query.transaction -> archive_tiers` (0.38 s) and `readiness` (0.35 s). I tried two cuts: rendering root-help markers lazily, and moving the two OTLP dialect constants out of the parser. Together they cut `click_app` from 1.17 s to 0.28 s cumulative, but wall time improved only about 5%, because the status path imports the same modules later. I reverted both: the second touches two closure-IN files, which is not worth a moved identity for 5%. - polylogue-jtwu.2 J2-1 is not fully met. Drop counters live in each emitter's process, so a reader never sees the daemon's or a finished CLI's drops. The answer is now honestly `degraded`, but making drops countable needs a durable counter in the ops tier (`ops.py`/`ops_write.py`, closure-IN). - polylogue-peo AC2-6 (next-start `TerminationReceipt` reconciler from systemd, journal, cgroup and heartbeat evidence) need an ops-tier table (closure-IN DDL) and host adapters. They are not in this PR. - Inherited: `tests/unit/daemon/test_daemon_http_security.py::TestNoTokenLogging::test_no_token_in_log_or_print_calls` fails identically on master (`polylogue/browser_capture/server.py:879`). This PR does not touch that file. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_015pdKaZWyGe6Ngvsz468dzg --------- Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Summary
Two independent groups, no file overlap: SSE event contracts + cursor aging
(
daemon-events), and route-observation receipts + drop accounting(
latency-observation).Both share one theme — a surface must not report a number it cannot stand
behind. A topic advertised without a contract, a short page reported as
complete, and a p95 over an unknown fraction of invocations are the same defect
wearing three costumes.
polylogue-20d.13.5 — every advertised topic now has a declared contract
EventSpeccarries kind, summary, object/source refs, archive and ledger tier,cursor field, frame, producer phase, payload projection, required fields,
audience and emitter.
GRANULAR_EVENT_KINDSis now derived fromEVENT_SPECS,so a kind cannot be advertised without a contract.
__post_init__rejects anobject_refoutside the projection, a frame that differs from the kind (the wirewriter uses kind as the frame), and a non-
polylogueemitter.The denominator cannot see the registry
Two independent denominators, both built by parsing the module from disk:
_advertised_topic_constants()ast.parse()sdaemon/events.pyand collectsevery module-level
EVENT_*string assignment;_production_emit_targets()ast.walk()s the same source foremit_daemon_event(<EVENT_*>)call sites.Neither imports the registry, so a topic cannot be certified by the structure
that declares it.
test_emitted_payload_matches_the_declared_projectiongoesfurther and runs each declared production emitter, checking real emitted keys
against the declared projection.
polylogue-20d.13.6 — an aged-out cursor is refused, not silently shortened
query_events_sincereturns a typedDaemonEventPage(status, events, retained_min_id, latest_id, resync). The refusal is decided inside the reader(
_cursor_refusal_reason), so a second caller cannot bypass it.__post_init__forbids an
AGED_OUTpage carrying rows and anOKpage carrying a resyncenvelope. The resync payload comes from
build_snapshot_envelope(), whichevents_http._build_snapshot_event()now also calls — coalescing and resync areliterally one shape.
The gap fixture prunes through the production enforcement point
(
set_daemon_event_retention(max_rows=2)plus one more emit), not a hand-rolledDELETE, and is covered at three levels: the reader, the HTTP poll shape(
outcome=degraded,resync=true,resync_reason=cursor_aged_out), and the realSSE stream (one
event: snapshotframe, zeroingestion_batchframes).polylogue-jtwu.1 — one route-observation spec and receipt
RouteObservationSpec+RouteObservationReceiptcarry build/archive/workloadscope, trace and run id with parent, surface/route/verb, daemon-vs-direct, named
phases with wall and CPU time, status, response bytes, evidence refs and
unavailable_measures. An unobtained measure is reported as unavailable, notzero.
archive_idis caller-supplied, deliberately not derived from the archive rootpath — telemetry must not bake an operator filesystem location into every row.
observe_routepersists through the unchangedrecord_route_observationwriter.to_workload_receipt()is theWorkloadReceiptadapter, androute-observationjoins
WORKLOAD_ADAPTER_DECLARATIONS.polylogue-jtwu.2 — percentiles cannot be rendered without their drop count
RouteObservationDropLedgercounts five emit-side reasons —no_archive_root,ops_db_missing,emit_failed,pruned,not_sampled— each attributed to its(surface, route). Theprunedreason closes the parent bead's own bullet("rows are currently pruned by retention and row cap without being counted"):
_emit_best_effortmeasuresconn.total_changesacross the write and charges thesurplus over the single insert.
compute_latency_percentilestakes a keyword-onlydropswith no default andreturns
RouteLatencyReport(buckets, drops)— an unqualified percentile is notexpressible through the API. Zero drops and unknown drops stay distinct:
accounting_completeis False for any cross-process reader,sample_completenessthen returns
Nonerather than1.0, and the CLI prints that the percentiles areover an unknown fraction of the invocations.
read_side_drops()makes thereader's own row-limit truncation a counted reason, and
unattributed_dropskeeps a drop for a route with zero surviving samples fromvanishing when the report flattens to buckets.
Anti-vacuity — seven mutations executed, red output captured, all reverted
EVENT_INSIGHT_UPDATEDconstant with no specGRANULARmismatch, "no production emit call"_cursor_refusal_reason→NoneDaemonEventPage(status=OK, events=(1 surviving row), retained_min_id=4)for cursor 1 — a short page reported as completeprune_daemon_eventsreturns 0[0,1,2,3,4,5] != [3,4,5]correlation_refs = []record()no-opsdropsa defaultVerification
devtools verify --quick→ exit 0, all 24 gates, post-rebasedevtools render all --check→ exit 0,grep -c 'out of sync'= 0 over thefull captured output, not judged from the tail
devtools test tests/unit/operations→ exit 1, exactly one failure,test_operation_snapshot.py::test_unseeded_audit_continuity_degrades_an_operation_read(
assert 1 >= 32), proven inherited by a detached checkout oforigin/masterin the same worktree — no baseline worktree builtClosure measured, not assumed
All nine changed files
out, measured at the real branch base and again atfinal head.
polylogue/daemon/event_bus.pywas measured IN and not touched —git diff --stat origin/master -- polylogue/daemon/event_bus.pyis empty.Residuals
20d.13.6AC S2-2 is NOT closed. The enforcement point(
prune_daemon_eventsinside every emit transaction), the injection point(
set_daemon_event_retention) and the enforcement proof all landed, but bothbounds default to
Noneandis_boundedreportsFalse. No retention valuewas invented. Nothing in production calls the setter, so the ledger is still
unbounded in practice — this makes that fact legible and enforceable, not fixed.
The value is an operator decision or a live-daemon measurement.
storage/sqlite/archive_tiers/ops_write.pyis schema-closure IN. It holdsrecord_route_observation, whose retention prune is the obvious place to countprune-drops. It was avoided entirely (
conn.total_changesdelta instead). Anyfollow-up wanting richer prune attribution must treat it as a rebuild-boundary
edit.
a new one is required" is false —
tests/unit/operations/test_route_observation.pyexists with 13 tests. Extended rather than duplicated.
20d.13's NOTES citedaemon/web_shell_realtime.pyas thebrowser consumer. That file does not exist, and no JS/TS consumer of the SSE
snapshotframe exists anywhere in the tree. The resync frame is correct on thewire and unconsumed.
reach ops.db" and "ops.db is locked", so a durable counter would have to survive
the condition that produced it. A fresh
analyze latencytherefore usuallyreports "not fully countable from this process". That is the honest answer.
latest_idrather thanreplaying the retained tail. That matches the existing snapshot contract, but it
is a deliberate semantic choice.
Closes polylogue-20d.13.5, polylogue-jtwu.1, polylogue-jtwu.2.
Advances polylogue-20d.13.6 (S2-1 and S2-3 satisfied, S2-2 open on the bound's value).
🤖 Generated with Claude Code
https://claude.ai/code/session_015WCh9YW3cRfsg3CZBKU7Fq