Skip to content

Implement atomic moveNode operation with fractional ordering #552

Closed

Description

@malibio

Overview

Current indentNode/outdentNode operations have race conditions due to separate updates for parent edges and sibling pointers. This causes temporary inconsistencies visible to the frontend. We need an atomic moveNode operation that uses fractional ordering to move nodes without cascading updates.

Self-Contained Scope

  • Atomic database operation for moving nodes to new parents
  • Fractional order calculation for insertion position
  • Single transaction ensuring no intermediate inconsistent states
  • Rebalancing logic when precision degrades
  • Comprehensive testing for concurrent operations

Implementation Approach

  1. Backend Operation: Implement atomic move_node in Rust using single transaction
  2. Order Calculation: Use fractional ordering from Issue Migrate database schema to use fractional ordering instead of beforeSiblingId linked-list #550
  3. Rebalancing: Detect and handle precision degradation
  4. Error Handling: Rollback on any failure within transaction
  5. Testing Strategy: Test concurrent moves and rapid operations

Acceptance Criteria

  • Implement move_node(node_id, new_parent_id, insert_after_sibling_id) in Rust
  • Calculate fractional order using algorithm from Issue Migrate database schema to use fractional ordering instead of beforeSiblingId linked-list #550
  • Use single TRANSACTION for delete old edge + create new edge
  • Handle edge cases: insert at beginning, insert at end, first child
  • Performance: O(1) operation (no sibling updates needed)
  • Integration test: Rapid indent/outdent doesn't cause orphaned nodes
  • Integration test: Concurrent moves from multiple clients resolve correctly
  • All existing hierarchy operations refactored to use new atomic operation

Technical Implementation Notes

Step 1: Update SurrealStore with Atomic Move Operation

File: packages/core/src/db/surreal_store.rs

use crate::db::fractional_ordering::FractionalOrderCalculator;

impl SurrealStore {
    /// Atomically move a node to a new position in the hierarchy
    ///
    /// This replaces the old multi-step indent/outdent operations with a single atomic transaction.
    /// Uses fractional ordering to avoid cascading sibling updates.
    pub async fn move_node(
        &self,
        node_id: &str,
        new_parent_id: Option<&str>,
        insert_after_sibling_id: Option<&str>,
    ) -> Result<()> {
        // Step 1: Get current siblings at target location
        let siblings = if let Some(parent) = new_parent_id {
            self.get_children_ordered(parent).await?
        } else {
            self.get_root_nodes_ordered().await?
        };

        // Step 2: Calculate fractional order for new position
        let new_order = if let Some(after_id) = insert_after_sibling_id {
            // Inserting after a specific sibling
            let after_index = siblings
                .iter()
                .position(|s| s.id == after_id)
                .ok_or_else(|| anyhow!("Sibling not found: {}", after_id))?;

            let prev_order = siblings[after_index].order;
            let next_order = siblings.get(after_index + 1).map(|s| s.order);

            FractionalOrderCalculator::calculate_order(Some(prev_order), next_order)
        } else {
            // Inserting at beginning
            let first_order = siblings.first().map(|s| s.order);
            FractionalOrderCalculator::calculate_order(None, first_order)
        };

        // Step 3: Check if rebalancing needed (precision degradation)
        let all_orders: Vec<f64> = siblings.iter().map(|s| s.order).collect();
        if FractionalOrderCalculator::needs_rebalancing(&all_orders) {
            // Rebalance before inserting to avoid precision issues
            self.rebalance_children(new_parent_id).await?;
            // Recalculate order after rebalancing
            // ... recalculation logic ...
        }

        // Step 4: Execute atomic move in single transaction
        let query = if let Some(parent) = new_parent_id {
            r#"
                BEGIN TRANSACTION;

                -- Step 1: Delete old parent edge (if exists)
                DELETE has_child WHERE out = $node_id;

                -- Step 2: Create new parent edge with fractional order
                RELATE $parent->has_child->$node_id CONTENT {
                    order: $order,
                    created_at: time::now(),
                    modified_at: time::now()
                };

                -- Step 3: Update node's modified timestamp
                UPDATE node:$node_id SET modified_at = time::now();

                COMMIT TRANSACTION;
            "#
        } else {
            // Moving to root (no parent)
            r#"
                BEGIN TRANSACTION;

                -- Delete parent edge to make node root
                DELETE has_child WHERE out = $node_id;

                -- Update node's modified timestamp
                UPDATE node:$node_id SET modified_at = time::now();

                COMMIT TRANSACTION;
            "#
        };

        // Execute with all parameters bound
        self.db
            .query(query)
            .bind(("node_id", node_id))
            .bind(("parent", new_parent_id.unwrap_or("root")))
            .bind(("order", new_order))
            .await
            .map_err(|e| anyhow!("Failed to move node: {}", e))?;

        Ok(())
    }
}

Step 2: Implement Outdent Operation with Sibling Transfer

File: packages/core/src/operations/hierarchy_ops.rs (create new)

use crate::db::surreal_store::SurrealStore;

pub struct HierarchyOperations<'a> {
    store: &'a SurrealStore,
}

impl<'a> HierarchyOperations<'a> {
    /// Outdent a node and transfer its following siblings as its children
    ///
    /// Example:
    /// Before: A -> [B, C, D, E]
    /// Outdent C
    /// After: [A, C] where C -> [D, E] and A -> [B]
    pub async fn outdent_node(&self, node_id: &str) -> Result<()> {
        // Get current hierarchy info
        let parent_id = self.store.get_parent(node_id).await?
            .ok_or_else(|| anyhow!("Cannot outdent root node"))?;

        let grandparent_id = self.store.get_parent(&parent_id).await?;

        // Get siblings that come after this node (they become its children)
        let siblings = self.store.get_children_ordered(&parent_id).await?;
        let node_index = siblings.iter()
            .position(|s| s.id == node_id)
            .ok_or_else(|| anyhow!("Node not found in parent's children"))?;

        let siblings_to_transfer = &siblings[node_index + 1..];

        // Execute atomic outdent with sibling transfer
        let query = r#"
            BEGIN TRANSACTION;

            -- Step 1: Move node to grandparent level (after its current parent)
            DELETE has_child WHERE out = $node_id;

            LET $parent_node = (SELECT * FROM has_child
                               WHERE in = $grandparent_id AND out = $parent_id)[0];
            LET $new_order = $parent_node.order + 1.0;

            RELATE $grandparent_id->has_child->$node_id CONTENT {
                order: $new_order
            };

            -- Step 2: Transfer following siblings to be children of node
            FOR $sibling IN $siblings_to_transfer {
                DELETE has_child WHERE out = $sibling.id;
                RELATE $node_id->has_child->$sibling.id CONTENT {
                    order: $sibling.order
                };
            };

            COMMIT TRANSACTION;
        "#;

        self.store.db
            .query(query)
            .bind(("node_id", node_id))
            .bind(("parent_id", parent_id))
            .bind(("grandparent_id", grandparent_id.unwrap_or("root".to_string())))
            .bind(("siblings_to_transfer", siblings_to_transfer))
            .await?;

        Ok(())
    }
}

Step 3: Integration Tests for Atomic Operations

File: packages/desktop-app/src/tests/integration/atomic-move-operations.test.ts

import { describe, it, expect, beforeEach } from 'vitest';
import { testDb } from '../test-utils';

describe('Atomic Move Operations', () => {
  beforeEach(async () => {
    await testDb.reset();
  });

  describe('move_node atomicity', () => {
    it('should complete move in single transaction', async () => {
      // Create test hierarchy
      const parent = await testDb.createNode({ content: 'Parent' });
      const child1 = await testDb.createNode({ content: 'Child 1' });
      const child2 = await testDb.createNode({ content: 'Child 2' });

      await testDb.addChild(parent.id, child1.id, 1.0);
      await testDb.addChild(parent.id, child2.id, 2.0);

      // Move child1 after child2 atomically
      await testDb.moveNode(child1.id, parent.id, child2.id);

      // Verify order changed
      const children = await testDb.getChildrenOrdered(parent.id);
      expect(children[0].id).toBe(child2.id);
      expect(children[1].id).toBe(child1.id);
      expect(children[1].order).toBeGreaterThan(children[0].order);
    });

    it('should handle concurrent moves without corruption', async () => {
      const parent = await testDb.createNode({ content: 'Parent' });
      const nodes = await Promise.all(
        Array.from({ length: 10 }, (_, i) =>
          testDb.createNode({ content: `Node ${i}` })
        )
      );

      // Add all nodes as children
      for (let i = 0; i < nodes.length; i++) {
        await testDb.addChild(parent.id, nodes[i].id, i + 1.0);
      }

      // Simulate concurrent moves
      const moves = [
        testDb.moveNode(nodes[0].id, parent.id, nodes[5].id),
        testDb.moveNode(nodes[3].id, parent.id, nodes[1].id),
        testDb.moveNode(nodes[7].id, parent.id, null), // Move to beginning
      ];

      await Promise.all(moves);

      // Verify hierarchy is still consistent
      const children = await testDb.getChildrenOrdered(parent.id);

      // All nodes should still be children
      expect(children.length).toBe(nodes.length);

      // Orders should be unique and properly spaced
      const orders = children.map(c => c.order);
      const uniqueOrders = new Set(orders);
      expect(uniqueOrders.size).toBe(orders.length);

      // Verify no orphaned nodes
      for (const node of nodes) {
        const hasParent = await testDb.getParent(node.id);
        expect(hasParent).toBe(parent.id);
      }
    });

    it('should handle rapid operations without precision loss', async () => {
      const parent = await testDb.createNode({ content: 'Parent' });
      const nodeA = await testDb.createNode({ content: 'A' });
      const nodeB = await testDb.createNode({ content: 'B' });

      await testDb.addChild(parent.id, nodeA.id, 1.0);
      await testDb.addChild(parent.id, nodeB.id, 2.0);

      // Rapid insertions between same two nodes
      for (let i = 0; i < 30; i++) {
        const newNode = await testDb.createNode({ content: `Insert ${i}` });
        await testDb.moveNode(newNode.id, parent.id, nodeA.id);
      }

      // Should trigger rebalancing and maintain precision
      const children = await testDb.getChildrenOrdered(parent.id);

      // Check minimum gap between consecutive orders
      for (let i = 1; i < children.length; i++) {
        const gap = children[i].order - children[i - 1].order;
        expect(gap).toBeGreaterThan(0.0001); // Minimum precision threshold
      }
    });
  });

  describe('outdent with sibling transfer', () => {
    it('should transfer following siblings as children', async () => {
      // Setup: Parent -> [A, B, C, D]
      const parent = await testDb.createNode({ content: 'Parent' });
      const nodeA = await testDb.createNode({ content: 'A' });
      const nodeB = await testDb.createNode({ content: 'B' });
      const nodeC = await testDb.createNode({ content: 'C' });
      const nodeD = await testDb.createNode({ content: 'D' });

      await testDb.addChild(parent.id, nodeA.id, 1.0);
      await testDb.addChild(parent.id, nodeB.id, 2.0);
      await testDb.addChild(parent.id, nodeC.id, 3.0);
      await testDb.addChild(parent.id, nodeD.id, 4.0);

      // Outdent B (should transfer C and D to be its children)
      await testDb.outdentNode(nodeB.id);

      // Verify: Root -> [Parent, B] where Parent -> [A] and B -> [C, D]
      const parentChildren = await testDb.getChildrenOrdered(parent.id);
      expect(parentChildren.length).toBe(1);
      expect(parentChildren[0].id).toBe(nodeA.id);

      const bChildren = await testDb.getChildrenOrdered(nodeB.id);
      expect(bChildren.length).toBe(2);
      expect(bChildren[0].id).toBe(nodeC.id);
      expect(bChildren[1].id).toBe(nodeD.id);

      const bParent = await testDb.getParent(nodeB.id);
      expect(bParent).toBeNull(); // B is now at root level
    });
  });
});

Resources & References

Dependencies

Related Issues

Definition of Done

  • Atomic move_node operation implemented in Rust
  • All hierarchy operations use new atomic API
  • No cascading sibling updates required
  • Concurrent operations tested and working
  • Performance verified as O(1) operation
  • Integration tests passing
  • Old multi-step operations removed

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions