Skip to content

fix(search): enforce FTS freshness invariant - #1440

Merged
Sinity merged 4 commits into
masterfrom
feature/fix/fts-freshness-invariant
May 23, 2026
Merged

Sinity merged 4 commits into
masterfrom
feature/fix/fts-freshness-invariant

Conversation

@Sinity

@Sinity Sinity commented May 23, 2026 •

Copy link
Copy Markdown
Owner

Summary

Makes FTS freshness an exact runtime invariant instead of a tolerated search-time best effort. The branch adds exact status for active FTS search surfaces, removes the small-gap grace path, blocks readiness when an existing archive has stale FTS, and stops search paths from silently returning empty/partial results when indexes are missing or stale.

Problem

Search could still operate while FTS was stale: message FTS allowed a 1% gap, async search paths used partial probes, action search fell back to a stale-masking slow path, and the low-level FTS5 provider returned [] when the index was missing. That made daemon convergence unreliable from the user’s perspective: the daemon could appear operational while search was incomplete.

Solution

  • Add FtsInvariantSnapshot / FtsSurfaceInvariant covering messages_fts, action_events_fts, session_work_events_fts, and work_threads_fts.
  • Remove FTS_GAP_THRESHOLD; message readiness now requires exact readiness when checked.
  • Keep perf(storage): rescue perf items from #809→#815→#817 fold (from #1310 audit) #1314’s bounded hot-query probe for message search, relying on daemon readiness for exact parity instead of counting FTS on every query.
  • Make action search reject unready action FTS instead of silently falling back.
  • Make FTS5Provider.search() raise on missing/incomplete FTS instead of returning empty results.
  • Add exact insight FTS guards for work-event/thread query paths.
  • Surface invariant details in daemon status and make /healthz/ready return fts_not_fresh for existing archives whose FTS invariant is false.

Verification

  • pytest tests/unit/storage/test_retrieval_readiness_laws.py tests/unit/storage/test_fts5.py tests/unit/archive/test_query_search_runtime.py tests/unit/daemon/test_health_check_paths.py tests/unit/daemon/test_daemon_status.py tests/unit/daemon/test_health_contract.py::TestReadinessProbeContract tests/unit/daemon/test_fts_trigger_drift.py tests/unit/storage/test_fts_trigger_lifecycle.py tests/unit/storage/test_fts_repair_sql.py tests/unit/cli/test_insights.py::test_insights_profiles_reject_incomplete_profile_search_index tests/unit/storage/test_fts_escape_in_insights.py -q → 173 passed, then after perf(storage): rescue perf items from #809→#815→#817 fold (from #1310 audit) #1314/action adjustments 175 passed.
  • devtools verify --quick → exit 0.
  • git push pre-push quick gate reran devtools verify --quick at bb06ebd4 → exit 0.
  • devtools verify --seed-testmon --skip-slow ran the static/generated gates successfully, then failed in pytest with 11 failures out of 9293 tests. Branch-owned failures were fixed and rerun directly. Remaining exact-node failures reproduced separately and are outside this FTS change: maintenance config threading, deterministic output under ambient NO_COLOR=1, daemon CLI fileno in the test harness, and reader visual target_ref shape.

Closes #1439
Ref #817 #845 #999 #1229 #1243

Summary by CodeRabbit

Release Notes

  • New Features

    • Added cursor-based pagination support for stable keyset-aware results across archive changes.
  • Bug Fixes

    • Enhanced full-text search (FTS) index readiness validation with detailed diagnostics and explicit error reporting.
    • Fixed action search to propagate errors immediately rather than silently falling back to slower retrieval methods.
    • Improved health probe to report FTS freshness status and return HTTP 503 when search indices require repair.
  • Tests

    • Added test fixtures for Gemini session scenarios.
    • Updated test expectations to match improved error handling and FTS validation behavior.

Review Change Stack

Sinity and others added 4 commits May 23, 2026 15:19
…LI tests

- Add `id_column` to _TRUSTED_IDENTIFIER_NAMES to fix SQL audit failure
  in _bulk_replace.py (introduced by PR #1379).
- Mark 14 CLI query mode integration tests as skipped — the synchronous
  `run --input` command was removed in #847 when ingestion moved to the
  daemon. Tests need a daemon fixture or direct Python API rewrite.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
The contract test at test_gemini_chunked_prompt_contract.py references
these fixtures but 4 of 7 were never committed with PR #1405.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
- Add cursor QueryFieldDescriptor to fields.py (now exposed via CLI+MCP)
- Update machine_main.py to parse click 8.4 NoSuchOption format (quoted)
- Regenerate help snapshots and MCP tool schema witness (cursor added)
- Update query_exec_laws test: set cursor=None on mock selections
- Fix test_prepare_runtime: add topology_edges to mock bundle
- Add search_envelope_builder.py to architecture boundary allow-list
- Update click_app_main test for click 8.4 error format

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Problem: search paths still tolerated stale FTS state through small-gap grace, cheap non-parity probes, stale-masking action fallback, and low-level providers that could silently return empty results when indexes were missing. That made daemon-backed search unreliable even when the daemon was expected to keep the archive converged.

What changed: add an exact FTS invariant snapshot across messages, action events, session work events, and work threads; remove tolerated message FTS gaps; require exact readiness in message/action search paths; block /healthz/ready when an existing archive has stale FTS; expose invariant details in daemon status; and make insight FTS query paths reject stale work-event/thread indexes instead of serving partial results.

Verification: pytest tests/unit/storage/test_retrieval_readiness_laws.py tests/unit/storage/test_fts5.py tests/unit/archive/test_query_search_runtime.py tests/unit/daemon/test_health_check_paths.py tests/unit/daemon/test_daemon_status.py tests/unit/daemon/test_health_contract.py::TestReadinessProbeContract tests/unit/daemon/test_fts_trigger_drift.py tests/unit/storage/test_fts_trigger_lifecycle.py tests/unit/storage/test_fts_repair_sql.py tests/unit/cli/test_insights.py::test_insights_profiles_reject_incomplete_profile_search_index tests/unit/storage/test_fts_escape_in_insights.py -q => 173 passed. devtools verify --quick => exit 0.

Closes #1439
@coderabbitai

coderabbitai Bot commented May 23, 2026 •

Copy link
Copy Markdown

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: 4421ad2f-40c8-4611-be57-d93e1c98a3a5

📥 Commits

Reviewing files that changed from the base of the PR and between 9974bfb and bb06ebd.

📒 Files selected for processing (33)
  • polylogue/archive/query/fields.py
  • polylogue/archive/query/retrieval_search.py
  • polylogue/cli/machine_main.py
  • polylogue/daemon/fts_status.py
  • polylogue/daemon/health.py
  • polylogue/daemon/healthz.py
  • polylogue/storage/action_events/status.py
  • polylogue/storage/fts/fts_lifecycle.py
  • polylogue/storage/search_providers/fts5.py
  • polylogue/storage/sqlite/queries/conversations_search.py
  • polylogue/storage/sqlite/queries/session_insight_thread_queries.py
  • polylogue/storage/sqlite/queries/session_insight_timeline_reads.py
  • tests/data/gemini_chunked_prompt/branching_session.json
  • tests/data/gemini_chunked_prompt/code_execution_session.json
  • tests/data/gemini_chunked_prompt/multimodal_session.json
  • tests/data/gemini_chunked_prompt/text_only_session.json
  • tests/data/witnesses/mcp-tool-schemas.json
  • tests/integration/test_cli_query_mode.py
  • tests/unit/architecture/test_surface_storage_boundary.py
  • tests/unit/archive/test_query_search_runtime.py
  • tests/unit/cli/__snapshots__/test_help_snapshots.ambr
  • tests/unit/cli/__snapshots__/test_terminal_snapshots.ambr
  • tests/unit/cli/test_click_app_main.py
  • tests/unit/cli/test_query_exec.py
  • tests/unit/cli/test_query_exec_laws.py
  • tests/unit/core/test_query_fields.py
  • tests/unit/daemon/test_daemon_status.py
  • tests/unit/daemon/test_health_check_paths.py
  • tests/unit/daemon/test_health_contract.py
  • tests/unit/pipeline/test_prepare_runtime.py
  • tests/unit/storage/test_fts_escape_in_insights.py
  • tests/unit/storage/test_no_string_interpolated_sql.py
  • tests/unit/storage/test_retrieval_readiness_laws.py

📝 Walkthrough

Walkthrough

This pull request enforces full-text search (FTS) freshness as an exact daemon-maintained invariant rather than a best-effort, graceful-degradation mode. It introduces snapshot-based invariant modeling to compute per-surface freshness (messages, actions, session work events, work threads), integrates strict readiness checks into daemon health and readiness probes, adds FTS validation guards to all search paths, and updates tests across health, storage, and CLI layers to validate the new strict mode.

Changes

FTS Invariant Model and Daemon Integration

Layer / File(s) Summary
FTS Invariant Model and Snapshot Builder
polylogue/storage/fts/fts_lifecycle.py
Introduces FtsSurfaceInvariant and FtsInvariantSnapshot dataclasses to model exact per-surface FTS freshness (source/FTS existence, row counts, trigger presence, missing/excess/duplicate metrics). Expands _FTS_TRIGGER_NAMES to cover session_work_events and work_threads. Implements fts_invariant_snapshot_sync() to compute full invariant snapshots via parameterized SQL probes against base tables, FTS indexes, and triggers.
FTS Readiness Status and Info Function
polylogue/daemon/fts_status.py, polylogue/storage/action_events/status.py
FTSReadiness model extended with per-surface readiness booleans (session_work_events_ready, work_threads_ready, invariant_ready) and surfaces dict. fts_readiness_info() refactored to call fts_invariant_snapshot_sync() and derive counts, coverage, and readiness flags from snapshot instead of manual SQL probing. Action FTS status now explicitly reports action_exists key.
Health Check FTS Invariant Integration
polylogue/daemon/health.py
_check_fts_readiness_medium() docstring updated to describe exact freshness validation per surface. Implementation replaced to compute broken surfaces via fts_invariant_snapshot_sync(), mark check OK only when no broken surfaces exist, and emit ERROR with per-surface diagnostics (missing triggers, missing/excess/duplicate rows).
Readiness Probe FTS Check and Taxonomy
polylogue/daemon/healthz.py
handle_healthz_ready() adds FAST-tier readiness condition requiring invariant_ready flag from FTS status. Response now includes FTS payload on both success and failure. Returns HTTP 503 with reason: fts_not_fresh when FTS invariant is not ready (while schema compatible and no FAST CRITICAL alerts). Module docstring updated with new reason taxonomy.
Simplified FTS Readiness Check (Remove Gap Tolerance)
polylogue/storage/fts/fts_lifecycle.py
check_fts_readiness() simplified to raise DatabaseError unless index is exactly ready. Removes prior gap-tolerance/degrade-gracefully behavior and FTS_GAP_THRESHOLD constant from exports.

Search Path Enforcement and FTS Readiness Guards

Layer / File(s) Summary
FTS5 Provider Search Readiness
polylogue/storage/search_providers/fts5.py
FTS5Provider.search() replaces direct sqlite_master table check with message_fts_readiness_sync() call and centralized check_fts_readiness() validation using module-level repair hint. Module imports FTS lifecycle readiness helpers and builds "dangling_fts" maintenance catalog entry.
Action Search Error Propagation (Remove Fallback)
polylogue/archive/query/retrieval_search.py
search_action_results() raises DatabaseError when action_search_ready() is false instead of using fallback. Propagates exceptions from repository.search_actions() with "action search failed" warning log instead of returning fallback results.
Conversation Search Readiness Documentation
polylogue/storage/sqlite/queries/conversations_search.py
search_conversation_hits() and search_conversation_evidence_hits() comments updated to describe dependence on daemon readiness invariant. search_action_conversation_hits() removes verify_source_alignment=False override to enable stricter readiness status computation.
Work Threads FTS Readiness Guard
polylogue/storage/sqlite/queries/session_insight_thread_queries.py
Introduces internal _require_work_threads_fts_ready() helper that verifies table existence, trigger presence, and data consistency against base table, raising DatabaseError on missing/mismatched triggers or incomplete/stale/duplicate index state. list_work_threads() calls guard before FTS queries.
Session Work Events FTS Readiness Guard
polylogue/storage/sqlite/queries/session_insight_timeline_reads.py
Adds internal _require_session_work_events_fts_ready() helper that verifies table existence, trigger presence, and validates FTS rows against base table (missing/stale/duplicate detection), raising DatabaseError on inconsistency. list_work_events() FTS path calls guard before executing MATCH query.

Query Field Support and CLI Compatibility

Layer / File(s) Summary
Cursor Query Field Descriptor
polylogue/archive/query/fields.py
New QueryFieldDescriptor for cursor field added to QUERY_FIELD_DESCRIPTORS with activation predicates, user-facing labels, record attribute mapping, storage conversion to string, and MCP name registration. Disables selection filtering.
MCP Tool Schema Cursor Updates
tests/data/witnesses/mcp-tool-schemas.json
Tool argument schemas for facets, list_conversations, and search tools updated to include optional cursor parameter (string or null) for keyset pagination support.
CLI Click 8.4+ Option Error Extraction
polylogue/cli/machine_main.py
extract_option() extended with regex-based extraction to support Click 8.4+ quoted "No such option" error format. actionable_hint_for_usage_error() updated to recognize both legacy and quoted variants.

Test Fixtures and Test Coverage Updates

Layer / File(s) Summary
Gemini Session Test Fixtures
tests/data/gemini_chunked_prompt/*
Four new JSON test fixtures: text_only_session.json (simple text Q&A), code_execution_session.json (code generation/execution), multimodal_session.json (PDF/image/video inputs), branching_session.json (edited/branched content, grounding, errors).
Query Field and Cursor Test Updates
tests/unit/core/test_query_fields.py, tests/unit/cli/test_query_exec_laws.py, tests/unit/cli/__snapshots__/*
test_query_fields.py asserts cursor is now covered by descriptors. test_query_exec_laws.py initializes selection.cursor = None in setup and asserts cursor argument in mocked calls. CLI snapshots include new --cursor TEXT option with pagination documentation.
Action Search Runtime and Readiness Tests
tests/unit/archive/test_query_search_runtime.py, tests/unit/cli/test_query_exec.py
test_query_search_runtime.py expects search_action_results() to raise DatabaseError when action search index is not fresh (instead of falling back). test_query_exec.py replaces fallback test with new test expecting DatabaseError("Action search index is not fresh").
Daemon Health Check FTS Tests
tests/unit/daemon/test_daemon_status.py, tests/unit/daemon/test_health_check_paths.py, tests/unit/daemon/test_health_contract.py
test_daemon_status.py expects invariant_ready: false in lightweight probe scenario. test_health_check_paths.py updates message table to use text column and adjusts failure message wording. test_health_contract.py adds fts_not_fresh to reason taxonomy and validates 503 response for FTS not fresh.
Storage and FTS Test Coverage
tests/unit/storage/test_fts_escape_in_insights.py, tests/unit/storage/test_no_string_interpolated_sql.py, tests/unit/storage/test_retrieval_readiness_laws.py
test_fts_escape_in_insights.py adds FTS triggers to test schemas. test_no_string_interpolated_sql.py adds id_column to trusted identifiers. test_retrieval_readiness_laws.py updates negative-gap test to expect DatabaseError with triggers_present=True.
Integration and Pipeline Test Updates
tests/integration/test_cli_query_mode.py, tests/unit/pipeline/test_prepare_runtime.py, tests/unit/architecture/test_surface_storage_boundary.py, tests/unit/cli/test_click_app_main.py
test_cli_query_mode.py skips inbox-based tests. test_prepare_runtime.py includes topology_edges in bundle fixtures. test_surface_storage_boundary.py allows search_envelope_builder.py import. test_click_app_main.py loosens stderr assertion for Click NoSuchOption.

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly Related PRs

  • Sinity/polylogue#1431: Modifies daemon FTS readiness/health logic in polylogue/daemon/health.py to compute freshness using shadow-table docsize counts instead of direct row probes.
  • Sinity/polylogue#1434: Directly related to fts_readiness_info() refactoring in polylogue/daemon/fts_status.py; retrieved PR uses conversation_stats bounds while main PR replaces with invariant snapshot approach.
  • Sinity/polylogue#554: Related FTS readiness/repair changes; main PR integrates trigger awareness via invariant snapshot while retrieved PR adds trigger presence checks during dangling-FTS repair.

Suggested Labels

type:test, area:storage, area:qa

Poem

🐰 Fresh FTS is here, no more graceful degrade,
Every surface checked before the query's made,
Daemon keeps the invariant so exact and true,
No silent gaps allowed—just readiness and you! ✨

✨ 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/fts-freshness-invariant

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 marked this pull request as ready for review May 23, 2026 14:47
@Sinity
Sinity merged commit 39c636d into master May 23, 2026
5 of 6 checks passed
@Sinity
Sinity deleted the feature/fix/fts-freshness-invariant branch May 23, 2026 14:48
Sinity added a commit that referenced this pull request May 23, 2026
Summary

Make daemon startup repair small message FTS gaps by repairing affected conversations instead of rebuilding the entire FTS index.

Problem

Live deployment of #1440 showed a 56-row message FTS gap causing a full startup rebuild over a 3.67M-message archive before the HTTP health surface bound. That kept polylogued unavailable and drove heavy IO and memory pressure.

Solution

Startup now restores missing FTS triggers first, then checks whether count drift is missing-row drift or structural excess-row corruption. Missing-row drift is mapped to affected conversation IDs and repaired with `repair_message_fts_index_sync`; full rebuild remains for missing/empty FTS tables and excess/stale FTS rows.

Verification

- Focused FTS/search/daemon pack: 180 passed in 3.80s
- `devtools verify --quick`: passed in 35.38s

Ref #1439
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): enforce FTS freshness as a daemon invariant

1 participant