Repository navigation
feat(daemon): add provider format-drift sentinel over live ingest - #3362
Conversation
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Warning Review limit reached
Next review available in: 43 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 (23)
✨ Finishing Touches🧪 Generate unit tests (beta)
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 |
Problem: Claude Code, Codex, ChatGPT, and Gemini change export/JSONL shapes without notice. Drift previously surfaced as silent parse degradation discovered manually weeks later (e.g. the ChatGPT asset-only-node and Antigravity non-UTF-8 drops in polylogue-qda). Nothing watched for new-unseen-shape rates in live ingest. What changed: - polylogue/schemas/drift_sentinel.py: classifies each validated sample's drift signal using the existing schema-inference machinery (SchemaRegistry.resolve_payload + SchemaValidator.validate). A fallback-to-package_default resolution is unseen_shape; a failed JSON-Schema validation is field_changed (a known field disappeared or changed type); a clean validation with unknown-but-permitted fields is the benign new_field case. field_changed/unseen_shape are risky, new_field is benign, and validation failure always outranks an unseen-shape classification. - ingest_worker.py now runs validate(include_drift=True) (previously False -- drift_warnings had no consumer) and threads a SchemaDriftObservation through IngestRecordResult/_PlanValidation. This never changes accept/reject semantics: STRICT-mode failure is still driven by is_valid/errors alone, and a drift-shaped record still materializes and ingests normally in advisory mode (the daemon default) -- the sentinel only augments ingest, it never gates it. - ops.db (additive-only, no migration -- the ops tier explicitly allows this) gains schema_drift_samples, keyed by (origin, element_kind, unseen_key_signature), pruned by time/row-count like the existing fts_drift_samples precedent. drift_sentinel_sampling.py bridges the batch summary to ops.db the same best-effort way sample_fts_drift_to_ops_sync bridges FTS samples: a missing/unreachable ops.db is swallowed, never raised. - summarize_schema_drift_since (ops_write.py) computes a 30-day windowed per-origin risky/benign rate with bounded example raw ids, consumed by three surfaces: `polylogue ops status` (new "Format drift sentinel" section), a new daemon health check (_check_schema_drift_medium, thresholds 5%/20% risky rate), and a last-resort marker in the root CLI callback (click_app.py) that prints to stderr on ANY polylogue invocation, independent of daemon liveness -- all three read the same windowed summary so they never disagree, and all three point the follow-up action at `devtools lab schema generate/promote` (the sentinel only detects). Verification: - devtools test tests/unit/schemas/test_drift_sentinel.py tests/unit/schemas/test_drift_sentinel_sampling.py tests/unit/storage/test_schema_drift_samples.py tests/unit/pipeline/test_schema_drift_sentinel_ingest.py tests/unit/pipeline/test_resilience.py tests/unit/cli/test_schema_drift_status.py tests/unit/cli/test_schema_drift_marker.py tests/unit/daemon/test_schema_drift_health_check.py -> 51 passed (anti-vacuity: a real test feeds ingest_record a field_changed sample and asserts result.sessions is non-empty in advisory mode -- proving the sentinel does not gate ingest). - devtools test tests/unit/pipeline/test_ingest_batch*.py tests/unit/pipeline/test_ingest_worker_assembly.py tests/unit/pipeline/test_malformed_jsonl_accounting.py tests/unit/pipeline/test_ingestion_chaos.py -> 128 passed (no ingest-path regression). - devtools test tests/unit/cli/test_status.py tests/unit/daemon/test_health_check_paths.py tests/unit/storage/test_fts_identity_ledger.py -> 108 passed, 1 pre-existing failure unrelated to this change (verified failing identically on origin/master before this branch's changes: test_archive_facade_route_catalog_covers_public_async_facade, a facade-route inventory drift for get_hook_event_summary_for_session and hermes_integration_health). - python -m mypy --strict on every changed module: no issues. - ruff check / ruff format --check: clean. - devtools render all --check: no drift (topology projection regenerated for the two new polylogue/schemas modules). - devtools verify --quick: all steps green (fixed a layering entrypoint-inventory gap for record_schema_drift_sample and added degrade-loudly/test-clock-hygiene allowlist entries for the new health-check except-branch and test fixture). Not run: the full devtools verify --seed-testmon suite (repo convention is testmon-affected selection or devtools test <files> for a focused change, not a blanket full-suite pass). Ref polylogue-da1 Co-Authored-By: Claude <[email protected]>
cc52780 to
2794ca2
Compare
Problem: four test_archive_maintenance_cli.py rebuild-index tests parsed
`result.output` as the sole JSON body of `--output-format json`. Click 8.4
removed `mix_stderr`; `.output` is now documented as "its own independent
stream that is mixing stdout and stderr, in the order they were written" --
`.stdout`/`.stderr` are the real separated channels. Once any stderr logging
fires during the invocation (structlog "backfill stage timings" from the
shared revision-backfill replay machinery, or rebuild_index.py's own
`rebuild_terminal_stage_complete` events at promotion), it leaked into
`.output` ahead of the JSON body and `json.loads` failed with
"Extra data: line 1 column 5" (the log line's leading 4-digit year parsing
as a bare JSON int, then everything after "-" as trailing garbage).
What changed:
- Switched the four affected `json.loads(...)` calls to `.stdout` (the
actual `--output-format json` contract surface), matching the channel-
separation contract test_stdout_stderr_split.py already documents
elsewhere in this repo.
- test_rebuild_index_deadline_defers_postflight_until_resume also had a
second, independent bug the JSON-parse failure was masking:
`monkeypatch.setattr("polylogue.maintenance.rebuild_index.time.time", ...)`
patches the *stdlib* `time` module's `time` attribute process-wide (module
objects are singletons), not a private copy scoped to rebuild_index.py --
every `time.time()` call anywhere in the process during the invocation
draws from the same finite `[100.0, 102.0]` mock. #3362 (84b8504, two
days ago) added an earlier `time.time()` call to the CLI callback itself
(`click_app.py:_emit_schema_drift_marker`), which now consumes the first
list value before rebuild_index.py's own `pass_started_at_ms` read gets a
turn, collapsing the intended 2-second elapsed gap to zero and silently
defeating the deadline check this test exists to prove (confirmed via a
traceback-tagged `time.time()` wrapper: click_app.py:535 fires before
rebuild_index.py:376). Replaced the finite 2-value list with a
monotonically-advancing `itertools.count(100.0, 50.0)` fake clock, robust
to however many intervening `time.time()` calls production code makes.
- tests/unit/cli/test_daemon_golden_parity.py::test_facets_json_parity_between_direct_and_daemon:
`elapsed_s` (top-level and nested under `availability` --
`FacetsResponse` duplicates it, polylogue/api/archive.py) is a genuine
per-call wall-clock measurement, not a parity signal; popped both before
comparing, alongside the pre-existing `generated_at` pop.
Verification:
- devtools test tests/unit/cli/test_archive_maintenance_cli.py -> 58 passed.
- devtools test tests/unit/cli/test_daemon_golden_parity.py -> 3 passed.
Ref polylogue-c66i
Co-Authored-By: Claude <[email protected]>
Problem: - tests/unit/daemon/test_daemon_http_security.py::TestNoTokenLogging::test_no_token_in_log_or_print_calls: the AST-based token-output scanner flagged two legitimate call sites its name-based taint tracking can't distinguish from real secret leaks: `_handle_query_units` (polylogue/daemon/http.py) echoes decoded query results, not the client-supplied `continuation_token` pagination cursor itself, back via `_send_json`; `_pairing_redeem` (polylogue/browser_capture/server.py, #3260) deliberately returns a freshly-issued `auth_token` to the client that just redeemed its one-time pairing code -- that disclosure IS the endpoint's whole purpose. - tests/unit/daemon/test_route_contracts.py::test_rebuild_index_handler_forwards_resumable_pass_options_through_writer_bridge: the handler (polylogue/daemon/http.py:_handle_rebuild_index, polylogue-ogn1) calls `write_bridge.run_sync_with_timeout(...)` (a longer-timeout variant sized for a bounded rebuild pass) instead of the bridge's default-timeout `run_sync`; the test still mocked/asserted on `run_sync`, so `call_args` was `None` and unpacking it raised `AttributeError` before the test's own assertions ran. - tests/unit/daemon/test_health_contract.py::TestTierInventoryContract::test_medium_tier_inventory_pinned: #3362 ("add provider format-drift sentinel over live ingest") added a new MEDIUM-tier health check (`_check_schema_drift_medium`, polylogue/daemon/health.py) that was never added to this test's pinned `EXPECTED_MEDIUM_CHECKS` inventory. What changed: - test_daemon_http_security.py: added both call sites to `intentional_secret_outputs` with rationale comments. - test_route_contracts.py: updated the mock/assertion to `run_sync_with_timeout` (actor, timeout, function, request) instead of `run_sync` (actor, function, request). - test_health_contract.py: added `"schema_drift"` to `EXPECTED_MEDIUM_CHECKS`. Verification: - devtools test tests/unit/daemon/test_daemon_http_security.py tests/unit/daemon/test_route_contracts.py tests/unit/daemon/test_health_contract.py -> 679 passed. Ref polylogue-c66i Co-Authored-By: Claude <[email protected]>
Summary
Adds a format-drift sentinel: every ingested record's schema-resolution/validation
signal is classified (unseen shape / benign new field / risky field-changed) and
recorded into ops.db, surfaced through
polylogue ops status, a new daemon healthcheck, and a last-resort stderr marker printed on any
polylogueinvocation.Problem
Claude Code, Codex, ChatGPT, and Gemini change their export/JSONL shapes without
notice. Drift previously surfaced as silent parse degradation, discovered manually
weeks later (e.g. the ChatGPT asset-only-node and Antigravity non-UTF-8 drops in
polylogue-qda). Nothing watched for new-unseen-shape rates in live ingest.
Solution
polylogue/schemas/drift_sentinel.py: classifies each validated sample's driftsignal using the existing schema-inference machinery
(
SchemaRegistry.resolve_payload+SchemaValidator.validate). Afallback-to-
package_defaultresolution isunseen_shape; a failed JSON-Schemavalidation is
field_changed(a known field disappeared or changed type); aclean validation with unknown-but-permitted fields is the benign
new_fieldcase.
field_changed/unseen_shapeare risky,new_fieldis benign, and avalidation failure always outranks an unseen-shape classification.
ingest_worker.pynow runsvalidate(include_drift=True)(previouslyFalse— nothing consumed
drift_warnings) and threads aSchemaDriftObservationthrough
IngestRecordResult/_PlanValidation. This never changes accept/rejectsemantics: STRICT-mode failure is still driven by
is_valid/errorsalone, anda drift-shaped record still materializes and ingests normally in advisory mode
(the daemon default) — the sentinel only augments ingest, it never gates it.
ops.db(additive-only, no migration — the ops tier explicitly allows this)gains
schema_drift_samples, keyed by(origin, element_kind, unseen_key_signature), pruned by time/row-count like the existingfts_drift_samplesprecedent.drift_sentinel_sampling.pybridges the batchsummary to ops.db the same best-effort way
sample_fts_drift_to_ops_syncbridges FTS samples: a missing/unreachable ops.db is swallowed, never raised.
summarize_schema_drift_since(ops_write.py) computes a 30-day windowedper-origin risky/benign rate with bounded example raw ids, consumed by three
surfaces:
polylogue ops status(new "Format drift sentinel" section), a newdaemon health check (
_check_schema_drift_medium, thresholds 5%/20% riskyrate), and a last-resort marker in the root CLI callback (
click_app.py) thatprints to stderr on any
polylogueinvocation, independent of daemon liveness— all three read the same windowed summary so they never disagree, and all
three point the follow-up action at
devtools lab schema generate/promote(the sentinel only detects; it never repairs).
Verification
devtools test tests/unit/schemas/test_drift_sentinel.py tests/unit/schemas/test_drift_sentinel_sampling.py tests/unit/storage/test_schema_drift_samples.py tests/unit/pipeline/test_schema_drift_sentinel_ingest.py tests/unit/pipeline/test_resilience.py tests/unit/cli/test_schema_drift_status.py tests/unit/cli/test_schema_drift_marker.py tests/unit/daemon/test_schema_drift_health_check.py→ 51 passed. Anti-vacuity: a real test feedsingest_recordafield_changedsample and assertsresult.sessionsis non-empty in advisory mode — proving the sentinel does not gate ingest (removing the_classify_plan_driftwiring or flippinginclude_driftback toFalsefails this suite).devtools test tests/unit/pipeline/test_ingest_batch*.py tests/unit/pipeline/test_ingest_worker_assembly.py tests/unit/pipeline/test_malformed_jsonl_accounting.py tests/unit/pipeline/test_ingestion_chaos.py→ 128 passed (no ingest-path regression).devtools test tests/unit/cli/test_status.py tests/unit/daemon/test_health_check_paths.py tests/unit/storage/test_fts_identity_ledger.py→ 108 passed, 1 pre-existing failure unrelated to this change (verified failing identically onorigin/masterbefore this branch:test_archive_facade_route_catalog_covers_public_async_facade, a facade-route inventory drift forget_hook_event_summary_for_session/hermes_integration_health).python -m mypy --stricton every changed module: no issues.ruff check/ruff format --check: clean.devtools render all --check: no drift (topology projection regenerated for the two newpolylogue/schemasmodules).devtools verify --quick: all steps green (fixed a layering entrypoint-inventory gap forrecord_schema_drift_sample, addeddegrade-loudly/test-clock-hygiene allowlist entries for the new health-check except-branch and test fixture).Not run: the full
devtools verify --seed-testmonsuite — per repo convention a focused change uses testmon-affected selection ordevtools test <files>, not a blanket full-suite pass.Acceptance criteria (polylogue-da1)
(origin, element_kind, unseen_key_signature), into ops.db via additive columns only.polylogue ops statusline reads "origin X: N% of records since <date> carry unseen shapes" with bounded example native ids; follow-up points atdevtools lab schema generate/promote.polylogueinvocation, independent of daemon health.devtools test <sentinel tests>green.Ref polylogue-da1