Repository navigation
refactor(cli): Remove the direct-read execution fallback - #5453
Conversation
The fixture gained a yield during the direct-read migration but kept its dict return annotation, so gate mypy refused it; ruff then wanted the import ordered. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01ToWqpkXotr573DiQex5vcy
|
Warning Review limit reachedNext included review available in 16 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 (13)
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 |
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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d91e2ce537
ℹ️ 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".
…lope (#5474) ## Summary `tests/unit/cli/test_cli_operation_authority.py` had **8 failures on master**: a daemon-down CLI mutation emitted `code: "runtime_error"` instead of the typed `daemon_required`. **8 red -> 4 red.** ## Root cause `OperationUnavailableError` is a `RuntimeError`, not a `ClickException`, so it missed `machine_main`'s `DaemonRequiredError` branch and reached the generic handler. That branch's own comment states exactly what this breaks: > *"the daemon-absent refusal is the one case a machine caller can act on directly, and folding it into `runtime_error` is exactly what made it unactionable."* The flattening arrived **by the other door** once #5453 stopped the CLI executing operations in-process (polylogue-3eexy). The guard existed; the new path went around it. ## Fix `machine_main` maps `OperationUnavailableError`, emitting `error_daemon_required` with `operation` carried as an envelope field so a client need not parse it from the message (polylogue-re6s3 AC4). The refusal message also names the operation, because the terminal format has no field to read it from — an operator told only *"start polylogued run"* cannot tell which route refused. ## Verification ``` devtools verify --quick -> PASSED exit=0 devtools test test_cli_operation_authority.py + companion -> 28 passed / 4 failed (was 24 / 8) ``` ## The remaining 4 are a different question, not this mapping A `mark` refuses at the `cli.query` that resolves its target, so the message truthfully names `cli.query` while the test expects `mutation.annotation.save`. That is a decision about **which operation a compound verb should name** — the one that actually refused, or the one the operator asked for. Both are defensible and the tests encode the second. Forcing them green here would mean naming an operation that did not fail, so they are left red with the reason recorded rather than papered over. ## How it was found A `gpt-5.6-luna` worker checking whether polylogue-d02y8 was close-ready reported these as inherited baseline failures. It is the third time this session a worker with no stake in a file surfaced a regression on master that `verify --quick` cannot see — none of these suites are in the quick set. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01ToWqpkXotr573DiQex5vcy Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
|
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. |
#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
Retires
direct_read/DIRECT_READso every read lowers to a daemon operation, and migrates the fixtures that assumed no-daemon direct execution. Bead: polylogue-3eexy.Produced by a
gpt-5.6-lunaworker across three passes; the mypy/ruff fix is the coordinator's.Solution
OperationContext.direct_read, the CLI direct executor/context, and all productiondirect_read/DIRECT_READreferences.DaemonFallback.DIRECT_READanddirect_allowed; eight read declarations converted toNEVER.daemon_requiredguidance ("start polylogued run…") instead of silently executing in-process.The fixture migration — why this took three passes
The first pass left 73 failures. The second reported them migrated but could not verify, because the host pytest pool has 3 slots and ~15 workers were competing for admission. I ran the selection myself and it was still red: 64 passed / 42 failed, dominated by 36 ×
SystemExit: 1plus a literalAssertionError: Error: start polylogued run to serve this operation— the new refusal text surfacing in tests that expected a result.That is worth recording: a worker's "migrated" report was not evidence, and landing on it would have broken master. The third pass, given the measured failures, classified each as a stale direct-execution assumption or a test needing the daemon fixture, and routed the
ArchiveStoreDoublequery laws through a daemon-operation seam. A bounded-stream fixture was corrected to declare its total message count; production behaviour was not changed to make tests pass.Verification
Receipts confirmed by the coordinator, not taken from the worker's report.
Schema closure:
operation_kernel.py,operation_context.py,daemon_protocol.pyall out — no derived-identity movement.Note for polylogue-tar1n
tar1nexplicitly delegates_execute_directlyto this bead and forbids other lanes from touchingcli/operation_kernel.py. That delegation is now discharged.🤖 Generated with Claude Code
https://claude.ai/code/session_01ToWqpkXotr573DiQex5vcy