Skip to content

fix: Converge FTS automerge on an index created after daemon startup - #5080

Merged
Sinity merged 1 commit into
masterfrom
fix/fts-automerge-fresh-archive
Sep 14, 2026
Merged

Sinity merged 1 commit into
masterfrom
fix/fts-automerge-fresh-archive

Conversation

@Sinity

@Sinity Sinity commented Sep 14, 2026

Copy link
Copy Markdown
Owner

Summary

Make the FTS5 automerge=0 tuning converge on an archive whose index.db did not exist at daemon startup, so the first post-wipe rebuild does not run at FTS5's default automerge=8. Fixes polylogue-n3mn4.

Problem

_configure_fts_automerge (daemon/cli.py:449) is a one-shot startup coroutine that short-circuits on a missing index:

db = _active_index_db_path()
if not db.exists():
    return

On a wiped archive nothing before that point creates index.db: the schema preflight returns early on a missing file, the startup raw-census recovery returns, and the startup FTS converge uses read-only connections. The index is first created later and lazily by the ingest write path (storage/sqlite/connection.py:115-119, via initialize_active_archive_root). _periodic_fts_merge (cli.py:509+) re-checked existence on each iteration but only issued merge=N; it never touched automerge. The setting lives in the persistent FTS %_config table, so it took effect only after the next daemon restart — meaning the entire first post-wipe rebuild indexed at automerge=8.

Reproduced directly before changing anything: bootstrap a fresh archive root, run the periodic pass, and every declared surface's %_config has no automerge row at all:

surfaces: ['messages_fts', 'blocks_command_trigram', 'session_work_events_fts']
messages_fts []   blocks_command_trigram []   session_work_events_fts []
after periodic: unchanged

Measured cost (120K docs, 80-doc commits — the per-session commit shape): automerge=8 → 10.27s load, 27.8MB; automerge=0 → 6.30s load, 31.5MB, no query-latency difference. 63% slower for the whole rebuild.

Solution

run_periodic_fts_merge_sync now calls configure_fts_automerge_sync on the connection it already opens, before issuing merge=N. configure_fts_automerge_sync became convergent rather than write-always: it reads the stored %_config value per surface and writes (and commits) only when it is not already 0, so the once-a-minute call is a cheap read on a converged archive. It still returns every ensured surface, and the derived _fts_surfaces set is unchanged.

Why this shape rather than configuring at schema bootstrap. The alternative — configure automerge where initialize_active_archive_root creates the index — was rejected for two reasons:

  1. It is still a single moment. Any future route that creates an FTS surface outside that one call (a migration adding a surface to an existing index, a tier rebuild) silently reverts to automerge=8 — the same defect in a new place. The periodic ensure re-derives the surface set from sqlite_master every 60s, so it converges from any starting state and covers any surface whenever it appears.
  2. devtools schema closure polylogue/storage/sqlite/archive_tiers/bootstrap.py reports IN — editing it moves the derived schema identity and forces a full reconvergence, for a pure-performance change. devtools schema closure polylogue/daemon/fts_automerge.py and polylogue/daemon/cli.py both report out, so this change moves no schema identity and carries no rebuild-ordering constraint.

The startup call is kept as a best-effort fast path (it saves up to one merge interval on a mature archive) with its docstring corrected to say it is explicitly not the guarantee.

Other FTS pragmas with the same exposure: none. automerge is the only FTS5 config value this codebase sets anywhere — no crisismerge, pgsz, deletemerge, secure-delete, or rank configuration exists. The only other FTS surface state, the triggers, is already write-path convergent: ensure_fts_triggers_sync is called from archive/write_effects.py:151 on the write path, not once at startup, so it cannot be skipped by a missing index.

Verification

devtools test tests/integration/test_live_write_amplification.py   → PASSED exit=0
devtools test tests/unit/daemon/test_daemon_cli.py                 → PASSED exit=0
devtools verify --quick                                            → exit=0 (all gates ok)
devtools schema closure polylogue/daemon/fts_automerge.py          → out
devtools schema closure polylogue/daemon/cli.py                    → out
devtools schema closure polylogue/storage/sqlite/archive_tiers/bootstrap.py → IN (the rejected alternative)

Anti-vacuity of the new test, verified by reverting the fix (removing the configure_fts_automerge_sync call from run_periodic_fts_merge_sync) and re-running. Observed:

devtools test: FAILED exit=1 diagnosis=pytest_failed
E  AssertionError: surfaces left on FTS5 default automerge after the first post-wipe pass:
   {'messages_fts': None, 'blocks_command_trigram': None, 'session_work_events_fts': None}

The fix was restored and the file re-verified green. The test drives the production routes end to end: no index.db → periodic pass no-ops without creating one → initialize_active_archive_root creates the tiers → one ordinary periodic turn leaves every declared surface at automerge=0, with no restart.

Residuals

  • Up to one merge interval (_FTS_MERGE_INTERVAL_SECONDS = 60) of a fresh rebuild still runs at automerge=8, since the periodic loop sleeps before its first pass. Negligible against a multi-hour rebuild, but it is not zero; closing it would require the bootstrap-side change and its closure move.
  • The per-minute ensure adds one SELECT per FTS surface (three today) to each maintenance pass, inside the writer turn the pass already takes.
  • No new measurement was taken in this PR; the 10.27s/6.30s figures are the bead's, carried forward.
  • Only the two named test files were run, plus the static gates. No affected/full suite.

🤖 Generated with Claude Code

https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK

_configure_fts_automerge is one-shot at daemon startup and returns early
when index.db is absent. On a wiped archive the index does not exist at
that point -- it is created later and lazily by the ingest write path --
so automerge=0 is never persisted and never retried, and the whole first
post-wipe rebuild indexes at FTS5's default automerge=8. The setting is
persistent in the FTS %_config table, so it only takes effect after the
next restart.

Measured on 120K docs in 80-doc commits (the per-session commit shape):
automerge=8 -> 10.27s load / 27.8MB; automerge=0 -> 6.30s load / 31.5MB,
with no query-latency difference.

run_periodic_fts_merge_sync now ensures automerge=0 on every surface it
finds before issuing merge=N. The periodic loop re-checks the index on
each iteration, so the tuning converges from any starting state and picks
up surfaces created after startup. configure_fts_automerge_sync reads the
stored value first and writes only when it is not already 0, so the
per-minute call is a read on a converged archive.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Sep 14, 2026

Copy link
Copy Markdown

Warning

Review limit reached

Next included review available in 22 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Advanced

Run ID: a2efa219-f5b5-41ae-b0c4-d506c79f58ea

📥 Commits

Reviewing files that changed from the base of the PR and between f90c94d and 2326e40.

📒 Files selected for processing (3)
  • polylogue/daemon/cli.py
  • polylogue/daemon/fts_automerge.py
  • tests/integration/test_live_write_amplification.py

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.

@Sinity
Sinity merged commit 95674b6 into master Sep 14, 2026
3 checks passed
@Sinity
Sinity deleted the fix/fts-automerge-fresh-archive branch September 14, 2026 15:35
Sinity added a commit that referenced this pull request Sep 14, 2026
…5084)

## Summary

`devtools gate atlas` is red on master. #5080 and #5081 both edited
`polylogue/daemon/cli.py`, which is anchored by `docs/atlas/daemon.md`
and `docs/atlas/00-core.md`, and neither PR re-verified the sheets. That
is my omission — CLAUDE.md requires running `devtools gate atlas` when
changing anchored code.

## Problem

Six sections reported `stale`. Two distinct causes:

- Five `daemon.md` anchors plus one in `00-core.md` still cited
pre-change line numbers. The net shift is **−71**, not the +7 that #5080
alone would suggest — #5081's deletion also touched the file.
- One anchor (`cli.py:1612-1637`) pointed at the raw-authority frontier
drain that #5081 deleted outright, so it could not be renumbered at all.

## Solution

Anchors were relocated by **locating the originally-cited block in the
current file by content**, using the verified-stamp commit as the source
of truth, rather than by arithmetic on line numbers. The
convergence-debt citation was re-pointed at
`_drain_convergence_debt_once` (`cli.py:1614-1636`), which still
supports the sheet's claim: debt identity is stage-scoped and the drain
excludes `derived`, `fts`, `fts_readiness`, `raw_parse_recovery` and
`embed`, which is exactly the assertion that FTS, embeddings, raw
parsing and session profiles no longer use debt rows as publication
authority.

Stamps then advanced to `ab81d4e5cc06`.

## Verification

```
devtools gate atlas
Atlas citations and verification stamps are current

devtools verify --quick
15/15 gates ok
```

## Residuals

The stamp is a commit SHA, so a PR that edits an anchored file can never
stamp itself — the sheet goes stale again the moment this merges if
another anchored file changes first. That is structural, and it is why
this kind of PR trails the change rather than accompanying it.

🤖 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 added a commit that referenced this pull request Sep 14, 2026
## Summary

Deletes two accommodations that existed only so a pre-wipe backup could
still be
restored: the Codex synthetic `session_meta` header replay helper, and
the
pre-split full-archive identity digest fallback in the durable migration
runner.
382 lines removed, 19 added.

## Problem (authorization)

Both items were previously classified "operator decision required",
blocked on
whether `daemon/backup.py` must stay able to restore pre-wipe backups.
The
operator's answer (2026-09-14): **"absolutely not, this sort of thing is
legacy
crap we want to purge."** That is the authorization for this change.

1. `operations/append_acquisition_replay.py` reconstructed the compact
synthetic
`session_meta` record that pre-retirement Codex append rows prepended to
each
retained delta. Post-wipe, every Codex append blob is a literal delta,
so the
two `sources/live/batch.py` call sites were already dead;
`daemon/backup.py`
   was the only surviving justification.
2. `migration_runner._archive_identity_continuity_matches` admitted the
old
full-archive digest found in manifests written before the durable-tier
identity split — restorability from a pre-wipe backup manifest, nothing
else.

## Solution

Item 1 — Codex synthetic header:

- deleted `polylogue/operations/append_acquisition_replay.py` entirely
  (`codex_legacy_header_size`, `replay_append_acquisition_payload`,
  `_codex_session_meta_id`, `_SESSION_META_READ_LIMIT`)
- deleted `sources/live/batch_support.codex_append_payload`: its
documented
purpose was "keeping both shapes in one encoder"; with the legacy shape
gone
the remaining shape is the literal payload, so the encoder is an
identity
  function. `batch.py` now returns the payload directly.
- removed both legacy-header branches in `sources/live/batch.py`
(delta-offset
  inference and byte-proven append head reconstruction)
- removed `daemon/backup._replay_append_payload` (its only body was the
  accommodation) and the Codex header-size subtraction inside
  `_legacy_append_replay`; the four call sites now use the read segment
directly, and a size mismatch is still caught by the existing SHA-256
check
  against `blob_hash` rather than by a typed `recorded_size_mismatch`.

Item 2 — pre-split identity digest:

- deleted `migration_runner._archive_identity_continuity_matches`, and
with it
  the now-unused `archive_root`/`connection` parameters of
`_assert_durable_database_continuity`; the four `durable_change_train`
call
  sites became direct digest equality.
- deleted the matching legacy-digest rewrite of
`retained_apply_evidence` in
`durable_change_train.refresh_released_source_train_continuity`. It is
the
same pre-split accommodation on the write side and became unreachable
once the
read-side fallback was gone (the equality checks above it now raise
first).

## Reader/writer enumeration

Searched `polylogue/`, `devtools/`, `tests/`, docs and generated
surfaces.

`codex_legacy_header_size` / `replay_append_acquisition_payload` /
`legacy_header`:

| Consumer | Disposition |
| --- | --- |
| `sources/live/batch.py:73` (import), `:4428`, `:4577` | removed;
post-wipe dead |
| `sources/live/batch.py:5105` (`legacy_header=False`) | now returns
payload directly |
| `daemon/backup.py:37` (import), `:733`, `:841` | removed |
| `sources/live/batch_support.py:49` `codex_append_payload` | deleted
(no callers left) |
| `tests/unit/sources/test_reviewed_acquisition_defects.py:14,34-45` |
test deleted (see Tests) |
| `tests/unit/daemon/test_backup.py:890`, `:994` | tests
deleted/retargeted (see Tests) |
| docs, `devtools/`, generated surfaces | no references (grep clean) |

`_archive_identity_continuity_matches`:

| Consumer | Disposition |
| --- | --- |
| `migration_runner.py:2390` (inside
`_assert_durable_database_continuity`) | removed |
| `durable_change_train.py:49` (import), `:2011`, `:2020`, `:3233` |
replaced by direct digest equality |
| `migration_runner.py:3136`,
`durable_change_train.py:1958,2001,3140,3215`
(`archive_root=`/`connection=` kwargs) | kwargs dropped |
| `tests/unit/storage/test_durable_change_train.py:1290`, `:360` | test
deleted / retargeted (see Tests) |
| docs, generated surfaces | no references |

No consumer was left without a replacement path.

## Tests

- **Deleted**
`tests/unit/sources/test_reviewed_acquisition_defects.py::test_codex_session_meta_read_is_bounded`
— its only subject was the bounded `readline` inside the deleted replay
helper. With the helper gone the test has no production route; deleting
it is
  correct, not a weakening.
- **Deleted**
`tests/unit/daemon/test_backup.py::test_backup_replays_historical_codex_append_header`
— asserted that backup proof reproduces the historical writer payload
with the
  synthetic header. That behavior is deliberately removed.
- **Deleted**
`tests/unit/storage/test_durable_change_train.py::test_continuity_admits_legacy_full_archive_identity_digest`
— named the admission of the legacy full-archive digest as its subject.
- **Retargeted**
`test_backup_replays_legacy_append_from_preceding_full_snapshot`
— the pre-envelope append window replay is still live behavior for both
origins; only the codex branch's legacy-header payload construction was
dropped, so the parametrized test now uses the literal delta for both.
The
  assertions (proof kind, exact start/end offsets, empty `unproven`) are
  unchanged.
- **Retargeted**
`test_released_source_train_can_record_an_authorized_mutation_refresh`
— it stamped the legacy full-archive digest into `apply_evidence.post`
to
simulate a pre-split manifest, then asserted the digest got rewritten.
The
simulation is removed and the assertion is now
`refreshed.apply_evidence.post
  == released.apply_evidence.post` (retained evidence carried through
unchanged) — a stricter equality than the two digest assertions it
replaces.
The rest of the test (refresh receipt, revision bump, proof refs,
pending-
  intent retry rejection) is untouched.

No assertion was weakened to make a deletion pass.

## Schema closure — this PR MOVES the derived schema identity

`devtools schema closure` on every touched product file:

```
IN   polylogue/operations/append_acquisition_replay.py   (deleted)
IN   polylogue/sources/live/batch.py
IN   polylogue/sources/live/batch_support.py
IN   polylogue/storage/sqlite/migration_runner.py
IN   polylogue/storage/sqlite/durable_change_train.py
out  polylogue/daemon/backup.py
```

Five of six are IN the closure, so **this must land before an archive
rebuild
starts, never during one**, the archive must reconverge, and the seeded
test-fixture cache (`tests/infra/workload_artifacts.py:809`) is
invalidated by
the landing. Both items were batched into one PR for exactly this
reason.

## Verification

```
devtools verify --quick
  gate format/lint/mypy/generated-surfaces/layering/patterns/doc-commands/
  schema-manifest/oracle-integrity/testmon-selection/consumer-reachability/
  test-packages/timestamp-doctrine/durable-enum-checks/schema-privacy ... ok
EXIT=0
```

```
devtools test tests/unit/daemon/test_backup.py tests/unit/storage/test_durable_change_train.py \
  tests/unit/sources/test_reviewed_acquisition_defects.py tests/unit/storage/test_revision_replay.py \
  tests/unit/storage/test_durable_migrations.py tests/unit/sources/test_live_batch_convergence.py \
  tests/unit/sources/test_live_batch_support.py
```
444 tests collected, 443 passed, 1 failed:

`tests/unit/sources/test_live_batch_support.py::test_full_ingest_writes_archive_with_route_observability`
(`assert indexed == 0` / `assert 1 == 0`).

That failure is **inherited from master, not caused by this change**: I
reset the
worktree to master content (`git checkout master -- .`) and ran
`devtools test tests/unit/sources/test_live_batch_support.py` — the same
single
test fails there
(receipt `20260914T155525Z-focused-test-2913679-9bfc6c77`). It concerns
FTS
deferral after #5080 and touches none of the deleted code.

## Residuals

- The inherited
`test_full_ingest_writes_archive_with_route_observability`
  failure on master is untouched and unexplained here.
- `daemon/backup._legacy_append_replay` and
`_legacy_append_without_window`
  survive: they replay pre-envelope append rows from the preceding full
snapshot, which is still exercised for both codex and claude-code
origins.
  Only the Codex header adjustment inside them was in scope.
-
`tests/unit/storage/test_revision_replay.py::test_fold_accepts_a_legacy_codex_append_payload_after_header_normalization`
is left alone: it exercises storage-level revision-governance fold, not
the
deleted helper, and that normalization still exists in the storage tier.
  Adjacent legacy worth a separate bead, not folded in here.
- No archive reconvergence was run as part of this PR; the closure move
is
  reported, not executed.

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

https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **Bug Fixes**
- Backup recovery now validates append data directly against its
recorded blob hashes.
- Append data is handled as literal file content, improving consistency
across live ingestion and recovery.
- Durable database continuity checks now require an exact archive
identity digest match.

- **Compatibility Changes**
- Legacy Codex append headers and historical payload replay are no
longer supported during recovery or verification.
  - Legacy archive-identity fallback handling has been removed.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
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