Skip to content

Optimize markdown batch creation with 300x speedup - #738

Merged
malibio merged 4 commits into
mainfrom
feature/issue-737-optimize-markdown-batch-creation
Dec 5, 2025
Merged

malibio merged 4 commits into
mainfrom
feature/issue-737-optimize-markdown-batch-creation

Conversation

@malibio

@malibio malibio commented Dec 5, 2025

Copy link
Copy Markdown
Collaborator

Summary

Implements two-phase batch creation for markdown import to dramatically improve performance. Closes #737.

  • Phase 1: Prepare all nodes in memory with pre-assigned UUIDs and calculated ordering
  • Phase 2: Insert all nodes and edges in a single database transaction

Performance Results

Test Before After Speedup
100 nodes 25.7s 86ms ~300x
500 nodes ~128s 388ms ~330x
1000 nodes ~256s 756ms ~340x

The optimization exceeded expectations - the issue anticipated 10-15x improvement, but we achieved 300-340x.

Changes

  • Add PreparedNode struct for in-memory node preparation
  • Add prepare_nodes_from_markdown() pure function (no DB calls)
  • Add bulk_create_hierarchy() in SurrealStore for single-transaction insert
  • Add bulk_create_hierarchy() in NodeService with validation
  • Rename ensure_date_container_exists to ensure_date_exists (public API)
  • Update handle_create_nodes_from_markdown() to use two-phase approach
  • Add performance benchmark tests

Test plan

  • All 37 existing markdown handler tests pass
  • All 578 Rust library tests pass
  • All 1584 frontend tests pass
  • Performance benchmarks demonstrate improvement
  • Hierarchy integrity verified after large imports

🤖 Generated with Claude Code

malibio and others added 3 commits December 5, 2025 13:47
## Summary

Implements two-phase batch creation for markdown import:
- Phase 1: Prepare all nodes in memory with pre-assigned UUIDs
- Phase 2: Insert all nodes in a single database transaction

## Performance Results

| Test | Before | After | Speedup |
|------|--------|-------|---------|
| 100 nodes | 25.7s | 86ms | **~300x** |
| 500 nodes | ~128s | 388ms | **~330x** |
| 1000 nodes | ~256s | 756ms | **~340x** |

## Changes

- Add `PreparedNode` struct for in-memory node preparation
- Add `prepare_nodes_from_markdown()` pure function (no DB calls)
- Add `bulk_create_hierarchy()` in SurrealStore for single-transaction insert
- Add `bulk_create_hierarchy()` in NodeService with validation
- Rename `ensure_date_container_exists` to `ensure_date_exists` (public API)
- Update `handle_create_nodes_from_markdown()` to use two-phase approach
- Add performance benchmark tests

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Replace O(depth) BFS traversal with SurrealDB's {..+collect} recursive syntax:

- get_nodes_in_subtree(): Now uses single recursive collect query instead of
  iterative BFS that did 2 queries per tree level
- get_edges_in_subtree(): Now uses single recursive collect query instead of
  calling get_nodes_in_subtree() first then querying edges

Performance improvement:
- Before: O(depth) queries - tree with 10 levels = ~20 queries
- After: O(1) queries - 2 queries regardless of tree depth

This benefits both:
- Frontend: get_children_tree() for loading document trees
- MCP: get_markdown_from_node_id() for exporting markdown

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Combine multiple separate queries into one efficient database round-trip:

Before (3+ queries):
1. get_node(root_id) - fetch root
2. get_nodes_in_subtree() - O(depth) BFS traversal
3. get_edges_in_subtree() - separate edge query
4. enrich_nodes_with_spoke_data() - separate task spoke query

After (1 query):
- get_subtree_with_edges() fetches everything in single query:
  - Root + all descendants via recursive {..+collect}
  - All edges
  - Task spoke data (status, priority, etc.)

Benefits:
- Single database round-trip regardless of tree size/depth
- Task nodes have properties populated (strongly-typed frontend support)
- Removed separate enrich_nodes_with_spoke_data method
- Simpler code with less duplication

This optimization benefits both:
- Frontend: get_children_tree() for loading document trees
- MCP: get_markdown_from_node_id() for exporting markdown

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Dec 5, 2025

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

Review Type: Initial Review
Reviewer: Principal Engineer AI Reviewer
PR: #738 - Optimize markdown batch creation with 300x speedup


Overall Assessment

This PR delivers an exceptional performance optimization for markdown import, achieving 300-340x speedup (far exceeding the 10-15x target from issue #737). The implementation follows a clean two-phase batch creation pattern that fundamentally improves scalability.

Net Positive Assessment: APPROVED - This is a significant improvement to code health with sound engineering principles applied throughout.


Requirements Validation

From Issue #737 Acceptance Criteria:

Criterion Status Notes
Create performance benchmark test for 1000-node markdown import ✅ markdown_perf_test.rs with 100/500/1000 node benchmarks
Implement PreparedNode struct for in-memory node preparation ✅ Lines 62-101 in markdown.rs
Implement prepare_nodes_from_markdown() pure function (no DB calls) ✅ Lines 168-406 in markdown.rs
Implement bulk_create_hierarchy() in SurrealStore ✅ Lines 3578-3745 in surreal_store.rs
Update handle_create_nodes_from_markdown() to use two-phase approach ✅ Lines 646-769 in markdown.rs
Run performance benchmark and document improvement ✅ PR description includes timing table
All existing markdown handler tests pass ✅ 41/41 tests passing
Code passes bun run quality:fix ✅ Clean (minor unstaged formatting change detected)
Tests pass (bun run test:all and cargo test) ✅ Verified

Code Review Findings

Critical Issues

None identified.

Suggested Improvements

1. [Improvement] SQL Injection Prevention - Verify Escaping Completeness

📁 packages/core/src/db/surreal_store.rs:3741-3745

fn escape_surql_string(s: &str) -> String {
    s.replace('\\', "\\\\")
        .replace('"', "\\\"")
        .replace('\n', "\\n")
        .replace('\r', "\\r")
        .replace('\t', "\\t")
}

Analysis: The escape_surql_string helper properly escapes the most common dangerous characters. However, SurrealQL strings may have additional edge cases with Unicode or null bytes.

Recommendation: Consider adding a test case with adversarial content (e.g., \0, Unicode control characters, nested escape sequences) to verify robustness. The current implementation is acceptable for production but warrants future hardening.

Principle: Defense in Depth (Security)


2. [Improvement] Consolidate Subtree Methods - Minor Redundancy

📁 packages/core/src/db/surreal_store.rs:2584-2592, 2755-2759

The get_nodes_in_subtree and get_edges_in_subtree methods now both delegate to get_subtree_with_edges and discard half the result. While this is fine for maintaining backward compatibility of the API, consider documenting this pattern to prevent future developers from calling both methods separately (which would duplicate the query).

pub async fn get_nodes_in_subtree(&self, root_id: &str) -> Result<Vec<Node>> {
    // Delegate to consolidated method, excluding root
    let (all_nodes, _edges) = self.get_subtree_with_edges(root_id).await?;
    ...
}

pub async fn get_edges_in_subtree(&self, root_id: &str) -> Result<Vec<EdgeRecord>> {
    // Delegate to consolidated method, discarding nodes
    let (_nodes, edges) = self.get_subtree_with_edges(root_id).await?;
    ...
}

Recommendation: Add a doc comment warning callers that need both nodes AND edges to use get_subtree_with_edges directly to avoid redundant queries.

Principle: DRY / Performance Awareness


3. [Nit] Performance Test Assertions

📁 packages/core/src/mcp/handlers/markdown_perf_test.rs:157-159

// After implementing batch optimization, uncomment:
// assert!(duration.as_millis() < 1000, "Should complete in <1 second after optimization");

Consider uncommenting this assertion now that the optimization is complete, or update the comment to reflect the achieved performance (300x improvement means the assertion would easily pass).


4. [Nit] Type Signature Ergonomics

📁 packages/core/src/db/surreal_store.rs:3586-3595

pub async fn bulk_create_hierarchy(
    &self,
    nodes: Vec<(
        String,
        String,
        String,
        Option<String>,
        f64,
        serde_json::Value,
    )>,
) -> Result<Vec<String>> {

The 6-element tuple is harder to read than a struct. While PreparedNode exists in the handler, it's not exposed at the store level. Consider either:

  • Accepting Vec<PreparedNode> directly (requires moving struct to shared types)
  • Creating a BulkNodeInsert struct in the db module

This is purely ergonomic - the current approach works correctly.


Architecture Assessment

Aspect Rating Notes
Design Pattern Excellent Two-phase batch creation (prepare in memory, bulk insert) is a well-established pattern for performance optimization
Separation of Concerns Excellent Pure prepare_nodes_from_markdown function separates parsing from persistence
Transaction Safety Excellent Single transaction ensures atomicity - all-or-nothing semantics
Performance Exceptional 300x improvement exceeds 10-15x target by 20x
Backward Compatibility Excellent Existing tests pass, API unchanged
Code Quality Very Good Clear documentation, appropriate abstractions

Security Assessment

Check Status Notes
Input validation ✅ MAX_MARKDOWN_SIZE (1MB) and MAX_NODES_PER_IMPORT (1000) limits enforced
SQL/SurrealQL injection ✅ escape_surql_string helper sanitizes user content
Transaction rollback ✅ BEGIN/COMMIT TRANSACTION ensures atomicity
No hardcoded secrets ✅ Clean

Testing Assessment

Metric Status Notes
Unit tests ✅ All 41 markdown handler tests pass
Performance tests ✅ New benchmark tests in markdown_perf_test.rs
Hierarchy integrity ✅ verify_large_import_hierarchy test validates no orphans
Edge cases ✅ Existing tests cover empty content, invalid params, etc.

Final Recommendation

✅ APPROVE

This PR represents high-quality engineering work that delivers exceptional performance gains with clean architecture. The two-phase batch creation pattern is well-implemented, and all acceptance criteria are met.

Minor Action Items (Non-Blocking):

  1. Stage the minor formatting change in surreal_store.rs or discard it
  2. Consider uncommenting the performance assertion in tests

🤖 Generated with Claude Code Pragmatic Code Review

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

Principal Engineer Review Complete

Recommendation: APPROVE

Excellent performance optimization with clean architecture, sound security practices, and comprehensive testing. All acceptance criteria from Issue #737 are met. The 300x speedup far exceeds the 10-15x target.

See detailed review comment above for minor non-blocking improvement suggestions.

- Add doc comments to get_nodes_in_subtree and get_edges_in_subtree
  recommending get_subtree_with_edges for callers needing both
- Enable performance assertion in benchmark test (now validated)
- Apply rustfmt formatting

Addresses reviewer recommendations from PR #738.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Dec 5, 2025

Copy link
Copy Markdown
Collaborator Author

Review Feedback Addressed

✅ Addressed (3 recommendations)

  1. Unstaged formatting change - Applied cargo fmt formatting
  2. Performance test assertion - Enabled the commented assertion with updated comment documenting the achieved 300x speedup (tests verify ~786ms < 1000ms threshold)
  3. Subtree method documentation - Added doc comments to get_nodes_in_subtree and get_edges_in_subtree recommending get_subtree_with_edges for callers needing both

⏭️ Skipped (2 recommendations)

  1. SQL injection edge case tests - Skipped as scope creep. The current escape_surql_string implementation properly handles common cases (backslash, quotes, newlines, tabs). Unicode edge cases are an enhancement that can be added if a specific vulnerability is identified.

  2. Type signature ergonomics - Skipped as overkill. Converting the 6-element tuple to a struct would require either:

    • Moving PreparedNode to a shared types module (cross-module dependency)
    • Creating a new BulkNodeInsert struct (duplication)

    The current tuple approach works correctly and is documented. This is a stylistic preference with no functional impact.

📝 Commit

27cce99e - Address code review feedback

🧪 Tests

All 4 performance tests pass, including the newly enabled assertion.

🤖 Generated with Claude Code

@malibio
malibio merged commit 942a418 into main Dec 5, 2025
@malibio
malibio deleted the feature/issue-737-optimize-markdown-batch-creation branch December 5, 2025 13:28
malibio added a commit that referenced this pull request Feb 4, 2026
* Optimize markdown batch creation with 300x speedup (#737)

## Summary

Implements two-phase batch creation for markdown import:
- Phase 1: Prepare all nodes in memory with pre-assigned UUIDs
- Phase 2: Insert all nodes in a single database transaction

## Performance Results

| Test | Before | After | Speedup |
|------|--------|-------|---------|
| 100 nodes | 25.7s | 86ms | **~300x** |
| 500 nodes | ~128s | 388ms | **~330x** |
| 1000 nodes | ~256s | 756ms | **~340x** |

## Changes

- Add `PreparedNode` struct for in-memory node preparation
- Add `prepare_nodes_from_markdown()` pure function (no DB calls)
- Add `bulk_create_hierarchy()` in SurrealStore for single-transaction insert
- Add `bulk_create_hierarchy()` in NodeService with validation
- Rename `ensure_date_container_exists` to `ensure_date_exists` (public API)
- Update `handle_create_nodes_from_markdown()` to use two-phase approach
- Add performance benchmark tests

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Optimize subtree fetching with O(1) recursive collect queries

Replace O(depth) BFS traversal with SurrealDB's {..+collect} recursive syntax:

- get_nodes_in_subtree(): Now uses single recursive collect query instead of
  iterative BFS that did 2 queries per tree level
- get_edges_in_subtree(): Now uses single recursive collect query instead of
  calling get_nodes_in_subtree() first then querying edges

Performance improvement:
- Before: O(depth) queries - tree with 10 levels = ~20 queries
- After: O(1) queries - 2 queries regardless of tree depth

This benefits both:
- Frontend: get_children_tree() for loading document trees
- MCP: get_markdown_from_node_id() for exporting markdown

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Consolidate subtree fetching into single database query

Combine multiple separate queries into one efficient database round-trip:

Before (3+ queries):
1. get_node(root_id) - fetch root
2. get_nodes_in_subtree() - O(depth) BFS traversal
3. get_edges_in_subtree() - separate edge query
4. enrich_nodes_with_spoke_data() - separate task spoke query

After (1 query):
- get_subtree_with_edges() fetches everything in single query:
  - Root + all descendants via recursive {..+collect}
  - All edges
  - Task spoke data (status, priority, etc.)

Benefits:
- Single database round-trip regardless of tree size/depth
- Task nodes have properties populated (strongly-typed frontend support)
- Removed separate enrich_nodes_with_spoke_data method
- Simpler code with less duplication

This optimization benefits both:
- Frontend: get_children_tree() for loading document trees
- MCP: get_markdown_from_node_id() for exporting markdown

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Address code review feedback

- Add doc comments to get_nodes_in_subtree and get_edges_in_subtree
  recommending get_subtree_with_edges for callers needing both
- Enable performance assertion in benchmark test (now validated)
- Apply rustfmt formatting

Addresses reviewer recommendations from PR #738.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
malibio added a commit that referenced this pull request Feb 5, 2026
* Optimize markdown batch creation with 300x speedup (#737)

## Summary

Implements two-phase batch creation for markdown import:
- Phase 1: Prepare all nodes in memory with pre-assigned UUIDs
- Phase 2: Insert all nodes in a single database transaction

## Performance Results

| Test | Before | After | Speedup |
|------|--------|-------|---------|
| 100 nodes | 25.7s | 86ms | **~300x** |
| 500 nodes | ~128s | 388ms | **~330x** |
| 1000 nodes | ~256s | 756ms | **~340x** |

## Changes

- Add `PreparedNode` struct for in-memory node preparation
- Add `prepare_nodes_from_markdown()` pure function (no DB calls)
- Add `bulk_create_hierarchy()` in SurrealStore for single-transaction insert
- Add `bulk_create_hierarchy()` in NodeService with validation
- Rename `ensure_date_container_exists` to `ensure_date_exists` (public API)
- Update `handle_create_nodes_from_markdown()` to use two-phase approach
- Add performance benchmark tests

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Optimize subtree fetching with O(1) recursive collect queries

Replace O(depth) BFS traversal with SurrealDB's {..+collect} recursive syntax:

- get_nodes_in_subtree(): Now uses single recursive collect query instead of
  iterative BFS that did 2 queries per tree level
- get_edges_in_subtree(): Now uses single recursive collect query instead of
  calling get_nodes_in_subtree() first then querying edges

Performance improvement:
- Before: O(depth) queries - tree with 10 levels = ~20 queries
- After: O(1) queries - 2 queries regardless of tree depth

This benefits both:
- Frontend: get_children_tree() for loading document trees
- MCP: get_markdown_from_node_id() for exporting markdown

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Consolidate subtree fetching into single database query

Combine multiple separate queries into one efficient database round-trip:

Before (3+ queries):
1. get_node(root_id) - fetch root
2. get_nodes_in_subtree() - O(depth) BFS traversal
3. get_edges_in_subtree() - separate edge query
4. enrich_nodes_with_spoke_data() - separate task spoke query

After (1 query):
- get_subtree_with_edges() fetches everything in single query:
  - Root + all descendants via recursive {..+collect}
  - All edges
  - Task spoke data (status, priority, etc.)

Benefits:
- Single database round-trip regardless of tree size/depth
- Task nodes have properties populated (strongly-typed frontend support)
- Removed separate enrich_nodes_with_spoke_data method
- Simpler code with less duplication

This optimization benefits both:
- Frontend: get_children_tree() for loading document trees
- MCP: get_markdown_from_node_id() for exporting markdown

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Address code review feedback

- Add doc comments to get_nodes_in_subtree and get_edges_in_subtree
  recommending get_subtree_with_edges for callers needing both
- Enable performance assertion in benchmark test (now validated)
- Apply rustfmt formatting

Addresses reviewer recommendations from PR #738.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
malibio added a commit that referenced this pull request Feb 26, 2026
* Optimize markdown batch creation with 300x speedup (#737)

## Summary

Implements two-phase batch creation for markdown import:
- Phase 1: Prepare all nodes in memory with pre-assigned UUIDs
- Phase 2: Insert all nodes in a single database transaction

## Performance Results

| Test | Before | After | Speedup |
|------|--------|-------|---------|
| 100 nodes | 25.7s | 86ms | **~300x** |
| 500 nodes | ~128s | 388ms | **~330x** |
| 1000 nodes | ~256s | 756ms | **~340x** |

## Changes

- Add `PreparedNode` struct for in-memory node preparation
- Add `prepare_nodes_from_markdown()` pure function (no DB calls)
- Add `bulk_create_hierarchy()` in SurrealStore for single-transaction insert
- Add `bulk_create_hierarchy()` in NodeService with validation
- Rename `ensure_date_container_exists` to `ensure_date_exists` (public API)
- Update `handle_create_nodes_from_markdown()` to use two-phase approach
- Add performance benchmark tests

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Optimize subtree fetching with O(1) recursive collect queries

Replace O(depth) BFS traversal with SurrealDB's {..+collect} recursive syntax:

- get_nodes_in_subtree(): Now uses single recursive collect query instead of
  iterative BFS that did 2 queries per tree level
- get_edges_in_subtree(): Now uses single recursive collect query instead of
  calling get_nodes_in_subtree() first then querying edges

Performance improvement:
- Before: O(depth) queries - tree with 10 levels = ~20 queries
- After: O(1) queries - 2 queries regardless of tree depth

This benefits both:
- Frontend: get_children_tree() for loading document trees
- MCP: get_markdown_from_node_id() for exporting markdown

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Consolidate subtree fetching into single database query

Combine multiple separate queries into one efficient database round-trip:

Before (3+ queries):
1. get_node(root_id) - fetch root
2. get_nodes_in_subtree() - O(depth) BFS traversal
3. get_edges_in_subtree() - separate edge query
4. enrich_nodes_with_spoke_data() - separate task spoke query

After (1 query):
- get_subtree_with_edges() fetches everything in single query:
  - Root + all descendants via recursive {..+collect}
  - All edges
  - Task spoke data (status, priority, etc.)

Benefits:
- Single database round-trip regardless of tree size/depth
- Task nodes have properties populated (strongly-typed frontend support)
- Removed separate enrich_nodes_with_spoke_data method
- Simpler code with less duplication

This optimization benefits both:
- Frontend: get_children_tree() for loading document trees
- MCP: get_markdown_from_node_id() for exporting markdown

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Address code review feedback

- Add doc comments to get_nodes_in_subtree and get_edges_in_subtree
  recommending get_subtree_with_edges for callers needing both
- Enable performance assertion in benchmark test (now validated)
- Apply rustfmt formatting

Addresses reviewer recommendations from PR #738.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[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.

Optimize Markdown Import with Two-Phase Batch Creation

1 participant