Skip to content

Keep merge_nodes inside the tree invariants (closes #2938) - #3094

Merged
malibio merged 3 commits into
mainfrom
issue-2938-merge-tree-invariants
Sep 26, 2026
Merged

malibio merged 3 commits into
mainfrom
issue-2938-merge-tree-invariants

Conversation

@malibio

@malibio malibio commented Sep 26, 2026

Copy link
Copy Markdown
Collaborator

Summary

merge_nodes_in_tx re-pointed every edge with a plain endpoint UPDATE, bypassing the tree invariants every other has_child write enforces.

Policy (open question 1: refuse, matching move_node):

  • The loser's parent edge re-points only onto a root survivor. When the survivor already has a parent, the edge is dropped and counted in edges_dropped; the survivor keeps its position (case 2).
  • Refused before any write when the result would break ADR-059 §2: member_of_not_root (cases 4 and 5; person exempt) or collection_not_root.
  • Also refused with merge_would_cycle when one node sits deeper than a direct child in the other's subtree. This is a third bypass the issue didn't list. A direct parent/child pair still merges (the edge between them becomes a self-edge).
  • merge_nodes reads the loser's parent before the merge and passes it as former_parent to refresh_for_rootness_in_tx, so the tree that lost the loser is re-queued after commit.

Open question 2 (Conflicts-view messaging) is UI and is not part of this PR.

Tests

  • tests/merge_nodes_test.rs: case 2, case 1, survivor directly under the loser, cases 4 and 5, and both cycle shapes.
  • former_embedding_root_tests: case 2 re-queues both roots; a rolled-back merge (unknown conflict id, failing after the deferral) queues nothing.
  • Mutation-checked: disabling each part of the fix (parent-edge drop, former-parent re-queue, §2 check, cycle check) fails the corresponding tests. The rollback test asserts existing behaviour.
  • bun run rust:test:lib: 1800 passed. quality:fix clean.

🤖 Generated with Claude Code

@malibio

malibio commented Sep 26, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #3094 (closes #2938)

Review Type: Initial Review

Requirements Check

Acceptance criterion Status Notes
Survivor has at most one has_child parent in every shape (cases 1–3 + loser-root/survivor-child) ✅ takes_loser_parent gates the re-point; otherwise the loser's parent edge is deleted and counted. Tested: two-children (case 2), root survivor (case 1), survivor = loser's direct child. Case 3 (same parent) now drops through the new branch instead of the unique-collision branch; same edges_dropped=1, and an existing test already covers it.
No node holds member_of while having a parent (cases 4 & 5), REFUSE policy naming ADR-059 §2 ✅ Step 0 refuses before any write. Both directions are tested (merge_refuses_to_give_a_filed_survivor_a_parent, merge_refuses_to_file_a_survivor_that_has_a_parent), and the tests assert that nothing was written or archived.
Survivor's resulting root and the loser's former root both re-queued; test asserts both stale for case 2 ✅ loser_parent is read before the merge and passed as former_parent. merging_children_of_two_trees_requeues_both_roots asserts ROOT_A and ROOT_B are both stale.
Rolled-back merge queues nothing (asserted) ✅ rolled_back_merge_queues_nothing fails on the conflict-id step, which runs after the refresh was deferred, so the test really does exercise the post-commit deferral.
Each new test mutation-checked ✅ The author reports a manual mutation pass: drop-parent, former-parent requeue, §2 and cycle each broke their matching tests. I found no test that passes trivially.
Doc comment (step 2) + call-site comment updated ✅ New step 0, a step-2 has_child paragraph and the edges_dropped wording are in merge_nodes_in_tx. The call-site comment in node_service/conflicts.rs is rewritten.
quality:fix clean, pre-push gate green ✅ The gate passed at push. I re-ran the merge-scoped nextest set locally: 26/26 pass.

Correctness walk-through (no defects found)

I traced every shape (S = survivor, L = loser):

  • S is L's direct child. survivor_parent is filtered to None, so the L→S edge becomes a self-edge and is dropped. S takes L's parent. The cycle check (b) asks whether L's parent is below S, which it cannot be. ✅
  • L is S's direct child. loser_parent is filtered to None, so there is no take and no refusal. The S→L edge hits the self-edge branch first, so it is counted once. ✅
  • S is two or more levels under L. survivor_parent is Some(middle) and is_descendant(L, S) is true, so the merge is refused. This is correct: middle would become S's child. ✅
  • L is two or more levels under a root S. The survivor would take middle as its parent, so the merge is refused. ✅ (see 🟢 Create design system foundation #2)
  • L is two or more levels under S, and S has its own parent. L's parent edge is dropped, and L's children join S with no cycle. Allowed. ✅
  • Filed root S, L a direct child of S. has_parent_after is false, so the merge is allowed. Filed root L that is S's direct parent. S becomes a root and inherits member_of. Allowed and correct. ✅
  • Person exemption. It keys on survivor.node_type. That is right, because the survivor is the node that holds the edges afterwards. It also matches check_root_only_member, which keys on the member's type. ✅
  • Recursive CTE. It uses UNION (set semantics), so it terminates even on corrupt cyclic data without the arbitrary depth < 100 cap that validate_no_cycle has. This is strictly safer. ✅

Code Review Findings

🟡 Important

1. The root-only-membership rule now has a third hand-written copy
📁 packages/core/src/db/sqlite_store/conflicts.rs:354-370

if has_parent_after {
    if survivor.node_type == "collection" { anyhow::bail!(super::collection_not_root(...)); }
    if survivor.node_type != "person" {
        let memberships = Self::member_of_targets_in_tx(tx, &[survivor_id, loser_id]).await?;
        if !memberships.is_empty() { anyhow::bail!("member_of_not_root: ...") }

check_root_only_member in relationships.rs is documented as "the single source of the rule for both guard twins, so they cannot drift." assert_may_gain_parent already restates the rule in SQL, and this PR adds a third copy. The copy includes the person exemption, which is exactly the part most likely to change (for example, if another grantee type is added under ADR-037). If that exemption changes in one place, merge would silently diverge from move_node and add_to_collection.
Recommendation: Keep member_of_targets_in_tx, which gives the better error message, but route the decision through the shared rule. For example: if !memberships.is_empty() { check_root_only_member(survivor_id.into(), survivor.node_type.clone(), has_parent_after as i64).map_err(...)? }. Alternatively, lift a tiny fn may_hold_membership_with_parent(node_type) -> bool that both check_root_only_member and this site call. The collection_not_root branch already reuses super::collection_not_root, which is good; the membership branch should get the same treatment.
Principle: DRY / single source of truth for invariants (this is a stated project rule for guard logic).

🟢 Suggestions

2. Root survivor with a loser deep in its own subtree is refused, but could be merged by dropping
📁 packages/core/src/db/sqlite_store/conflicts.rs:374-386 (branch else if takes_loser_parent)
The same shape with a survivor that has a parent is allowed: the loser's parent edge is dropped. When the survivor is a root, the "take the loser's position" rule instead picks a parent that lies inside the survivor's own subtree, and the merge is refused. The natural result here would be to treat it like the has-parent case: drop the loser's parent edge and leave S a root. That would mean takes_loser_parent = survivor_parent.is_none() && loser_parent.is_some() && !is_descendant(S, loser_parent), with no refusal. Refusing is safe and consistent with move_node, so this is not a blocker. It is still an asymmetric user-visible refusal ("Move one of the nodes out of the other's subtree first") for a merge that has a clean result.
Principle: Principle of least surprise; avoid refusing valid operations.

3. Cycle checks walk whole subtrees downward, where a walk up the ancestors is enough
📁 packages/core/src/db/sqlite_store/conflicts.rs:374-386, is_descendant_in_tx (:628-646)
Check (b), is_descendant_in_tx(tx, survivor_id, loser_parent), walks the entire subtree of a root survivor, and a root survivor is typically a whole document. Check (a) does the same for the loser's subtree. Both questions can be answered by walking up from the candidate node (loser_parent for b, survivor_parent for a) and looking for the other id. That costs O(depth) instead of O(subtree size), and it is one indexed parent lookup per hop. Merge is user-initiated and rare, so this is not urgent. The only way it would matter is a merge inside a large page taking noticeably long while the write lock is held.
Principle: Choose the traversal direction that bounds the work (tree depth ≪ subtree size).

4. The two remaining refusal branches have no tests
📁 packages/core/tests/merge_nodes_test.rs
There is no test for a collection survivor that would gain a parent (collection_not_root), and none for the person exemption: a filed person survivor taking the loser's parent should succeed. The exemption is the branch most likely to regress if finding 1 is refactored. Each is about five lines with the existing text/collection helpers.
Principle: Test every branch of a guard, including the exemptions.

5. Policy refusals surface as query_failed
📁 packages/core/src/services/node_service/conflicts.rs:275-283
The member_of_not_root and merge_would_cycle refusals are user-actionable policy errors, but they are mapped through NodeServiceError::query_failed. That matches how move_node maps its guard errors today, so this is consistent and not a regression. If the Conflicts view needs to show "un-file the node first" differently from a real DB failure, a typed variant (invalid operation / invariant violation) would let the frontend branch without string-matching. This can be a follow-up.

Nits

  • Nit: conflicts.rs:378, loser_parent.as_deref().expect("takes_loser_parent"). Matching on (survivor_parent, loser_parent), or if let (true, Some(p)) = (...), avoids the expect and makes the invariant structural.
  • Nit: conflicts.rs:~304. The re-flowed doc line "this step's own self-edge, parent-edge and unique-constraint drops, not anything" now runs past the surrounding comment width. rustfmt won't re-wrap it.
  • Nit: The member_of_not_root message says "would leave it holding collection membership". "It" is ambiguous between loser and survivor. "would leave '{survivor}' holding …" reads more clearly.

Standards check

  • No issue numbers in code comments (only ADR references). ✅
  • No backward-compat or migration code. ✅
  • Step 0 runs through tx.conn() rather than the non-tx guards, so it avoids the write-guard deadlock the issue warned about. ✅
  • The change stays inside the issue's scope. ✅

Recommendation: APPROVE

The fix is correct in every shape I traced, the refusal policy matches move_node, the former-root re-queue reuses the existing post-commit mechanism, and the tests are meaningful: they assert that nothing was written on refusal and that nothing was queued on rollback. Finding 1 (the third copy of the root-only rule) is worth folding in before merge because it is cheap and it is exactly the kind of drift the project's single-source guard rule exists to prevent. The rest are optional.

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

@malibio

malibio commented Sep 26, 2026

Copy link
Copy Markdown
Collaborator Author

Review addressed (467bfd3)

  • ✅ 🟡 Duplicated membership rule: member_may_have_parent in relationships.rs is now the single source of the person exemption, used by check_root_only_member and merge_nodes_in_tx.
  • ✅ 🟢 Avoidable refusal: a root survivor whose loser has a parent inside the survivor's own subtree now drops that parent edge instead of refusing. This matches what happens when the survivor already has a parent. merge_would_cycle now covers only a survivor inside the loser's subtree.
  • ✅ 🟢 Subtree walks: is_ancestor_in_tx walks up the parent chain, so the cost is O(depth).
  • ✅ 🟢 Untested branches: added tests for a collection survivor (refused), a filed person survivor (may take a parent), and the in-subtree drop. Each fails under a mutation of its branch.
  • ✅ Nits: the error message names the survivor, the doc line is re-wrapped, and the .expect is gone (replaced by a match).
  • ⏭️ 🟢 Typed error: skipped. move_node reports the same refusals as query_failed, so a typed error belongs in a follow-up that covers both.

rust:test:lib: 1800 passed. merge_nodes_test: 19 passed. Push check passed.

@malibio

malibio commented Sep 26, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review: PR #3094 (re-review of 467bfd3)

Review Type: Re-Review

Previous Review Summary: The previous review made 5 recommendations and 3 nits. 4 recommendations and all 3 nits are addressed. 1 recommendation is not addressed, and the reason is acceptable. There is 1 new finding, a nit.

# Prior finding Status
🟡1 Membership rule duplicated ✅ Addressed. member_may_have_parent in relationships.rs is now the single predicate. Both check_root_only_member and merge_nodes_in_tx call it, and its doc names all three callers. It is pub(super), which is the narrowest visibility that reaches conflicts.rs.
🟢2 Avoidable refusal when a root survivor's loser sits deep in its subtree ✅ Addressed. takes_loser_parent is now false in that case, and the edge loop's !takes_loser_parent branch drops the loser's parent edge. The old merge_refuses_a_loser_below… test became merge_drops_a_parent_edge_from_inside_the_survivors_subtree.
🟢3 Cycle checks walked whole subtrees ✅ Addressed. The checks now call is_ancestor_in_tx, which walks up the parent chain, so each check costs O(depth).
🟢4 collection_not_root branch and person exemption untested ✅ Addressed. Both branches now have a test. merge_lets_a_filed_person_survivor_take_a_parent also asserts the membership survives.
🟢5 Refusals mapped to query_failed ⏭️ Not addressed, deferred to a follow-up. This is acceptable: it matches move_node, it is not a regression, and a typed error belongs in a cross-cutting change.
Nits .expect, doc width, ambiguous "it" ✅ All three fixed. The structural match replaces the .expect, the doc is re-wrapped, and the message now names the survivor.

Correctness walk-through of the new logic

is_ancestor_in_tx(A, N) means "A == N, or A is an ancestor of N". The query seeds with SELECT ?2, walks up has_child, and uses UNION, so it terminates even on corrupt cyclic data. S is the survivor and L is the loser.

  • Site 1 is is_ancestor(L, survivor_parent). survivor_parent is already filtered to != L, so the == arm can never fire here. The check is true exactly when S sits at depth ≥2 under L, and then the merge is refused. At depth 1, survivor_parent is filtered to None and this site does not run. That is correct: the L→S edge becomes a self-edge. ✅
  • Site 2 is is_ancestor(S, loser_parent) and runs only when S is otherwise a root. loser_parent is filtered to != S, so again only the strict-ancestor arm matters. The check is true exactly when L sits at depth ≥2 under S; then the edge is dropped and S stays a root. ✅

I traced every shape against the edge loop and found no defect:

  • S is L's direct child, and L has a parent Lp. survivor_parent is None. is_ancestor(S, Lp) is false because Lp is above L. S takes Lp, and the L→S edge hits the self-edge branch first. ✅
  • S is L's direct child, and L is a root. There is no take, has_parent_after is false, and S becomes a root. The membership check is correctly skipped. ✅
  • L is S's direct child, and S is a root. loser_parent is None, so there is no take. The S→L edge becomes a self-edge. The self-edge branch runs before the !takes_loser_parent branch, so the edge is counted once. ✅
  • L is at depth ≥2 under a root S. The middle→L edge is dropped and counted once. L's children re-point onto S with no cycle, because S is a root and those children were already in S's tree. has_parent_after is false, so a filed root survivor is no longer refused here. That is correct, because S stays a root. ✅
  • L is at depth ≥2 under S, and S has its own parent. Site 1 is false (L is not above S), so the behavior is unchanged: the edge is dropped. ✅
  • S is at depth ≥2 under L. The merge is refused before any write. ✅
  • has_parent_after now uses takes_loser_parent. This is correct: the §2 and collection checks now fire only when S really ends up with a parent. ✅
  • Requeue at the service layer. In the dropped-edge case, the former parent (middle) resolves to S's root, so that tree is still queued. ✅

Tests. 33 of 33 pass locally under cargo nextest run -p nodespace-core --test merge_nodes_test --lib -E 'test(merge) | test(merging) | test(root_only)'. Each new test targets its own branch:

  • The drop test asserts edges_dropped == 1, that S is still a root, that middle has no children left, and that the loser's child is re-pointed.
  • The collection test would fail if the collection_not_root guard were removed.
  • The person test would fail if member_may_have_parent stopped exempting person.

Code Review Findings

Nits

  • Nit: The inline comment on the edge loop's parent-edge drop branch is stale.
    📁 packages/core/src/db/sqlite_store/conflicts.rs:523-524
    The comment reads "The loser's own parent edge, when the survivor already has a parent". The branch now also fires when S is a root and the loser's parent lies inside S's subtree. Recommendation: Reword it to key on takes_loser_parent, for example: "The loser's own parent edge, when the survivor does not take it (it already has a parent, or that parent is inside its own subtree)". The step-2 doc comment was updated; this inline comment was missed. Principle: Comments must describe current intent; a stale one misleads the next reader of the invariant.

No other new issues.

Recommendation: APPROVE

@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 26, 2026

Copy link
Copy Markdown
Collaborator Author

Re-review addressed (17c4fa6)

  • ✅ Nit: reworded the stale inline comment on the parent-edge drop branch. It now matches takes_loser_parent: the survivor already has a parent, or that parent is inside the survivor's own subtree.

Comment-only change, so no re-review is needed. merge_nodes_test: 19 passed. Push check passed.

malibio and others added 3 commits September 26, 2026 20:29
merge_nodes_in_tx re-pointed every edge with a plain endpoint UPDATE, so
a merge could give the survivor two has_child parents, leave it holding
member_of while it has a parent (ADR-059 §2), or close a has_child cycle.

- The loser's parent edge re-points only onto a root survivor; otherwise
  it is dropped and counted, and the survivor keeps its position.
- The merge is refused before any write when the result would break
  ADR-059 §2 (member_of_not_root / collection_not_root) or form a cycle
  (merge_would_cycle), matching move_node's refusal.
- merge_nodes passes the loser's former parent to
  refresh_for_rootness_in_tx, so the tree that lost the loser is
  re-queued after commit.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…fusing an in-subtree parent

- member_may_have_parent is now the one source of the ADR-059 §2 person
  exemption, used by check_root_only_member and merge_nodes_in_tx.
- A root survivor no longer refuses a loser whose parent sits in the
  survivor's own subtree: the loser's parent edge is dropped, as it is
  when the survivor already has a parent. merge_would_cycle now covers
  only a survivor inside the loser's subtree.
- The cycle check walks up the parent chain (O(depth)) instead of down
  a whole subtree.
- New tests: in-subtree parent edge dropped, collection survivor refused,
  filed person survivor may take a parent. Each is mutation-checked.
- Error message names the survivor; doc line re-wrapped.

Skipped: a typed error for merge refusals. move_node reports the same
refusals as query_failed, so a typed error belongs in a follow-up that
covers both.

Co-Authored-By: Claude Opus 5.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