Skip to content

Optimize Markdown Import with Two-Phase Batch Creation #737

Closed

Description

@malibio

Overview

The create_nodes_from_markdown MCP handler is slow for large documents because it creates nodes sequentially, with each node requiring multiple database operations. This issue implements a two-phase batch optimization that pre-calculates all node data in memory, then inserts everything in a single database transaction.

Problem Statement

Current Performance Issue:

For a 50-node markdown document, the current implementation performs:

  • ~150+ database operations (3 per node: INSERT node, INSERT spoke, INSERT edge)
  • Sequential execution due to parent-child ID dependencies
  • Estimated 150-750ms for database I/O alone

Root Cause:

In packages/core/src/mcp/handlers/markdown.rs, the parse_markdown() function calls create_node() for each parsed line (line 735-744):

let node_id = create_node(
    node_service,
    node_type,
    &content,
    parent_id.clone(),
    context.root_id.clone(),
    insert_after,
    properties,
).await?; // BLOCKS on 3 DB operations per node

Each create_node() call chains to:

  1. NodeService::create_node_with_parent() - validation
  2. SurrealStore::create_node() - DB INSERT for node
  3. SurrealStore::move_node() - DB queries for fractional order + INSERT edge

Proposed Solution

Two-Phase Batch Creation:

Phase Description Database Operations
Phase 1 Parse markdown, pre-assign UUIDs, calculate fractional orders in-memory 0
Phase 2 Single transaction bulk INSERT (all nodes + all edges) 1

Expected Performance:

  • 50 nodes: 150-750ms → 20-50ms (10-15x speedup)
  • 1000 nodes: 3-15 seconds → 200-500ms (10-15x speedup)

Acceptance Criteria

  • Create performance benchmark test for 1000-node markdown import (baseline measurement)
  • Implement PreparedNode struct for in-memory node preparation
  • Implement prepare_nodes_from_markdown() pure function (no DB calls)
  • Implement bulk_create_hierarchy() in SurrealStore (single transaction)
  • Update handle_create_nodes_from_markdown() to use two-phase approach
  • Run performance benchmark again and document improvement in PR
  • All existing markdown handler tests pass
  • Code passes bun run quality:fix
  • Tests pass (bun run test:all and cargo test)

Technical Specifications

Reference Files

  • Markdown Handler: packages/core/src/mcp/handlers/markdown.rs

    • Current parse_markdown() function (lines 490-783)
    • Current create_node() function (lines 786-844)
    • ParserContext struct (lines 121-237)
  • Node Service: packages/core/src/services/node_service.rs

    • create_node_with_parent() (lines 1208-1280)
    • Existing bulk_create() for reference (lines 3669-3696)
  • SurrealDB Store: packages/core/src/db/surreal_store.rs

    • create_node() (lines 988-1100)
    • move_node() with fractional ordering (lines 3112-3288)
    • FractionalOrderCalculator usage pattern
  • Existing Tests: packages/core/src/mcp/handlers/markdown_test.rs

    • All tests must continue passing

Implementation Details

Step 1: Create Performance Benchmark Test

Create a new test file packages/core/src/mcp/handlers/markdown_perf_test.rs:

#[cfg(test)]
mod perf_tests {
    use std::time::Instant;
    
    /// Generate markdown with N nodes for benchmarking
    fn generate_large_markdown(node_count: usize) -> String {
        let mut md = String::from("# Root Document\n\n");
        for i in 0..node_count {
            let depth = i % 4; // Vary heading depth
            let prefix = "#".repeat(depth + 2);
            md.push_str(&format!("{} Section {}\n\nContent paragraph {}.\n\n", prefix, i, i));
        }
        md
    }
    
    #[tokio::test]
    async fn benchmark_1000_node_import() {
        let (node_service, _temp_dir) = setup_test_service().await;
        
        let markdown = generate_large_markdown(1000);
        let params = json!({
            "markdown_content": markdown,
            "title": "Benchmark Test"
        });
        
        let start = Instant::now();
        let result = handle_create_nodes_from_markdown(&node_service, params).await;
        let duration = start.elapsed();
        
        assert!(result.is_ok());
        println!("1000-node import took: {:?}", duration);
        
        // Document baseline - update this after optimization
        // BEFORE: Expected ~3-15 seconds
        // AFTER: Expected ~200-500ms
    }
}

Step 2: Create PreparedNode Struct

Add to packages/core/src/mcp/handlers/markdown.rs:

/// A node prepared for bulk insertion with pre-calculated hierarchy
#[derive(Debug, Clone)]
struct PreparedNode {
    /// Pre-assigned UUID (generated before DB access)
    id: String,
    /// Node type (text, header, task, etc.)
    node_type: String,
    /// Node content
    content: String,
    /// Parent node ID (references another PreparedNode.id or existing node)
    parent_id: Option<String>,
    /// Pre-calculated fractional order for sibling positioning
    order: f64,
    /// Node properties (status for tasks, etc.)
    properties: Value,
}

Step 3: Implement prepare_nodes_from_markdown()

Extract parsing logic into a pure function that returns Vec<PreparedNode>:

/// Parse markdown into prepared nodes without any database access
/// 
/// This is Phase 1 of the two-phase batch creation:
/// 1. Parse markdown line-by-line (existing logic)
/// 2. Pre-assign UUIDs to all nodes
/// 3. Calculate parent_id references using pre-assigned UUIDs
/// 4. Calculate fractional orders in-memory (no DB queries)
///
/// Returns Vec<PreparedNode> ready for bulk insertion
fn prepare_nodes_from_markdown(
    markdown: &str,
    root_id: Option<String>,
) -> Result<Vec<PreparedNode>, MCPError> {
    let mut prepared_nodes = Vec::new();
    
    // Track in-memory sibling order per parent
    // Key: parent_id (or empty string for root-level)
    // Value: last assigned order value
    let mut next_order_per_parent: HashMap<String, f64> = HashMap::new();
    
    // Reuse existing parsing logic from parse_markdown()
    // But instead of calling create_node(), build PreparedNode
    
    // ... parsing logic here ...
    
    // For each parsed element:
    // 1. Generate UUID: let node_id = uuid::Uuid::new_v4().to_string();
    // 2. Calculate order: next_order_per_parent.get(&parent_key).map(|v| v + 1.0).unwrap_or(1.0)
    // 3. Push PreparedNode to vector
    
    Ok(prepared_nodes)
}

Key Insight: The fractional order calculation currently queries the database for existing siblings. In the batch approach, we calculate orders sequentially in-memory since we control the insertion order.

Step 4: Implement bulk_create_hierarchy() in SurrealStore

Add to packages/core/src/db/surreal_store.rs:

/// Bulk create nodes with hierarchy in a single transaction
///
/// This method creates multiple nodes and their parent-child edges
/// atomically. All nodes and edges are inserted in a single transaction
/// for optimal performance.
///
/// # Arguments
/// * `nodes` - Vector of PreparedNode with pre-calculated IDs, parents, and orders
///
/// # Returns
/// * `Ok(Vec<String>)` - Vector of created node IDs in insertion order
/// * `Err` - If transaction fails (all changes rolled back)
pub async fn bulk_create_hierarchy(
    &self,
    nodes: Vec<PreparedNode>,
) -> Result<Vec<String>> {
    if nodes.is_empty() {
        return Ok(Vec::new());
    }
    
    // Build single transaction query
    let mut query = String::from("BEGIN TRANSACTION;\n");
    
    for node in &nodes {
        // 1. INSERT node hub record
        query.push_str(&format!(
            r#"CREATE node:{} CONTENT {{
                node_type: "{}",
                content: "{}",
                properties: {},
                version: 1,
                created_at: time::now(),
                modified_at: time::now()
            }};
            "#,
            node.id,
            node.node_type,
            escape_surql_string(&node.content),
            serde_json::to_string(&node.properties).unwrap_or_else(|_| "{}".to_string())
        ));
        
        // 2. INSERT spoke record if node type has spoke table
        // (task, date, etc. have separate spoke tables)
        if Self::has_spoke_table(&node.node_type) {
            query.push_str(&self.build_spoke_insert(&node));
        }
        
        // 3. INSERT has_child edge if node has parent
        if let Some(ref parent_id) = node.parent_id {
            query.push_str(&format!(
                r#"RELATE node:{}->has_child->node:{} CONTENT {{
                    order: {},
                    created_at: time::now()
                }};
                "#,
                parent_id,
                node.id,
                node.order
            ));
        }
    }
    
    query.push_str("COMMIT TRANSACTION;\n");
    
    // Execute single transaction
    self.db.query(&query).await
        .context("Failed to execute bulk hierarchy creation transaction")?;
    
    // Emit domain events for each created node
    for node in &nodes {
        self.emit_node_created_event(&node.id);
    }
    
    Ok(nodes.iter().map(|n| n.id.clone()).collect())
}

/// Check if a node type has a spoke table
fn has_spoke_table(node_type: &str) -> bool {
    matches!(node_type, "task" | "date")
}

/// Escape string for SurrealQL
fn escape_surql_string(s: &str) -> String {
    s.replace('\\', "\\\\")
     .replace('"', "\\\"")
     .replace('\n', "\\n")
     .replace('\r', "\\r")
}

Step 5: Update handle_create_nodes_from_markdown()

Modify packages/core/src/mcp/handlers/markdown.rs:

pub async fn handle_create_nodes_from_markdown<C>(
    node_service: &Arc<NodeService<C>>,
    params: Value,
) -> Result<Value, MCPError>
where
    C: surrealdb::Connection,
{
    // ... existing parameter parsing and validation ...
    
    // Phase 1: Parse and prepare all nodes in memory (no DB calls)
    let prepared_nodes = prepare_nodes_from_markdown(
        &remaining_content,
        Some(root_id.clone()),
    )?;
    
    // Phase 2: Bulk insert all nodes in single transaction
    let created_ids = node_service
        .store
        .bulk_create_hierarchy(prepared_nodes)
        .await
        .map_err(|e| MCPError::internal_error(format!("Bulk creation failed: {}", e)))?;
    
    // ... existing response formatting ...
}

Testing Requirements

  1. All existing tests must pass: Run cargo test -p nodespace-core mcp::handlers::markdown
  2. Performance benchmark: Create markdown_perf_test.rs with 1000-node test
  3. Document before/after: Include timing comparison in PR description

Validation Checklist

Before marking complete:

  • Run cargo test -p nodespace-core mcp::handlers::markdown - all pass
  • Run cargo clippy --all-targets - no warnings
  • Run cargo fmt --all -- --check - properly formatted
  • Run performance benchmark - document improvement

Dependencies

None - this is a self-contained optimization.

Related Issues

None - standalone performance improvement.

Non-Goals

  • Async/background processing (future enhancement if needed)
  • Parallel child creation (ordering complications)
  • Changes to MCP tool interface (backward compatible)

Activity

  1. malibio commented on Dec 5, 2025

    @malibio
    CollaboratorAuthor

    Test Baseline (pre-implementation):

    • Frontend: 1584 tests passed
    • Rust: 574 passed, 2 ignored

    Starting implementation of two-phase batch creation optimization.

  2. self-assigned this
    on Dec 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

backendenhancementperformance

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions