Skip to content

fix(embeddings): reconcile orphan rows across index rebuild generations - #2749

Closed
Sinity wants to merge 3 commits into
masterfrom
fix/orphan-embedding-reconcile
Closed

Sinity wants to merge 3 commits into
masterfrom
fix/orphan-embedding-reconcile

Conversation

@Sinity

@Sinity Sinity commented Jul 12, 2026

Copy link
Copy Markdown
Owner

Summary

Adds a bounded, resumable, idempotent reconciler for embeddings.db rows
(message_embeddings_meta / message_embeddings vec0 / embedding_status)
that no longer correspond to any message/session identity in index.db,
wires it into daemon convergence as a periodic background pass, and exposes
a manual inspect/break-glass CLI command.

Problem

embeddings.db is a rebuildable tier but is not rebuilt in lockstep with
index.db. A full re-ingest, ops reset --index, or a provider
full-replace parse can leave embedding rows pointing at message/session
identities that no longer exist in the rebuilt index. A live 2026-07-10
audit found 675,825 message_embeddings_meta rows vs 675,725
status-summed embedded messages — 11,348 orphan message ids and 6 orphan
embedding_status rows for absent sessions — inflating coverage counters
and storage, and pushing approximate coverage past 100%.

Solution

  • polylogue/storage/embeddings/reconcile.py (new): reconcile_embedding_orphans
    / inspect_embedding_orphans operate over embeddings.db with index.db
    ATTACHed, guarded by three rules:
    • Identity guard — a NOT EXISTS join on message_id/session_id
      against the live index is the only deletion trigger.
    • Content-hash guard — a message that still exists in the index is
      never removed for a stale content_hash; that's the changed-text
      re-embed path (polylogue-0k6) via needs_reindex + in-place upsert, not
      this reconciler's job.
    • Quiet-window guard — a candidate embedded within the last 5 minutes
      is skipped, since index materialization for a full-replace session is
      not guaranteed atomic across every message row.
    • Recomputes message_count_embedded for sessions with removed rows.
      Bounded via max_count (default 500) and resumable — more_pending
      tells the caller whether to run again.
  • polylogue/daemon/embedding_backlog.py /
    polylogue/daemon/cli.py: wires periodic_embedding_orphan_reconcile_check
    into the daemon's periodic-loop list (15 minute interval, 500-row bounded
    batches), alongside the existing embedding backlog drain loop.
  • polylogue/cli/commands/maintenance.py: adds
    polylogue ops maintenance embedding-orphan-reconcile (defaults to
    dry-run/inspect; --yes to apply), mirroring the existing
    blob-reference-prune-orphans command shape.

Alternatives rejected

The bead design note suggested coordinating with the not-yet-landed
blue-green generation swap (polylogue-b5l). Since that generation-pointer
infrastructure doesn't exist yet, this reconciler uses direct identity
comparison against the live index.db rather than a generation epoch —
functionally equivalent for the reported bug (dangling identities), and it
does not block on b5l landing first. When b5l ships, the identity join can
additionally be generation-scoped without changing this reconciler's public
shape.

Verification

devtools test tests/unit/storage/test_embedding_orphan_reconcile.py \
  tests/unit/daemon/test_embedding_orphan_reconcile_daemon.py \
  tests/unit/cli/test_archive_maintenance_cli.py
# 55 passed

mypy --strict polylogue/storage/embeddings/reconcile.py \
  polylogue/storage/embeddings/__init__.py polylogue/cli/commands/maintenance.py \
  polylogue/daemon/embedding_backlog.py polylogue/daemon/cli.py \
  tests/unit/storage/test_embedding_orphan_reconcile.py \
  tests/unit/daemon/test_embedding_orphan_reconcile_daemon.py \
  tests/unit/cli/test_archive_maintenance_cli.py
# Success: no issues found in 8 source files

ruff check / ruff format --check on all touched files: clean

Manual end-to-end smoke against a real polylogue demo seed archive: deleted
a live embedded message from index.db, confirmed
ops maintenance embedding-orphan-reconcile (dry-run) reports the orphan,
--yes removes exactly it and recounts message_count_embedded, and a
follow-up dry-run reports a clean, idempotent archive.

devtools render topology-projection && devtools render topology-status
run for the new module (repo convention); devtools verify --quick ran
clean via the pre-push hook.

Remaining / follow-up

Acceptance criteria call for "live inspect-before/after evidence reporting
the 11,348/6 baseline and resulting exact counts" against the real archive.
This worktree has no access to the operator's real archive, so that run is
a follow-up: execute
polylogue ops maintenance embedding-orphan-reconcile --yes against the
live archive and record the before/after counts on the bead before closing
it.

Ref polylogue-1dk1

Note: GitHub CI may show a billing-lock-related failure unrelated to this diff (per task instructions).

Co-Authored-By: Claude [email protected]

Problem: embeddings.db (message_embeddings_meta / message_embeddings vec0 /
embedding_status) is not rebuilt in lockstep with index.db. A full
re-ingest, ops reset --index, or a provider full-replace parse can leave
embedding rows pointing at message/session identities that no longer
exist in the rebuilt index. A live 2026-07-10 audit found 675,825
message_embeddings_meta rows vs 675,725 status-summed embedded messages:
11,348 orphan message ids and 6 orphan embedding_status rows, inflating
coverage counters past 100%.

Solution: add polylogue/storage/embeddings/reconcile.py
(reconcile_embedding_orphans / inspect_embedding_orphans) — a bounded,
resumable, idempotent reconciler over an attached index.db, guarded by:
identity (NOT EXISTS join on message_id/session_id is the sole deletion
trigger), content-hash (an identity-present row is never deleted for a
stale content_hash — that's 0k6's re-embed territory), and quiet-window
(skip rows embedded within the last 5 minutes, in case index
materialization for a full-replace session is mid-write). Recomputes
message_count_embedded for sessions with removed message rows.

Wired into daemon convergence as periodic_embedding_orphan_reconcile_check
(polylogue/daemon/embedding_backlog.py, 15 minute interval, 500-row
bounded batches) alongside the existing embedding backlog drain loop, and
exposed as the manual break-glass/inspect path via
`polylogue ops maintenance embedding-orphan-reconcile` (--yes to apply,
defaults to dry-run/inspect), mirroring the existing
blob-reference-prune-orphans command shape.

Verification:
- devtools test tests/unit/storage/test_embedding_orphan_reconcile.py
  tests/unit/daemon/test_embedding_orphan_reconcile_daemon.py
  tests/unit/cli/test_archive_maintenance_cli.py -> 55 passed
- mypy --strict on all touched files -> Success: no issues found in 8
  source files
- ruff check / format --check on all touched files -> clean
- Manual end-to-end smoke against a real `polylogue demo seed` archive:
  deleted a live embedded message from index.db, confirmed
  `ops maintenance embedding-orphan-reconcile` (dry-run) reports the
  orphan, `--yes` removes exactly it and recounts message_count_embedded,
  and a follow-up dry-run reports a clean, idempotent archive
- devtools render topology-projection && devtools render topology-status
  (new module regenerates docs/plans/topology-target.yaml +
  docs/topology-status.md per repo convention)

Remaining: acceptance criteria call for "live inspect-before/after
evidence reporting the 11,348/6 baseline and resulting exact counts" —
this worktree has no access to the real user archive, so that run is a
follow-up the operator (or a session with archive access) needs to
execute via `polylogue ops maintenance embedding-orphan-reconcile --yes`
before the bead is closed. Bead left open per instructions.

Ref polylogue-1dk1

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

coderabbitai Bot commented Jul 12, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

@Sinity, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 23 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: c7a5d3da-36a0-45ce-a929-762b1c5f1678

📥 Commits

Reviewing files that changed from the base of the PR and between 97ee3b9 and b0385d0.

📒 Files selected for processing (10)
  • docs/plans/topology-target.yaml
  • docs/topology-status.md
  • polylogue/cli/commands/maintenance.py
  • polylogue/daemon/cli.py
  • polylogue/daemon/embedding_backlog.py
  • polylogue/storage/embeddings/__init__.py
  • polylogue/storage/embeddings/reconcile.py
  • tests/unit/cli/test_archive_maintenance_cli.py
  • tests/unit/daemon/test_embedding_orphan_reconcile_daemon.py
  • tests/unit/storage/test_embedding_orphan_reconcile.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/orphan-embedding-reconcile

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.

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

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

Sinity added 2 commits July 12, 2026 10:58
Problem: orphan embedding deletion, vector recount, and status cleanup committed separately, while surviving sessions were not returned to the ambient embedding backlog. Manual apply could also race the daemon or an index generation replacement.\n\nMake the reconciliation pass one rollback-safe transaction, revalidate the active index identity before commit, and require daemon-coordinator or exclusive offline authority for mutation. Count meta-only and vec0-only populations independently and mark surviving affected sessions for reindex.\n\nAdd production-route tests for rollback and retry, bounded selector eligibility, daemon coordination, offline lease exclusion, index identity drift, and asymmetric embedding rows.\n\nRef polylogue-1dk1\n\nCo-Authored-By: Claude <[email protected]>
Problem: orphan reconciliation could treat a schema-stale active index as deletion truth. The live archive currently has index v32 while the packaged schema is v34, so automatic daemon cleanup could remove embeddings before the authoritative rebuild completes.\n\nRequire apply mode to verify the attached index user_version matches the packaged index schema before beginning its transaction. Keep dry-run census available, and pin refusal through substrate, daemon, and CLI production routes with mutation-sensitive v32 regressions.\n\nRef polylogue-1dk1\n\nCo-Authored-By: Claude <[email protected]>
Sinity added a commit that referenced this pull request Jul 12, 2026
…2755)

## Summary

Adds bounded, resumable reconciliation for orphan rows in
`embeddings.db`, runs it through daemon convergence, and exposes a
dry-run-first maintenance command. Mutation is atomic and
writer-coordinated, preserves surviving sessions for re-embedding,
accounts for asymmetric meta/vec0 populations, and refuses to use a
schema-stale active index as deletion truth. Dry-run output reports the
bounded meta/vector/status candidate set separately from rows actually
removed.

## Problem

`embeddings.db` is not rebuilt in lockstep with `index.db`. Full
replacement or index rebuild can leave metadata, vec0, and status rows
whose message/session identities no longer exist, inflating storage and
coverage counters. A 2026-07-12 read-only census of the current active
generation found 741,267 metadata rows, including 22,442 identities
absent from the active index, plus 17,231 status rows with 303
absent-session rows.

That active index is schema v32 while the packaged index schema is v34
and daemon ingest is still running. Those counts are diagnostic only:
the active generation is not yet authoritative deletion truth, so
destructive cleanup must wait for the rebuild.

This replaces conflicting PR #2749 from fresh master after PR #2754
changed generated topology.

## Solution

- Add `polylogue/storage/embeddings/reconcile.py` with one `BEGIN
IMMEDIATE` transaction covering meta/vec0 deletion, surviving-session
recount + `needs_reindex = 1`, and absent-session status cleanup.
Exceptions roll back the whole pass and retry remains idempotent.
- Select orphan identities from the union of metadata and vec0 so
meta-only and vec0-only rows are independently counted and removed.
Identity absence is the only deletion trigger; identity-present
content-hash mismatches remain preserved for `polylogue-0k6`.
- Track the bounded candidate identity/meta/vector/status populations
separately from apply-only removal counters, so plain and JSON dry-run
output reports what would actually be removed without pretending a
mutation occurred.
- Revalidate the resolved active index path/device/inode before mutation
and before commit.
- Require apply mode to verify attached `PRAGMA idx.user_version` equals
packaged `INDEX_SCHEMA_VERSION`. Dry-run inspection remains available on
mismatched generations; daemon and CLI mutation refuse the live
v32-vs-v34 state.
- Serialize the daemon pass through `DaemonWriteCoordinator`; require
the CLI `--yes` path to hold the exclusive offline rebuild lease and
reject a running daemon.
- Bound daemon and default manual-apply passes to 500 identities. Manual
dry-run remains unbounded unless `--max-count` is supplied.
- Run one periodic daemon pass every 15 minutes once the archive is
schema-authoritative; expose `polylogue ops maintenance
embedding-orphan-reconcile` for inspect/break-glass operation.
- Regenerate topology projection/status against current master.

### Acceptance-criteria disposition

| Criterion | Disposition |
| --- | --- |
| Synthetic rebuild retains deleted-message and absent-session embedding
rows | Satisfied by real SQLite/vec0 fixtures. |
| Automatic bounded convergence removes only orphan rows and updates
counters | Satisfied; daemon coordinator route is covered. |
| Interruption/retry is atomic and idempotent | Satisfied by a real
trigger-injected failure across delete/recount/status cleanup followed
by successful retry. |
| Active vectors survive and affected surviving sessions re-enter
backlog | Satisfied; the test invokes the production pending-session
selector after reconciliation. |
| Generation/identity/content-hash guards are mutation-sensitive |
Identity/content-hash/path+inode/schema guards are covered.
Generation-pointer lifecycle remains tracked by `polylogue-b5l`; this
slice refuses schema-stale generations now. |
| Superseded changed-text rows | Deferred to the existing focused
lifecycle bead `polylogue-0k6`; this reconciler deliberately preserves
identity-present rows. |
| Live before/after cleanup proof | Deferred until the authoritative v34
index rebuild. The bead must remain open until apply records exact
before/after counts. |

## Verification

```text
devtools test tests/unit/storage/test_embedding_orphan_reconcile.py tests/unit/daemon/test_embedding_orphan_reconcile_daemon.py tests/unit/cli/test_archive_maintenance_cli.py
66 passed in 123.66s

devtools verify --quick
15/15 steps exit 0; total 24.7s
```

The focused run exercises real SQLite/vec0 rows, the production
pending-session selector, the daemon coordinator route, and plain/JSON
CLI routes. The rollback test fails if the transaction boundary is
removed; the schema/path guards and offline lease tests fail if their
production checks are removed. The manual-bound regression seeds 501
real candidates and requires the default apply pass to remove exactly
500 while leaving resumable debt.

### Adversarial review notes

- Iteration 1 found one real gap: dry-run rendered apply-only zero
removal counters despite nonzero candidates. Commit `ba5d8820b` adds
separate bounded candidate counters and production plain/JSON CLI
regressions.
- Automated Codex review found that manual apply overrode the storage
default with an unbounded `None`. Commit `a1df0b4ab` restores the
500-identity apply default and adds a 501-candidate production-route
regression; the review thread is answered and resolved.
- No further legitimate code or closure gaps remained after the
corrected diff was reviewed against every acceptance criterion.
- GitHub-hosted jobs currently fail before allocation with zero steps/no
logs under the repository billing lock, so local gates above are the
executable verification evidence.

No destructive live apply was run. Apply and bead closure remain
deferred until the active index is rebuilt from v32 to packaged v34 and
the resulting before/after census is recorded.

Ref polylogue-1dk1

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


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

## Summary by CodeRabbit

* **New Features**
  * Added tools to inspect and reconcile orphaned embedding records.
* Added a safe, read-only dry-run mode with JSON and human-readable
reports.
* Added optional cleanup mode with safeguards against concurrent or
stale index changes.
* Added automatic background maintenance to gradually process orphaned
records.
* **Bug Fixes**
* Removed obsolete embedding records and refreshed related embedding
status entries while preserving active data.

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

---------

Co-authored-by: Claude <[email protected]>
@Sinity

Sinity commented Jul 12, 2026

Copy link
Copy Markdown
Owner Author

Superseded by merged PR #2755. The replacement includes the writer-safety, authoritative-index, truthful dry-run, and bounded-manual-apply fixes plus current-master topology.

@Sinity Sinity closed this Jul 12, 2026
@Sinity
Sinity deleted the fix/orphan-embedding-reconcile branch July 12, 2026 16:54
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