Skip to content

perf(daemon): targeted FTS repair in archive convergence, not full rebuild (#1851) - #1895

Merged
Sinity merged 1 commit into
masterfrom
feature/perf/measure-ingest-write-amplification-1851
Jun 15, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/perf/measure-ingest-write-amplification-1851

Conversation

@Sinity

@Sinity Sinity commented Jun 15, 2026 •

Copy link
Copy Markdown
Owner

Summary

Kills the live-ingest write amplification: the archive FTS convergence paths now repair only the changed sessions' messages_fts rows instead of re-indexing the entire corpus on every batch.

Problem

_archive_fts_execute / _archive_fts_execute_many / _archive_fts_execute_sessions (the split-file archive runtime path) computed the changed session_ids for a source path, then ignored them and called _archive_rebuild_messages_fts → rebuild_fts_index_sync — a full delete-all + re-insert of every message row in the corpus. A one-message append re-indexed the whole FTS index → ~14 MiB of writes per batch regardless of payload (~1000× amplification for small appends). The legacy monolith path already did targeted repair (_repair_changed_session_fts); the archive path never got the equivalent.

Solution

_archive_repair_sessions_fts(conn, session_ids) uses the existing targeted primitive repair_message_fts_index_sync (per-session delete+insert of messages_fts rows) and _mark_message_fts_ready_after_targeted_repair, falling back to the full rebuild only when scope is unknown (no ids). All three archive FTS execute paths route through it.

Correctness preserved: _archive_fts_needs_repair returns False after targeted repair (index complete for the changed sessions), readiness/freshness state is updated through the existing helper, and the unknown-scope fallback keeps the full-rebuild behavior. No durability/raw-evidence change.

Verification

devtools test tests/unit/daemon/test_convergence_stages.py   # 28 passed (2 new)
devtools test test_fts_global_repair test_fts5 test_fts_repair_sql   # green
devtools verify --quick   # exit 0

New tests: test_fts_stage_uses_targeted_repair_not_full_rebuild (spies that the targeted primitive is called and rebuild_fts_index_sync is not, while messages_fts stays complete) and test_archive_repair_sessions_fts_falls_back_to_full_rebuild_without_ids. One unrelated status --json subprocess test flaked only in a mixed-file batch (passes isolated + in-file; pre-existing #1878-class cross-test stdout pollution).


Issue slice: #1851 slice 5 (concrete write reduction) + regression tests
Files inspected: daemon/convergence_stages.py, storage/fts/fts_lifecycle.py, daemon/health.py, pipeline/services/indexing.py
Files changed: daemon/convergence_stages.py, tests/unit/daemon/test_convergence_stages.py
Old surface removed or retained: full-rebuild retained as unknown-scope fallback; targeted repair added for known scope
Contracts/tests added: targeted-path-taken assertion; unknown-scope fallback; messages_fts completeness
Generated artifacts updated: none (internal daemon logic, no CLI/doc surface)
Verification commands and results: see above — 28 passed, verify --quick exit 0
Known caveats / SPEC_MISMATCH: amplification source attributed by code, not yet by a committed byte-measurement artifact
Follow-up intentionally not included: slices 1-2/4 — deterministic fixture + page/WAL byte attribution + a benchmark-campaign artifact for before/after comparison across PRs

Ref #1851

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Enhanced Full-Text Search index repair efficiency by performing targeted repairs on affected sessions instead of full index rebuilds when session scope is available. Full index rebuilds remain available as a fallback for unscoped repairs.
  • Tests

    • Added unit tests to verify Full-Text Search repair behavior and fallback scenarios.

…build (#1851)

Problem: the archive (split-file) FTS convergence paths
(_archive_fts_execute / _execute_many / _execute_sessions) computed the
changed session ids for a source path but then ignored them and called
_archive_rebuild_messages_fts → rebuild_fts_index_sync, a FULL delete-all +
re-insert of every message row in the corpus. So a single small append
re-indexed the entire FTS index — ~14 MiB of writes per live-ingest batch
regardless of payload size (~1000x amplification for small appends). The
legacy monolith path already did targeted repair; the archive path never got
the equivalent.

What changed: add _archive_repair_sessions_fts(conn, session_ids) which uses
the existing targeted primitive repair_message_fts_index_sync (per-session
delete+insert of messages_fts rows, the same one the legacy path uses) and
marks the surface ready, falling back to the full rebuild only when scope is
unknown (no session ids). Route all three archive FTS execute paths through it.

Correctness: messages_fts stays complete for the repaired sessions
(_archive_fts_needs_repair returns False after), readiness/freshness state is
updated via the existing _mark_message_fts_ready_after_targeted_repair, and the
unknown-scope fallback preserves the full-rebuild behavior. No durability or
raw-evidence change.

Scope (partial, #1851): this lands slice 5 (the concrete write reduction) and
its regression tests. The formal write-byte measurement artifact (slices 1-2/4
— deterministic fixture + page/WAL attribution + benchmark script) is a
follow-up; the amplification source is already attributed here by code.

Verification: devtools test tests/unit/daemon/test_convergence_stages.py → 28
passed (2 new: targeted-path-taken / full-rebuild-not-called, and unknown-scope
fallback); adjacent FTS tests (test_fts_global_repair, test_fts5,
test_fts_repair_sql) green; devtools verify --quick exit 0. (One unrelated
test_status --json subprocess test flaked only in a mixed-file batch — passes
isolated and in-file; pre-existing #1878-class cross-test stdout pollution,
not this diff.)

Ref #1851

Co-Authored-By: Claude <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 15, 2026 •

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

Introduces _archive_repair_sessions_fts, a new helper that performs session-scoped messages_fts repairs via repair_message_fts_index_sync and marks FTS readiness afterward. All three FTS execute paths (_archive_fts_execute, _archive_fts_execute_many, _archive_fts_execute_sessions) switch from full archive rebuilds to this targeted helper, with full rebuild retained as a fallback when the session ID set is empty.

Changes

Targeted session FTS repair

Layer / File(s) Summary
_archive_repair_sessions_fts helper and callsite wiring
polylogue/daemon/convergence_stages.py
Adds _archive_repair_sessions_fts implementing targeted messages_fts repair via repair_message_fts_index_sync plus _mark_message_fts_ready_after_targeted_repair, with a full-rebuild fallback for empty scopes. Replaces the prior full-rebuild call in _archive_fts_execute, _archive_fts_execute_many, and _archive_fts_execute_sessions with this helper.
Tests for targeted repair and fallback
tests/unit/daemon/test_convergence_stages.py
Adds test_fts_stage_uses_targeted_repair_not_full_rebuild (asserts targeted repair is called, full rebuild is not) and test_archive_repair_sessions_fts_falls_back_to_full_rebuild_without_ids (asserts rebuild_fts_index_sync is called when session IDs are absent).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Possibly related PRs

  • Sinity/polylogue#1520: Both PRs modify _mark_message_fts_ready_after_targeted_repair usage and the targeted-repair path in convergence_stages.py.

Poem

🐇 Hop, hop, no more full sweeps tonight,
Just the sessions that changed get their FTS set right.
A targeted fix, a narrow repair,
Less write-amplification fills the air.
The fallback still waits if the scope is unknown,
But mostly we patch just what we have shown! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.00% 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 'perf(daemon): targeted FTS repair in archive convergence, not full rebuild (#1851)' directly and clearly summarizes the main change: replacing full FTS rebuilds with targeted repairs in archive convergence.
Description check ✅ Passed The PR description comprehensively covers all required template sections: Summary (what and why), Problem (necessity), Solution (what was done), Verification (commands and results), and includes a detailed Risks/Follow-ups section with scope attribution.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/perf/measure-ingest-write-amplification-1851

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 bc4bd65 into master Jun 15, 2026
12 of 13 checks passed
@Sinity
Sinity deleted the feature/perf/measure-ingest-write-amplification-1851 branch June 15, 2026 11:39

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

ℹ️ 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
Sinity added a commit that referenced this pull request Jun 15, 2026
…1900)

## Summary
Adds `devtools ingest-amplification-probe` — a deterministic,
host-independent measurement of per-tier write bytes per live-ingest
batch, establishing the post-fix baseline for #1851 (slices 1-2/4).
Additive tooling; no production ingest/daemon/storage code touched.

## Problem
#1851 wanted the amplification not just fixed (#1895) but **measured and
attributed**, with a repeatable artifact comparable across PRs. There
was no such measurement.

## Solution
`devtools/ingest_amplification_probe.py` (new) bootstraps a fresh 5-tier
archive in an env-isolated temp dir (`XDG_DATA_HOME` +
`POLYLOGUE_ARCHIVE_ROOT` — never touches real data), builds a
deterministic synthetic corpus, ingests N single-session append batches
through the existing public `parse_sources_archive` path (read-only
use), and after each batch attributes bytes via `PRAGMA page_count *
page_size` + WAL size per tier DB plus the blob store. Emits a stable
JSON report (per-batch + per-tier deltas, amplification ratios,
per-component shares). Registered as a `CommandSpec`.

**Key finding:** on the `parse_sources_archive` path the raw payload is
not materialized to source.db/blob (only a 32-byte hash + small rows) —
the full blob is written by the daemon's lease path. So this probe
measures the parsed-index durable footprint vs raw wire payload
(~0.8–1.0× post-fix, 100% in index.db); `blob_store` is kept as an
attributed component (shows 0 here rather than hiding it).

## Verification
```
devtools test tests/unit/devtools/test_ingest_amplification_probe.py   # 5 passed
devtools test test_command_catalog test_cli_wrapper                    # 11 passed
devtools verify --quick   # exit 0
```
Deterministic: two runs produce byte-identical JSON.

Ref #1851

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
@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.

  • 63.F047 / P2: fixed-already at the checked revision: The replacement FTS publisher revalidates _schema_compatible before reporting publication success at polylogue/storage/fts/derivation.py:545. Missing message triggers make that condition fail and return False at line 548, so targeted repair cannot certify success while leaving the trigger set absent as the old low-level path did.

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