Repository navigation
fix(daemon): report FTS ledger counts - #1520
Conversation
Problem: fast daemon status used durable FTS freshness state for readiness but returned zero row counts, and targeted FTS repair could overwrite exact ledger counts with zeros. That made live status look empty even when the archive was large. What changed: status now reads recorded ledger counts without archive-wide FTS scans, and targeted changed-conversation repair preserves existing count snapshots while clearing resolved missing/excess counters. Verification: pytest tests/unit/daemon/test_daemon_status.py tests/unit/daemon/test_convergence_stages.py -q; devtools verify --quick.
|
Warning Review limit reached
Your plan includes 1 review of capacity. Refill in 51 minutes and 11 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 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (5)
📝 WalkthroughWalkthroughPR extends FTS readiness tracking to derive metrics from the ChangesFTS Readiness from Recorded Freshness State
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 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.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 66924a29d5
ℹ️ 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".
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 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/daemon/convergence_stages.py`:
- Around line 818-829: The SELECT against fts_freshness_state assumes all count
columns exist and can fail on legacy schemas; update the code around
_table_exists and the conn.execute block (the query selecting source_rows,
indexed_rows, missing_rows, excess_rows, duplicate_rows for surface
'messages_fts') to guard for missing columns: either inspect the table schema
(e.g., PRAGMA table_info or SELECT name FROM
pragma_table_info('fts_freshness_state')) and only request existing columns, or
wrap the execute in a try/except catching the DB error and falling back to a
safe default (counts = (0,0,0,0,0)); ensure the variable counts is set to the
retrieved values when available and to the zero-tuple when columns are missing
or an error occurs so targeted repair marking won’t abort.
In `@polylogue/daemon/fts_status.py`:
- Around line 94-99: The integer fields in the record ("source_rows",
"indexed_rows", "missing_rows", "excess_rows", "duplicate_rows") are being
coerced with int(...) which can raise ValueError/TypeError for malformed SQLite
values; in the function constructing the status dict (fts_status module) wrap
each int(...) conversion in a safe parse that catches ValueError and TypeError
and falls back to 0 (e.g. try: val = int(record.get("source_rows") or 0) except
(ValueError, TypeError): val = 0) for each named key, and keep the existing
"detail" handling intact (None if missing or None else str(record["detail"])).
In `@tests/unit/daemon/test_convergence_stages.py`:
- Around line 288-327: Replace the direct SQL setup in
test_targeted_fts_ready_marker_preserves_ledger_counts with the repository
fixtures: obtain the archive DB connection from workspace_env and populate the
conversation and message using ConversationBuilder (create conversation id
"conv-ledger" and a message "msg-ledger" with text "indexed text" and provider
"codex") instead of executing raw INSERTs; then call
record_fts_surface_state_sync(conn, ...) and
stages._mark_message_fts_ready_after_targeted_repair(conn) using that same
connection and keep the same SELECT/assert checks to validate the
fts_freshness_state row.
In `@tests/unit/daemon/test_daemon_status.py`:
- Around line 447-509: The test currently mutates SQLite directly; instead use
the workspace_env fixture to get an isolated storage environment and use
ConversationBuilder to populate messages, action events, and the
fts_freshness_state rows so setup is consistent with other storage-backed tests.
Replace manual sqlite3.executescript in
test_fts_readiness_reports_recorded_freshness_counts_without_exact_scan with
calls to ConversationBuilder (e.g., add_message/add_action_event or equivalent
builder methods) to create 200 messages (199 indexed + 1 missing) and 7 action
events, and use the builder or a helper to insert the two fts_freshness_state
records (surface 'messages_fts' and 'action_events_fts' with the same counts and
detail 'repair pending') using workspace_env's DB path; keep the traced_connect
patch on polylogue.storage.sqlite.connection_profile.sqlite3.connect and
continue to call fts_readiness_info(db_path) to assert the same readiness
fields.
🪄 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: 931412f9-c78a-41dd-a82a-649989e0ca1f
📒 Files selected for processing (4)
polylogue/daemon/convergence_stages.pypolylogue/daemon/fts_status.pytests/unit/daemon/test_convergence_stages.pytests/unit/daemon/test_daemon_status.py
| def test_targeted_fts_ready_marker_preserves_ledger_counts(tmp_path: Path) -> None: | ||
| from polylogue.storage.fts.freshness import record_fts_surface_state_sync | ||
|
|
||
| db_path = tmp_path / "archive.sqlite" | ||
| with open_connection(db_path) as conn: | ||
| conn.execute( | ||
| "INSERT INTO conversations(conversation_id, provider_name, provider_conversation_id, version) VALUES(?,?,?,1)", | ||
| ("conv-ledger", "codex", "provider-conv"), | ||
| ) | ||
| conn.execute( | ||
| "INSERT INTO messages(message_id, conversation_id, role, text, provider_name, version) VALUES(?,?,?,?,?,1)", | ||
| ("msg-ledger", "conv-ledger", "user", "indexed text", "codex"), | ||
| ) | ||
| record_fts_surface_state_sync( | ||
| conn, | ||
| surface="messages_fts", | ||
| state="stale", | ||
| source_rows=100, | ||
| indexed_rows=99, | ||
| missing_rows=1, | ||
| detail="pre-existing exact snapshot", | ||
| ) | ||
| stages._mark_message_fts_ready_after_targeted_repair(conn) | ||
| row = conn.execute( | ||
| """ | ||
| SELECT state, source_rows, indexed_rows, missing_rows, excess_rows, duplicate_rows, detail | ||
| FROM fts_freshness_state | ||
| WHERE surface='messages_fts' | ||
| """, | ||
| ).fetchone() | ||
|
|
||
| assert tuple(row) == ( | ||
| "ready", | ||
| 100, | ||
| 99, | ||
| 0, | ||
| 0, | ||
| 0, | ||
| "targeted changed-conversation repair complete", | ||
| ) |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Align this storage test with workspace_env and ConversationBuilder.
This test sets up archive rows through direct SQL. Please migrate setup to the shared storage test fixtures/builders to match repository test conventions.
As per coding guidelines, "Use workspace_env fixture for tests that touch storage or pipeline. Use ConversationBuilder for populating test databases with fluent chain methods."
🤖 Prompt for 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.
In `@tests/unit/daemon/test_convergence_stages.py` around lines 288 - 327, Replace
the direct SQL setup in test_targeted_fts_ready_marker_preserves_ledger_counts
with the repository fixtures: obtain the archive DB connection from
workspace_env and populate the conversation and message using
ConversationBuilder (create conversation id "conv-ledger" and a message
"msg-ledger" with text "indexed text" and provider "codex") instead of executing
raw INSERTs; then call record_fts_surface_state_sync(conn, ...) and
stages._mark_message_fts_ready_after_targeted_repair(conn) using that same
connection and keep the same SELECT/assert checks to validate the
fts_freshness_state row.
| def test_fts_readiness_reports_recorded_freshness_counts_without_exact_scan(tmp_path: Path) -> None: | ||
| from polylogue.daemon.fts_status import fts_readiness_info | ||
|
|
||
| db_path = tmp_path / "polylogue.db" | ||
| queries: list[str] = [] | ||
| with sqlite3.connect(db_path) as conn: | ||
| conn.executescript( | ||
| """ | ||
| CREATE TABLE messages (message_id TEXT, text TEXT); | ||
| CREATE TABLE messages_fts (text TEXT); | ||
| CREATE TABLE messages_fts_docsize (id INTEGER PRIMARY KEY, sz BLOB); | ||
| CREATE TRIGGER messages_fts_ai AFTER INSERT ON messages BEGIN SELECT 1; END; | ||
| CREATE TRIGGER messages_fts_ad AFTER DELETE ON messages BEGIN SELECT 1; END; | ||
| CREATE TRIGGER messages_fts_au AFTER UPDATE ON messages BEGIN SELECT 1; END; | ||
| CREATE TABLE action_events (event_id TEXT); | ||
| CREATE TABLE action_events_fts (text TEXT); | ||
| CREATE TABLE action_events_fts_docsize (id INTEGER PRIMARY KEY, sz BLOB); | ||
| CREATE TRIGGER action_events_fts_ai AFTER INSERT ON action_events BEGIN SELECT 1; END; | ||
| CREATE TRIGGER action_events_fts_ad AFTER DELETE ON action_events BEGIN SELECT 1; END; | ||
| CREATE TRIGGER action_events_fts_au AFTER UPDATE ON action_events BEGIN SELECT 1; END; | ||
| CREATE TABLE fts_freshness_state ( | ||
| surface TEXT PRIMARY KEY, | ||
| state TEXT NOT NULL, | ||
| checked_at TEXT NOT NULL, | ||
| source_rows INTEGER NOT NULL DEFAULT 0, | ||
| indexed_rows INTEGER NOT NULL DEFAULT 0, | ||
| missing_rows INTEGER NOT NULL DEFAULT 0, | ||
| excess_rows INTEGER NOT NULL DEFAULT 0, | ||
| duplicate_rows INTEGER NOT NULL DEFAULT 0, | ||
| detail TEXT | ||
| ); | ||
| INSERT INTO fts_freshness_state | ||
| (surface, state, checked_at, source_rows, indexed_rows, missing_rows, excess_rows, duplicate_rows, detail) | ||
| VALUES | ||
| ('messages_fts', 'ready', '2026-05-24T00:00:00+00:00', 200, 199, 1, 0, 0, 'repair pending'), | ||
| ('action_events_fts', 'ready', '2026-05-24T00:00:00+00:00', 7, 7, 0, 0, 0, NULL); | ||
| """ | ||
| ) | ||
|
|
||
| original_connect = sqlite3.connect | ||
|
|
||
| def traced_connect(*args: Any, **kwargs: Any) -> sqlite3.Connection: | ||
| conn = original_connect(*args, **kwargs) | ||
| conn.set_trace_callback(queries.append) | ||
| return cast(sqlite3.Connection, conn) | ||
|
|
||
| with patch("polylogue.storage.sqlite.connection_profile.sqlite3.connect", side_effect=traced_connect): | ||
| readiness = fts_readiness_info(db_path) | ||
|
|
||
| assert readiness["message_indexable_count"] == 200 | ||
| assert readiness["message_indexed_count"] == 199 | ||
| assert readiness["action_event_count"] == 7 | ||
| assert readiness["action_event_indexed_count"] == 7 | ||
| assert readiness["coverage_pct"] == 99.5 | ||
| surfaces = readiness["surfaces"] | ||
| assert isinstance(surfaces, dict) | ||
| messages = surfaces["messages_fts"] | ||
| assert isinstance(messages, dict) | ||
| assert messages["missing_rows"] == 1 | ||
| assert messages["freshness_detail"] == "repair pending" | ||
| assert all("COUNT(*) FROM messages" not in query for query in queries) | ||
| assert all("messages_fts_docsize" not in query for query in queries) | ||
|
|
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Use workspace_env + ConversationBuilder for this storage-backed test setup.
This new test provisions archive state via direct SQLite DDL/DML. Please migrate setup to the shared test fixtures/builders for consistency and strict test-environment guarantees.
As per coding guidelines, "Use workspace_env fixture for tests that touch storage or pipeline. Use ConversationBuilder for populating test databases with fluent chain methods."
🤖 Prompt for 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.
In `@tests/unit/daemon/test_daemon_status.py` around lines 447 - 509, The test
currently mutates SQLite directly; instead use the workspace_env fixture to get
an isolated storage environment and use ConversationBuilder to populate
messages, action events, and the fts_freshness_state rows so setup is consistent
with other storage-backed tests. Replace manual sqlite3.executescript in
test_fts_readiness_reports_recorded_freshness_counts_without_exact_scan with
calls to ConversationBuilder (e.g., add_message/add_action_event or equivalent
builder methods) to create 200 messages (199 indexed + 1 missing) and 7 action
events, and use the builder or a helper to insert the two fts_freshness_state
records (surface 'messages_fts' and 'action_events_fts' with the same counts and
detail 'repair pending') using workspace_env's DB path; keep the traced_connect
patch on polylogue.storage.sqlite.connection_profile.sqlite3.connect and
continue to call fts_readiness_info(db_path) to assert the same readiness
fields.
Problem: the FTS freshness writer assumes the current count columns exist, so a legacy lightweight freshness table can make targeted daemon repair fail with no such column. What changed: the freshness table ensure helper now adds missing count/detail columns before writing, and targeted repair gates its count-preservation read on the full column set. Verification: pytest tests/unit/daemon/test_convergence_stages.py tests/unit/daemon/test_daemon_status.py tests/unit/storage/test_dangling_fts_derived_surfaces.py -q; ruff check; mypy.
Problem: daemon status reads row counts from the FTS freshness ledger, and malformed dynamic SQLite values could raise outside the sqlite3.Error fallback. What changed: ledger count parsing now safely falls back to zero for malformed values, with a focused daemon-status regression test. Verification: pytest tests/unit/daemon/test_daemon_status.py tests/unit/daemon/test_convergence_stages.py tests/unit/storage/test_dangling_fts_derived_surfaces.py -q; ruff check; mypy.
|
Review follow-up:
Verification after follow-up:
|
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
Summary
Fast daemon FTS status now reports row-count fields from the durable
fts_freshness_stateledger instead of returning zeros, and targeted changed-conversation FTS repair no longer overwrites existing ledger counts with zeros.Problem
The live daemon status endpoint reported
message_indexed_count=0andmessage_indexable_count=0while the archive was large. The request-safe status path intentionally avoids exact FTS scans, but it also discarded count fields that the freshness ledger can already store. A targeted repair path then made the symptom worse by markingmessages_ftsready with default zero counts.Solution
polylogue.daemon.fts_statusnow reads optional ledger columns (source_rows,indexed_rows, missing/excess/duplicate counts, and detail) without touching FTS shadow-table counts. The targeted FTS repair marker inpolylogue.daemon.convergence_stagespreserves existing ledger counts while clearing resolved missing/excess/duplicate counters on a successful cheap readiness probe.Verification
pytest tests/unit/daemon/test_daemon_status.py tests/unit/daemon/test_convergence_stages.py -q→ 36 passed.devtools verify --quick→ exit_code 0, total_duration_s 35.04.devtools verify --quickon66924a29→ exit_code 0, total_duration_s 35.57.Ref #1515
Summary by CodeRabbit
Improvements
Tests