Skip to content

Implement Atomic Transactional Node Operations #532

Closed

Description

@malibio

Implement Atomic Transactional Node Operations

Problem

Node creation and hierarchy operations currently use multiple separate database calls, which can lead to:

  • Inconsistent state if operations fail mid-sequence
  • Race conditions with concurrent operations
  • Performance overhead from multiple round-trips
  • No rollback if later operations fail

Current Implementation (Non-Atomic)

Example: Creating a child node

// Call 1: Create node record
let node_id = create_node(params).await?;
// ❌ If this succeeds but next fails → orphan node created

// Call 2: Create type-specific record (if properties exist)
create_task_record(node_id, properties).await?;
// ❌ If this succeeds but next fails → node without type data

// Call 3: Create has_child edge
set_parent(&node_id, Some(&parent_id)).await?;
// ❌ If this fails → node exists but no parent relationship

Problems:

  • ❌ 3 database round-trips (~15-30ms latency)
  • ❌ Partial failures leave inconsistent state
  • ❌ No automatic rollback
  • ❌ Race conditions possible

Proposed Solution

Use SurrealDB transactions to make operations atomic:

pub async fn create_child_node(
    &self,
    parent_id: &str,
    node_type: &str,
    content: &str,
    properties: Value,
    before_sibling_id: Option<&str>,
) -> Result<Node> {
    let node_id = Uuid::new_v4().to_string();

    // Single atomic transaction - all or nothing
    let mut response = self.db.query(r#"
        BEGIN TRANSACTION;

        -- 1. Create node record
        CREATE type::thing('node', $node_id) SET
            type = $node_type,
            content = $content,
            before_sibling_id = $before_sibling_id,
            _schema_version = 1,
            created_at = time::now(),
            modified_at = time::now(),
            embedding_vector = null,
            embedding_stale = false,
            mentions = [],
            mentioned_by = [];

        -- 2. Create type-specific record (if properties exist)
        IF type::is::object($properties) AND count($properties.*) > 0 THEN
            CREATE type::thing($node_type, $node_id) CONTENT $properties;
            UPDATE type::thing('node', $node_id) SET data = type::thing($node_type, $node_id);
        END;

        -- 3. Create parent-child edge
        RELATE type::thing('node', $parent_id)->has_child->type::thing('node', $node_id);

        COMMIT TRANSACTION;

        -- Return the created node with type data hydrated
        SELECT * FROM type::thing('node', $node_id) FETCH data;
    "#)
        .bind(("node_id", &node_id))
        .bind(("node_type", node_type))
        .bind(("content", content))
        .bind(("before_sibling_id", before_sibling_id))
        .bind(("parent_id", parent_id))
        .bind(("properties", properties))
        .await?;

    let node: Option<SurrealNode> = response.take(0)?;
    node.map(Node::from)
        .ok_or_else(|| anyhow::anyhow!("Failed to create node"))
}

Benefits:

  • ✅ Atomic - all operations succeed or all fail
  • ✅ Single database round-trip (~10-15ms total)
  • ✅ Automatic rollback on error
  • ✅ No inconsistent states
  • ✅ Better performance (~50% faster)

Operations to Make Atomic

1. Create Child Node (High Priority)

Current: 3 separate calls
New: Single transaction
Impact: Most common operation, biggest performance gain

2. Move Node (Change Parent)

Current:

// Delete old edge
delete_parent_edge(node_id).await?;
// Create new edge
set_parent(node_id, new_parent_id).await?;

New (Atomic):

BEGIN TRANSACTION;
DELETE has_child WHERE out = type::thing('node', $node_id);
RELATE type::thing('node', $new_parent)->has_child->type::thing('node', $node_id);
COMMIT TRANSACTION;

3. Delete Node with Cascade

Current: Manual cascade logic
New (Atomic):

BEGIN TRANSACTION;
-- Delete node
DELETE type::thing('node', $node_id);
-- Delete type record
DELETE type::thing($node_type, $node_id);
-- Delete edges (CASCADE should handle this automatically)
DELETE has_child WHERE in = type::thing('node', $node_id) OR out = type::thing('node', $node_id);
DELETE mentions WHERE in = type::thing('node', $node_id) OR out = type::thing('node', $node_id);
COMMIT TRANSACTION;

4. Type Switching with Variants

Current: Multiple updates
New (Atomic):

BEGIN TRANSACTION;
-- Update node type
UPDATE type::thing('node', $node_id) SET type = $new_type;
-- Create new type record
CREATE type::thing($new_type, $node_id) CONTENT $new_properties;
-- Update data link
UPDATE type::thing('node', $node_id) SET data = type::thing($new_type, $node_id);
-- Update variants map
UPDATE type::thing('node', $node_id) SET variants.$old_type = $old_data_link;
COMMIT TRANSACTION;

Implementation Phases

Phase 1: Create Child Node (Quick Win)

Priority: CRITICAL (most common operation)
Effort: 2-3 hours
Files: packages/core/src/db/surreal_store.rs

impl SurrealStore {
    pub async fn create_child_node_atomic(
        &self,
        parent_id: &str,
        node: Node,
    ) -> Result<Node> {
        // Implementation above
    }
}

Phase 2: Move/Reparent Operations

Priority: HIGH (tree manipulation)
Effort: 1-2 hours

pub async fn move_node_atomic(
    &self,
    node_id: &str,
    new_parent_id: Option<&str>,
    new_before_sibling_id: Option<&str>,
) -> Result<()> {
    // Single transaction for move + reorder
}

Phase 3: Delete with Cascade

Priority: MEDIUM
Effort: 2-3 hours

pub async fn delete_node_cascade_atomic(&self, node_id: &str) -> Result<DeleteResult> {
    // Single transaction deletes node + type record + all edges
}

Phase 4: Type Switching

Priority: LOW (less common operation)
Effort: 2-3 hours

pub async fn switch_node_type_atomic(
    &self,
    node_id: &str,
    new_type: &str,
    new_properties: Value,
) -> Result<Node> {
    // Atomic type switch with variants preservation
}

Acceptance Criteria

Phase 1

  • create_child_node_atomic() implemented
  • Single transaction creates node + type record + edge
  • Failure at any step rolls back entire operation
  • Performance improvement measurable (target: <15ms for create)
  • Tests verify atomicity (can't create partial nodes)

Phase 2

  • move_node_atomic() implemented
  • Deletes old edge and creates new edge atomically
  • No orphan nodes during move operations
  • Tests verify edge transitions are atomic

Phase 3

  • delete_node_cascade_atomic() implemented
  • Deletes node, type records, and all edges in one transaction
  • No orphan edges or type records
  • Tests verify complete cleanup

Phase 4

  • switch_node_type_atomic() implemented
  • Type switch preserves old type in variants map
  • All updates happen atomically
  • Tests verify no partial type switches

Testing Requirements

Atomicity Tests

#[tokio::test]
async fn test_create_child_rolls_back_on_edge_failure() {
    let store = setup_test_store().await;

    // Mock edge creation to fail
    let result = store.create_child_node_atomic(
        "nonexistent-parent",  // Invalid parent → edge creation fails
        test_node
    ).await;

    assert!(result.is_err());

    // Verify node was NOT created (transaction rolled back)
    let node_exists = store.get_node(&test_node.id).await.unwrap();
    assert!(node_exists.is_none(), "Node should not exist after rollback");
}

#[tokio::test]
async fn test_create_child_all_or_nothing() {
    let store = setup_test_store().await;
    let parent = create_test_node(&store, "parent").await;

    // Create child with properties (3 operations)
    let child = store.create_child_node_atomic(
        &parent.id,
        Node::new("task".into(), "Test".into(), None, json!({
            "priority": "HIGH",
            "status": "OPEN"
        }))
    ).await.unwrap();

    // Verify all 3 operations succeeded
    // 1. Node exists
    let node = store.get_node(&child.id).await.unwrap().unwrap();
    assert_eq!(node.type, "task");

    // 2. Type record exists
    assert!(node.data.is_some());

    // 3. Edge exists
    let children = store.get_children(&parent.id).await.unwrap();
    assert_eq!(children.len(), 1);
    assert_eq!(children[0].id, child.id);
}

Performance Tests

#[tokio::test]
async fn benchmark_atomic_vs_non_atomic() {
    let store = setup_test_store().await;
    let parent = create_test_node(&store, "parent").await;

    // Benchmark non-atomic (3 separate calls)
    let start = Instant::now();
    let non_atomic = create_child_non_atomic(&store, &parent.id).await;
    let non_atomic_duration = start.elapsed();

    // Benchmark atomic (single transaction)
    let start = Instant::now();
    let atomic = store.create_child_node_atomic(&parent.id, test_node).await;
    let atomic_duration = start.elapsed();

    // Atomic should be ~40-60% faster
    assert!(atomic_duration < non_atomic_duration * 0.6,
        "Atomic ({:?}) should be faster than non-atomic ({:?})",
        atomic_duration, non_atomic_duration);
}

Performance Expectations

Before (Multiple Calls):

  • Create child node: ~30-45ms (3 round-trips × ~10-15ms each)
  • Move node: ~20-30ms (2 round-trips)
  • Delete cascade: ~40-60ms (4+ round-trips)

After (Atomic Transactions):

  • Create child node: ~10-15ms (1 round-trip)
  • Move node: ~10-15ms (1 round-trip)
  • Delete cascade: ~15-20ms (1 round-trip)

Overall improvement: ~50-70% faster, plus consistency guarantees!

SurrealDB Transaction Reference

-- Basic transaction
BEGIN TRANSACTION;
-- Multiple operations
COMMIT TRANSACTION;

-- Rollback on error
BEGIN TRANSACTION;
-- Operations...
CANCEL TRANSACTION;  -- Explicit rollback

-- Automatic rollback on error
BEGIN TRANSACTION;
CREATE node:invalid THROW "Error";  -- Auto-rolls back
COMMIT TRANSACTION;

Transaction guarantees:

  • ✅ ACID compliant
  • ✅ Automatic rollback on any error
  • ✅ Isolation from concurrent transactions
  • ✅ All operations succeed or all fail

Migration Strategy

Backward Compatible Rollout:

// Phase 1: Add new atomic methods (don't remove old ones)
impl SurrealStore {
    // New atomic version
    pub async fn create_child_node_atomic(...) -> Result<Node> { }

    // Keep old version temporarily
    pub async fn create_node(...) -> Result<Node> { }
}

// Phase 2: Update callers to use atomic methods
// Phase 3: Remove old non-atomic methods

No data migration needed - this is purely an implementation change.

Edge Cases

1. Cyclic Reference Prevention in Transaction

BEGIN TRANSACTION;

-- Check for cycle BEFORE creating edge
LET $would_cycle = (
    SELECT * FROM type::thing('node', $parent)
    WHERE id IN (
        SELECT ->has_child->node.{..} FROM type::thing('node', $child)
    )
);

IF count($would_cycle) > 0 THEN
    THROW "Cannot create parent-child relationship - would create cycle";
END;

RELATE type::thing('node', $parent)->has_child->type::thing('node', $child);

COMMIT TRANSACTION;

2. Concurrent Creation Conflicts

Handled automatically by transaction isolation - concurrent transactions won't interfere.

3. Failed Type Record Creation

Transaction ensures: If type record creation fails, entire node creation rolls back.

Implementation Details

File Structure

Main implementation: packages/core/src/db/surreal_store.rs

New methods:

  • create_child_node_atomic() - Create node + type record + edge
  • move_node_atomic() - Delete old edge + create new edge + reorder
  • delete_node_cascade_atomic() - Delete node + type record + all edges
  • switch_node_type_atomic() - Update type + create type record + update variants

Helper:

/// Execute multiple operations in a transaction
async fn execute_transaction(&self, operations: Vec<String>) -> Result<Response> {
    let mut query = String::from("BEGIN TRANSACTION;\n");

    for op in operations {
        query.push_str(&op);
        query.push('\n');
    }

    query.push_str("COMMIT TRANSACTION;");

    self.db.query(&query).await
}

Acceptance Criteria

Functional

  • All critical operations are atomic (create, move, delete)
  • Transaction rollback on any error
  • No partial/inconsistent states possible
  • Cyclic reference prevention still works

Performance

  • Create child node: <15ms (vs ~30-45ms before)
  • Move node: <15ms (vs ~20-30ms before)
  • Delete cascade: <20ms (vs ~40-60ms before)
  • Overall 50-70% faster than non-atomic approach

Testing

  • Atomicity tests (verify rollback on failure)
  • Performance benchmarks (atomic vs non-atomic)
  • Concurrency tests (multiple transactions don't interfere)
  • Edge case tests (cycles, missing parents, etc.)

Related Issues

Estimated Effort

  • Phase 1 (create child): 2-3 hours
  • Phase 2 (move node): 1-2 hours
  • Phase 3 (delete cascade): 2-3 hours
  • Phase 4 (type switching): 2-3 hours
  • Testing: 3-4 hours
  • Total: 10-15 hours (1-2 days)

Priority

HIGH - Improves consistency, performance, and developer experience. Should be implemented alongside #530 for maximum benefit.

Non-Goals

  • Transaction history/audit log (future enhancement)
  • Distributed transactions (single embedded database only)
  • Optimistic locking (already handled by version field)
  • Transaction retry logic (manual retry at application layer)

Activity

  1. self-assigned this
    on Nov 17, 2025
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