Repository navigation
perf(daemon): downgrade FTS trigger drift to INFO during fresh bulk catch-up (#1613) - #1652
Conversation
…atch-up A long fresh-init or large-blob catch-up batch holds an in-flight BEGIN IMMEDIATE transaction with FTS triggers dropped (suspend_fts_triggers in ingest_batch/_core.py). commit_archive_write_effects restores them inside the same transaction before the commit lands, so a separate readonly probe never observes the dropped state in steady-state operation. But operators were seeing CRITICAL "FTS trigger drift: 15/15 missing" during a healthy v9->v16 bootstrap rebuild because the fast-tier health check had no way to distinguish "writer is mid-batch right now" from "SIGKILL leaked triggers". Conflating both in one CRITICAL alert is exactly the boy-who-cried-wolf signal #1605 warns against. Changes: - New HealthSeverity.INFO ranks alongside OK for overall_status rollup so a known-transient bulk-stage signal does not flip the daemon-level health color. - _check_fts_trigger_drift_fast now consults live_ingest_attempt for a row with status='running' in a bulk-suspending phase (full_parse, full_worker_wait) with a fresh heartbeat (within 120s). When found, the alert downgrades to INFO with the attempt id and phase. Stale or orphaned in-flight rows (no heartbeat in the freshness window) still escalate to CRITICAL because that signature is identical to the SIGKILL leak. - Notification backends (apprise, journald) and tier_summary builder learn the new INFO key. Tests: - Seven new cases in test_fts_trigger_drift.py pin both branches: fresh-bulk → INFO, full_parse phase → INFO, stale-bulk → CRITICAL, non-bulk phase → CRITICAL, no attempt table → CRITICAL, completed attempt → CRITICAL, INFO does not escalate overall. - Inherited test failures fixed alongside (CLAUDE.md S19a): - test_raw_failure_sample.py, test_status_maintenance_failures.py, test_provenance_endpoint.py had CREATE TABLE statements with duplicate source_name columns that newer SQLite rejects. - test_health_contracts.py tier_summary literal assertions updated for the new INFO key. Closes #1613 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Warning Review limit reached
More reviews will be available in 5 minutes and 21 seconds. Learn how PR review limits work. Your organization has run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After more reviews become available, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available. Please see our Fair Usage Limits Policy for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (12)
✨ 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 |
…ebuild (#1653) ## Summary Surface DELETE-phase progress in ``rebuild_session_insights_sync`` so the operator log shows forward motion at table granularity instead of "hang" until the first chunk inserts. The seven unconditional DELETEs hold the write lock for seconds at production scale, minutes at 10x. Also pin the atomicity invariant that #1607 questioned — the implicit transaction started by the first DELETE actually does span every subsequent DML through the eventual ``conn.commit()``, so a SIGKILL mid-rebuild does not leave the archive empty. Ref #1607 ## Problem From #1607: > ``polylogue/storage/insights/session/rebuild.py:667-673`` runs seven > unconditional ``DELETE`` statements at the start of every full > insight rebuild [...] cumulative DELETE phase is on the order of > seconds of pure write-lock-under-trigger. On a future 10x archive, > this scales to minutes. During those seconds-to-minutes [...] there > is no progress reporting; the operator sees no output until the > first new row lands. The "non-transactional" framing in the issue is wrong (see Solution below), but the silent DELETE phase is a real operator-experience gap. ``polylogue qa --rebuild-insights`` looked hung on the production archive every time. ## Solution New helper ``_delete_tables_with_progress_sync`` loops the seven DELETEs and emits one ``ProgressCallback`` event per table (``desc="rebuild: cleared <name>"``, ``amount=rowcount``). The ``rebuild_session_insights_sync(conversation_ids=None)`` full-rebuild path and its async counterpart route DELETEs through the helper, threading the existing ``progress_callback`` parameter through. Targeted rebuilds (``conversation_ids != None``) are unchanged because their DELETEs are per-conversation and finish quickly. The CLI progress sink already attached to ``rebuild_session_insights_sync`` (``make_session_insight_progress_callback``) now naturally surfaces a "rebuild: cleared session_work_events" → ... → "rebuild: cleared repo_identities" sequence before the materialize loop's "Materializing: 1/N" output. No CLI changes required. ### Atomicity (AC2) #1607 claims the DELETEs and the rebuild loop are non-transactional and that a SIGKILL between them leaves the archive empty. Tracing the code shows otherwise: - ``conn.execute("DELETE ...")`` opens an implicit transaction (Python sqlite3 default isolation). - Every subsequent ``replace_*_bulk_sync`` runs DML without committing — they all stay in the same implicit tx. - The function commits exactly once at the bottom via ``conn.commit()``. In WAL mode, the DELETEs are not durable until COMMIT. A SIGKILL between DELETE and INSERT rolls back the WAL on next open. Pinned by ``test_full_rebuild_rolls_back_on_exception_keeping_prior_profiles`` which: 1. Runs one rebuild to establish a baseline of session_profiles. 2. Monkeypatches ``build_session_insight_record_bundles`` to raise ``RuntimeError`` from inside the chunk loop. 3. Asserts that ``COUNT(session_profiles)`` after the failed rebuild equals the baseline (not zero). The "AC1 declared op-spec contract" and "AC4 refuse-or-pause live ingest" branches require new infrastructure and stay open against #1607. ## Verification Verification angles considered: - **Direct behavior** ✓ — ``test_delete_tables_with_progress_emits_one_event_per_table`` exercises the helper with a 3-table scenario, asserts ``desc=...`` for each and ``amount=`` matching ``rowcount`` (including 0 for empty tables). - **Direct integration** ✓ — ``test_full_rebuild_emits_progress_for_each_deleted_table`` runs the real ``rebuild_session_insights_sync`` with a seeded conversation and asserts the seven cleared-table events fire in order. - **Counterfactual / robustness** ✓ — ``test_delete_tables_progress_callback_is_optional`` pins that ``progress_callback=None`` does not raise and still runs the DELETEs. - **Atomicity invariant** ✓ — ``test_full_rebuild_rolls_back_on_exception_keeping_prior_profiles`` proves the #1607 "non-atomic" hypothesis wrong with executable evidence. - **Existing-test compatibility** ✓ — ``test_session_insight_rebuild_sync_reports_progress`` updated to filter "Materializing:" events from "rebuild: cleared" events; both sequences pinned. Verification angles skipped: - **Concurrency / lifecycle** — N/A; the function is single-threaded inside one transaction. - **Performance / amplification** — the helper itself runs the same seven DELETEs as before; the extra callback invocation is constant overhead per table. Inherited test failures fixed alongside (CLAUDE.md §19a): - ``tests/unit/storage/test_dead_schema_sweep.py`` — ``test_schema_version_is_14`` was asserting against an outdated constant. Schema is now 16. Renamed the test, updated the comment. - ``tests/unit/storage/test_query_mappers.py`` — ``test_maps_all_fields`` asserted ``source_name == "chatgpt"`` and ``source_name == "inbox"`` on the same row. Removed the duplicate-and-contradictory assertion; seed sets "inbox". Commands run: ``` $ nix develop -c pytest tests/unit/storage/test_session_insight_rebuild_progress.py \ tests/unit/cli/test_insights.py::test_session_insight_rebuild_sync_reports_progress 5 passed in 0.21s $ nix develop -c devtools verify --quick exit_code: 0 ``` ## Notes - Other pre-existing test failures (``test_repair_blobs.py``, ``test_fts5.py``, ``test_schema_safety.py``, the cross-test order flake in ``test_daemon_http_contracts.py`` mentioned in #1652) are out of scope here. They reproduce on master too. Will be tracked as a follow-up sweep. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Session rebuild operations now emit progress feedback events as tables are cleared, providing real-time visibility into ongoing operations. * **Bug Fixes** * Improved transaction error handling to ensure data integrity—failed rebuild operations now automatically roll back to preserve existing data. * **Tests** * Added comprehensive test coverage for progress event reporting and transaction atomicity during rebuild operations. <!-- review_stack_entry_start --> [](https://app.coderabbit.ai/change-stack/Sinity/polylogue/pull/1653?utm_source=github_walkthrough&utm_medium=github&utm_campaign=change_stack) <!-- review_stack_entry_end --> <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
… stale column, renamed index) (#1660) Three small fixes for pre-existing test failures discovered during the 2026-05-27 backlog sweep ([#1657](#1657)). Each was a stale-test issue rather than a production-code bug. ## Changes - **\`tests/unit/storage/test_schema_safety.py\`** — required-index list named the pre-#635 \`idx_conversations_provider\` index, which was renamed to \`idx_conversations_source_name\` during the provider->source storage-column vocabulary transition. Updated the test, added a one-line comment explaining the rename. - **\`tests/unit/storage/test_repair_blobs.py\`** — \`_reference_blob\` helper's INSERT into \`raw_conversations\` passed seven VALUES against a six-column list, tripping \`OperationalError: 7 values for 6 columns\`. The extra \`'referenced.json'\` literal pre-dated a schema column removal. - **\`tests/unit/storage/test_fts5.py\`** — \`test_search_includes_conversation_metadata\` asserted both \`hit.source_name == "claude-ai"\` and \`hit.source_name == "my-source"\` on the same row (impossible). Same shape as the duplicate-column failures fixed in PR #1651/#1652/#1653. Removed the contradictory second assertion. ## Verification \`\`\` $ nix develop -c pytest tests/unit/storage/test_repair_blobs.py \\ tests/unit/storage/test_schema_safety.py tests/unit/storage/test_fts5.py 96 passed in 3.01s $ nix develop -c devtools verify --quick exit_code: 0 \`\`\` ## Out of scope The order-dependent flake in \`test_daemon_http_contracts.py\` (KeyError 'fts_readiness' / 'component_state' under specific pytest-randomly seeds) is tracked separately under #1657. It needs a cross-test mock-state-leak investigation that doesn't fit this PR's small-cleanup shape. Ref #1657. Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Summary
Stop the FAST-tier
fts_trigger_drifthealth check from cryingCRITICAL during a healthy v9→vN bootstrap rebuild. A long
fresh-init or large-blob batch holds an in-flight BEGIN IMMEDIATE
with FTS triggers dropped (the
suspend_fts_triggerswindow iningest_batch/_core.py);commit_archive_write_effectsrestoresthem inside the same transaction before commit. The probe never
observed the dropped state in steady state, but had no way to tell
"writer is mid-batch right now" from "SIGKILL leaked triggers" if
it did — both surfaced as CRITICAL.
Closes #1613.
Problem
From the dogfood report on the v9→v16 rebuild:
The user-facing recovery suggestion is operator-driven and expensive,
but the cause is a normal in-flight bulk batch. Once the batch commits,
triggers are present again — the writer never leaves drift past the
chunk boundary in the happy path. The alert was conflating the
in-flight window (transient) with real drift (SIGKILL leak), so an
operator watching the live dashboard during a fresh-init bootstrap
saw CRITICAL "fixing itself" eventually, which is exactly the
boy-who-cried-wolf signature #1605 warns against.
I verified the happy-path commit cycle traces cleanly: BEGIN IMMEDIATE
→
suspend_fts_triggers_sync(conn, mark_stale=False)→... drain results ... →
ensure_fts_triggers_sync(re-creates) →conn.commit(). Cross-connection visibility in WAL mode issnapshot-isolated; a separate readonly probe sees pre-drop sqlite_master
or post-restore sqlite_master, never the middle. The CRITICAL the
operator saw came from the writer's own connection or from a
real SIGKILL leak — but the alert text was the same either way.
Solution
Introduce
HealthSeverity.INFOfor known-transient states that theoperator should be told about but never paged for. INFO ranks alongside
OK in the overall_status rollup so a healthy bootstrap does not flip
the daemon-level health color.
_check_fts_trigger_drift_fastconsultslive_ingest_attemptfora fresh in-flight row:
status='running'ANDphase IN ('full_parse','full_worker_wait')AND
updated_atwithin_BULK_ATTEMPT_FRESHNESS_S(120s) →alert downgrades to INFO with attempt id + phase + heartbeat time.
status='completed'or non-bulk phase → CRITICAL stays as before,because that signature is identical to the SIGKILL leak.
Notification backends (apprise, journald) and the tier_summary builder
learn the new INFO key. The overall-health computation got factored
into
_compute_overall_health()so the rollup invariant is testablewithout spinning up the full check loop.
Verification
Verification angles considered:
fresh bulk + full_parse → INFO; stale bulk (10min old) → CRITICAL.
completed status → CRITICAL, missing live_ingest_attempt table →
CRITICAL. Each of these closes a specific way the gate could be
too permissive.
(separate test pinning the rollup invariant via
_compute_overall_health).assertions in
test_health_contracts.pyupdated for the new key.Notification backend severity-mapping tables widened.
Verification angles skipped:
SELECT 1 FROM live_ingest_attempt WHERE status='running' AND phase IN (...) ORDER BY updated_at DESC LIMIT 1with an existing index on(status, updated_at DESC, ...). Constant-time.Inherited failures fixed alongside (CLAUDE.md §19a — inherited
baseline must be clean before the new work merges):
test_raw_failure_sample.py,test_status_maintenance_failures.py,test_provenance_endpoint.pyhadCREATE TABLEstatements thatdeclared
source_nametwice. Newer SQLite rejects the duplicatecolumn outright; older SQLite silently took the first value (which
changed which value the test ended up reading in some cases). Removed
the duplicate; the production schema has only one
source_name.Commands run:
Notes
polylogue/daemon/health.pyfile-size budget bumps from 1400 to1500 to fit the new helper. The
daemon/health/split-candidaterecommendation in the budget reason stands.
rows" branch of the issue is already satisfied by
commit_archive_write_effectscallingrepair_message_fts_index_syncfor changed conversations aftertrigger restore. Documented in the FTS5 Model section of
docs/internals.md.test_daemon_http_contracts.py(KeyError 'fts_readiness' /'component_state' under certain random seeds) reproduces on master
without these changes too. Not in scope here; a follow-up will
trace the cross-test state leak.