Skip to content

C3c: Atomic child-transfer-on-split — single MoveChildrenToParent RPC (all-or-nothing) #1275

Closed

Description

@malibio

Tracking: Spun off from architectural-audit #1228, finding C3 (child-transfer-on-split). C3a/C3b are done; C3c is the deferred atomic-operation sub-piece.
Priority: ui / backend (cross-cutting: proto + core + daemon + frontend)
Risk class: live-outliner data integrity (#557 class), but the new RPC is additive, so lower-risk than editing existing move/reorder paths.

Problem

When a node is inserted mid-list under an expanded parent that has children (splitting a line where the cursor is not at start), the parent's existing children are transferred to become children of the new node. Today this is orchestrated client-side as N separate per-child MoveNode RPCs with optimistic UI + best-effort manual rollback.

Verified — packages/desktop-app/src/lib/services/reactive-node-service.svelte.ts, createNode (~352–398), branch !insertAtBeginning && children.length > 0 && isExpanded:

  1. Optimistic UI: loop structureTree.moveInMemoryRelationship(afterNodeId, nodeId, child.id) per child.
  2. Background Promise: after waitForNodeSaves([nodeId]), loops backendAdapter.moveNode(child.id, child.version, nodeId, null) — N RPCs, N transactions, per-child OCC — then version-syncs each via updateNode(..., { skipPersistence: true, skipConflictDetection: true }).
  3. On failure: rollback loop in structureTree + conflictNotifications.add({ conflictType: 'child-transfer-failure', message: "Changes couldn't be saved. Please try again." }).

Why this is wrong

  • Not atomic. A mid-batch failure (RPC error / OCC conflict on child K) leaves 1..K-1 re-parented and K..N not. Rollback is best-effort client-side and can race a concurrent edit or a second split.
  • N round-trips for one conceptual op.
  • Per-child version dance with skipConflictDetection is fragile and bypasses the unified C5 conflict pipeline.

Daemon surface today

Proto has only single-node rpc MoveNode (line 28) + rpc ReorderNode (29). SqliteStore has bulk_create_hierarchy (sqlite_store.rs:1724) for creating a tree atomically, but no "re-parent N existing children to a new parent atomically" op. C3c adds one.

ADR grounding

  • ADR-026: Write Flow & Conflict Resolution — OCC + LWW (incl. the merged C5 amendment): the daemon is the sole writer and OCC adjudicator — detects version mismatch, re-fetches authoritative state, returns structured VersionConflict (OpsError::VersionConflict { current_node } → Status::Aborted → CommandError { code: "VERSION_CONFLICT" }). The batch RPC funnels through this same pipeline.
  • ADR-031: Daemon-Client Architecture: all graph mutations live in NodeService in nodespaced; clients are thin proxies. C3c moves the orchestration that currently leaks into reactive-node-service down into the daemon — exactly the ADR-031 contract.
  • ADR-024: Parent-Child as Operation Parameters: hierarchy is graph-native (has_child edges, fractional order in properties). The batch op manipulates has_child edges + emits RelationshipUpdated, like move_node.

Target architecture

A new additive daemon RPC + core op that re-parents an explicit set of existing children to a new parent in one transaction, returning the updated children (new versions + authoritative order) so the frontend reconciles via the existing event/hierarchy-sync path.

Proto (packages/proto/proto/node_service.proto)

rpc MoveChildrenToParent(MoveChildrenToParentRequest) returns (MoveChildrenToParentResponse);
message MoveChildrenToParentRequest {
  string new_parent_id = 1;            // the freshly-created split node
  repeated ChildMove children = 2;     // ordered; preserves sibling order
}
message ChildMove { string node_id = 1; int64 version = 2; }  // per-child OCC
message MoveChildrenToParentResponse { repeated NodeData children = 1; }

Decisions (recommended answers; confirm in PR):

  • Order: compute the batch order in one pass (new parent starts empty — it's the just-created split node); assign sequential fractional orders in array order via FractionalOrderCalculator. Do not per-child recompute via move_node.
  • OCC: all-or-nothing — validate every child's expected_version up front inside the txn; any mismatch → VersionConflict for the first offender + full rollback (nothing moves). Bump each moved child's version on success.
  • Validation: reuse move_node's guards — reject date nodes, verify new parent exists + can_have_children() (C3b/C3b: Enforce container rule (canHaveChildren) in the daemon; source the frontend UI gate from schema #1264), cycle check (is_descendant).

Core op (packages/core/src/services/node_service/mod.rs)

New NodeService::move_children_to_parent(&self, new_parent: &str, children: &[(String, i64)]) -> Result<Vec<Node>, NodeServiceError> (pattern: move_node at mod.rs:1582, reorder_node 1703). Up-front validation; delegate the mutation to a new SqliteStore::move_children_to_parent doing it in one self.db.transaction() (mirror bulk_create_hierarchy, sqlite_store.rs:1724): per child delete old has_child edge, insert new edge under new_parent at computed order, bump version; tx.commit() once. Emit one RelationshipUpdated has_child event per moved child (shape per move_node, mod.rs:1648). Return updated Nodes.

Daemon handler (packages/daemon/src/services/node_service.rs)

Add move_children_to_parent next to move_node (line 480). Map errors via the existing service_error_to_status (so VersionConflict → Aborted + x-version-conflict; test pattern at node_service.rs:1668). Return children as NodeData via node_to_proto.

Frontend (reactive-node-service.svelte.ts + backend-adapter.ts)

  • Add backendAdapter.moveChildrenToParent(newParentId, children: {id,version}[]): Promise<Node[]> (interface + Tauri impl + mock; sites near backend-adapter.ts:110/228/467/592).
  • In createNode, keep the optimistic moveInMemoryRelationship loop; replace the per-child RPC loop with one moveChildrenToParent call. Prefer reconciling order via the RelationshipUpdated → hierarchy-sync.ts applyHasChildUpdated path (C3a-consistent, idempotent on existing children); use the response only for version sync.
  • On failure: one rollback pass + preserve the existing Add user notification for background child transfer failures #656 notification verbatim (conflictType: 'child-transfer-failure', same message; it's a typed member at conflict-notifications.svelte.ts:11). Re-trigger from the new RPC error path; don't re-derive or drop it. A daemon VERSION_CONFLICT on the batch surfaces this same notification.

Acceptance criteria

  • New MoveChildrenToParent RPC + core op + SqliteStore transaction; single-node MoveNode/ReorderNode untouched.
  • createNode mid-list-split under expanded parent issues exactly one RPC (spy: moveNode no longer called in this branch; moveChildrenToParent called once).
  • Optimistic structureTree update preserved.
  • Authoritative order/version reconciled via response and/or RelationshipUpdated → hierarchy-sync (C3a-consistent).
  • On failure: exactly one rollback pass + the Add user notification for background child transfer failures #656 'child-transfer-failure' notification fires (asserted).
  • No skipConflictDetection per-child loop and no partial-transfer path remaining (delete the old loop — greenfield).

Testing

  • Atomicity (cargo test): inject mid-batch failure (child K stale version) → assert ALL-or-NOTHING: every child still under the original parent, none under the new, no dangling has_child edges.
  • OCC mapping (daemon): stale version → Status::Aborted + x-version-conflict (extend error_mapping_version_conflict_returns_aborted).
  • Frontend (bun run test, never bun test): vi.mock('@tauri-apps/api/core'); spy backendAdapter. Assert single moveChildrenToParent on success; on rejection assert single rollback + 'child-transfer-failure' notification (exact Add user notification for background child transfer failures #656 message). createLogger not console.
  • Order: transferred children retain relative order under the new parent (sequential fractional orders, no collisions); bun run test:db reload shows same order.

Risks

  • Delete obsolete cache management code from SharedNodeStore #557-class: mitigated by atomicity (single txn — strictly safer than today's N-RPC best-effort).
  • Additive RPC = lower risk: no existing move/reorder/bulk behavior changes.
  • Double-apply: emitting RelationshipUpdated while also syncing from the response could double-apply order — use the response for version only, the event path for order (applyHasChildUpdated is idempotent on existing children).

Coordination

ADR update

Add a short amendment to ADR-026 (or a note under ADR-031's hierarchy-op contract) documenting batch child re-parenting as a single daemon-adjudicated OCC transaction, all-or-nothing. Lands in nodespace-docs on a doc/ branch, cross-linked.

Standard NodeSpace startup / PR sequence

EnterWorktree({name: "issue-<N>-c3c-atomic-child-transfer"}), bun install, bun run test baseline, gh:*. Before PR: bun run test:all + bun run test:db (no new failures), bun run quality:fix + commit (revert unrelated cargo fmt churn via git status), bun run gh:pr <N>, /pragmatic-code-review, then ExitWorktree + gh pr merge --squash --delete-branch.


Spun off from #1228 (architectural audit), finding C3 (C3c — atomic child-transfer-on-split). Parallel-safe with C5 (#1268). Preserves #656 (#1272).

Activity

  1. malibio commented on May 30, 2026

    @malibio
    CollaboratorAuthor

    Frontend baseline: 133 test files, 3867 tests passed. Starting C3c implementation.

  2. self-assigned this
    on May 30, 2026
  3. added a commit that references this issue on May 30, 2026
    9bac6ec
  4. added a commit that references this issue on May 30, 2026
    6b2783a
  5. added a commit that references this issue on Jun 22, 2026
    95fb507
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions