Skip to content

feat: Add structured event logging and convert daemon convergence - #5059

Merged
Sinity merged 3 commits into
masterfrom
work/logging-design
Sep 14, 2026
Merged

Sinity merged 3 commits into
masterfrom
work/logging-design

Conversation

@Sinity

@Sinity Sinity commented Sep 14, 2026

Copy link
Copy Markdown
Owner

Summary

A structured event layer with an allowlisted field boundary, the daemon convergence path converted as the reference deployment, and the legacy form ratcheted so it can only shrink.

Problem

polylogue/logging.py wrapped structlog, and ~140 modules already imported get_logger and passed structured fields to it. But configure_logging() is only called on --verbose/--json-logs. In every other case get_logger returned _StdlibBoundLogger, whose bind() is a documented no-op and whose _stdlib_log_kwargs discards every keyword except exc_info/stack_info/stacklevel/extra.

So in the common case — including an ordinary polylogued run — the structured fields those modules carefully passed were being thrown away. The sink was a bare StreamHandler(sys.stderr) with no formatter: no timestamp, no level, no logger name. There was no PII boundary of any kind.

Measured at 73766c276: 24 logging.getLogger sites across 19 modules; 295 log/print sites in the daemon alone.

Solution

Three primitives — emit / span / bind — kept in polylogue/logging.py, which is already a universally-imported leaf. That placement is why gate layering reports 0 violations for a cross-cutting concern; a new observability/ package would have created them.

Correlation rides a ContextVar. The propagation matrix was verified empirically rather than assumed: await, asyncio.to_thread, and the writer lease all propagate (_run_in_daemon_thread already calls copy_context()). Python 3.14 propagates context into new threading.Threads — confirmed after a test written to pre-3.14 semantics failed. The genuine trap is pooled threads created before the bind, exactly daemon/execution.py's long-lived pool; propagate() exists for those and the test asserts that real distinction rather than a folk one.

PII boundary is an allowlist in code (polylogue/logging_fields.py), not reviewer discipline. emit("x", text=transcript) cannot leak: text is unregistered, the value never reaches a record, and the drop itself emits as log.field_rejected. bind validates too, since content bound once would ride every downstream event. Non-scalars reduce to <TypeName> rather than repr. Exactly one free-text field exists, error_detail, truncated to 300 chars and redactable — with a test asserting the quarantine set stays at one entry so it cannot drift.

span.__exit__ runs before any enclosing except, so a swallowed exception is still recorded. A span that exits without a declared outcome emits .unmeasured at WARNING and never success.

What this makes visible

INFO  daemon.stage.executed duration_ms=0.0 outcome=ok path=claude-code/a.jsonl stage=acquire span_id=94e3…
ERROR daemon.stage.execute_failed error_type=RuntimeError outcome=error path=claude-code/a.jsonl stage=parse span_id=94e3…
WARNI daemon.converge.file.degraded errors=1 outcome=degraded path=claude-code/a.jsonl reason=stage_errors span_id=94e3…

Note what the prose hid: index reported ok on a file whose parse had already failed.

Verification

devtools test tests/unit/test_structured_logging.py   # 45 passed
devtools test tests/unit/daemon                       # 2202 passed
devtools verify --quick                               # 15/15 gates
devtools gate layering                                # 0 violations
devtools render all --check                           # in sync

The devtools/patterns/legacy-stdlib-logger.yml ratchet is enforcing against a recorded baseline of 23. Anti-vacuity proven by introducing a new logging.getLogger and observing status: failed, then removing it — it also caught an unintended call in the author's own reset_events().

Two real bugs in the new code were found by the daemon suite rather than assumed absent: configure_events() stacked a sink per call, and a bind() was entered without being exited.

Residuals

23 legacy sites remain by design — this pass proves the design on convergence and leaves a conversion recipe rather than converting the tree. Nothing goes dark during the migration: configure_events() bridges surviving stdlib records as stdlib.record with the prose in error_detail, so an event carrying prose is an unconverted call site.

Largest unconverted daemon modules: cli.py (59 prose calls) and http.py (31). execution.py's pool submissions will need propagate() wrappers when those call sites are converted.

🤖 Generated with Claude Code

https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK

Sinity and others added 3 commits September 14, 2026 11:25
Polylogue's logging was structured in name only. configure_logging() is
only called on the --verbose/--json-logs paths; everywhere else
get_logger returns _StdlibBoundLogger, whose bind() is a no-op and whose
_stdlib_log_kwargs discards every keyword except exc_info/stack_info/
stacklevel/extra. The structured fields ~140 modules pass were therefore
thrown away in the common case, and the sink was a bare StreamHandler
with no formatter.

Add emit/span/bind on top of a contextvars correlation carrier:

- span emits its terminal event from __exit__, before any enclosing
  except, so an exception swallowed upstream is still recorded; a span
  that exits without declaring an outcome reports `unmeasured` at
  WARNING rather than defaulting to success.
- Reserved keys (ts, level, event) are assigned after caller fields, so
  a call site cannot rename its own event or restate its own level.
- emit compares one integer before doing any work, and nothing is
  serialized unless a sink consumes it.

The PII boundary is an allowlist in code (logging_fields.py), not
reviewer discipline: an unregistered field name never reaches a record,
and the drop is itself emitted as log.field_rejected. Exactly one
free-text field exists (error_detail), truncated and redactable.

reset_events() is wired into the conftest autouse fixture because event
configuration is process-global: without it one CLI command's sink keeps
rendering into the next test's captured output.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
The converger is the reference deployment for the event layer and the
hardest case: async tasks, threads, the writer lease, and long unattended
passes. All 14 legacy call sites are converted; the module no longer
holds a logger.

Interpolated prose like

    logger.warning("converger: execute failed for %s stage=%s: %s", ...)

becomes daemon.stage.execute_failed with stage/path/error_type fields, so
a rebuild log can be filtered and counted rather than only read.

converge_file now runs inside a span and declares its outcome explicitly.
A file whose stages remain pending behind a barrier reports
`degraded reason=stages_pending` rather than being scrolled past as a
success, and stage execution emits its own outcome from the stage's own
success claim rather than assuming it. Status probe failures report
`unmeasured`, which is the defect where a timed-out probe rendered ready.

polylogued run binds one run_id for the process, so every event from one
daemon run correlates across tasks, threads and the writer-lease hop
(write_coordinator already copies the context before that hop).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
Register docs/structured-logging.md in the docs surface: the event
vocabulary, the correlation matrix (what propagates automatically and
the one case that does not), the outcome-honesty rules, the field
allowlist, and the conversion recipe for the remaining modules.

Add legacy-stdlib-logger to the existing pattern registry rather than
inventing a parallel gate — verify_patterns already provides exactly the
needed semantics, a grandfathered baseline that may shrink and never
grow. It cannot land at zero and does not pretend to: the baseline
records 23 current matches, a new occurrence anywhere fails the gate,
and converting a module shrinks it. The end state is a baseline holding
only polylogue/logging.py, which legitimately owns the one sanctioned
logging.getLogger call.

The rule matches logger acquisition rather than each call, because
acquisition is the reviewable choke point.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: 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.

@Sinity
Sinity merged commit dcb1700 into master Sep 14, 2026
2 checks passed
@Sinity
Sinity deleted the work/logging-design branch September 14, 2026 09:33
Sinity added a commit that referenced this pull request Sep 14, 2026
Two PRs, each green on its own, were red once both had landed. #5056 added
`logging.getLogger` to `sources/retained_acquisition.py` for the ZIP
member-skip warning; #5059 recorded the `legacy-stdlib-logger` baseline at 23
entries. Neither PR's CI saw the other's change, so master ended up scanning
24 matches against a 23-entry baseline and `gate patterns` began blocking
every PR opened afterwards, including ones touching neither file.

Convert that site to `source.zip.members_refused`. No new allowlist field is
needed: `path` and `skipped` are registered, and the refused-member list rides
in `error_detail`, the one existing quarantined field.

Also prune 22 stale baseline entries whose sites no longer exist, several of
them naming the long-deleted `storage/repair.py`. Pruning shrinks the ratchet,
which is the permitted direction; silencing the gate by adding an entry is the
forbidden one.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
Sinity added a commit that referenced this pull request Sep 14, 2026
…ty (#5065)

## Summary

`devtools gate patterns` is **red on master**, blocking every PR opened
since, including ones that touch neither implicated file. This restores
it and makes the baselines honest.

## Problem

Two PRs, each green on its own, red once both had landed:

- **#5056** (error paths) added `logger = logging.getLogger(__name__)`
to `polylogue/sources/retained_acquisition.py` for the ZIP-member-skip
warning.
- **#5059** (structured logging) recorded the `legacy-stdlib-logger`
ratchet baseline at 23 entries.

Neither PR's CI ever saw the other's change. After both merged, master
scanned 24 matches against a 23-entry baseline, so the gate reported a
new match and set `blocking: true`. PRs #5061, #5062, #5063 and #5064
all failed for this inherited reason.

Separately, the baselines carried **22 stale entries** whose sites no
longer exist — several naming `polylogue/storage/repair.py`, a file
deleted some time ago.

## Solution

Convert the one blocking site to a structured event,
`source.zip.members_refused`. No new allowlist field was needed: `path`
and `skipped` are already registered, and the refused-member list rides
in `error_detail`, the single existing quarantined field.

Prune the 22 stale entries. Pruning **shrinks** the ratchet, which is
the permitted direction; adding an entry to silence the gate is the
forbidden one.

## Verification

```
devtools gate patterns   ->  blocking: false, new_matches: 0, stale_matches: 0
```

Baselines now match the scan exactly in both directions. Before this
change the same command reported 1 new match and 22 stale entries. No
test asserts on the old warning text, so no test changes were required.

## Note for the ratchet's owner — not addressed here

A structural gap surfaced while fixing this. `legacy-stdlib-logger`
matches `logging.getLogger(...)`, but the form most of the tree actually
uses is the `polylogue.logging.get_logger` wrapper, which the rule does
not match. A concurrent conversion of 90 prose sites across
`daemon/cli.py` and `daemon/http.py` therefore eliminated **zero**
baseline entries — the gate meant to enforce "no legacy logging" is
blind to the dominant legacy form.

Widening the existing rule would grow its baseline by roughly 140
modules, which the ratchet forbids. The coherent route is a second rule
with its own baseline at the true remaining count: a new ratchet may
start wherever reality is, while an existing one may only shrink. That
is a deliberate decision and belongs in its own change.

🤖 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