Skip to content

perf(daemon): cut live-ingest write amplification via FTS5 automerge tuning - #1864

Merged
Sinity merged 1 commit into
masterfrom
feature/perf/fts-automerge-1851
Jun 13, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/perf/fts-automerge-1851

Conversation

@Sinity

@Sinity Sinity commented Jun 13, 2026 •

Copy link
Copy Markdown
Owner

Summary

Live-ingest batches wrote ~14.4 MiB to the archive DBs regardless of payload size — a few-KB JSONL append cost ~14 MiB (~1000× app-level write amplification, #1851). This tunes FTS5 segment-merge behaviour so per-batch write cost tracks the actual append, dropping a small batch from ~10–14 MiB to ~1–2 MiB (≥5×). No schema bump, no re-ingest.

Problem

Measured on the deployed daemon: ~14.4 MiB DB write I/O per batch, payload-independent (2 KB–200 KB all cost ~14 MiB). A scout traced it (.agent/scratch/1851-write-amp-scout.md): the three FTS5 surfaces (messages_fts, session_work_events_fts, threads_fts) use the default automerge=8. On a mature archive the existing FTS segments are hundreds of MB; each small batch adds one tiny level-0 segment and periodically triggers an automerge of the large existing segments — so the WAL write scales with total index size, not the append. That is exactly the observed payload-independence.

Secondary: ensure_fts_triggers_sync ran 9 executescript() calls whose implicit COMMITs fragmented the ingest transaction into 3 WAL transactions.

Solution

  • Fix A — polylogue/daemon/fts_automerge.py: configure_fts_automerge_sync persists automerge=0 for each present FTS surface at daemon startup (wired in daemon/cli.py); run_periodic_fts_merge_sync runs a bounded ('merge', 500) pass folded into the existing 5-minute checkpoint loop so segment cost is amortised without an unbounded write. Both skip gracefully on fresh archives / busy DB.
  • Fix B — polylogue/storage/fts/fts_lifecycle.py: ensure_fts_triggers_sync early-returns when all triggers are present (steady state), eliminating the 9 premature COMMITs and restoring transaction atomicity. The bulk-suspend/restore path is unaffected (not-all-present still recreates).

Verification

nix develop -c devtools test tests/integration/test_live_write_amplification.py
# 7 passed
nix develop -c mypy --strict <touched files>   # Success

tests/integration/test_live_write_amplification.py seeds 80 sessions to build a non-trivial FTS index, applies automerge=0, then asserts a subsequent small write stays ≤3.5 MiB WAL (observed ~1–2 MiB; unfixed baseline ~10–14 MiB). Also pins: FTS query correctness with automerge=0, the trigger early-return issues no executescript, and missing-trigger restoration still works.

Ref #1851

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added FTS5 automerge management and periodic bounded index merging in the daemon.
  • Bug Fixes

    • Reduced live write amplification and avoided unnecessary WAL fragmentation during steady-state FTS maintenance.
  • Documentation

    • Updated topology/status counts in generated docs.
  • Tests

    • Added integration and unit tests covering FTS automerge configuration, trigger behavior, and write-amplification regression checks.

@coderabbitai

coderabbitai Bot commented Jun 13, 2026 •

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

Implements FTS5 automerge control: new module to disable per-write automerge at startup and run bounded periodic merges; integrates startup and periodic tasks into the daemon; adds an early-return in trigger ensure to avoid DDL during steady state; and adds integration and unit tests plus topology metadata updates.

Changes

FTS Automerge Control and Write Amplification Mitigation

Layer / File(s) Summary
FTS automerge startup and periodic merge implementation
polylogue/daemon/fts_automerge.py
New module exports configure_fts_automerge_sync to set automerge=0 for managed FTS surfaces and run_periodic_fts_merge_sync to apply bounded merge work-units periodically; per-surface errors are suppressed and commits occur only when changes were made.
Daemon CLI startup and maintenance wiring
polylogue/daemon/cli.py
Adds _configure_fts_automerge() to run startup configuration after FTS readiness and _periodic_fts_merge() background loop (5-minute interval), integrated into the daemon maintenance tasks.
FTS trigger steady-state fast path
polylogue/storage/fts/fts_lifecycle.py
ensure_fts_triggers_sync now checks for expected triggers and returns early when present, avoiding DDL generation/execution and implicit transaction commits.
FTS automerge and write amplification tests
tests/integration/test_live_write_amplification.py
Adds WAL-measurement helpers and a slow integration regression asserting small-write WAL growth stays within budget after automerge fix; unit tests for configure_fts_automerge_sync behavior and idempotence; steady-state and repair tests for trigger handling; functional FTS query test.
Topology metadata and status documentation
docs/plans/topology-target.yaml, docs/topology-status.md
Adds polylogue/daemon/fts_automerge.py to topology plan and updates LOC for cli.py and fts_lifecycle.py; topology status counts updated (Stable: 691; Total declared and Realized polylogue/**/*.py: 826).

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰 I nudged automerge to take a nap tonight,
so merges can sip tea and do their work light.
WALs breathe easier, tests nod and agree—
slow steady merges keep the bytes worry‑free. 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 73.08% 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 clearly and concisely summarizes the main change: reducing write amplification in live-ingest by tuning FTS5 automerge behavior, matching the core objective across multiple files.
Description check ✅ Passed The description includes all required sections: Summary (problem and solution impact), Problem (root cause analysis), Solution (both fixes A and B with modules touched), and Verification (exact test commands and results).
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/fts-automerge-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.

github-actions Bot pushed a commit that referenced this pull request Jun 13, 2026
github-actions Bot pushed a commit that referenced this pull request Jun 13, 2026

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

ℹ️ 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".

if not _table_exists(conn, surface):
continue
with suppress(sqlite3.OperationalError):
conn.execute(f"INSERT INTO {surface}({surface}, rank) VALUES('automerge', 0)")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Disable crisis merges along with automerge

When a source emits 16+ live-ingest batches between the five-minute periodic merge passes, this only disables incremental automerge; SQLite's separate crisismerge setting remains at its default 16 and still immediately merges all b-trees on that level during the triggering INSERT/UPDATE/DELETE (see the FTS5 docs: https://sqlite.org/fts5.html#the_crisismerge_configuration_option). That means bursty live writes can still pay the same large per-write WAL spike this change is meant to eliminate, just less frequently, unless crisismerge is also raised/managed or the periodic merge is guaranteed to run before the threshold.

Useful? React with 👍 / 👎.

Comment thread polylogue/daemon/cli.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: 1

🤖 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 `@tests/integration/test_live_write_amplification.py`:
- Around line 43-52: The _checkpoint_truncate function can leak the SQLite
connection if conn.execute raises; ensure the connection is always closed by
wrapping use of the connection in a try/finally (or use a context manager) so
that conn.close() runs even on exceptions: open the connection into conn via
sqlite3.connect(str(db)) and call conn.execute(...) inside the try block, then
call conn.close() in the finally block (or replace with a with
sqlite3.connect(...) as conn: block) to guarantee closure on success or error.
🪄 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: 260e89b5-1982-4289-b99b-a116f8889544

📥 Commits

Reviewing files that changed from the base of the PR and between daf7cd5 and fb3b56e.

📒 Files selected for processing (6)
  • docs/plans/topology-target.yaml
  • docs/topology-status.md
  • polylogue/daemon/cli.py
  • polylogue/daemon/fts_automerge.py
  • polylogue/storage/fts/fts_lifecycle.py
  • tests/integration/test_live_write_amplification.py

Comment on lines +43 to +52
def _checkpoint_truncate(db: Path) -> None:
"""TRUNCATE checkpoint to zero the WAL before a measurement window."""
if not db.exists():
return
try:
conn = sqlite3.connect(str(db))
conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
conn.close()
except sqlite3.Error:
pass

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Resource leak if checkpoint execution fails.

If sqlite3.connect() succeeds but conn.execute() raises sqlite3.Error, the connection is never closed.

🐛 Proposed fix using try/finally
 def _checkpoint_truncate(db: Path) -> None:
     """TRUNCATE checkpoint to zero the WAL before a measurement window."""
     if not db.exists():
         return
     try:
         conn = sqlite3.connect(str(db))
-        conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
-        conn.close()
-    except sqlite3.Error:
-        pass
+        try:
+            conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
+        finally:
+            conn.close()
+    except sqlite3.Error:
+        pass
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def _checkpoint_truncate(db: Path) -> None:
"""TRUNCATE checkpoint to zero the WAL before a measurement window."""
if not db.exists():
return
try:
conn = sqlite3.connect(str(db))
conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
conn.close()
except sqlite3.Error:
pass
def _checkpoint_truncate(db: Path) -> None:
"""TRUNCATE checkpoint to zero the WAL before a measurement window."""
if not db.exists():
return
try:
conn = sqlite3.connect(str(db))
try:
conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
finally:
conn.close()
except sqlite3.Error:
pass
🤖 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/integration/test_live_write_amplification.py` around lines 43 - 52, The
_checkpoint_truncate function can leak the SQLite connection if conn.execute
raises; ensure the connection is always closed by wrapping use of the connection
in a try/finally (or use a context manager) so that conn.close() runs even on
exceptions: open the connection into conn via sqlite3.connect(str(db)) and call
conn.execute(...) inside the try block, then call conn.close() in the finally
block (or replace with a with sqlite3.connect(...) as conn: block) to guarantee
closure on success or error.

…tuning

Each live-ingest batch wrote ~14.4 MiB to the archive DBs regardless of payload
(a few-KB JSONL append cost ~14 MiB) — ~1000x app-level write amplification.

Root cause: the three FTS5 surfaces (messages_fts, session_work_events_fts,
threads_fts) used the default automerge=8. On a mature archive the existing
segments are hundreds of MB; each small batch adds a tiny level-0 segment and
periodically triggers a merge of the large existing segments, so the WAL write
scales with total index size, not the append — exactly the payload-independence
observed.

Fix A: set FTS5 automerge=0 on all surfaces at daemon startup
(polylogue/daemon/fts_automerge.py:configure_fts_automerge_sync, wired in
daemon/cli.py) so no merge is triggered per write; a bounded periodic merge
('merge', 500) folded into the existing 5-minute checkpoint loop amortises
segment cost without an unbounded write.

Fix B: early-return in ensure_fts_triggers_sync when all triggers are present
(fts_lifecycle.py) — skips 9 executescript() calls whose implicit COMMITs
fragmented the ingest transaction into 3 WAL transactions; restores atomicity.

Verification: tests/integration/test_live_write_amplification.py seeds 80
sessions, applies automerge=0, and asserts a subsequent small write stays
≤3.5 MiB WAL (observed ~1-2 MiB vs ~10-14 MiB baseline — ≥5x). FTS query
correctness with automerge=0 and the trigger early-return are also pinned.
7 passed. No schema bump, no re-ingest.

Ref #1851
Co-Authored-By: Claude Opus 4.8 <[email protected]>
@Sinity
Sinity force-pushed the feature/perf/fts-automerge-1851 branch from ed71638 to 1e7d8fc Compare June 13, 2026 21:36
@Sinity
Sinity merged commit 559920b into master Jun 13, 2026
12 of 16 checks passed
@Sinity
Sinity deleted the feature/perf/fts-automerge-1851 branch June 13, 2026 21:41
Sinity added a commit that referenced this pull request Sep 14, 2026
A deliberate sweep for facts stated by hand in more than one place. Four
had
**already drifted**; two of those produce wrong observable outcomes on
the
from-scratch rebuild path this campaign is about to run.

## 1. FTS5 automerge silently skipped a trigger-maintained table

Owner: the index-tier DDL. `polylogue/daemon/fts_automerge.py`
hand-listed two
surfaces (`messages_fts`, `session_work_events_fts`) behind a "must be
kept in
sync" comment pointing at **a file that no longer exists**.

**Drifted:** `blocks_command_trigram` — an FTS5 table on `blocks` — was
missing
from the list, so neither the startup `automerge=0` pass nor the bounded
periodic
merge ever reached it. It kept FTS5's default automerge and paid
**unbounded
inline segment merges on the live-ingest writer** — exactly the write
amplification #1864 removed for the other two, on the heaviest path
during a
from-scratch rebuild.

Now read from `sqlite_master`; no new import edge.

## 2. `config paths` reported `archive_complete` for an archive missing
`audit.db`

Owner: `ARCHIVE_TIER_SPECS` via `archive_layout.ARCHIVE_TIER_ORDER`.

**Drifted:** `cli/commands/paths.py` listed five of six tiers, omitting
`audit` —
in two places (`tier_paths` and `_TIER_ENUM_BY_NAME`). With `audit.db`
absent,
`final_shape_ready` was true, `storage_layout` said `archive_complete`,
`archive_layout_ready` stayed true, and
**`missing_backup_required_tier:audit`
could never fire** — for a durable, append-only tier.

That is the readiness signal an operator reads while standing an archive
up from
scratch. A fourth copy in the CLI test pinned the drift; it now derives
too.

## 3. The affected-run worker cap exceeded the corpus cap in its own
cgroup

Owner: `worker_memory.width_within(PYTEST_SLICE_MEMORY_HIGH_MIB)`.

**Drifted:** `AFFECTED_MAX_WORKERS = 4` against a derived
`CORPUS_MAX_WORKERS =
3` — admitting the selective run *wider than the full corpus*, peak
10,127 MiB
against a 9,830 MiB headroom budget that exists precisely because a
corpus run
was already OOM-killed in that cgroup. Now `min(policy,
CORPUS_MAX_WORKERS)`; a
third copy in the test reads the constant.

## 4. Three drifted doc facts

`docs/insights-rigor-matrix.md` declared `rigor.py` its source of truth
and then
hand-wrote 11 of 13 contracts, omitting `command_shapes`/`tool_episodes`
and
naming `threads` as `work_threads` — an insight type nothing answers to.
Now a
generated surface under `render all --check`.

`docs/provider-origin-identity.md` enumerated "every current `Origin`
token"
*inside the paragraph forbidding second token lists*, and omitted
`beads-issue`;
`docs/data-model.md` carried the same 11-of-12 list. Both copies deleted
rather
than corrected.

## Anti-vacuity

- **FTS:** `test_configure_covers_every_declared_fts5_surface`
enumerates the
built schema's FTS5 tables and asserts each is at `automerge=0`.
Restoring the
hand list goes red on `blocks_command_trigram` — proven directly, not
assumed.
- **Tiers:** fixture and assertions generated from `ARCHIVE_TIER_ORDER`;
the
blocker test now asserts `missing_backup_required_tier:audit` is
emitted.
  Restoring the five-name literal goes red.
- **Width:** `test_affected_width_never_exceeds_the_memory_owner`
asserts the cap
is at or below `CORPUS_MAX_WORKERS`; a literal above it goes red, and
lowering
  the slice moves the cap with no edit.
- **Rigor matrix:** editing any contract now makes `render all --check`
report it
  out of sync — a gate the hand-written matrix was never subject to.

## Checked and agreeing, no change

pytest slice 12G ↔ Sinnix `runtime-defaults.nix` (the sibling-repo drift
is *not*
present here); worker/controller peak constants; `polylogued` 14G/18G ↔
`memoryBudgetGiB`; cloud worker width (4 copies); `.agentctl` pool names
↔ Sinnix
`POLICY_POOLS`; version 0.3.0; `requires-python` across 10 sites; the
devtools
catalog and `docs/devtools.md` (genuinely generated); gate names;
storage tier
lists in `archive_identity.py` and `daemon/status.py`; `Origin` ↔
`ORIGIN_SPECS`
(import-time parity guard); `INSIGHT_REGISTRY` ↔ `_RIGOR_MATRIX`.

**One false positive, deliberately not acted on:** the agent manual's
"ten-tool"
claim against a 12-tool registry is *correct* — `registry.py` carries a
`target_visible` flag, the two event tools declare no transaction
projection, and
`test_tool_declarations.py:68` already pins the partition. Coupling it
would have
created a false dependency.

## Filed rather than derived

`polylogue-xbg9e` (P2) corpus width derives 3 while Sinnix provisioned 4
—
headroom counted twice, a cross-repo decision. `polylogue-29naz` (P2)
MCP
`_INSIGHT_PROJECTIONS` hand list, including an already-visible
`tool-episodes`/`tool_episodes` spelling split. `polylogue-b1vr1` (P3)
ungated
second tier lists, plus two items flagged **unsure** rather than
coupled:
`migration_runner.py:1125` vs `:1210` differing `required_tiers`, and
`manifest_models.py`'s five-tier Literals. `polylogue-mnwxy` (P3) mypy
3.11 /
ruff py310 vs `requires-python >=3.14`.

## Verification

```
devtools test test_paths.py test_verification_admission.py test_live_write_amplification.py
  PASSED exit=0   receipt 20260914T061123Z-focused-test-1405648-6665bbdd
devtools verify --quick     15/15
devtools render all --check clean
```

Residual: `config paths` output still has no `audit_database_path` key
or
"Audit DB" line — a surface-contract change left out of the readiness
fix
deliberately, noted in `polylogue-b1vr1`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK

---------

Co-authored-by: Claude Opus 5 (1M context) <[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.F041 / P2: fixed-already at the checked revision: Periodic FTS merging now calls configure_fts_automerge_sync on every opened index at polylogue/daemon/fts_automerge.py:127. An index created after startup therefore receives the automerge setting during the same daemon lifetime instead of depending on a restart.

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