Skip to content

Re-queue the old embedding root when a node leaves its tree - #2936

Merged
malibio merged 2 commits into
mainfrom
issue-2907-requeue-old-embedding-root
Sep 25, 2026
Merged

malibio merged 2 commits into
mainfrom
issue-2907-requeue-old-embedding-root

Conversation

@malibio

@malibio malibio commented Sep 25, 2026

Copy link
Copy Markdown
Collaborator

Closes #2907

Problem

When a node left a tree (outdent to root, reparent across trees, has_child edge delete), only its new embedding root was queued. The old root's vector kept the departed subtree's text. That caused stale search results, and an ADR-059 §7 leak after an outdent followed by filing the line into a restricted collection.

Fix

  • refresh_for_rootness takes a former_parent. After the edge write, queue_former_embedding_root queues that parent's embedding root when it differs from the node's current root, so a move within one tree adds nothing. Every call site now has to say whether it detached.
  • Paths that detach: move_node, move_node_unchecked, create_parent_edge (its store move_node replaces an existing parent), delete_relationship and remove_relationship_in_tx for has_child. Audited sites that never replace a parent pass None: append/generic has_child create, bulk cold-sweep attach, merge survivor.
  • Tx path: refresh_for_rootness_in_tx records the embedding half on NodeServiceTx. with_transaction runs it only after a successful commit, and a rollback queues nothing. Side effect: tx edge writes now also queue the gained tree, which they never did.
  • refresh_for_rootness is split into a title half and an embedding half (refresh_embedding_for_rootness) so the tx path can reuse the embedding half.

Tests

New former_embedding_root_tests module (9 tests): outdent (checked and unchecked), cross-tree reparent (both roots queued), create_parent_edge reparent, relationship-API edge delete, tx edge delete after commit, rollback queues nothing, move within one tree queues only that tree, and outdent then file into a restricted collection (old root queued, rebuilt aggregate excludes the line).

Mutation check: disabling the former-root queue fails all 7 tests that expect a queue. The within-tree and rollback tests are negative guards. The "queued once" part of the within-tree criterion can't be observed at the stale-marker level, because marking a root stale is idempotent.

nodespace-core lib: 1726 passed. Pre-push gate green.

Out of scope / follow-up

merge_nodes deletes the loser without queuing the loser's tree. That's the same stale-aggregate class, but it isn't a node leaving its tree.

🤖 Generated with Claude Code

…2907)

refresh_for_rootness now takes the former has_child parent. After the edge
write it queues that parent's embedding root when it differs from the node's
new root, so the tree a node left is re-embedded instead of keeping the
departed subtree's text (stale search, and an ADR-059 §7 leak after an
outdent-then-file into a restricted collection).

Covered paths: move_node, move_node_unchecked, create_parent_edge (its
store move replaces an existing parent), delete_relationship and
remove_relationship_in_tx for has_child. The tx path now records the
embedding half on NodeServiceTx and with_transaction runs it after commit,
so a rolled-back transaction queues nothing.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@malibio

malibio commented Sep 25, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review: PR #2936 (closes #2907)

Review Type: Initial Review (the PR had no reviews or comments before this one)

Summary

This is a clean, well-targeted fix. refresh_for_rootness now takes the node's former has_child parent. After the write, queue_former_embedding_root resolves that parent's embedding root and queues it if it differs from the node's current root. Resolving the old root through former_parent after the write is simpler than the capture-before pattern the issue proposed, and it is correct:

  • former_parent is still in the tree the node left, so get_embedding_root_id(former_parent) returns exactly the root whose aggregate held the subtree.
  • It handles ADR-059 §7 re-rooted boundary descendants for free: if former_parent is itself a boundary root, that boundary root is what gets queued.

The NodeServiceTx deferred-refresh mechanism is sound:

  • The refresh list is drained inside the store closure and returned only on Ok.
  • It runs after store.with_transaction has committed, so a closure error, a commit failure or a panic all drop it.
  • with_transaction is already non-reentrant (it debug-asserts on batch_state), so nesting is not a concern.
  • The unwrap_or_else(into_inner) poison handling matches the file's existing pattern.

A side benefit: the tx paths (merge_nodes, invariant-rule has_child create/remove) now get their embedding half at all, where before they got only the title. That fits this change's purpose.

Ran bun run rust:test:lib -- former_embedding_root: 9/9 pass.

Requirements Check

  • ✅ Outdent to root re-queues the former root: outdent_to_root_requeues_the_former_root and unchecked_outdent_requeues_the_former_root.
  • ✅ Cross-tree reparent re-queues both roots: reparent_across_trees_requeues_both_roots. create_parent_edge is also covered, a good catch because its store move_node silently replaces an existing parent.
  • ✅ has_child edge delete through the relationship API re-queues the former root: covers delete_relationship and remove_relationship_in_tx (after commit), plus a rollback test that asserts nothing is queued.
  • ✅ A move within one tree queues that tree only: a_move_within_one_tree_queues_only_that_tree. "Once" isn't observable because the stale marker is idempotent (see finding 3).
  • ✅ Outdent-then-file case covered: the stale assertion is mutation-sensitive; the aggregate assertion is not (see finding 3).
  • ⚠️ Each test mutation-checked: not re-verified here (the review is no-edit). By inspection, the stale assertions in the outdent, unchecked-outdent, reparent, create_parent_edge, edge-delete and tx-commit tests only turn true through the former-root queue. The rollback test catches a deferred refresh that runs ungated: queue_root_for_embedding(LINE) would then mark ROOT_A stale. The within-tree test can't fail when the new queue is removed; that is expected for a negative case.
  • ⚠️ quality:fix / test:all: not run here; the pre-push gate covers them.
  • ❌/⚠️ Issue's "Paths to cover": move_children_to_parent: not addressed (finding 1).

Code Review Findings

🟡 Important

1. move_children_to_parent is not covered, and the PR doesn't say why
📁 packages/core/src/services/node_service/hierarchy.rs:663-800

The issue lists this path under "Paths to cover" and asks to "audit every call site; each one that can change the parent must queue the old root". move_children_to_parent swaps every child's has_child parent through store.move_children_to_parent. It never calls refresh_for_rootness, so it queues neither the new root nor the former ones. It is exposed as a Tauri command. The API requires new_parent_id to be an empty container but does not require it to be in the same tree, so a cross-tree call leaves the old tree's vector holding the moved children's text. That is the same stale-search and ADR-059 §7 exposure this PR fixes elsewhere.

In practice, split targets are fresh siblings in the same tree, so today's real-world impact is probably zero. That is why this is 🟡 and not 🔴.

Recommendation: pick one:

  • (a) Capture each child's parent id in the pre-validation loop, which already calls get_node and is_root_node per child. After the version-bump transaction commits, call refresh_embedding_for_rootness(child, false, Some(former_parent)), or queue the new parent's root once and call queue_former_embedding_root for each distinct former parent.
  • (b) If same-tree is a real invariant of the split flow, enforce it (reject a cross-tree new_parent_id) and add a comment saying why no embedding refresh is needed.

Either way, the audit result should be explicit.
Principle: completeness of an invariant. A "re-queue on leave" rule that holds on 5 of 6 detach paths is still a leak.

🟢 Suggestions

2. merge_nodes passes former_parent: None, but re-pointing can move edges between trees
📁 packages/core/src/services/node_service/conflicts.rs:283-287

merge_nodes_in_tx re-points every edge touching the loser, including its has_child children and possibly its parent edge, onto the survivor. If loser and survivor are in different trees, the loser's former tree loses the children's text and is not re-queued. None is defensible for the survivor, whose own parent doesn't change unless it was a root. The children's former root, though, is the loser's root, and nothing queues it.

This is rare and user-initiated, so a follow-up issue is fine. Also add a one-line comment at the call site explaining why None is used, so the next auditor doesn't have to re-derive it.
Principle: make deliberate omissions visible (explicit over implicit).

3. outdent_then_file…: the aggregate assertion is not mutation-sensitive
📁 packages/core/src/services/node_service/embedding.rs:543-578

let rebuilt = TextNodeBehavior.get_aggregated_content(&root_a, &svc).await.unwrap_or_default();
assert!(!rebuilt.contains("LINE_TEXT"), ...);

get_aggregated_content walks has_child live, so once the move commits it excludes LINE whether or not the former root was queued. Only is_stale(ROOT_A) carries the test, and that makes it largely a duplicate of outdent_to_root_requeues_the_former_root. The add_to_collection step also can't affect the outcome. The assertion does document the AC's "rebuilt aggregate excludes the line", so keeping it is fine. Consider adding a comment noting that the staleness check is the regression guard, so nobody later "simplifies" it away. Separately, unwrap_or_default() would let an aggregation error pass as an empty string, which trivially satisfies !contains. Use .unwrap() instead.
Principle: every assertion should be able to fail; unwrap_or_default in an assertion input hides errors.

4. The current root is resolved twice per detach
📁 packages/core/src/services/node_service/embedding.rs:113-130, crud.rs:2952-2974

queue_root_for_embedding(node_id) resolves the node's root, then queue_former_embedding_root resolves it again with get_embedding_root_id(node_id). Each resolution is a recursive walk up the tree. The cost is negligible for interactive moves. If it ever matters, queue_root_for_embedding could return the root it queued so the former-root comparison reuses it.
Principle: avoid redundant I/O (minor; YAGNI applies until profiled).

Nits

  • Nit: crud.rs:2956: in a --no-default-features build, former_parent is an unused parameter because its only use is inside #[cfg(feature = "nlp")]. This matches existing warnings (bulk.rs:188, crud.rs:1893), and that build already fails to compile in context_ops.rs on main, so it has no practical effect.
  • Nit: hierarchy.rs:378-383, 513-518, 880-885: the .filter(|p| Some(*p) != new_parent) guard is repeated at three call sites. queue_former_embedding_root already skips a same-root former parent, so the guard is only a shortcut that saves two root walks. It's fine as is; a short comment would make that clear.

CLAUDE.md adherence

✅ No backward-compat code, no lint suppression, no issue numbers in code comments (only ADR references). Comments explain why. The call-site signature change was applied everywhere in the same PR, with no dual API kept.

Recommendation: APPROVE

The change is a clear net improvement and is correct on every path it touches. The deferred-after-commit mechanism is well built and tested for both commit and rollback. Address finding 1 before merge, either by covering move_children_to_parent or by enforcing and documenting its same-tree invariant. Findings 2-4 are optional or can go to a follow-up issue.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Automated pragmatic-code-review: APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

…ile test

- move_children_to_parent: the new parent need not be in the children's
  tree, so capture each child's parent during pre-validation (this also
  replaces the separate root check) and refresh with it after the edge swap.
  New cross-tree batch test, mutation-checked.
- Outdent-then-file test: the aggregate was None after the outdent and
  unwrap_or_default made the exclusion assertion vacuous. Keep a child in
  the old tree so the rebuilt aggregate is real text, assert it before and
  after, and expect() rather than default.
- merge_nodes: comment why the survivor has no former parent.

Skipped: the double root lookup per detach (negligible for interactive
moves) and the unused parameter in a non-nlp build (that build does not
exist).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@malibio

malibio commented Sep 25, 2026

Copy link
Copy Markdown
Collaborator Author

Review addressed (96b7858)

✅ 🟡 1. move_children_to_parent: now covered. Pre-validation captures each child's parent, which also replaces the separate root check. After the edge swap, each child is refreshed with its former parent. New test batch_move_children_across_trees_requeues_both_roots: removing the former parent makes it fail.

✅ 🟢 2. merge_nodes: added a call-site comment. The survivor never loses its own parent. The loser's tree losing the loser is a delete, not a move, and is out of scope here.

✅ 🟢 3. The aggregate assertion couldn't fail: confirmed and fixed. After the outdent ROOT_A had no descendants, so the aggregate was None and the old !contains check ran against an empty string. The test now keeps a child in the old tree and checks the aggregate both before and after: the line is there before; after, the kept child's text is there and the line's isn't. It uses expect() instead of unwrap_or_default().

✅ Nit, repeated .filter: the refresh_for_rootness doc now defines former_parent as the parent the write took away (None when kept), so the filter at each call site reads as exactly that.

⏭️ 🟢 4. Double root lookup: skipped. The cost is negligible for interactive moves; worth revisiting only if a bulk detach path appears.
⏭️ Nit, unused parameter in a non-nlp build: skipped. That build doesn't exist.

Tests: nodespace-core lib 1727 passed. Pre-push gate green.

Re-review needed: yes. #1 adds new behavior on a public API path.

@malibio

malibio commented Sep 25, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review (Re-Review): PR #2936 (closes #2907)

Review Type: Re-Review. Scope is the new commit only: 521ae2b9..96b78588.

Previous Review Summary

Requirements Check

  • ✅ Issue path "move_children_to_parent" is now covered. Each child is refreshed with its former parent after the store edge swap. The new test batch_move_children_across_trees_requeues_both_roots moves LINE from ROOT_A under a target in ROOT_B. It asserts both roots are stale. ROOT_A can only become stale through the former-parent queue, so the assertion fails if the fix is removed.
  • ✅ Outdent-then-file test: its assertions can now fail (details below).
  • ✅ bun run rust:test:lib -- former_embedding_root: 10/10 pass (was 9; the batch test is new).

Code Review Findings

🟢 Verified correct (answers to the specific checks)

1. The refresh ordering matches move_node.
📁 packages/core/src/services/node_service/hierarchy.rs:758-767 vs :507-535

move_node runs: store move_node → refresh_for_rootness → update_node_with_version_bump. move_children_to_parent now runs: store edge swap → per-child refresh_for_rootness → version-bump transaction. Same order. Two things make it safe:

  • The title half cannot race the version bump. Every moved child was already a child (is_root = false, and roots are rejected up-front), so compute_title returns the same title, set_title is never called, and the node.version that the bump transaction checks is unchanged.
  • If the bump transaction fails (OCC), the edge swap has already committed as its own atomic write, as in move_node. Re-queuing the old and new roots is therefore still correct, and at worst it causes a redundant rebuild of an idempotent stale marker. Refreshing before the bump is right. Deferring it past the bump would skip the refresh on a bump failure while the edges have in fact moved.

2. get_parent is equivalent to is_root_node.
📁 hierarchy.rs:717-722

is_root_node is literally self.get_parent(node_id).await?.is_none() (hierarchy.rs:183-188). The let … else has the same query, the same error propagation and the same hierarchy_violation message, and it gains the parent id in the same round trip. It is a pure improvement (DRY, one fewer query per child).

3. The rewritten outdent-then-file test can now fail.
📁 packages/core/src/services/node_service/embedding.rs:557-603

  • The STAYS child gives ROOT_A a non-empty aggregate after the outdent. That removes the vacuous !"".contains(..) case.
  • The pre-move assert!(aggregate(ROOT_A).contains("LINE_TEXT")) is a real precondition. Without it, a fixture where LINE was never in ROOT_A would pass vacuously.
  • The post-move contains("STAYS_TEXT") can fail.
  • expect() replaces unwrap_or_default(), so an aggregation error is no longer silently treated as an empty string.
  • The new comment says outright that is_stale(ROOT_A) is the regression guard, because aggregation reads the tree live. That was the documentation the first review asked for. The !contains("LINE_TEXT") half is still not sensitive to the fix itself. That is inherent and is now acknowledged.

4. The merge_nodes comment is accurate.
📁 conflicts.rs:280-283

It records the deliberate None and why: the survivor only gains edges, and the loser leaving is a delete, not a move. This meets the "make omissions visible" request.

5. The refresh_for_rootness doc now defines former_parent precisely.
📁 crud.rs:2914-2917

It reads "the parent the write took away: None when the node had no parent, or kept it". The new call site's .filter(|p| *p != new_parent_id) follows that definition exactly. It is also unreachable in practice, since new_parent_id must be an empty container and so cannot be a moved child's current parent. That is harmless and consistent.

Nits

  • Nit: hierarchy.rs:760-767: the refresh runs once per child. A split of N siblings from the same parent therefore resolves and queues the same old and new roots N times. That is 2N root walks where 2 would do. The stale marker is idempotent and split batches are small, so this is acceptable. If a bulk caller ever appears, dedupe former_parents (for example with a BTreeSet) and queue each distinct former root once. The first review skipped the same kind of optimization (Enhanced BaseNode with Hierarchical Circle Indicators + TextNode Implementation #4) under YAGNI, and that reasoning holds here.

CLAUDE.md adherence

✅ No lint suppression, no backward-compat shims, and no issue numbers in comments (only ADR refs). Comments explain why ("The new parent need not be in the children's tree, so each child may have left one").

Recommendation: APPROVE

Every prior recommendation was addressed or skipped with a sound reason. The move_children_to_parent fix is correctly ordered and mirrors move_node, and it has a test that fails without it. The rewritten test now contains assertions that can fail. There are no new blocking issues. No further re-review is needed.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Automated pragmatic-code-review (re-review): APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

@malibio

malibio commented Sep 25, 2026

Copy link
Copy Markdown
Collaborator Author

Re-review addressed

⏭️ Nit, one refresh per child in move_children_to_parent: skipped. Marking a root stale is idempotent and split batches are small. Deduplicate the former parents if a bulk caller ever uses this path.

No code changes. No re-review needed. The PR is ready for merge at the maintainer's discretion.

@malibio
malibio merged commit 6823d80 into main Sep 25, 2026
@malibio
malibio deleted the issue-2907-requeue-old-embedding-root branch September 25, 2026 09:51
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.

Re-queue the old embedding root when a node leaves its tree

1 participant