Skip to content

feat(daemon): add provider format-drift sentinel over live ingest - #3362

Merged
Sinity merged 1 commit into
masterfrom
feature/feat/format-drift-sentinel
Jul 27, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/feat/format-drift-sentinel

Conversation

@Sinity

@Sinity Sinity commented Jul 27, 2026

Copy link
Copy Markdown
Owner

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 health
check, and a last-resort stderr marker printed on any polylogue invocation.

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 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 a
    validation failure always outranks an unseen-shape classification.
  • ingest_worker.py now runs validate(include_drift=True) (previously False
    — nothing consumed drift_warnings) 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; 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 feeds ingest_record a field_changed sample and asserts result.sessions is non-empty in advisory mode — proving the sentinel does not gate ingest (removing the _classify_plan_drift wiring or flipping include_drift back to False fails 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 on origin/master before this branch: test_archive_facade_route_catalog_covers_public_async_facade, a facade-route inventory drift for get_hook_event_summary_for_session/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, 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 — per repo convention a focused change uses testmon-affected selection or devtools test <files>, not a blanket full-suite pass.

Acceptance criteria (polylogue-da1)

  • Records whose shape doesn't match the committed schema package are counted, keyed by (origin, element_kind, unseen_key_signature), into ops.db via additive columns only.
  • Ingest never fails/skips on drift — verified by a test feeding an unseen-shape record.
  • Distinguishes benign new-field drift from risky missing/changed-field drift, with different alert thresholds (5%/20% risky rate).
  • Rate is windowed since a date (30 days), not lifetime.
  • Daemon health check + polylogue ops status line reads "origin X: N% of records since <date> carry unseen shapes" with bounded example native ids; follow-up points at devtools lab schema generate/promote.
  • Last-resort status-line marker visible on any polylogue invocation, independent of daemon health.
  • devtools test <sentinel tests> green.

Ref polylogue-da1

@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, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

@Sinity, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 43 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 50d858aa-03f4-4084-bdda-a5fa21bc58f2

📥 Commits

Reviewing files that changed from the base of the PR and between b064158 and 2794ca2.

📒 Files selected for processing (23)
  • docs/plans/degrade-loudly-allowlist.yaml
  • docs/plans/layering.yaml
  • docs/plans/test-clock-allowlist.yaml
  • docs/plans/topology-target.yaml
  • docs/topology-status.md
  • polylogue/cli/click_app.py
  • polylogue/cli/commands/status.py
  • polylogue/daemon/health.py
  • polylogue/pipeline/services/ingest_batch/_core.py
  • polylogue/pipeline/services/ingest_batch/_models.py
  • polylogue/pipeline/services/ingest_worker.py
  • polylogue/schemas/drift_sentinel.py
  • polylogue/schemas/drift_sentinel_sampling.py
  • polylogue/storage/sqlite/archive_tiers/ops.py
  • polylogue/storage/sqlite/archive_tiers/ops_write.py
  • tests/unit/cli/test_schema_drift_marker.py
  • tests/unit/cli/test_schema_drift_status.py
  • tests/unit/daemon/test_schema_drift_health_check.py
  • tests/unit/pipeline/test_resilience.py
  • tests/unit/pipeline/test_schema_drift_sentinel_ingest.py
  • tests/unit/schemas/test_drift_sentinel.py
  • tests/unit/schemas/test_drift_sentinel_sampling.py
  • tests/unit/storage/test_schema_drift_samples.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/format-drift-sentinel

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.

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]>
@Sinity
Sinity force-pushed the feature/feat/format-drift-sentinel branch from cc52780 to 2794ca2 Compare July 27, 2026 21:20
@Sinity
Sinity merged commit 84b8504 into master Jul 27, 2026
3 checks passed
@Sinity
Sinity deleted the feature/feat/format-drift-sentinel branch July 27, 2026 21:25
Sinity added a commit that referenced this pull request Jul 29, 2026
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]>
Sinity added a commit that referenced this pull request Jul 29, 2026
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]>
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