Skip to content

fix(search): ground FTS freshness in invariants - #1500

Merged
Sinity merged 1 commit into
masterfrom
feature/fix/fts-freshness-invariants
May 24, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/fix/fts-freshness-invariants

Conversation

@Sinity

@Sinity Sinity commented May 24, 2026 •

Copy link
Copy Markdown
Owner

Summary

Daemon startup now grounds the durable FTS freshness ledger in exact executable invariants instead of structural table/trigger checks. If startup observes a stale FTS surface, it rebuilds before search is served. The message indexable-row definition now matches the actual FTS projection by excluding empty messages.text unless content blocks/tool input/metadata contribute searchable content.

Problem

During the schema-v9 live re-ingest, the daemon recorded messages_fts=ready with source_rows=0,indexed_rows=0 on a fresh DB. Catch-up then inserted over a million messages while the readiness ledger still said ready, so search readiness could trust a stale durable row. Direct live evidence before repair showed 1,313,271 indexable message rows versus 818,824 messages_fts_docsize rows.

Solution

_ensure_fts_startup_readiness() now records fts_freshness_state from fts_invariant_snapshot_sync() and rebuilds when the invariant is stale. The startup path still restores missing triggers and rebuilds for the SIGKILL/bulk-suspend failure mode.

The invariant and trigger projection now agree that empty message text is not searchable content. This fixed the live false-stale result after rebuild: with the corrected definition, the partial live DB reported messages_fts|ready|...|743090|743090|0|0|0|.

Closes #1499

Verification

  • pytest tests/unit/daemon/test_daemon_cli.py -q → 19 passed
  • pytest tests/unit/daemon/test_daemon_status.py tests/unit/daemon/test_health_contract.py tests/unit/storage/test_perf_rescue_1314.py -q → 41 passed
  • pytest tests/unit/daemon/test_daemon_cli.py tests/unit/storage/test_retrieval_readiness_laws.py -q → 25 passed
  • python - <<'PY' ... _ensure_fts_startup_readiness() ... PY against the live partial DB → first run rebuilt in 186.188s; after the empty-text fix, exact startup readiness completed in 21.788s and recorded all FTS surfaces ready.
  • devtools verify --quick → pass, 34.42s

Summary by CodeRabbit

Release Notes

  • Bug Fixes
    • Improved Full-Text Search (FTS) initialization to use invariant snapshot verification for more reliable startup readiness detection.
    • Messages with empty text are no longer indexed in Full-Text Search, ensuring only meaningful content is searchable.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 24, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

@Sinity, we couldn't start this review because you've used your available PR reviews for now.

Your plan currently allows 1 review/hour. Refill in 54 minutes and 44 seconds.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more review capacity refills, 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 have higher rate limits than trial, open-source, and free plans. In all cases, review capacity refills continuously over time.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 2c4f12b5-e3b5-4ef4-9abb-0c8f8d124fe1

📥 Commits

Reviewing files that changed from the base of the PR and between 78545de and 5aa1ae6.

📒 Files selected for processing (6)
  • polylogue/daemon/cli.py
  • polylogue/storage/fts/fts_lifecycle.py
  • polylogue/storage/fts/sql.py
  • polylogue/storage/sqlite/schema_ddl_archive.py
  • tests/unit/daemon/test_daemon_cli.py
  • tests/unit/storage/test_retrieval_readiness_laws.py
📝 Walkthrough

Walkthrough

Empty-string message text is excluded from FTS indexable-row counts across SQL helpers, trigger generation, and invariant snapshots. Daemon startup now bases FTS readiness on an executable invariant snapshot instead of structural checks, rebuilding FTS if the snapshot indicates staleness and recording the invariant state for durable verification.

Changes

FTS Freshness via Invariant Snapshots

Layer / File(s) Summary
Empty-string message text exclusion in indexable counts
polylogue/storage/fts/sql.py, polylogue/storage/fts/fts_lifecycle.py, polylogue/storage/sqlite/schema_ddl_archive.py, tests/unit/storage/test_retrieval_readiness_laws.py
FTS_INDEXABLE_MESSAGE_COUNT_SQL and trigger DDL now use NULLIF(text, '') IS NOT NULL to exclude empty-string text from indexable-message counts. Invariant snapshot computations similarly treat empty strings as absent, and test baselines are updated to match.
Daemon startup readiness via invariant snapshot
polylogue/daemon/cli.py, tests/unit/daemon/test_daemon_cli.py
_ensure_fts_startup_readiness() replaces direct empty/READY checks with fts_invariant_snapshot_sync and record_fts_invariant_snapshot_sync calls: captures the snapshot, rebuilds FTS if snapshot.ready is false, and persists the invariant state. Unit tests verify invariant-snapshot mocking and rebuild behavior under both ready and stale scenarios.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • Sinity/polylogue#1443: Modifies _ensure_fts_startup_readiness flow in daemon/cli.py to change what startup readiness probes execute by removing expensive docsize/count/join probes.
  • Sinity/polylogue#1362: Updates _ensure_fts_startup_readiness() to handle trigger restoration after schema drift, operating on the same startup-recovery code path.
  • Sinity/polylogue#1434: Modifies _ensure_fts_startup_readiness() logic and unit tests to change FTS startup readiness/rebuild decisions via a different mechanism.

Poem

🐰 Invariants now guide the way,
No empty text shall lead astray,
Snapshots catch what startup sees,
Fresh search blooms with certainty. 💫

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix(search): ground FTS freshness in invariants' clearly and concisely summarizes the main change: replacing structural checks with executable invariant-based startup readiness.
Description check ✅ Passed The PR description covers all required template sections: Summary explains the change, Problem provides context for why it was necessary, Solution details what was done, and Verification lists exact test commands and live validation results.
Linked Issues check ✅ Passed The PR fully addresses issue #1499 objectives: startup now records FTS freshness from executable invariant snapshots [#1499], rebuilds when stale [#1499], and aligns empty-text definition across invariant and FTS projection [#1499].
Out of Scope Changes check ✅ Passed All changes are directly aligned with the stated objectives: daemon CLI logic, FTS lifecycle invariants, SQL predicates, DDL schema archive, and corresponding unit tests—no unrelated refactoring or scope creep detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fix/fts-freshness-invariants

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 78545de9e7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread polylogue/storage/fts/fts_lifecycle.py Resolved
Daemon startup no longer records a durable FTS ready row from structural table and trigger checks alone. It now records the exact FTS invariant snapshot and rebuilds before serving search when the invariant is stale.

Align the message indexable-row definition with the actual FTS projection by excluding empty message text unless content blocks, tool input, or metadata provide searchable content.

Closes #1499
@Sinity
Sinity force-pushed the feature/fix/fts-freshness-invariants branch from 78545de to 5aa1ae6 Compare May 24, 2026 16:04

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@polylogue/storage/fts/fts_lifecycle.py`:
- Around line 872-873: The no-content-block rebuild branches still use the
legacy WHERE text IS NOT NULL predicate which allows empty-string texts to be
counted/inserted, so update those SQL fragments to use the same empty-text
invariant as the rest of the code: replace occurrences of "WHERE text IS NOT
NULL" in the no-content-block rebuild SQL (the SELECT/COUNT and any INSERT ...
SELECT clauses) with "WHERE NULLIF(text, '') IS NOT NULL" so they ignore
empty-string text; search for the SQL fragments in
polylogue/storage/fts/fts_lifecycle.py (the no-content-block rebuild branches
around the existing NULLIF usage) and make the replacement in each branch (the
three spots noted).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 5d0f06d8-b6ac-48ca-95ef-02cfe30dabe1

📥 Commits

Reviewing files that changed from the base of the PR and between fdb1e45 and 78545de.

📒 Files selected for processing (6)
  • polylogue/daemon/cli.py
  • polylogue/storage/fts/fts_lifecycle.py
  • polylogue/storage/fts/sql.py
  • polylogue/storage/sqlite/schema_ddl_archive.py
  • tests/unit/daemon/test_daemon_cli.py
  • tests/unit/storage/test_retrieval_readiness_laws.py

Comment thread polylogue/storage/fts/fts_lifecycle.py Resolved
@Sinity
Sinity merged commit ee5a507 into master May 24, 2026
6 checks passed
@Sinity
Sinity deleted the feature/fix/fts-freshness-invariants branch May 24, 2026 16:06
Sinity added a commit that referenced this pull request May 24, 2026
Summary: Make live ingest maintain FTS freshness as a write-side invariant instead of relying on trigger timing alone.

Problem: After exact startup readiness landed in #1500, the production archive still drifted during live catch-up. With the daemon stopped, exact invariants showed 10,414 missing message FTS rows and 3,777 missing action-event FTS rows. The missing message rows were block-only messages whose searchable text lives in content_blocks; live full/append ingest had opted out of conversation-scoped repair unless triggers were suspended, and explicit repair flags were ignored when triggers existed.

Solution: Treat repair_message_fts/repair_action_fts as literal write-effect requests, make live full and append ingest request conversation-scoped message/action repairs for changed conversations, refresh trigger definitions before stale-startup rebuilds, and make exact invariant snapshots read one stable transaction.

Verification: pytest tests/unit/archive/test_write_gateway.py tests/unit/daemon/test_daemon_cli.py tests/unit/sources/test_live_batch_support.py tests/unit/storage/test_retrieval_readiness_laws.py tests/unit/storage/test_perf_rescue_1314.py tests/unit/pipeline/test_ingest_batch.py tests/unit/pipeline/test_ingest_batch_wal_checkpoint.py tests/unit/storage/test_fts_trigger_lifecycle.py -q (87 passed); devtools verify --quick (exit_code 0); pre-push devtools verify --quick (exit_code 0); production archive targeted repair reported all FTS surfaces ready with zero missing/excess/duplicates.

Closes #1501
Sinity added a commit that referenced this pull request Aug 17, 2026
polylogue-gibn1, decisive: instrumented the sole consumer of
summary.fts_repair_session_ids (_commit_sync_ingest_side_effects) and it never
printed across five sessions and sixty messages in the failing
convergence-evidence test. The repair is nested inside `if transaction_started`,
so a route with an externally managed transaction skips FTS repair along with
every other post-write side effect.

Eliminated: repair_message_fts (defaults True everywhere, no daemon override),
the repair queue itself (content_changed appends unconditionally), the invariant
reader, and the triggers. Three independent places each assume another will
populate the index: replay defers the reinsert, ingest-side repair never runs,
and the path-scoped convergence check is a hardcoded `return False`.

Read the #1498 cascade retro as CLAUDE.md requires; its closed list names the
adjacent history (#1462, #1469, #1472, #1500, #1502), several of which narrowed
FTS repair to avoid redundant work. Those PR bodies are the place to start.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HWcPJJJvuF25CqVwTFgSQC
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 73.F072 / P2: refuted at the checked revision: The finding requires maintaining the legacy schema branch without content blocks. AGENTS.md:75-76 excludes predecessor archive layouts and :192-194 requires compatibility paths to be removed, not aligned with fresh-format FTS rebuilds.

Only the rows listed above are dispositioned. Held findings remain open.

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.

fix(search): ground FTS freshness in executable invariants

1 participant