Repository navigation
refactor(daemon): Convert the daemon CLI and HTTP surface to structured events - #5067
Conversation
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Warning Review limit reachedNext included review available in 9 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 (6)
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 |
The daemon CLI and HTTP conversions need scalar names the allowlist did not yet carry: maintenance loop identity (`loop`, `mode`, `kind`), reconciliation dispositions (`cleared`, `retained`, `unresolved`), WAL checkpoint frames and pages, daemon pass fan-out sizes, bounded spool `depth`, and a `budget_ms` duration for hold budgets. Every addition is a scalar token, count or duration. No free-text field is added: `error_detail` remains the only quarantined field, and the test asserting that set stays at one entry is unchanged. This file is inside the derived schema identity closure (`devtools schema closure polylogue/logging_fields.py` reports IN), so the index tier identity moves: a3fdaeec... -> 2542e251... It must land before a from-scratch rebuild starts, never during one. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
`polylogue/daemon/cli.py` carried 59 interpolated prose log sites behind
`get_logger`, whose `bind()` is a no-op and whose kwargs are discarded on the
default (non-`--verbose`) path. Those lines could not be filtered, counted or
correlated, and several reported nothing an operator could act on.
Every site is now `emit`/`span`, each carrying the fields that make a wrong
outcome legible: which loop, which path, which stage, how many, and — where
the code swallows a failure to keep a periodic loop ticking — an explicit
`error_type`/`error_detail` at the level the failure deserves.
Two units of work with a real duration and outcome became spans:
`daemon.drive_catchup.pass` and `daemon.convergence_debt.pass`. Both are
wrapped so their terminal event is emitted from `__exit__`, before the handler
that swallows the exception, so a retry pass that fails is recorded at ERROR
instead of disappearing into a warning the reader cannot distinguish from
noise.
`daemon.stopped` now reports `degraded` when the writer did not drain, rather
than `ok` with a flag the reader has to notice.
The `raw_intake_discovery` callable submitted into `daemon/execution.py`'s
compute kernel is wrapped in `propagate()`. That pool is constructed before any
bind, so its worker threads carry no contextvars; verified directly — a bare
submit sees `{}` where a propagated one sees the bound `run_id`.
`log_mapped_bytes_budget_check` took a prose logger and passed structured
keywords that the stdlib path dropped outright, so the mmap/cgroup numbers
never reached anyone. The call site now emits them itself.
Verification: devtools test tests/unit/daemon; devtools gate layering (0
violations); devtools render all --check (no "out of sync").
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
`polylogue/daemon/http.py` carried 31 prose log sites. Its route-level error handler logged `"sqlite error in %s"` with the exception text going only to a traceback, so a reader could not tell an archive-busy 503 from a genuine failure, nor which route produced it. Every site is now `emit`, carrying `route`, `status_code`, `error_type` and `error_detail`, with `reason` distinguishing `archive_busy` from `sqlite_error` on the webui read paths — the distinction the prose collapsed. `_sync_run` gains a `daemon.http.scheduled_route` span: the scheduled route body is exactly a unit of work with a duration and an outcome, and its admission class, queue delay and timeout now sit on one correlated record. A timeout raises, so the span's own `.error` terminal event fires; the declared `reason`/`timeout_ms` ride along rather than asserting a success that was never observed. The callable handed to the compute kernel is wrapped in `propagate()`. The kernel's `ThreadPoolExecutor` predates every bind, so without it the route body would run with no correlation context and its events could not be joined to the span that scheduled them. Span fields read the request line through `getattr`, because narrow in-process handler doubles carry none and observability must never be what breaks a route. Verification: devtools test tests/unit/daemon; devtools gate layering (0 violations); devtools render all --check (no "out of sync"). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
`daemon.maintenance_loops.parked` joined all seventeen loop names into `error_detail`, which is the quarantined free-text field and truncates at 300 characters. The tail of the list was silently dropped -- from an alert whose entire purpose is to say exactly what the schema-blocked startup froze. Each loop now gets its own `daemon.maintenance_loop.parked` event carrying `loop=<name>`, so every frozen loop is individually greppable and none is lost to truncation. The summary event keeps the count. The two test assertions this exposed are corrected with it: `.start` is DEBUG and sits below the default capture threshold, so the convergence-debt test asserts on the terminal event alone. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
1523134 to
226aff3
Compare
…events (#5072) ## Summary All 34 remaining daemon modules converted to structured events. **Zero legacy loggers remain anywhere in `polylogue/daemon/` outside `cli.py`/`http.py`**, which landed separately in #5067. Ratchet baseline 23 → 20 — exactly the three eliminated. Largest: `judgment_automation` 23 sites, `convergence_stages` 17, `metrics` 12, `status` 11, `embedding_backlog` 11, `write_coordinator` 10, `derivation` 8. A dead logger in `backup.py` was removed outright. ## What this makes legible ``` INFO daemon.stage.executed duration_ms=0.0 outcome=ok path=claude-code/a.jsonl stage=acquire WARNI daemon.stage.execute.degraded attempts=44 calls=40 gaps=2 outcome=degraded path=claude-code/a.jsonl reason=unresolved_workflow_gaps runs=12 stage=claude_workflow WARNI daemon.stage.drained action=batch attempted=3 confirmed=1 debt=1 failed=2 outcome=degraded payload_failures=0 reason=transport_failures rejected=0 remaining=2 transport_failures=2 ``` The old code logged `gaps=2` inside an **INFO** sentence — a degraded stage reported at the same level as a healthy one. And prose collapsed transport failures, payload failures and rejections into a single line; they now have separate counted lanes with a reason naming the dominant one. `convergence_stages.py` carries `make_default_convergence_stages`, the stage list that drives the entire from-scratch rebuild, so this is the module that decides whether a multi-hour build's degradation is visible without reading source. ## `propagate()` — verified, not assumed `BoundedComputeAdapter.__init__` builds the `ThreadPoolExecutor` eagerly and `_run_task` submits a bare closure. Measured with the pool pre-warmed: bare submit → `{}`, wrapped → `{'run_id': 'rebuild01'}`. Added at both `operation_runtime.py` submit sites. ## Fields 46 new, all count/token/identifier/duration/flag; three registered but never emitted were dropped. `error_detail` remains the only `text`-kind field, asserted by its pinning test. One deliberate omission: a failed Apprise `add()` used to interpolate the notification URL with `%r`, and those URLs embed tokens. The **position** is logged instead of the URL. ## Verification ``` devtools test tests/unit/daemon -> PASSED 2233/2233, exit 0 (429s) devtools verify --quick -> exit 0, all 15 gates devtools gate layering -> exit 0 devtools gate patterns -> passed, 20 matches, 0 prunable devtools render all --check -> exit 0, "out of sync" -> 0 ``` The tip was checked before **and** after that run (`3b342d756`, clean both times), because a green belonging to a different tree than the one reported has already bitten this campaign twice today in both directions. The count is 2233 rather than an earlier 2230 because the rebase brought three more daemon tests in with #5063/#5064 — both numbers are real measurements of different trees. Seven tests pinned the old prose through `caplog` or subprocess stderr; each now asserts on the event and its fields and names its anti-vacuity condition. The raw-authority-cache test is strictly stronger than before: it now requires the first pass to report `degraded` with cohorts pending and the second `ok`, a distinction a single INFO line could not express. ## Landing order `polylogue/daemon/write_coordinator.py` and `polylogue/logging_fields.py` are **IN** the derived-schema closure; the other 35 changed files are `out`. The index identity moves, ops does not. **This must land before a from-scratch rebuild starts, never during one** — encountered for real during development, where editing mid-run produced 133 `SchemaSkewError` failures because the seeded-artifact cache keys on `derived_schema_identity`. Note `write_coordinator.py` now carries both #5062's lease-delegation imports and this change's event imports, so both feed the index identity. The interim identity hashes measured during development are superseded by each rebase; only the finally-landed identity is worth recording. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Summary
The two largest unconverted daemon modules, converted to structured events:
daemon/cli.py59 sites → 57emit+ 2span,daemon/http.py31 sites → 31emit+ 1span. Zerologger.references remain in either; both module-level loggers are deleted. Neither file contained a bareprint.What this makes legible
A convergence-debt retry whose coordinator raises, with the exception swallowed so the periodic loop survives:
The old line was
logger.warning("convergence: check failed", exc_info=True)— the same severity as a transient lock, with no cause and no path. The failure propagates out of the span so its.errorfires from__exit__, then is suppressed outside so the loop keeps ticking: the failure is recorded even though the code deliberately carries on.HTTP route failures now name the route and the cause:
A real defect the conversion surfaced
daemon.maintenance_loops.parkedjoined all seventeen frozen loop names intoerror_detail— the quarantined field, truncated at 300 characters. The alert whose entire purpose is to say what a schema-blocked startup froze was silently dropping the tail of its own list. Each loop now emits its owndaemon.maintenance_loop.parkedcarryingloop=<name>, individually greppable and untruncatable; the summary event keeps the count.Deliberately left alone
Seven
click.echosites incli.pyare product surface, not logging: the startup banner,polylogued statusJSON and plaintext output,polylogued healthoutput, the version line, and the stop acknowledgement. These are what the operator invoked the command to read. Converting them would delete the CLI's output rather than relocate it.propagate()— verified, not assumedexecution.py:368builds theThreadPoolExecutorinBoundedComputeAdapter.__init__and_run_task.run()is submitted with no context copy. Direct probe against pool threads created before the bind:Added at both in-scope submits:
cli.py:2915andhttp.py:1729— without the latter, a route's events could not be joined to the span that scheduled them.Fields
New tokens
loop,mode,kind; countscleared,retained,unresolved,bytes_before,bytes_after,busy_pages,checkpointed_pages,tiers,sources,loops,services,orphaned,alerts,delivered,depth; durationbudget_ms. All scalar. No new free-text field —error_detailremains the sole quarantined entry and its pinning test is untouched.Verification
Ten tests asserted on
patch.object(daemon_cli.logger, ...)orcaplog; all rewritten ontopolylogue.logging.capture()and asserting event name, level, outcome, reason and typed fields — behaviour, not wording. Each anti-vacuity note names the event whose removal turns it red.Landing order
polylogue/logging_fields.pyis IN the derived-schema closure. Index identity movesa3fdaeec…->2542e251…(ops unchanged). This must land before a from-scratch rebuild starts; landing it mid-run silently invalidates that run.cli.pyandhttp.pyare bothout.Residual — the ratchet did not move, and could not
legacy-stdlib-loggermatcheslogging.getLogger($$$). Neither target file ever used it — both went throughpolylogue.logging.get_logger, which the rule does not match. So converting 90 prose sites eliminated zero baseline entries, and the baseline is lowered by exactly that: nothing, 24 before and after.That is a genuine gap: the gate's choke point misses the wrapper ~140 modules actually use. Widening the rule would grow its baseline by all of them, which the ratchet forbids, so the coherent route is a second rule with its own baseline at the true remaining count. Deliberately not done here.
devtools test tests/unit/daemonis a focused selection and proves the daemon unit scope on this tip only. Callers outside that scope were checked by grep, not by execution.🤖 Generated with Claude Code
https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK