Repository navigation
fix(daemon): fix FTS commit ordering and quarantine visibility bugs - #882
Conversation
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]>
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (2)
📝 WalkthroughWalkthroughThis 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. ChangesArtifact Ingestion Quality Control
Estimated code review effort🎯 2 (Simple) | ⏱️ ~12 minutes Poem
✨ Finishing Touches📝 Generate docstrings
🧪 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 |
There was a problem hiding this comment.
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.quarantinedto treatvalidation_status == FAILEDas quarantined even whenparse_erroris 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.
| @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) | ||
|
|
| # 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. |
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
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
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.
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.
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
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
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
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.
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.
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
) (#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]>
Summary
Two correctness fixes found during #852 mass-execution reconnaissance.
Problem
FTS commit ordering (refactor(storage): reduce FTS bloat and stale schema/read-path drift #817):
restore_fts_triggers_sync()ran AFTERconn.commit()in the finally block. If it failed, data was already committed with suspended FTS triggers, causing silent stale search results.Quarantine invisibility (fix(daemon): surface raw validation and parse failures in ingest/status #844):
RawIngestArtifactState.quarantinedchecked onlyparse_error, but strict schema validation failures setvalidation_errorwithoutparse_error, making them invisible to operators.Solution
FTS triggers now restored BEFORE
conn.commit()— if restore fails, the exception propagates before marking the batch committed.quarantinedproperty now also checksvalidation_status is ValidationStatus.FAILED.Verification
devtools verify --quick— all 14 gates passedRefs #817 #844 #852
Summary by CodeRabbit