Skip to content

Refactor tree loading to use efficient adjacency list strategy #630

Closed

Description

@malibio

Refactor Tree Loading to Use Efficient Adjacency List Strategy

Problem

Current implementation uses recursive database queries (N queries for N levels):

get_node_tree() {
  1. Query for root node
  2. Query for root's children  
  3. For each child, query its children (recursive)
  4. Build nested structure
}

This results in N database queries where N = tree depth.

Proposed Solution

Use adjacency list strategy with 2 queries total regardless of depth:

get_node_tree_optimized(root_id) {
  1. Query: SELECT * FROM node WHERE <subtree filter>  // All nodes in one query
  2. Query: SELECT in, out FROM has_child WHERE <subtree filter>  // All edges in one query
  3. Build HashMap<parent_id, Vec<child_id>> in Rust (adjacency list)
  4. Walk HashMap to construct nested JSON (pure memory, no DB)
  5. Return complete nested structure
}

Benefits

  • Performance: O(1) queries instead of O(depth) queries
  • Network: Single round-trip for nodes + edges
  • Scalability: Deep trees don't multiply query count
  • Simplicity: Clear separation of data fetch vs tree construction

Implementation Plan

  1. Add get_nodes_in_subtree(root_id) - returns flat list of all descendant nodes
  2. Add get_edges_in_subtree(root_id) - returns flat list of all descendant edges
  3. Implement adjacency list builder in Rust
  4. Build nested tree from adjacency list (client-side recursion, no DB)
  5. Replace recursive build_node_tree_recursive() with new approach

Related Confusion

Multiple getChildren methods exist causing confusion:

  • get_children() - database query
  • getChildren() - structure tree method
  • getNodesForParent() - node data with structure
  • loadChildrenTree() - nested tree load

Recommendation: Consolidate to 3 clear methods:

  • getWholeTree() - Complete nested tree with all data
  • getStructureTree() - Just parent-child relationships (no node data)
  • getDirectChildren(parentId) - Just immediate children (one level)

Testing

  • Benchmark current vs new approach with deep trees (depth 5-10)
  • Verify no regressions in browser/desktop modes
  • Ensure LIVE SELECT still works correctly

Priority

Medium - Current implementation works but is suboptimal for deep hierarchies

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