Skip to content

refactor(storage): trim FTS bloat and migrate stale tag read paths (#817) - #1098

Merged
Sinity merged 2 commits into
masterfrom
feature/refactor/fts-bloat-and-stale-reads-v2
May 16, 2026
Merged

Sinity merged 2 commits into
masterfrom
feature/refactor/fts-bloat-and-stale-reads-v2

Conversation

@Sinity

@Sinity Sinity commented May 16, 2026

Copy link
Copy Markdown
Owner

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

Sinity and others added 2 commits May 16, 2026 18:00
Add three focused regression tests under
tests/unit/storage/test_fts_bloat_invariants.py that lock in the
post-#944 external-content FTS conversion:

- test_messages_fts_is_contentless_external_content asserts the DDL
  carries content='messages', content_rowid='rowid'. A future schema
  edit that drops the option (or flips back to standalone FTS5) fails
  loudly.
- test_messages_fts_storage_does_not_duplicate_message_bodies
  synthesises ~10 MB of message text and uses dbstat to confirm
  messages_fts_* pages stay well under the messages table size
  (observed ratio ~0.2; threshold 0.5 guards against a regression to
  a full duplicate copy).
- test_messages_fts_deletion_consistency_with_external_content guards
  the AD trigger so DELETE on messages drops the corresponding FTS
  row, preventing the regression that forced the earlier content-sync
  revert.

Ref #817

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`history_entries` is typed `list[dict[str, Any]]` (line 328), so the
`isinstance(entry, dict)` guard at line 347 was always true. mypy
--strict flagged it as `redundant-expr`, blocking the verify-quick
gate. Removing the guard makes the local mypy baseline clean.
@coderabbitai

coderabbitai Bot commented May 16, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Sinity has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 55 minutes and 38 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, 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 the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 3e9b1837-7a2e-48b6-9eb1-ac6abc2fb92d

📥 Commits

Reviewing files that changed from the base of the PR and between 1c116a7 and 2cd503a.

📒 Files selected for processing (2)
  • devtools/evidence_dashboard.py
  • tests/unit/storage/test_fts_bloat_invariants.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/refactor/fts-bloat-and-stale-reads-v2

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 merged commit 673fd25 into master May 16, 2026
3 checks passed
@Sinity
Sinity deleted the feature/refactor/fts-bloat-and-stale-reads-v2 branch May 16, 2026 16:05

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

ℹ️ 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 devtools/evidence_dashboard.py Resolved
@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.

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