Skip to content

fix(daemon): fix FTS commit ordering and quarantine visibility bugs - #882

Merged
Sinity merged 1 commit into
masterfrom
feature/fix/quarantine-fts-fix
May 7, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/fix/quarantine-fts-fix

Conversation

@Sinity

@Sinity Sinity commented May 7, 2026 •

Copy link
Copy Markdown
Owner

Summary

Two correctness fixes found during #852 mass-execution reconnaissance.

Problem

  1. FTS commit ordering (refactor(storage): reduce FTS bloat and stale schema/read-path drift #817): restore_fts_triggers_sync() ran AFTER conn.commit() in the finally block. If it failed, data was already committed with suspended FTS triggers, causing silent stale search results.

  2. Quarantine invisibility (fix(daemon): surface raw validation and parse failures in ingest/status #844): RawIngestArtifactState.quarantined checked only parse_error, but strict schema validation failures set validation_error without parse_error, making them invisible to operators.

Solution

  1. FTS triggers now restored BEFORE conn.commit() — if restore fails, the exception propagates before marking the batch committed.

  2. quarantined property now also checks validation_status is ValidationStatus.FAILED.

Verification

  • devtools verify --quick — all 14 gates passed
  • 2 files, +9/-1

Refs #817 #844 #852

Summary by CodeRabbit

  • Bug Fixes
    • Improved data ingestion reliability by enhancing transaction handling during processing.
    • Refined artifact quarantine detection logic to better identify and handle problematic items based on validation status.

Two correctness fixes found during #852 mass-execution recon:

1. FTS triggers now restored BEFORE conn.commit() in ingest batch processing.
   Previously restore_fts_triggers_sync() ran after commit in the finally
   block — if it failed, data was already committed with suspended triggers,
   causing silent stale search results. (#817)

2. Raw artifact quarantine now correctly catches strict schema validation
   failures. The quarantined property checked only parse_error, but strict
   validation failures set validation_error without parse_error, making them
   invisible to operators. (#844)

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Copilot AI review requested due to automatic review settings May 7, 2026 06:48
@Sinity
Sinity merged commit 9246930 into master May 7, 2026
3 of 4 checks passed
@Sinity
Sinity deleted the feature/fix/quarantine-fts-fix branch May 7, 2026 06:48
@coderabbitai

coderabbitai Bot commented May 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: d79835b0-e592-4ffc-8d74-ecc5f82e295a

📥 Commits

Reviewing files that changed from the base of the PR and between 42952da and d1b8b30.

📒 Files selected for processing (2)
  • polylogue/pipeline/services/ingest_batch/_core.py
  • polylogue/storage/raw/artifacts.py

📝 Walkthrough

Walkthrough

This PR refines artifact ingestion batch processing by updating quarantine classification criteria to consider validation status and integrating FTS trigger restoration into the commit sequence before the SQLite transaction finalization.

Changes

Artifact Ingestion Quality Control

Layer / File(s) Summary
Artifact Quarantine Classification
polylogue/storage/raw/artifacts.py
RawIngestArtifactState.quarantined property now considers both parse_error is not None and validation_status == ValidationStatus.FAILED to determine quarantine status for unparsed artifacts.
Commit-Time FTS Trigger Restoration
polylogue/pipeline/services/ingest_batch/_core.py
_commit_ingest_results calls restore_fts_triggers_sync(conn) after flushing pending entries and before conn.commit() to restore FTS triggers while the transaction remains active.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

🐰 In batches we ingest with care,
Quarantine the bad, triggers to spare,
FTS restored before commit's call,
Order matters most of all! 🌲

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fix/quarantine-fts-fix

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.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR addresses two daemon/storage correctness issues: ensuring FTS triggers are restored before an ingest batch is committed (to avoid durable stale search state), and making strict schema-validation failures visible as “quarantined” artifacts for operator/status surfaces.

Changes:

  • Update RawIngestArtifactState.quarantined to treat validation_status == FAILED as quarantined even when parse_error is absent.
  • Restore FTS triggers before conn.commit() in the ingest batch commit path so trigger-restore failures prevent the batch from being marked committed.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
polylogue/storage/raw/artifacts.py Expands quarantine classification to include strict validation failures (ValidationStatus.FAILED).
polylogue/pipeline/services/ingest_batch/_core.py Restores FTS triggers before committing ingest results to prevent committing with triggers suspended.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines 51 to 54
@property
def quarantined(self) -> bool:
return not self.parsed and self.parse_error is not None
return not self.parsed and (self.parse_error is not None or self.validation_status is ValidationStatus.FAILED)

Comment on lines +882 to +885
# Restore FTS triggers BEFORE commit so they are durable with the data.
# CREATE TRIGGER is DDL and auto-commits the pending transaction, so the
# explicit conn.commit() below becomes a no-op. If restore fails, the
# exception propagates before we mark the batch as committed.
Sinity added a commit that referenced this pull request May 7, 2026
Sinity added a commit that referenced this pull request May 7, 2026
Two correctness fixes found during #852 reconnaissance.

- #817 (FTS safety): `restore_fts_triggers_sync()` ran AFTER
  `conn.commit()` in the finally block, so a failed restore
  left data committed with suspended FTS triggers and silent
  stale search results. Restore now runs BEFORE commit; if
  restore raises, the exception propagates and the batch is
  not marked committed.
- #844 (quarantine visibility): the `quarantined` property on
  `RawIngestArtifactState` only checked `parse_error`, so
  strict-validation failures (which set `validation_error`
  without `parse_error`) were invisible to operators. Now
  also checks `validation_status is ValidationStatus.FAILED`.

Refs #817, #844
Sinity added a commit that referenced this pull request May 7, 2026
Two follow-ups merged together.

- #882 (FTS / quarantine): regression tests in
  `tests/unit/storage/test_backend.py` pinning the FTS
  trigger-restore-before-commit ordering and the
  `quarantined` property's coverage of
  `validation_status=FAILED` so the original PR #882 fixes
  cannot silently regress.
- #830 (tiered health): `polylogue/daemon/cli.py` wires the
  periodic health-check loop into the daemon main loop and
  schedules notifications when a check transitions to a worse
  severity.

Refs #830, #882
Sinity added a commit that referenced this pull request May 7, 2026
Direct, no-PR. Local repair in
`tests/unit/storage/test_backend.py`: the wave that landed
PRs #882/#903/#911 left two FK-test cases referencing helper
names that had been renamed in the same wave, so
`devtools verify` failed at the test stage even though every
individual PR's CI was green. Realigns the helper names; pure
test-file repair, no production code change.
Sinity added a commit that referenced this pull request May 7, 2026
Direct, no-PR. `tests/unit/storage/test_backend.py` accumulated
regression cases from the FK / quarantine / FTS / blob waves
(PRs #879/#881/#882/#903/#911) and exceeded its previous LOC
budget. Bumps `docs/plans/file-size-budgets.yaml` to 1750 so
`devtools verify-file-budgets` passes; the tests stay grouped
in one place rather than splitting along an arbitrary cut.
Sinity added a commit that referenced this pull request May 7, 2026
Three follow-up fixes after the larger schema/daemon waves
landed, each tied to a distinct issue but sharing files in the
ingest_batch and convergence layers.

- #817 (FTS safety): adds a regression test pinning that the FTS
  trigger restore runs before commit so a SIGKILL during
  trigger-suspend cannot leave the index permanently desynced
  (the original ordering bug from PR #882).
- #844 (detection visibility): populates `detection_warnings`
  during parse-error handling in `pipeline/services/
  ingest_batch/_core.py` and surfaces them through
  `daemon/status.py` so silently dropped artifacts become
  visible.
- #864 (provider_meta graduation): adds the canonical `cwd_path`
  filter in `storage/sqlite/queries/filter_builder.py` and a
  `working_directories` backfill in `schema_bootstrap.py`,
  finishing the move off `provider_meta` JSON paths for the
  cwd-based filter.

Refs #817, #844, #864
Sinity added a commit that referenced this pull request May 7, 2026
Two correctness fixes found during #852 reconnaissance.

- #817 (FTS safety): `restore_fts_triggers_sync()` ran AFTER
  `conn.commit()` in the finally block, so a failed restore
  left data committed with suspended FTS triggers and silent
  stale search results. Restore now runs BEFORE commit; if
  restore raises, the exception propagates and the batch is
  not marked committed.
- #844 (quarantine visibility): the `quarantined` property on
  `RawIngestArtifactState` only checked `parse_error`, so
  strict-validation failures (which set `validation_error`
  without `parse_error`) were invisible to operators. Now
  also checks `validation_status is ValidationStatus.FAILED`.

Refs #817, #844
Sinity added a commit that referenced this pull request May 7, 2026
Two follow-ups merged together.

- #882 (FTS / quarantine): regression tests in
  `tests/unit/storage/test_backend.py` pinning the FTS
  trigger-restore-before-commit ordering and the
  `quarantined` property's coverage of
  `validation_status=FAILED` so the original PR #882 fixes
  cannot silently regress.
- #830 (tiered health): `polylogue/daemon/cli.py` wires the
  periodic health-check loop into the daemon main loop and
  schedules notifications when a check transitions to a worse
  severity.

Refs #830, #882
Sinity added a commit that referenced this pull request May 7, 2026
Direct, no-PR. Local repair in
`tests/unit/storage/test_backend.py`: the wave that landed
PRs #882/#903/#911 left two FK-test cases referencing helper
names that had been renamed in the same wave, so
`devtools verify` failed at the test stage even though every
individual PR's CI was green. Realigns the helper names; pure
test-file repair, no production code change.
Sinity added a commit that referenced this pull request May 7, 2026
Direct, no-PR. `tests/unit/storage/test_backend.py` accumulated
regression cases from the FK / quarantine / FTS / blob waves
(PRs #879/#881/#882/#903/#911) and exceeded its previous LOC
budget. Bumps `docs/plans/file-size-budgets.yaml` to 1750 so
`devtools verify-file-budgets` passes; the tests stay grouped
in one place rather than splitting along an arbitrary cut.
Sinity added a commit that referenced this pull request May 7, 2026
Three follow-up fixes after the larger schema/daemon waves
landed, each tied to a distinct issue but sharing files in the
ingest_batch and convergence layers.

- #817 (FTS safety): adds a regression test pinning that the FTS
  trigger restore runs before commit so a SIGKILL during
  trigger-suspend cannot leave the index permanently desynced
  (the original ordering bug from PR #882).
- #844 (detection visibility): populates `detection_warnings`
  during parse-error handling in `pipeline/services/
  ingest_batch/_core.py` and surfaces them through
  `daemon/status.py` so silently dropped artifacts become
  visible.
- #864 (provider_meta graduation): adds the canonical `cwd_path`
  filter in `storage/sqlite/queries/filter_builder.py` and a
  `working_directories` backfill in `schema_bootstrap.py`,
  finishing the move off `provider_meta` JSON paths for the
  cwd-based filter.

Refs #817, #844, #864
Sinity added a commit that referenced this pull request May 16, 2026
) (#1098)

## Summary

Pin the post-#944 external-content FTS conversion with three focused
regression tests, and clear an inherited mypy `redundant-expr` failure
that was blocking the local `devtools verify --quick` baseline.

The headline scope of #817 — FTS storage bloat, external-content delete
correctness, FTS trigger commit-ordering, JSON tag read paths — already
landed across #944 / #882. After auditing each acceptance criterion on
master and against the corrections in the reopened-issue comments
(`live_cursor` is active, `conversation_tags` is active,
`ArchiveWriteGateway` is active), the actionable remaining work for this
scope is *durable evidence*: the invariants must not silently regress,
and the catalogue must hold them after future schema edits.

## Problem

The original PR for #817 attempted the external-content FTS conversion
but reverted it because a DELETE on `messages` left the row matchable in
FTS. The conversion was reapplied in #944 (with the corrected
`messages_fts_ad` trigger), but no committed test verifies either:

- the DDL still uses `content='messages', content_rowid='rowid'`,
- on synthetic data the FTS pages stay well under the source-table
  pages (the original "~6 GB bloat" claim),
- DELETE on `messages` is propagated to `messages_fts` via the AD
  trigger (the exact bug that forced the earlier revert).

Without that coverage, the next schema edit that touches
`MESSAGE_FTS_DDL`
or the trigger DDL in `polylogue/storage/fts/fts_lifecycle.py` can
silently bring the bloat back, and CI will not notice.

Concurrent finding: `devtools verify --quick` on master fails with one
mypy `[redundant-expr]` error in `devtools/evidence_dashboard.py:347`
introduced by #1091. That blocks every push from this branch (and
every other branch), so it is folded into this PR.

## Solution

`tests/unit/storage/test_fts_bloat_invariants.py` (new file, owned by
the storage tier):

- `test_messages_fts_is_contentless_external_content` — reads
  `sqlite_master.sql` for `messages_fts` and asserts the DDL still
  carries both `content='messages'` and `content_rowid='rowid'`.
- `test_messages_fts_storage_does_not_duplicate_message_bodies` —
  synthesises 2000 messages × ~5 KB and uses the `dbstat` virtual
  table to compare `SUM(pgsize) WHERE name LIKE 'messages_fts%'` to
  `SUM(pgsize) WHERE name LIKE 'messages%'`. Observed ratio on the
  fixture is ~0.2; threshold is 0.5, well below the ~1.0 a regression
  to standalone FTS5 would produce.
- `test_messages_fts_deletion_consistency_with_external_content` —
  inserts two messages with unique tokens, deletes one, and asserts
  the deleted token no longer matches while the surviving token still
  does. Pins the `messages_fts_ad` trigger semantics.

The dedicated file (151 LOC) was placed alongside `test_fts5.py` instead
of inlined because `test_fts5.py` is already at its declared
`docs/plans/file-size-budgets.yaml` ceiling of 1650 LOC.

`devtools/evidence_dashboard.py` — drop the `isinstance(entry, dict)`
guard on a `list[dict[str, Any]]` so mypy --strict is clean again.

### Audit results for the original #817 acceptance criteria

| AC | State | Evidence |
| --- | --- | --- |
| FTS bloat measured before/after | Pinned by new tests | Synthetic
fixture: messages = ~11 MB, messages_fts_* = ~2.1 MB (ratio ~0.19) |
| Removed indexes/tables/columns have query evidence | No removal in
this PR — `idx_messages_provider_role`, `idx_messages_provider_stats`,
all four `idx_conv_stats_*` indexes are actively used by `EXPLAIN QUERY
PLAN` on the filter pushdowns and provider-rollup queries | EQP probes
against synthetic data |
| Remaining tag reads use canonical M2M tag model |
`storage/sqlite/queries/conversations_identity.py:list_tags` already
prefers the `conversation_tags`+`tags` M2M join; the JSON
`metadata->'tags'` query is an explicitly documented fallback for
unmigrated archives only. The other `json_extract(metadata, '$.tags')`
matches in `schema_bootstrap.py` are one-time migration backfill SQL
(`SchemaBackfillDescriptor`), not runtime reads | Grep + file inspection
|
| FTS trigger suspension/repair regression coverage | Pre-existing
`test_fts_triggers_restored_after_exception` (test_fts5.py:1498),
`test_fts_triggers_restored_after_exception_during_ingest`
(test_backend.py:1652), plus daemon startup-repair path in
`polylogue/daemon/cli.py:_fts_startup_check` | Existing tests + daemon
code |
| Schema/fresh-init implications recorded | No schema change in this PR.
The new tests are read-only against the current `SCHEMA_DDL` | N/A |

ANALYZE scheduling already exists in
`polylogue/daemon/cli.py:_periodic_db_optimize` (daily `PRAGMA
optimize`).

### Files NOT changed (intentional)

Per the worktree scope, only `polylogue/storage/sqlite/`,
`polylogue/storage/search_providers/`, repository read-side mixins, and
related tests are owned by this PR. The mypy fix in `devtools/` is an
inherited blocker that must be cleared to push from this branch; it is
intentionally minimal (one line) and unrelated to ownership boundaries.

## Verification

```
$ nix develop -c pytest tests/unit/storage/test_fts_bloat_invariants.py -q
...                                                                      [100%]
3 passed in 20.23s

$ nix develop -c mypy --strict polylogue tests/unit/storage devtools
Success: no issues found in 873 source files

$ nix develop -c devtools verify-file-budgets
file-size budgets: clean

$ git push  # (pre-push hook = devtools verify --quick)
... exit_code: 0
```

Measured FTS bloat (synthetic 2000-message fixture, ~10 MB of message
text, post-VACUUM):

```
messages table pages:     10,936,320 bytes  (~10.4 MB)
messages_fts_data:         2,109,440 bytes
messages_fts_docsize:         28,672 bytes
messages_fts_config:           4,096 bytes
messages_fts_idx:              4,096 bytes
messages_fts total:        2,146,304 bytes  (~2.0 MB)
ratio:                          ~0.20
```

Stale JSON-tag read paths migrated: 0 (the only remaining JSON read in
`list_tags` is an explicit fallback for unmigrated archives, kept on
purpose per the issue's "stale JSON tag reads should use
`conversation_tags`+`tags`" framing combined with the schema-bootstrap
backfill that turns the JSON tags into M2M rows on first start).

Ref #817

---------

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.

2 participants