Skip to content

fix: adopt salvaged worktree hardening (MMR shape selection + promised store chunk-id) - #449

Merged
EtanHey merged 2 commits into
mainfrom
fix/salvaged-worktree-hardening
Jun 5, 2026
Merged

EtanHey merged 2 commits into
mainfrom
fix/salvaged-worktree-hardening

Conversation

@EtanHey

@EtanHey EtanHey commented Jun 5, 2026 •

Copy link
Copy Markdown
Owner

Summary

Two uncommitted-dirt patches salvaged from worktrees of already-merged branches, judged ADOPT per orc delegation (dispositions: orchestrator docs.local/audits/2026-06-05-worktree-salvage/DISPOSITIONS.md):

  • fix(search): MMR rerank picks the modal embedding shape instead of first-seen. With MMR default-ON since fix: enable MMR diversity by default #439, one wrong-dimension embedding arriving first (e.g. mid re-embedding migration) silently dropped every other candidate from the rerank. +1 regression test.
  • fix(mcp): pre-assign one promised chunk_id before the first store attempt and thread it through store_memory, the busy queue, and drain replay — the caller-visible ID can no longer drift from the persisted one across retry/queue paths. +2 tests (retry identity, queue→drain identity).

Third salvaged patch (chunk-origin provenance tests) DISCARDED: RED TDD specs for implementation that never landed in #436.

Test plan

  • All targeted tests pass on main (25 passed across the 3 affected test files)
  • Full pre-push gate green (2,458 pytest + bun + FTS5 determinism)

Review-required policy — orc merges.

🤖 Generated with Claude Code


Note

Medium Risk
Changes affect default-on MMR reranking and MCP store identity on lock/retry paths; behavior is tightened with targeted tests but touches core search and ingest flows.

Overview
MCP store now generates a single promised_chunk_id at the start of _store and uses it for the response, direct store_memory writes, arbitrated queueing, and DB-busy queue fallbacks (including drain replay). Callers no longer see a different ID after retries or queued writes.

Hybrid search MMR no longer locks embedding dimension to the first loaded vector. It picks the most common shape among top candidates (ties favor the earliest rank), so one wrong-dimension embedding during re-embedding migration does not drop the rest from diversification.

Regression tests cover retry/queue→drain ID stability and mixed-dimension MMR ordering.

Reviewed by Cursor Bugbot for commit 103bc81. Bugbot is set up for automated code reviews on this repo. Configure here.

Note

Fix MMR shape selection and preassign chunk IDs in the store handler

  • SearchMixin._mmr_rerank_scored_results now selects the most common embedding shape among top candidates instead of using the first encountered shape, then filters to that shape before running MMR diversity ranking.
  • _store handler now preassigns a chunk ID via _new_manual_chunk_id() at the start of the request and passes it through all code paths (immediate write, arbitrated write, and lock-error queue fallback), so callers always receive the same promised ID regardless of outcome.
  • Behavioral Change: MMR result order may change when top candidates have mixed-dimension embeddings, since the shape chosen can differ from the previous first-seen behavior.
📊 Macroscope summarized 103bc81. 2 files reviewed, 0 issues evaluated, 0 issues filtered, 0 comments posted

🗂️ Filtered Issues

No issues evaluated.

EtanHey and others added 2 commits June 5, 2026 13:26
Salvaged from fix/enable-mmr-diversity worktree (branch merged via #439,
this hardening was uncommitted dirt). With MMR default-ON since #439, a
single wrong-dimension embedding arriving first (e.g. mid re-embedding
migration) poisoned shape selection and silently dropped every other
candidate from the rerank. Pick the most common shape across candidates
instead; ties break to earliest-seen.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Salvaged from fix/brain-store-queue-returns-id worktree (branch merged,
this follow-up was uncommitted dirt). The handler minted a fresh chunk_id
per attempt, so a busy-retry or queue fallback could persist a different
ID than the one already returned to the caller — breaking store-then-verify
flows. Mint one promised ID up front and thread it through store_memory,
the busy queue, and the drain replay.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

@greptile-apps greptile-apps 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.

Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.

@coderabbitai

coderabbitai Bot commented Jun 5, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

@EtanHey, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 6 minutes and 44 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

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.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: d0cc4bda-827c-4af9-822f-461e0e6c863c

📥 Commits

Reviewing files that changed from the base of the PR and between e95c40d and 103bc81.

📒 Files selected for processing (4)
  • src/brainlayer/mcp/store_handler.py
  • src/brainlayer/search_repo.py
  • tests/test_mmr_default_off.py
  • tests/test_store_handler.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/salvaged-worktree-hardening

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.

@EtanHey

EtanHey commented Jun 5, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@EtanHey

EtanHey commented Jun 5, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@EtanHey

EtanHey commented Jun 5, 2026

Copy link
Copy Markdown
Owner Author

@cursor @BugBot review

@cursor

cursor Bot commented Jun 5, 2026

Copy link
Copy Markdown

You need to increase your spend limit or enable usage-based billing to run background agents. Go to Cursor

@coderabbitai

coderabbitai Bot commented Jun 5, 2026 •

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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: 103bc815c3

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

_queue_store(
{
"chunk_id": queued_chunk_id,
"chunk_id": promised_chunk_id,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Handle queued supersedes for already-inserted chunks

When store_memory succeeds but store.supersede_chunk() raises a lock error, this fallback now queues the same preassigned promised_chunk_id that was already inserted. On drain, _apply_store detects that exact chunk ID/content already exists and returns before applying event["supersedes"] (checked src/brainlayer/drain.py lines 320-335), so the old chunk is never marked superseded even though the MCP call reports the write as queued. This affects lock contention specifically after the new chunk insert and before the supersede update; the queue path needs to still apply supersedes for an existing same-id chunk, or avoid reusing the already-inserted ID in that fallback.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium

If store.supersede_chunk() or other post-store operations raise a lock error, the exception handler queues the store with promised_chunk_id even though store_memory already succeeded. When _flush_pending_stores replays the queue, store_memory is called again with the same chunk_id, triggering merge_existing_chunk_seen which incorrectly increments seen_count. The queued item should track whether the store already succeeded so replay doesn't reprocess it.

🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
In file @src/brainlayer/mcp/store_handler.py around line 521:

If `store.supersede_chunk()` or other post-store operations raise a lock error, the exception handler queues the store with `promised_chunk_id` even though `store_memory` already succeeded. When `_flush_pending_stores` replays the queue, `store_memory` is called again with the same `chunk_id`, triggering `merge_existing_chunk_seen` which incorrectly increments `seen_count`. The queued item should track whether the store already succeeded so replay doesn't reprocess it.

Evidence trail:
src/brainlayer/mcp/store_handler.py:591-611 (store_memory succeeds, returns result), :618 (supersede_chunk can raise lock error after store succeeded), :673-695 (exception handler queues with promised_chunk_id without tracking store success), :465-483 (_flush_pending_stores replays with same chunk_id). src/brainlayer/store.py:176-179 (checks if chunk exists, calls merge_existing_chunk_seen). src/brainlayer/dedupe.py:615-649 (merge_existing_chunk_seen increments seen_count at line 649). src/brainlayer/vector_store.py:2228-2231 (supersede_chunk executes UPDATE that can raise BusyError).

@EtanHey
EtanHey merged commit 8ae963e into main Jun 5, 2026
6 checks passed
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