Skip to content

refactor(daemon): Convert the daemon CLI and HTTP surface to structured events - #5067

Merged
Sinity merged 4 commits into
masterfrom
work/log-daemon-cli
Sep 14, 2026
Merged

Sinity merged 4 commits into
masterfrom
work/log-daemon-cli

Conversation

@Sinity

@Sinity Sinity commented Sep 14, 2026

Copy link
Copy Markdown
Owner

Summary

The two largest unconverted daemon modules, converted to structured events: daemon/cli.py 59 sites → 57 emit + 2 span, daemon/http.py 31 sites → 31 emit + 1 span. Zero logger. references remain in either; both module-level loggers are deleted. Neither file contained a bare print.

What this makes legible

A convergence-debt retry whose coordinator raises, with the exception swallowed so the periodic loop survives:

DEBUG daemon.convergence_debt.pass.start  loop=convergence debt retry path=.../index.db span_id=9cc444b0
ERROR daemon.convergence_debt.pass.error  duration_ms=0.056 error_detail=database disk image is malformed
                                          error_type=RuntimeError outcome=error span_id=9cc444b0
INFO  daemon.convergence_debt.pass.ok     duration_ms=0.028 outcome=ok retried=7

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 .error fires 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:

ERROR daemon.http.route_failed error_detail=no such table: messages_fts error_type=OperationalError
                               outcome=error reason=sqlite_error route=_handle_session_read status_code=500

A real defect the conversion surfaced

daemon.maintenance_loops.parked joined all seventeen frozen loop names into error_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 own daemon.maintenance_loop.parked carrying loop=<name>, individually greppable and untruncatable; the summary event keeps the count.

Deliberately left alone

Seven click.echo sites in cli.py are product surface, not logging: the startup banner, polylogued status JSON and plaintext output, polylogued health output, 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 assumed

execution.py:368 builds the ThreadPoolExecutor in BoundedComputeAdapter.__init__ and _run_task.run() is submitted with no context copy. Direct probe against pool threads created before the bind:

bare   : {}
wrapped: {'run_id': 'probe01'}

Added at both in-scope submits: cli.py:2915 and http.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; counts cleared, retained, unresolved, bytes_before, bytes_after, busy_pages, checkpointed_pages, tiers, sources, loops, services, orphaned, alerts, delivered, depth; duration budget_ms. All scalar. No new free-text field — error_detail remains the sole quarantined entry and its pinning test is untouched.

Verification

devtools test tests/unit/daemon   -> PASSED, 2230/2230
devtools gate layering            -> 0 violations; cli.py 1/3, http.py 8/11 — the ratchet shrank
devtools render all --check       -> exit 0, grep "out of sync" -> 0 matches

Ten tests asserted on patch.object(daemon_cli.logger, ...) or caplog; all rewritten onto polylogue.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.py is IN the derived-schema closure. Index identity moves a3fdaeec… -> 2542e251… (ops unchanged). This must land before a from-scratch rebuild starts; landing it mid-run silently invalidates that run. cli.py and http.py are both out.

Residual — the ratchet did not move, and could not

legacy-stdlib-logger matches logging.getLogger($$$). Neither target file ever used it — both went through polylogue.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/daemon is 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

@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 14, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

Next included review available in 9 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: be546a4e-2121-43b1-bc7d-8e2ed871a547

📥 Commits

Reviewing files that changed from the base of the PR and between 4cb910c and 226aff3.

📒 Files selected for processing (6)
  • polylogue/daemon/cli.py
  • polylogue/daemon/http.py
  • polylogue/logging_fields.py
  • tests/unit/daemon/test_catch_up_gate_timeout.py
  • tests/unit/daemon/test_daemon_cli.py
  • tests/unit/daemon/test_insights_browser_endpoint.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.

Sinity and others added 4 commits September 14, 2026 13:25
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
@Sinity
Sinity force-pushed the work/log-daemon-cli branch from 1523134 to 226aff3 Compare September 14, 2026 11:29
@Sinity
Sinity merged commit c06465f into master Sep 14, 2026
3 checks passed
@Sinity
Sinity deleted the work/log-daemon-cli branch September 14, 2026 11:35
Sinity added a commit that referenced this pull request Sep 14, 2026
…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]>
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