Repository navigation
fix(daemon): classify genuine convergence-debt deferrals as deferred - #3621
Conversation
Problem: ops.db's convergence_debt.status vocabulary declares both
'failed' and 'deferred' (storage/sqlite/archive_tiers/ops.py CHECK
constraint), but live measurement showed only 'failed' rows ever
written. cursor.py's _convergence_debt_status() special-cased exactly
one condition -- stage == "insights" and error text matching the
literal string "insights deferred until source quiet" -- to produce
'deferred'. Every other false_means_pending stage (fts, embed,
sinex_publication, raw_parse_recovery) and every explicit
"deferred FTS to preserve writer availability" backpressure write in
batch.py fell through to the 'failed' default, even though nothing
had actually failed. Daemon health/alerting (convergence_debt_status.py,
convergence_debt_alert.py) filters on status == 'failed', so this made
routine backpressure look like a broken stage.
Solution: replace the stage-name/error-text sniffing with the real
signal already present in daemon/convergence.py -- StageState.PENDING,
which is set only for a false_means_pending stage's non-exceptional
False return or downstream-barrier queuing, never for a check/execute
exception. Added ConvergenceDebt.deferred and
sources.live.convergence_debt.is_deferred_stage_state(), threaded an
explicit deferred: bool through CursorStore.record_convergence_debt /
_sync_convergence_debt_to_ops / add_convergence_debt, and removed the
dead _convergence_debt_status special-case. Updated the two explicit
"deferred FTS" call sites in batch.py and the retry-replay path in
daemon/cli.py's _drain_convergence_debt_once (which reconstructs debt
rows from retried StageState directly) to pass the same signal.
Read-side audit: convergence_debt_status.py already filters strictly
on status == 'failed' for its failed_count/stage_summaries/alerting
projection, and convergence_debt_alert.py consumes only that filtered
view -- so newly-correct 'deferred' rows are now excluded from
alerting as intended, without any separate read-side change. The one
site that reads both statuses together (api/archive.py's
standing-queries producer-debt count) already unions ('failed',
'deferred') and needed no change.
Verification: devtools test on the touched daemon/cursor/batch/
convergence_debt test files plus the new
test_convergence_debt_deferred_vocabulary.py (8 new/updated unit
tests exercising is_deferred_stage_state and the ConvergenceDebt
classification directly, plus a CursorStore-level test asserting a
genuine deferral writes status='deferred' against a real failure
writing status='failed') -- 322 passed. devtools verify --quick
green (added the new daemon/cli.py -> sources.live.convergence_debt
baseline entry the layering ratchet requires for the new import).
tests/unit/sources/test_live_watcher.py::test_end_to_end_hidden_root_file_creation_triggers_ingest
failed once under parallel load and passed on immediate retry in
isolation, both before and after this change -- pre-existing
filesystem-watcher timing flake, not touched by this diff.
Ref polylogue-6krh
|
Warning Review limit reached
Next review available in: 35 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Plus 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 |
## Summary Five small, independent quality fixes batched into one PR (H5 quality sweep, `.agent/campaigns/2026-08-overhaul/` queue row #12): two real code fixes with red-before/green-after tests (`polylogue-f47j`, `polylogue-iuyr`), one narrowing fix for a mislabelled-session bug found by a parallel audit (`polylogue-omsw` class), and two beads (`polylogue-6krh`, `polylogue-es7b`) that turned out to already be fully fixed and tested on `master` when investigated — verified rather than assumed. ## Problem - **polylogue-f47j**: `registry.promote_cluster`'s samples-based candidate generator (`generate_schema_from_samples`) never received a `PrivacyConfig`, unlike the full `generate` pipeline's `_generate_cluster_schema`. An explicit deny rule supplied by a caller was silently ignored on the samples path — the same class of gap that let a low-cardinality UUID-shaped field record its literal per-record values verbatim during a 2026-07-29 promotion (caught after the fact by `devtools schema_audit`, fixed at the time by manual annotation stripping, not by this fix). **Cold review on an earlier revision of this PR caught that the initial fix only plumbed `privacy_config` through the library function — it was still unreachable from `devtools schema-promote`, the actual command a live promotion runs, so every real run would have stayed exactly as unredacted as before this PR until that was completed** (see Solution and the second commit below). The compensating control that actually caught the 2026-07-29 leak (`devtools schema_audit`'s privacy-guard check) still runs in no gate — tracked separately as polylogue-32pwq, not in this PR's scope. - **polylogue-iuyr**: `compute_session_cost`'s per-model loop called `estimate_cost()` for every model with a normalized name, but `estimate_cost()` silently returns `0.0` when the pricing catalog has no entry for that model. A model with real, nonzero reported/estimated tokens but no catalog price (e.g. `claude-opus-5`, a confirmed live catalog gap) surfaced as `confidence='reported'` with `total_api_cost_usd=0.0` — indistinguishable from a provider that genuinely billed zero. - **polylogue-omsw class (Hermes skill templates)**: the Hermes watch source recursively scans its entire `~/.hermes` home directory (not just a sessions subtree), so skill prompt-prefill templates under `optional-skills/**/templates/*.json` reached artifact classification tagged `provider="hermes"`. Their bare `{"role", "content"}` array shape satisfied the generic `looks_like_record_entry` heuristic in `_classify_list` and got claimed as a session, then quarantined when it failed to parse ("session artifact produced no materializable sessions"). Found by a parallel dyica-classification audit (2026-08-19, bucket B6), both live template files still on disk for testing. - **polylogue-6krh / polylogue-es7b**: both were re-investigated per the dispatch and found to already be fully fixed **and tested** on `master` (see disposition matrix below) — no code changes made in this PR for either. ## Solution - `polylogue/schemas/generation/schema_builder.py`: `generate_schema_from_samples` gains a `privacy_config` parameter, threaded into its `_annotate_schema` call (the same redaction path `_generate_cluster_schema` already used). - `polylogue/schemas/tooling_registry.py`: `promote_cluster` gains the same `privacy_config` parameter and forwards it. - `polylogue/schemas/operator/registry.py`: `SchemaRegistryLike.promote_cluster` protocol updated to match (plus `tests/unit/scenarios/test_corpus.py`'s fake registry, to keep mypy's Protocol-conformance check green). - **Completing the wiring to the real caller** (added after cold review): `polylogue/schemas/operator/models.py`'s `SchemaPromoteRequest` gains a `privacy_config: JSONDocument | None` field (the same shape `SchemaInferRequest` already carries); `polylogue/schemas/operator/inference.py`'s `promote_schema_cluster` forwards it through `_privacy_config()` (now also exported as `privacy_config_from_payload` for reuse) into `registry.promote_cluster()`; `devtools/schema_promote.py` gains `--privacy`/`--privacy-config` flags, reusing `build_schema_privacy_config` — the exact same resolution the full `generate` pipeline's equivalent flags already use, not a parallel config path. - `polylogue/archive/semantic/cost_compute.py`: the per-model breakdown loop now checks `pricing_catalog_source(norm)` before trusting a `'reported'`/ `'estimated'` confidence; a model with no catalog entry downgrades to `'unknown'` regardless of token evidence, so `estimate_cost()`'s silent `0.0` can never be read as a confident zero. - `polylogue/archive/artifact_taxonomy/runtime.py`: `_classify_list` narrows the Hermes branch — a list-shaped payload under `provider="hermes"` is only session-eligible when it's a genuine ATOF event stream (the one list-shaped Hermes source class; state.db/ATIF/session-snapshots are all single JSON documents). Any other Hermes list payload is refused outright instead of falling through to the generic `looks_like_record_stream` heuristic. Alternative considered and rejected for the Hermes fix: narrowing the Hermes *parser* predicates (`polylogue/sources/parsers/hermes*.py`), as originally suggested. Traced the actual claim path instead — the parsers were never reached; `archive/artifact_taxonomy/runtime.py`'s generic `_classify_list` (shared by every provider) is what admitted the template as a session, so that is where the fix belongs. ## Verification - `devtools test tests/unit/schemas/test_promote_cluster_privacy_config.py` — 4 passed (f47j library-level plumbing; red confirmed by reverting the source change and re-running before committing). - `devtools test tests/unit/core/test_operator_inference.py` — 6 passed, including `test_promote_cluster_with_samples_honors_privacy_config_through_the_real_operator_route` (f47j, operator-route completion; red confirmed — reverting the wiring made `SchemaPromoteRequest(..., privacy_config=...)` raise `TypeError: unexpected keyword argument`, i.e. the field genuinely didn't exist before this fix). Also ran `tests/unit/core/test_operator_models.py`, `tests/unit/cli/test_operator_support_runtime.py`, `tests/unit/schemas/test_operator_commit.py`, `tests/unit/schemas/test_promotion_audit_privacy_guard.py`, `tests/unit/schemas/test_promotion_monotonicity.py` — 38 passed total, no regressions. - `devtools test tests/unit/core/test_cost_compute.py` — 10 passed (iuyr; red confirmed the same way). - `devtools test tests/unit/sources/test_artifact_taxonomy.py` — 19 passed (Hermes fix; red confirmed the same way, plus the ATOF anti-over-narrow twin passes both before and after). - `devtools test` across every Hermes-touching test file (parsers, dispatch, live watcher/batch, storage, daemon) — 880 passed, no regressions. - `devtools verify --quick` — clean (format + lint + mypy + render-all-check + layering + schema policy + promotion audit). - Full `devtools verify` **withheld**: this worktree's testmon graph would need a full bootstrap (~45 min, first run in a freshly-provisioned lane venv) that dies with the worktree at merge time — per the digest-drift/lane-lifecycle policy, that cost buys nothing the coordinator's own terminal verify at merge doesn't already provide. The four focused suites above plus `--quick` are the substitute gate for this PR; the coordinator's merge-time `devtools workspace merge` / terminal verify is the release-baseline attestation of record. ## Bead disposition matrix | Bead | Disposition | Evidence | Notes | | --- | --- | --- | --- | | polylogue-f47j | **SATISFIED** — close-candidate | commits 5bb08f4, dc8dd06; `tests/unit/schemas/test_promote_cluster_privacy_config.py`, `tests/unit/core/test_operator_inference.py::test_promote_cluster_with_samples_honors_privacy_config_through_the_real_operator_route` | All three layers now land: (1) `privacy_config` threaded through the library's samples path, (2) `promotion_audit`'s `check_privacy_guards` wiring (AC #2) was already present on `master` before this PR — verified live, not assumed, (3) the operator-route wiring (`SchemaPromoteRequest` → `promote_schema_cluster` → `devtools schema-promote --privacy`) that a cold review found missing from the first revision — without it the library fix was unreachable from any real promotion. | | polylogue-iuyr | **SATISFIED** — close-candidate | commit 8aa2629; `tests/unit/core/test_cost_compute.py::test_catalog_gap_model_with_real_tokens_is_not_a_confident_zero` | Catalog-gap models now downgrade to `unknown` confidence instead of a confident `$0.00`. | | polylogue-6krh | **SATISFIED, no diff in this PR** — close-candidate | `polylogue/sources/live/cursor.py:_sync_convergence_debt_to_ops` (writes `status='deferred'` for deliberate deferrals); both `batch.py` deferral call sites already pass `deferred=True`; all five reader/alert surfaces named in the bead (`health.py`, `status.py`, cli `status.py`, `api/archive.py`, `metrics.py`) already track `failed_count`/`deferred_count` separately; `tests/unit/sources/test_convergence_debt_deferred_vocabulary.py` covers the full writer→reader chain end to end. This was PR #3621, already merged. Remaining scope per the bead's own design note is **post-deploy live verification only** (not code) plus the t0m73 vocabulary-honesty registry check, which the bead explicitly says to note rather than build. Not something this PR can evidence from a worktree. | | polylogue-es7b | **PARTIAL** — item (a) only, bead stays open | `polylogue/storage/embeddings/materialization.py`'s exception handler (fallback to `Origin.UNKNOWN_EXPORT` sentinel, `record_embedding_failure` always called); `tests/unit/storage/test_embedding_contracts.py::test_archive_failure_ledger_survives_origin_lookup_failure` | Item (a) (the one this sweep was scoped to) is already fixed and tested on `master`, no diff in this PR. Items (b)/(c)/(d) from the bead's own evidence (`write_coordinator.py` detached-writer counter, `RuntimeError` suppress potential hang, `sampling_db.py` missing-tier-file warning) are untouched and out of scope for this sweep — no successor bead exists yet for those; **not included in the machine pr-scope carrier below** since a partial disposition requires a linked successor I'm not able to create from a read-only lane. Coordinator: file a successor for (b)/(c)/(d) before considering this bead closeable. | | polylogue-omsw | **Referenced, not dispositioned** | commit c8e9f22 | Ref polylogue-omsw — this PR fixes one instance of the same artifact-misclassification class the bead already tracks (Hermes skill templates, dyica classification 2026-08-19 bucket B6), added as scope creep by the coordinator mid-PR. The bead's own scope (tool-result/journal sidecars, file-history-snapshot, codex-database misclassification) is broader and untouched here — do not close polylogue-omsw from this PR. | The machine-readable carrier below covers only `polylogue-f47j` and `polylogue-iuyr` (the two beads this PR both mutates code for and can satisfy without a successor). `polylogue-6krh` and `polylogue-es7b` are evidenced in prose above rather than the typed carrier, since satisfying or partial-closing them accurately would require either a diff this PR doesn't carry (6krh — already fixed elsewhere) or a successor Bead this lane cannot create (es7b's residual items b/c/d). <!-- polylogue-pr-scope:v2 { "assigned_beads": [ "polylogue-f47j", "polylogue-iuyr" ], "dispositions": [ { "bead_id": "polylogue-f47j", "disposition": "satisfied", "evidence": [ { "kind": "commit", "ref": "5bb08f4fe" }, { "kind": "commit", "ref": "dc8dd062b" }, { "kind": "test", "ref": "tests/unit/schemas/test_promote_cluster_privacy_config.py" }, { "kind": "test", "ref": "tests/unit/core/test_operator_inference.py::test_promote_cluster_with_samples_honors_privacy_config_through_the_real_operator_route" } ], "successors": [] }, { "bead_id": "polylogue-iuyr", "disposition": "satisfied", "evidence": [ { "kind": "commit", "ref": "8aa262901" }, { "kind": "test", "ref": "tests/unit/core/test_cost_compute.py::test_catalog_gap_model_with_real_tokens_is_not_a_confident_zero" } ], "successors": [] } ], "mutated_beads": [], "scope_digest": "8bfb7aa6968f56d6b00d47cebabfa8afbac9f613975abaa524fc6cd7a5273511", "scope_kind": "bead", "version": 2 } -->
Summary
convergence_debt.statuswas written as'failed'for essentially every deliberate backpressure deferral (false_means_pendingstages), even though the schema's CHECK constraint has declared a two-value vocabulary ('failed','deferred') all along.Problem
Live measurement of
ops.db'sconvergence_debttable showed a status distribution of{failed: 3}with'deferred'never observed, despitefalse_means_pendingbeing a documented, deliberate daemon pattern (a stage does bounded successful work and returnsFalseso the remaining backlog is retried as debt, not treated as an error).Root cause:
sources/live/cursor.py's_convergence_debt_status()special-cased exactly one condition to'deferred'—stage == "insights"anderrormatching the literal string"insights deferred until source quiet". Every otherfalse_means_pendingstage (fts,embed,sinex_publication,raw_parse_recovery) fell through to'failed', as did the two explicit "deferred FTS to preserve writer availability" backpressure writes inbatch.py. Daemon health/alerting (convergence_debt_status.py,convergence_debt_alert.py) filters onstatus == 'failed', so a stage doing exactly what it was designed to do (defer bounded work under backpressure) looked like a broken stage that had failed repeatedly.Solution
Replaced the stage-name/error-text sniffing with the signal that was already present and reliable:
StageState.PENDING(daemon/convergence.py). That state is set only for afalse_means_pendingstage's non-exceptionalFalsereturn or downstream-barrier queuing — never for a check/execute exception, which always producesStageState.FAILED.ConvergenceDebt.deferred: boolandsources/live/convergence_debt.py::is_deferred_stage_state(), computed from the realStageStatevalue rather than parsing error text.deferred: boolthroughCursorStore.record_convergence_debt→_sync_convergence_debt_to_ops→add_convergence_debt'sstatusargument, replacing (and removing) the dead_convergence_debt_status()special-case.sources/live/batch.pyand the debt-retry replay path indaemon/cli.py::_drain_convergence_debt_once(which reconstructs rows from retriedStageStatedirectly) to pass the same signal.storage/sqlite/archive_tiers/index_fast_forward_executor.py's directadd_convergence_debt(..., status="deferred")call for targeted-reprocess debt was already correct and untouched.Read-side audit (per the mission's alerting-safety requirement):
convergence_debt_status.py::_archive_convergence_debt_summary_infoalready filters strictly onstatus == "failed"for itsfailed_count/stage_summaries/recentprojection, andconvergence_debt_alert.pyconsumes only that filtered view. So genuinely-deferred rows are now correctly excluded from alerting because the write side got them right — no separate read-side change needed, and no risk of masking real failures since only rows whose underlyingStageStatewasPENDING(never used for exceptions) get relabeled.api/archive.py's one site that reads both statuses together (status IN ('failed', 'deferred')for standing-queries producer-debt count) already unions them and needed no change.Verification
devtools teston the touched daemon/cursor/batch/convergence_debt files plus the newtests/unit/sources/test_convergence_debt_deferred_vocabulary.py(8 unit tests directly exercisingis_deferred_stage_stateandconvergence_debt_from_state's classification, independent of any one stage's error text) and aCursorStore-level test asserting a genuine deferral writesstatus='deferred'against a genuine failure writingstatus='failed': 322 passed.devtools verify --quick: green. Required a newdocs/plans/layering-surface-baseline.jsonentry fordaemon/cli.py's newsources.live.convergence_debtimport (the layering ratchet's existing ~302-entry ledger already contains the same shape of import fordaemon/cli.py→sources.live.cursor/sources.live.batch).tests/unit/sources/test_live_watcher.py::test_end_to_end_hidden_root_file_creation_triggers_ingestfailed once under parallel load and passed on immediate retry, reproduced identically on the unmodified tree — pre-existing filesystem-watcher timing flake, unrelated to this diff.Scope note
One pre-existing stale baseline entry (
polylogue/mcp/server_prompts.py→polylogue.storage.sqlite.archive_tiers.write) was found during this audit but is unrelated to convergence-debt and left untouched to keep this PR focused.Ref polylogue-6krh