Skip to content

Fix Indent/Outdent Operations (12 test failures) #228

Closed

Description

@malibio

Bug: Indent/Outdent Operations Failures

Related to: Issue #208 (Comprehensive Test Coverage)
Test File: src/tests/integration/indent-oudent-operations.test.ts
Failures: 7 tests still failing

🚨 CRITICAL ARCHITECTURE REQUIREMENT

DO NOT Bypass PersistenceCoordinator

In both production code AND tests:

❌ WRONG - Direct database calls:

await tauriNodeService.updateNode(...);  // Bypasses coordinator
await sharedNodeStore.waitForNodeSaves([...]); // Manual coordination

✅ CORRECT - Use PersistenceCoordinator flow:

// Production code:
sharedNodeStore.updateNode(nodeId, changes, source);
  └─> PersistenceCoordinator.persist(...) // Automatic

// If you need to wait:
sharedNodeStore.deleteNode(nodeId, source, false, [depId1, depId2]);
  └─> PersistenceCoordinator.persist(..., { dependencies: [...] })

🔴 Red Flags to Avoid:

  • await tauriNodeService.* - Direct backend calls
  • await sharedNodeStore.waitForNodeSaves - Manual coordination (only use in tests for verification)
  • Calling database operations outside the service layer

The PersistenceCoordinator handles:

  • Dependency ordering (parent before child)
  • Race condition prevention
  • FOREIGN KEY constraint resolution
  • Debouncing vs immediate persistence

⚠️ Prerequisites

Must complete Issue #245 first (test infrastructure fix) - ✅ COMPLETE

The PersistenceCoordinator setup will help isolate which failures are real bugs vs infrastructure issues (race conditions, database locking).


Problem

The comprehensive tests in issue #208 have exposed bugs in indent/outdent operations:

  • Sibling chain updates not working correctly
  • Depth recalculation failures
  • Children not transferring properly during outdent
  • Hierarchy events not emitting correctly

Current Test Failures (7 remaining)

  1. should emit hierarchy changed events for indent/outdent
  2. should handle multiple consecutive indents
  3. should handle multiple consecutive outdents
  4. should indent node to become child of previous sibling
  5. should maintain sibling chain integrity when outdenting first child
  6. should outdent node to parent level
  7. should position outdented node after its old parent
  8. should transfer siblings below when outdenting

Implementation Guidelines

Step 1: Run Tests First

bun run test src/tests/integration/indent-outdent-operations.test.ts

Document specific failures to understand root causes.

Step 2: Review Production Code

Check reactive-node-service.svelte.ts:

  • indentNode() method
  • outdentNode() method

Ensure they use PersistenceCoordinator pattern (no direct await calls to database).

Step 3: Fix Implementation Bugs

Based on test failures, fix the actual logic issues while maintaining PersistenceCoordinator architecture.

Step 4: Update Tests (If Needed)

If tests are using old patterns:

  • Update to call service.indentNode() instead of direct database calls
  • Remove manual await waitForNodeSaves() - coordinator handles this
  • Verify using service layer, not bypassing it

Acceptance Criteria

  • All 7+ tests pass
  • No direct database calls bypassing PersistenceCoordinator
  • Sibling chain integrity maintained
  • Proper event emissions
  • Tests use service layer (reactiveNodeService), not direct sharedNodeStore manipulation
  • Quality checks pass: bun run quality:fix

Estimated Effort

  • Time: 2-3 hours
  • Complexity: Medium
  • Risk: Low (well-tested, clear patterns)

Testing

Run: bun run test src/tests/integration/indent-outdent-operations.test.ts

Activity

  1. self-assigned this
    on Oct 12, 2025
  2. malibio commented on Oct 12, 2025

    @malibio
    CollaboratorAuthor

    Progress Update - Issue #228

    ✅ Completed: PersistenceCoordinator Queue-Based Sequencing (Merged to Main)

    Commit: a9d233a on main branch

    We implemented queue-based dependency sequencing in PersistenceCoordinator to prevent race conditions. This infrastructure is now available codebase-wide.

    Key Changes:

    • Operations with pending dependencies now wait in a queue instead of executing in parallel
    • Added persistenceDependencies field to UpdateOptions for explicit dependency declaration
    • Operations automatically unblock when their dependencies complete
    • Prevents FOREIGN KEY violations from parallel database writes

    🔄 In Progress: Indent/Outdent Race Condition Fixes

    Branch: feature/issue-228-indent-outdent-fixes
    PR: #253
    Current Test Status: 8/14 passing (6 failing with HTTP 500 errors)

    What Works:

    • Queue-based sequencing infrastructure is in place
    • Basic indent/outdent operations work for simple cases
    • Dependencies are being declared in UpdateOptions

    What's Still Broken:

    • HTTP 500 errors (FOREIGN KEY violations) in complex scenarios
    • Circular dependencies being created in consecutive indent/outdent operations
    • Operations still executing out of order despite dependency declarations

    🔍 Root Cause Analysis

    The Problem:

    When multiple nodes are indented/outdented in quick succession, we're creating circular dependency chains:

    Operation A (indent node-2): depends on node-3 (from removeFromSiblingChain)
    Operation B (indent node-3): depends on node-2 (from removeFromSiblingChain)
    → Circular dependency → Both block forever OR execute in parallel → HTTP 500
    

    Example from test logs:

    [PersistenceCoordinator] Operation blocked: { nodeId: 'node-2', blockingDeps: [ 'node-3' ] }
    [PersistenceCoordinator] Operation blocked: { nodeId: 'node-3', blockingDeps: [ 'node-2' ] }
    

    Why This Happens:

    In indentNode() and outdentNode():

    1. We call removeFromSiblingChain(nodeId) which updates the next sibling
    2. We declare that updated sibling as a dependency for the main node update
    3. When multiple nodes are indented consecutively, they update each other as siblings
    4. This creates circular dependency chains

    Current Dependency Declaration (Lines 880-889 in reactive-node-service.svelte.ts):

    const persistenceDependencies: string[] = [];
    persistenceDependencies.push(prevSiblingId); // Only depend on parent
    
    // We removed updatedSiblingId to avoid circulars, but this causes parallel execution

    🎯 What Needs to Be Done

    Option A: Fix Dependency Declarations (Simpler, Recommended)

    The sibling chain cleanup from removeFromSiblingChain() and the main node update are actually independent operations - they can happen in parallel without violating constraints. The issue is we're over-constraining.

    Solution:

    1. Keep current approach: Do NOT add removedSiblingId as dependency
    2. Fix the actual logic bugs causing circular references in beforeSiblingId
    3. Ensure SharedNodeStore's automatic dependencies (containerNodeId, beforeSiblingId) are sufficient

    Files to investigate:

    • reactive-node-service.svelte.ts:889 - indentNode() dependency declaration
    • reactive-node-service.svelte.ts:990 - outdentNode() dependency declaration
    • Check if beforeSiblingId calculations are creating circular references

    Option B: Refactor to Batch Operations (More complex)

    Instead of multiple separate updateNode() calls, batch all updates in indent/outdent into a single atomic operation.

    Would require:

    • New batchUpdateNodes() method in SharedNodeStore
    • Single database transaction for all updates
    • More complex implementation but cleaner dependency model

    📋 Remaining Work Checklist

    • Investigate circular beforeSiblingId references - Why are consecutive indents creating node-2 ↔ node-3 circles?
    • Fix dependency declarations - Ensure we only depend on nodes that MUST complete first (parents), not positioning references
    • Test with queue sequencing - Verify that proper dependencies + queue blocking eliminates HTTP 500 errors
    • Handle edge cases - Multiple consecutive indents/outdents, sibling transfers, complex hierarchies
    • All 14 tests passing - No HTTP 500 errors, correct in-memory and database state
    • Merge to main - Once all tests pass reliably

    🔧 For Next AI Agent - Quick Start Guide

    Branch: feature/issue-228-indent-outdent-fixes
    Test Command: bun run test src/tests/integration/indent-outdent-operations.test.ts

    Key Files:

    • src/lib/services/reactive-node-service.svelte.ts - indentNode() and outdentNode() functions
    • src/lib/services/persistence-coordinator.svelte.ts - Queue-based sequencing (already on main)
    • src/tests/integration/indent-outdent-operations.test.ts - Test scenarios

    Investigation Steps:

    1. Run tests and look for "Operation blocked" messages with circular dependencies
    2. Add logging to see what beforeSiblingId values are being set during consecutive indents
    3. Check if the issue is in dependency declaration OR in the actual beforeSiblingId logic
    4. Focus on the "should handle multiple consecutive indents" test - it consistently shows node-2 ↔ node-3 circular deps

    Expected Outcome:

    • All 14 tests pass
    • No HTTP 500 errors in test output
    • No "Operation blocked" messages with circular dependencies
    • Database state matches expected hierarchy after indent/outdent

    Note: The PersistenceCoordinator infrastructure is solid and working. The remaining issue is specific to how indent/outdent operations declare their dependencies and update sibling chains.

  3. malibio commented on Oct 12, 2025

    @malibio
    CollaboratorAuthor

    📖 Detailed Handoff Documentation

    For the next AI agent picking up this work, I've created a comprehensive handoff guide:

    Document: docs/architecture/development/issue-228-handoff.md

    This includes:

    • Complete root cause analysis
    • Step-by-step investigation guide
    • Quick start commands
    • Expected outcomes
    • Key insights about circular dependencies

    To continue this work in a new session, provide this prompt:

    I need to complete Issue #228 - Fix Indent/Outdent Operations.
    
    Please read the handoff documentation at docs/architecture/development/issue-228-handoff.md 
    and continue from where the previous agent left off.
    
    Current status: 8/14 tests passing, circular dependency issue identified.
    Branch: feature/issue-228-indent-outdent-fixes
    
    Your goal: Get all 14 tests passing by fixing the circular dependencies in 
    indent/outdent operations without using manual await calls.
    
  4. malibio commented on Oct 12, 2025

    @malibio
    CollaboratorAuthor

    ✅ Update: Branch Rebased on Main

    The feature/issue-228-indent-outdent-fixes branch has been rebased on main and now includes the queue-based sequencing infrastructure from PersistenceCoordinator.

    This means:

    • ✅ Queue-based dependency blocking is available on the feature branch
    • ✅ All main branch updates are included
    • ✅ Ready for next agent to continue without rebasing

    The branch is fully up-to-date and ready for the final push to fix the circular dependency issue.

  5. malibio commented on Oct 12, 2025

    @malibio
    CollaboratorAuthor

    🔧 Complete Handoff Guide for Next AI Agent

    Quick Start

    cd /Users/malibio/nodespace/nodespace-core
    git checkout feature/issue-228-indent-outdent-fixes
    bun install
    bun run test src/tests/integration/indent-outdent-operations.test.ts

    Expected: 8/14 passing, 6 failing with HTTP 500 errors


    Root Cause: Circular Dependencies

    When consecutive indents happen, we create circular dependency chains:

    Test scenario: "should handle multiple consecutive indents"

    service.indentNode('node-2'); // node-2 becomes child of node-1
    service.indentNode('node-3'); // node-3 becomes child of node-2

    What happens:

    1. First indent: removeFromSiblingChain('node-2') updates node-3
    2. We add node-3 as dependency: persistenceDependencies: ['node-3', 'node-1']
    3. Second indent: Similar pattern
    4. Result: node-2 blocked by node-3, node-3 blocked by node-2 → Deadlock

    From test logs:

    [PersistenceCoordinator] Operation blocked: { nodeId: 'node-2', blockingDeps: [ 'node-3' ] }
    [PersistenceCoordinator] Operation blocked: { nodeId: 'node-3', blockingDeps: [ 'node-2' ] }
    

    Investigation Steps

    1. Add debug logging to see exact dependency chains:
    // In indentNode() before updateNode call:
    console.log('[DEBUG] Indent:', { nodeId, persistenceDependencies, beforeSiblingId });
    1. Run specific failing test:
    bun run test src/tests/integration/indent-outdent-operations.test.ts -t "should handle multiple consecutive indents"
    1. Check for circular patterns in the debug output

    2. Verify SharedNodeStore's automatic dependencies (lines 272-302 in shared-node-store.ts) - it automatically adds beforeSiblingId as dependency if not persisted. This might conflict with our explicit dependencies.


    Potential Solutions

    Option 1: Don't depend on removeFromSiblingChain updates (Current approach)

    • The sibling cleanup is independent from parent updates
    • Problem: Still getting HTTP 500s - WHY?
    • Next: Check if SharedNodeStore's automatic beforeSiblingId dependency is creating the circular refs

    Option 2: Sequential execution with waitForPersistence

    async function indentNode(nodeId: string): Promise<boolean> {
      // Wait for ALL pending ops before starting
      const allNodeIds = Array.from(sharedNodeStore.nodes.keys());
      await PersistenceCoordinator.getInstance().waitForPersistence(allNodeIds, 5000);
      
      // Now do indent logic...
    }
    • Pros: Eliminates all races
    • Cons: Loses parallelism, requires async functions

    Option 3: Batch atomic operations

    • Create single PersistenceCoordinator operation for all updates
    • No inter-operation dependencies needed
    • Requires new batch API

    Key Files & Line Numbers

    Main implementation:

    • src/lib/services/reactive-node-service.svelte.ts
      • Lines 844-932: indentNode()
      • Lines 949-1068: outdentNode()
      • Lines 824-842: removeFromSiblingChain()

    Current dependency declaration:

    • Line 889: persistenceDependencies.push(prevSiblingId) - Only parent
    • Line 981: mainNodeDeps.push(oldParentId) - Only old parent

    SharedNodeStore automatic dependencies:

    • src/lib/services/shared-node-store.ts Lines 272-302
    • Automatically adds: containerNodeId, beforeSiblingId if not persisted
    • This might be creating the circular deps!

    Success Criteria

    ✅ All 14 tests pass
    ✅ No HTTP 500 errors
    ✅ No circular dependency blocks
    ✅ bun run quality:fix passes
    ✅ Database state matches expected hierarchy


    Prompt for Next Session

    Continue work on Issue #228 - Fix Indent/Outdent Operations
    
    Branch: feature/issue-228-indent-outdent-fixes (already rebased on main)
    Status: 8/14 tests passing, circular dependency deadlocks identified
    
    The PersistenceCoordinator queue-based sequencing is working correctly. The issue is 
    that indent/outdent operations are declaring dependencies that create circular chains 
    (node-2 depends on node-3, node-3 depends on node-2).
    
    Investigate whether the circular dependencies come from:
    1. Our explicit persistenceDependencies declarations, OR  
    2. SharedNodeStore's automatic beforeSiblingId dependencies (lines 297-302)
    
    Goal: Get all 14 tests passing without manual await calls, using only the 
    PersistenceCoordinator dependency mechanism.
    
  6. 39 remaining items

  7. added 4 commits that reference this issue on Feb 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions