Skip to content

perf(daemon): downgrade FTS trigger drift to INFO during fresh bulk catch-up (#1613) - #1652

Merged
Sinity merged 1 commit into
masterfrom
feature/perf/fts-trigger-bulk-stage-alert
May 27, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/perf/fts-trigger-bulk-stage-alert

Conversation

@Sinity

@Sinity Sinity commented May 27, 2026

Copy link
Copy Markdown
Owner

Summary

Stop the FAST-tier fts_trigger_drift health check from crying
CRITICAL 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_triggers window in
ingest_batch/_core.py); commit_archive_write_effects restores
them 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:

[critical] FTS trigger drift: 15/15 missing (...); restore with
`polylogue check --repair-fts` (rebuild ~O(messages))

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 is
snapshot-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.INFO for known-transient states that the
operator 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_fast consults live_ingest_attempt for
a fresh in-flight row:

  • status='running' AND phase IN ('full_parse','full_worker_wait')
    AND updated_at within _BULK_ATTEMPT_FRESHNESS_S (120s) →
    alert downgrades to INFO with attempt id + phase + heartbeat time.
  • Stale row (no heartbeat in the freshness window) or
    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 testable
without spinning up the full check loop.

Verification

Verification angles considered:

  • Direct behavior ✓ — fresh bulk + full_worker_wait → INFO;
    fresh bulk + full_parse → INFO; stale bulk (10min old) → CRITICAL.
  • Counterfactual / lifecycle ✓ — non-bulk phase → CRITICAL,
    completed status → CRITICAL, missing live_ingest_attempt table →
    CRITICAL. Each of these closes a specific way the gate could be
    too permissive.
  • Contract ✓ — INFO severity does not escalate overall_status
    (separate test pinning the rollup invariant via
    _compute_overall_health).
  • Existing-test compatibility ✓ — tier_summary literal
    assertions in test_health_contracts.py updated for the new key.
    Notification backend severity-mapping tables widened.

Verification angles skipped:

  • Concurrency — N/A; the probe is a single-shot read.
  • Performance — the added query is SELECT 1 FROM live_ingest_attempt WHERE status='running' AND phase IN (...) ORDER BY updated_at DESC LIMIT 1 with an existing index on
    (status, updated_at DESC, ...). Constant-time.
  • Witness — N/A; the bug is timing-based, not minimizable input.

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.py had CREATE TABLE statements that
    declared source_name twice. Newer SQLite rejects the duplicate
    column 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:

$ nix develop -c pytest tests/unit/daemon/test_fts_trigger_drift.py
33 passed in 0.48s

$ nix develop -c pytest tests/unit/daemon/test_raw_failure_sample.py \
    tests/unit/daemon/test_status_maintenance_failures.py
31 passed in 0.26s

$ nix develop -c devtools verify --quick
exit_code: 0

Notes

  • polylogue/daemon/health.py file-size budget bumps from 1400 to
    1500 to fit the new helper. The daemon/health/ split-candidate
    recommendation in the budget reason stands.
  • The "AC2 — live appends during catch-up must not skip FTS shadow
    rows" branch of the issue is already satisfied by
    commit_archive_write_effects calling
    repair_message_fts_index_sync for changed conversations after
    trigger restore. Documented in the FTS5 Model section of
    docs/internals.md.
  • The unrelated order-dependent flake in
    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.

…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]>
@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.

@coderabbitai

coderabbitai Bot commented May 27, 2026

Copy link
Copy Markdown

Warning

Review limit reached

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

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: d75f1cc1-d608-4536-b290-1c7edb4ce8ce

📥 Commits

Reviewing files that changed from the base of the PR and between 8f4941b and a99c27b.

📒 Files selected for processing (12)
  • AGENTS.md
  • docs/internals.md
  • docs/plans/file-size-budgets.yaml
  • docs/plans/test-clock-allowlist.yaml
  • polylogue/daemon/health.py
  • polylogue/daemon/notification_backends/apprise_backend.py
  • polylogue/daemon/notification_backends/journald.py
  • tests/unit/daemon/test_fts_trigger_drift.py
  • tests/unit/daemon/test_health_contracts.py
  • tests/unit/daemon/test_provenance_endpoint.py
  • tests/unit/daemon/test_raw_failure_sample.py
  • tests/unit/daemon/test_status_maintenance_failures.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/perf/fts-trigger-bulk-stage-alert

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 and usage tips.

@Sinity
Sinity merged commit afc5118 into master May 27, 2026
7 checks passed
@Sinity
Sinity deleted the feature/perf/fts-trigger-bulk-stage-alert branch May 27, 2026 08:11
Sinity added a commit that referenced this pull request May 27, 2026
…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 -->

[![Review Change
Stack](https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg)](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]>
Sinity added a commit that referenced this pull request May 27, 2026
… 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]>
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.

perf(daemon): FTS trigger suspension during catch-up surfaces as CRITICAL health drift; needs scoped lifetime

1 participant