Repository navigation
Description
Context
Currently, NodeSpace uses a beforeSiblingId linked-list pattern stored on node fields to maintain sibling order. This causes significant problems:
- Cascading Updates: Inserting a node between siblings requires updating multiple nodes (O(n) complexity)
- Hybrid Architecture Mess: Structure is split between node fields (
beforeSiblingId) and graph edges (has_child) - Complex Frontend Logic: See
reactive-node-service.svelte.tslines 126-259 for the convoluted sorting algorithm - Race Conditions: Multiple separate updates can leave hierarchy temporarily inconsistent
IMPORTANT: NodeSpace has ZERO users and NO production deployment. We will directly implement the new schema without any data migration.
Problem Example
Current approach when inserting node C between A and B:
// Before: A -> B -> D
// After: A -> C -> B -> D
// Requires 2 updates:
UPDATE node:A SET beforeSiblingId = 'C'; // Update A to point to C
UPDATE node:C SET beforeSiblingId = 'B'; // Update C to point to B
// Risk: If second update fails, hierarchy is broken!Proposed Solution: Fractional Ordering
Instead of linked-list, use fractional numbers on edges:
// Before: A(order:1.0) -> B(order:2.0) -> D(order:3.0)
// After: A(order:1.0) -> C(order:1.5) -> B(order:2.0) -> D(order:3.0)
// Only 1 operation needed:
RELATE parent->has_child->C CONTENT { order: 1.5 };
// No sibling updates required!Step-by-Step Implementation Guide
Step 1: Update Database Schema (Direct Implementation - No Migration)
File: packages/core/src/db/schema.sql (update existing)
-- ============================================================================
-- REMOVE beforeSiblingId from node table
-- ============================================================================
-- Current schema (DELETE THIS):
-- DEFINE FIELD beforeSiblingId ON TABLE node TYPE string;
-- New schema (REPLACE WITH):
DEFINE TABLE node SCHEMAFULL;
DEFINE FIELD id ON TABLE node TYPE string ASSERT $value != NONE;
DEFINE FIELD content ON TABLE node TYPE string DEFAULT "";
DEFINE FIELD nodeType ON TABLE node TYPE string DEFAULT "text";
DEFINE FIELD properties ON TABLE node TYPE object DEFAULT {};
DEFINE FIELD version ON TABLE node TYPE int DEFAULT 1;
DEFINE FIELD createdAt ON TABLE node TYPE datetime DEFAULT time::now();
DEFINE FIELD modifiedAt ON TABLE node TYPE datetime DEFAULT time::now();
-- NO beforeSiblingId field!
-- ============================================================================
-- ADD order field to has_child edges
-- ============================================================================
DEFINE TABLE has_child SCHEMAFULL TYPE RELATION IN node OUT node;
DEFINE FIELD order ON TABLE has_child TYPE float ASSERT $value != NONE;
DEFINE FIELD createdAt ON TABLE has_child TYPE datetime DEFAULT time::now();
-- Index for efficient ordering queries
DEFINE INDEX idx_child_order ON TABLE has_child COLUMNS in, order;
DEFINE INDEX idx_unique_child ON TABLE has_child COLUMNS in, out UNIQUE;Step 2: Update Seeding Script (No Migration - Direct Implementation)
File: packages/core/src/db/seed.ts
// BEFORE (DELETE THIS):
async function createNodeWithSiblingChain(parent: string, beforeSibling?: string) {
return await db.create('node', {
content: 'Node',
beforeSiblingId: beforeSibling // DELETE THIS
});
}
// AFTER (REPLACE WITH):
async function createNodeWithOrder(parentId: string, order: number) {
const node = await db.create('node', {
content: 'Node',
nodeType: 'text',
properties: {}
// NO beforeSiblingId!
});
// Create edge with fractional order
await db.query(`
RELATE $parent->has_child->$child CONTENT {
order: $order,
createdAt: time::now()
}
`, {
parent: parentId,
child: node.id,
order: order
});
return node;
}
// Example seed data:
const child1 = await createNodeWithOrder('node:root', 1.0);
const child2 = await createNodeWithOrder('node:root', 2.0);
const child3 = await createNodeWithOrder('node:root', 3.0);Step 3: Implement Fractional Order Calculator in Rust
File: packages/core/src/db/fractional_ordering.rs (create new)
use anyhow::Result;
/// Calculates the fractional order for inserting a node between two siblings
pub struct FractionalOrderCalculator;
impl FractionalOrderCalculator {
/// Calculate order value for inserting between prev and next
///
/// # Examples
/// ```
/// // Insert at beginning (before all)
/// calculate_order(None, Some(1.0)) => 0.5
///
/// // Insert at end (after all)
/// calculate_order(Some(3.0), None) => 4.0
///
/// // Insert between two nodes
/// calculate_order(Some(1.0), Some(2.0)) => 1.5
/// ```
pub fn calculate_order(
prev_order: Option<f64>,
next_order: Option<f64>,
) -> f64 {
match (prev_order, next_order) {
(None, None) => 1.0, // First child
(None, Some(next)) => next - 1.0, // Before first
(Some(prev), None) => prev + 1.0, // After last
(Some(prev), Some(next)) => (prev + next) / 2.0, // Between siblings
}
}
/// Check if rebalancing is needed (gap too small)
pub fn needs_rebalancing(orders: &[f64]) -> bool {
if orders.len() < 2 {
return false;
}
for i in 1..orders.len() {
let gap = orders[i] - orders[i - 1];
if gap < 0.0001 { // Precision threshold
return true;
}
}
false
}
/// Rebalance orders to have even spacing
///
/// # Example
/// Input: [1.0, 1.0001, 1.0002, 1.0003]
/// Output: [1.0, 2.0, 3.0, 4.0]
pub fn rebalance(count: usize) -> Vec<f64> {
(1..=count).map(|i| i as f64).collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_calculate_order_first_child() {
assert_eq!(FractionalOrderCalculator::calculate_order(None, None), 1.0);
}
#[test]
fn test_calculate_order_before_first() {
assert_eq!(FractionalOrderCalculator::calculate_order(None, Some(2.0)), 1.0);
}
#[test]
fn test_calculate_order_after_last() {
assert_eq!(FractionalOrderCalculator::calculate_order(Some(3.0), None), 4.0);
}
#[test]
fn test_calculate_order_between() {
assert_eq!(FractionalOrderCalculator::calculate_order(Some(1.0), Some(3.0)), 2.0);
}
#[test]
fn test_needs_rebalancing() {
assert!(!FractionalOrderCalculator::needs_rebalancing(&[1.0, 2.0, 3.0]));
assert!(FractionalOrderCalculator::needs_rebalancing(&[1.0, 1.00001, 1.00002]));
}
}Step 4: Update SurrealStore to Use Fractional Ordering
File: packages/core/src/db/surreal_store.rs
Update all methods that create or modify hierarchy to use fractional ordering instead of beforeSiblingId.
Step 5: Update Frontend Types
File: packages/desktop-app/src/lib/types/node.ts
// BEFORE (DELETE):
export interface Node {
id: string;
content: string;
nodeType: string;
beforeSiblingId?: string; // DELETE THIS LINE
properties: Record<string, unknown>;
version: number;
createdAt: string;
modifiedAt: string;
}
// AFTER (REPLACE WITH):
export interface Node {
id: string;
content: string;
nodeType: string;
properties: Record<string, unknown>;
version: number;
createdAt: string;
modifiedAt: string;
// NO beforeSiblingId - structure is in edges only!
}Step 6: Delete Complex Sorting Logic
File: packages/desktop-app/src/lib/services/reactive-node-service.svelte.ts
// DELETE THIS ENTIRE FUNCTION (lines 126-259):
function sortChildrenByBeforeSiblingId(nodes: Node[]): Node[] {
// ... 130+ lines of complex linked-list sorting ...
}
// No replacement needed - database returns children already sorted by order!Testing Checklist
Unit Tests
- Test
FractionalOrderCalculator::calculate_orderwith all cases - Test
needs_rebalancingdetects small gaps - Test
rebalancecreates even spacing
Integration Tests
- Test inserting node between siblings (no cascading updates)
- Test inserting at beginning of children list
- Test inserting at end of children list
- Test moving node to different parent
- Test rapid insertions trigger rebalancing
- Test concurrent moves from different clients
Performance Tests
- Verify O(1) insertion (no sibling updates)
- Measure operation time: should be <10ms
- Test with 1000+ nodes in single parent
Acceptance Criteria
-
order: floatfield added tohas_childedge schema -
beforeSiblingIdfield removed from node table schema - Fractional order calculation implemented in Rust with tests
- Rebalancing logic triggers when gap < 0.0001
- All existing hierarchy tests pass with new schema
- Performance: Insert node in O(1) time without sibling updates
- No more
sortChildrenByBeforeSiblingIdfunction in frontend - Seeding script works with fractional ordering
Common Pitfalls to Avoid
- Don't forget to remove
beforeSiblingIdfrom TypeScript types - UpdateNodeinterface - Remember rebalancing - Without it, precision will degrade after ~30 insertions
- Test concurrent operations - Two users moving same node should work
- Update all create/update operations - Every place that creates edges needs order field
Files to Modify/Create
- CREATE:
packages/core/src/db/fractional_ordering.rs - MODIFY:
packages/core/src/db/surreal_store.rs- Update move operations - MODIFY:
packages/core/src/db/schema.sql- Add order field, remove beforeSiblingId - MODIFY:
packages/core/src/db/seed.ts- Use fractional ordering - MODIFY:
packages/desktop-app/src/lib/types/node.ts- Remove beforeSiblingId - DELETE: Lines 126-259 in
reactive-node-service.svelte.ts(sortChildrenByBeforeSiblingId)
Dependencies
- Define core tables as SCHEMAFULL with strict validation #560 (SCHEMAFULL table definitions should be done together)
Success Metrics
After implementation:
- Inserting a node between siblings takes <10ms (vs current 50ms+)
- No cascading updates in database logs
- Frontend receives children already sorted (no client-side sorting needed)
- Zero references to
beforeSiblingIdin codebase
Activity
Add LIVE SELECT architecture documentation and align data schema specs
Address review: Fix order binding and dynamic spoke properties
Define core tables as SCHEMAFULL with strict validation (#563)
WIP: Implement FractionalOrderCalculator foundation for Issue #550
WIP: Phase 1 Complete - Remove all before_sibling_id references
WIP: Phase 2 Complete - Implement fractional ordering for has_child e…
Remove all before_sibling_id references - complete cleanup
WIP: Remove all before_sibling_id references - Phase 3 complete
Fix: Update tests and systems for fractional ordering - Phase 3 complete
Phase 4: Implement position-based insertion with reorder_node API
4 remaining items
WIP: Fix fractional ordering implementation - Phase 6 completion
Phase 6: Fix fractional ordering implementation - schema and ordering…
WIP: Fix fractional ordering implementation - Phase 6 completion
Phase 6: Fix fractional ordering implementation - schema and ordering…
Resolve merge conflicts from rebase onto main
Migrate database schema to use fractional ordering instead of beforeS…
Add LIVE SELECT architecture documentation and align data schema specs
Define core tables as SCHEMAFULL with strict validation (#563)
Migrate database schema to use fractional ordering instead of beforeS…
Add LIVE SELECT architecture documentation and align data schema specs
Define core tables as SCHEMAFULL with strict validation (#563)
Migrate database schema to use fractional ordering instead of beforeS…
Define core tables as SCHEMAFULL with strict validation (#563)
Migrate database schema to use fractional ordering instead of beforeS…