Repository navigation
perf(daemon): cut live-ingest write amplification via FTS5 automerge tuning - #1864
Conversation
|
Caution Review failedPull request was closed or merged during review 📝 WalkthroughWalkthroughImplements 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. ChangesFTS Automerge Control and Write Amplification Mitigation
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 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 docstrings
🧪 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: 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)") |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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
📒 Files selected for processing (6)
docs/plans/topology-target.yamldocs/topology-status.mdpolylogue/daemon/cli.pypolylogue/daemon/fts_automerge.pypolylogue/storage/fts/fts_lifecycle.pytests/integration/test_live_write_amplification.py
| 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 |
There was a problem hiding this comment.
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.
| 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]>
ed71638 to
1e7d8fc
Compare
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]>
|
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
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 defaultautomerge=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_syncran 9executescript()calls whose implicit COMMITs fragmented the ingest transaction into 3 WAL transactions.Solution
polylogue/daemon/fts_automerge.py:configure_fts_automerge_syncpersistsautomerge=0for each present FTS surface at daemon startup (wired indaemon/cli.py);run_periodic_fts_merge_syncruns 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.polylogue/storage/fts/fts_lifecycle.py:ensure_fts_triggers_syncearly-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
tests/integration/test_live_write_amplification.pyseeds 80 sessions to build a non-trivial FTS index, appliesautomerge=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 withautomerge=0, the trigger early-return issues noexecutescript, and missing-trigger restoration still works.Ref #1851
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Bug Fixes
Documentation
Tests