Skip to content

fix(daemon): report FTS ledger counts - #1520

Merged
Sinity merged 3 commits into
masterfrom
feature/fix/fts-ledger-counts-clean
May 24, 2026
Merged

Sinity merged 3 commits into
masterfrom
feature/fix/fts-ledger-counts-clean

Conversation

@Sinity

@Sinity Sinity commented May 24, 2026 •

Copy link
Copy Markdown
Owner

Summary

Fast daemon FTS status now reports row-count fields from the durable fts_freshness_state ledger 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=0 and message_indexable_count=0 while 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 marking messages_fts ready with default zero counts.

Solution

polylogue.daemon.fts_status now 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 in polylogue.daemon.convergence_stages preserves 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.
  • Push hook reran devtools verify --quick on 66924a29 → exit_code 0, total_duration_s 35.57.

Ref #1515

Summary by CodeRabbit

  • Improvements

    • Enhanced full-text search status tracking to use recorded freshness metrics for more efficient readiness checks.
    • Improved status reporting to include detailed freshness information and row counts.
    • Made status reporting more robust with safer schema parsing and better edge-case handling.
  • Tests

    • Added tests validating freshness state preservation during repair operations.
    • Added tests confirming efficient readiness reporting without full table scans.

Review Change Stack

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.
@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 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 @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: e0c99373-0eba-4e19-b6ee-2165e35d7e2d

📥 Commits

Reviewing files that changed from the base of the PR and between 66924a2 and 3838b88.

📒 Files selected for processing (5)
  • polylogue/daemon/convergence_stages.py
  • polylogue/daemon/fts_status.py
  • polylogue/storage/fts/freshness.py
  • tests/unit/daemon/test_convergence_stages.py
  • tests/unit/daemon/test_daemon_status.py
📝 Walkthrough

Walkthrough

PR extends FTS readiness tracking to derive metrics from the fts_freshness_state ledger using schema-aware helpers, updates fts_readiness_info to populate surface counters and coverage from recorded freshness data, and ensures convergence stages preserves ledger counts when marking readiness without performing exact table scans.

Changes

FTS Readiness from Recorded Freshness State

Layer / File(s) Summary
Freshness state reading infrastructure
polylogue/daemon/fts_status.py
New _get_surface_readiness_from_freshness and related helpers introspect fts_freshness_state schema via PRAGMA table_info and safely extract per-surface numeric fields (source_rows, indexed_rows, missing_rows, excess_rows, duplicate_rows) plus optional detail; _payload_int normalizes counts to integers.
FTS readiness metrics from freshness state
polylogue/daemon/fts_status.py, tests/unit/daemon/test_daemon_status.py
Surface assembly in fts_readiness_info now populates row counters and freshness metadata (freshness_known, freshness_state, freshness_detail) from ledger records; aggregate payload computes final message/action counts and recalculates coverage_pct from indexed_rows/source_rows ratio with invariant_ready fallback; test validates metrics are derived from recorded freshness without executing exact-scan queries.
Convergence stages readiness recording
polylogue/daemon/convergence_stages.py, tests/unit/daemon/test_convergence_stages.py
_mark_message_fts_ready_after_targeted_repair fetches existing fts_freshness_state counts and passes them to record_fts_surface_state_sync, zeroing structural mismatches on READY transition; test verifies state transition and count preservation.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • Sinity/polylogue#1434: Both PRs modify fts_readiness_info coverage and count calculation logic, one sourcing per-surface counts from fts_freshness_state and the other deriving via conversation_stats.
  • Sinity/polylogue#1445: Both PRs modify fts_readiness_info readiness computation path and related test assertions around metrics and SQL execution in test_daemon_status.py.
  • Sinity/polylogue#1500: Both PRs adjust how FTS freshness counts are derived from and persisted in fts_freshness_state, with this PR consuming recorded counts and the other computing initial ledger values.

Poem

🐰 A ledger of FTS tales, no scans to tell—
Freshness counts recorded, preserved so well.
Schema introspection, counts dance with grace,
Coverage blooms from metrics we trace.
The rabbit approves of this tidy embrace! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 6.67% 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(daemon): report FTS ledger counts' accurately and concisely describes the main change: enabling FTS status reporting to use ledger counts instead of zeros.
Description check ✅ Passed The description includes all required template sections: Summary, Problem, Solution, and Verification. Changelog was appropriately skipped as this is not user-visible.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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-ledger-counts-clean

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: 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".

Comment thread polylogue/daemon/convergence_stages.py Resolved

@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: 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

📥 Commits

Reviewing files that changed from the base of the PR and between d99baf2 and 66924a2.

📒 Files selected for processing (4)
  • polylogue/daemon/convergence_stages.py
  • polylogue/daemon/fts_status.py
  • tests/unit/daemon/test_convergence_stages.py
  • tests/unit/daemon/test_daemon_status.py

Comment thread polylogue/daemon/convergence_stages.py Resolved
Comment thread polylogue/daemon/fts_status.py Resolved
Comment on lines +288 to +327
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",
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ 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.

Comment on lines +447 to +509
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ 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.

Sinity added 2 commits May 24, 2026 23:40
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.
@Sinity

Sinity commented May 24, 2026

Copy link
Copy Markdown
Owner Author

Review follow-up:

  • Addressed the real legacy-schema finding by gating targeted-repair count reads on the full column set and by making ensure_fts_freshness_table_* add missing ledger columns before writes.
  • Addressed malformed ledger values with _int_or_zero and a regression test.
  • Left the two fixture-conversion suggestions unapplied: these tests intentionally create minimal/legacy structural schemas and trace exact SQL to prove the request-safe path does not execute archive-wide counts. ConversationBuilder would create the canonical full schema and obscure the legacy/structural contract under test.

Verification after follow-up:

  • 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 -> 40 passed.
  • devtools verify --quick -> exit_code 0, total_duration_s 39.66.

@Sinity
Sinity merged commit d5a5b71 into master May 24, 2026
6 checks passed
@Sinity
Sinity deleted the feature/fix/fts-ledger-counts-clean branch May 24, 2026 21:45
@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.

  • 62.F052 / P1: refuted at the checked revision: The requested fallback explicitly preserves the retired three-column freshness schema. AGENTS.md:192-194 rejects compatibility fallbacks and migration/readback of prior archives into fresh v1, so adapting current queries to that historical table shape is not a supported remedy.

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.

1 participant