Skip to content

Implement PersistenceCoordinator for Dependency-Based Persistence #240

Closed

Description

@malibio
No description provided.

Activity

  1. malibio commented on Oct 12, 2025

    @malibio
    CollaboratorAuthor

    Dependencies Analysis

    Status: This issue is foundational and blocks other test failures.

    Current Blocker: Debug Logging

    Debug logging added in shared-node-store.ts:292-293 causes database writes in tests where DB isn't initialized, causing 24+ test failures.

    Quick fix needed: Remove debug logging before implementing full solution.

    Blocked Issues

    Dependency Graph

    #240 (PersistenceCoordinator)
      ↓ blocks
    #232 (Enter Key fixes)
      ↓ blocks  
    #230 (Sibling Chain fixes)
    

    Recommendation

    Implement PersistenceCoordinator first (4-5 days) rather than patching individual tests. This:

    • ✅ Fixes root cause of spurious persistence
    • ✅ Fixes race conditions properly
    • ✅ Required for MCP integration (Add MCP stdio server for AI agent access #112)
    • ✅ Makes tests reliable
    • ✅ Endorsed by frontend-architect agent review

    Implementation Order

    1. Remove debug logging (15 min)
    2. Create PersistenceCoordinator (1-2 days)
    3. Refactor SharedNodeStore (1 day)
    4. Refactor BaseNodeViewer (1 day)
    5. Fix remaining Fix Enter Key & Node Creation Operations (17 test failures) #232, Fix Sibling Chain Integrity (7 test failures) #230 failures (1 day)

    See docs/architecture/persistence-layer.md for complete architecture design.

  2. malibio commented on Oct 12, 2025

    @malibio
    CollaboratorAuthor

    Implementation Guidance for AI Agent

    Question 1: Quick Fix vs Full Implementation

    Answer: Do BOTH in sequence:

    Step 1 (15 minutes): Remove debug logging first

    • Remove lines 292-293 from shared-node-store.ts
    • Commit as: "Remove debug logging blocking tests (#240)"
    • This unblocks test development immediately

    Step 2 (4-5 days): Implement full PersistenceCoordinator

    • Follow the implementation plan in the issue

    Question 2: Which API Design to Implement?

    Answer: Implement the Combined Approach from persistence-layer.md

    This is the hybrid recommended by the frontend-architect agent:

    // API to implement:
    class PersistenceCoordinator {
      persist(
        nodeId: string,
        operation: () => Promise<void>,
        options: {
          mode: 'immediate' | 'debounce',
          debounceMs?: number,  // Default 500ms
          dependencies?: Array<
            | string                    // Node ID
            | (() => Promise<void>)    // Lambda function  
            | { nodeIds: string[] }    // Batch
          >
        }
      ): void;
    
      isPersisted(nodeId: string): boolean;  // Reactive
      isPending(nodeId: string): boolean;    // Reactive
      waitForPersistence(nodeIds: string[], timeoutMs?: number): Promise<Set<string>>;
    }

    Key design choices:

    • ✅ Use mode: 'immediate' | 'debounce' (simple, clear)
    • ✅ Use dependencies array (declarative, flexible)
    • ✅ Use SvelteMap for reactive state (Svelte 5 native)
    • ✅ Return void, not handles (Svelte's reactivity manages observability)

    Ignore: The flush strategies approach (elegant-persistence-solution.md) - it's more complex than needed.


    Question 3: Test Mode for Database Operations

    Answer: Yes! Add a test mode that mocks persistence.

    class PersistenceCoordinator {
      private testMode = false;
      private mockPersistence: Map<string, boolean> = new Map();
    
      /**
       * Enable test mode (skips actual database calls)
       */
      enableTestMode(): void {
        this.testMode = true;
      }
    
      private async executePersistence(
        nodeId: string,
        operation: () => Promise<void>
      ): Promise<void> {
        if (this.testMode) {
          // Mock persistence - just mark as complete
          await new Promise(resolve => setTimeout(resolve, 10)); // Simulate async
          this.mockPersistence.set(nodeId, true);
          return;
        }
    
        // Real persistence
        await queueDatabaseWrite(nodeId, operation);
      }
    
      // For tests: check if mock persistence happened
      getMockPersistedNodes(): string[] {
        return Array.from(this.mockPersistence.keys());
      }
    
      // For tests: reset state
      resetTestState(): void {
        this.mockPersistence.clear();
        this.persistenceStatus.clear();
      }
    }

    Usage in tests:

    beforeEach(() => {
      persistenceCoordinator.enableTestMode();
      persistenceCoordinator.resetTestState();
    });
    
    test('coordinates dependencies correctly', async () => {
      persistenceCoordinator.persist('parent', async () => {}, {
        mode: 'immediate'
      });
    
      persistenceCoordinator.persist('child', async () => {}, {
        mode: 'immediate',
        dependencies: ['parent']
      });
    
      await sleep(50);
    
      // Verify order without hitting database
      const persisted = persistenceCoordinator.getMockPersistedNodes();
      expect(persisted).toEqual(['parent', 'child']);
    });

    Implementation Order (Recommended)

    Phase 1: Quick Fix (15 min)

    # Remove debug logging
    git checkout -b fix/remove-debug-logging
    # Edit shared-node-store.ts, remove lines 292-293
    git commit -m "Remove debug logging blocking tests (#240)"
    git push

    Phase 2: Core PersistenceCoordinator (1-2 days)

    git checkout -b feature/issue-240-persistence-coordinator
    
    # Create coordinator with:
    # - persist() method
    # - dependency resolution
    # - debouncing
    # - test mode support
    # - comprehensive tests

    Phase 3: Refactor SharedNodeStore (1 day)

    # Same branch
    # - Remove saveNodeImmediately()
    # - Remove updateNodeContentDebounced()
    # - Delegate to coordinator

    Phase 4: Refactor BaseNodeViewer (1 day)

    # Same branch  
    # - Replace manual tracking with coordinator
    # - Update watchers

    Phase 5: Tests & PR (1 day)

    # Same branch
    # - Update all tests
    # - Verify all pass
    # - Create PR

    Key Files Reference

    Read these for context:

    • docs/architecture/persistence-layer.md ← Primary API spec
    • packages/desktop-app/src/lib/services/shared-node-store.ts ← Current implementation
    • packages/desktop-app/src/lib/design/components/base-node-viewer.svelte ← Watcher usage

    Create:

    • packages/desktop-app/src/lib/services/persistence-coordinator.svelte.ts
    • packages/desktop-app/src/tests/services/persistence-coordinator.test.ts

    Final Note

    The goal is to eliminate the saveNodeImmediately backdoor by providing declarative dependency management. All persistence should go through ONE path with different mode and dependencies options.

    Good luck! 🚀

  3. self-assigned this
    on Oct 12, 2025
  4. malibio commented on Oct 12, 2025

    @malibio
    CollaboratorAuthor

    Progress Update

    ✅ Completed (40-50% of Issue)

    Quick Fix - PR #242 (Merged)

    • Removed debug logging from shared-node-store.ts (lines 292-293)
    • Removed debug logging from base-node-viewer.svelte (line 190)
    • Unblocked 24+ test failures

    Core Implementation - PR #243 (Draft)

    • Implemented persistence-coordinator.svelte.ts (590 lines)
      • Singleton pattern with reactive Svelte 5 $state
      • Declarative dependency management (node IDs, lambdas, batches, handles)
      • Debouncing strategies (immediate vs debounced)
      • Test mode support
      • Performance metrics tracking
    • Comprehensive test suite (850+ lines, 36 tests)
      • All tests passing
      • Coverage: dependency resolution, error handling, concurrent operations, reactive state
    • Quality checks passed (0 linting errors)

    🔄 Remaining Work (50-60% of Issue)

    1. Refactor SharedNodeStore (~1 day)

    • Remove saveNodeImmediately() backdoor method
    • Remove updateNodeContentDebounced() method
    • Remove pendingContentSaves map
    • Replace direct tauriNodeService calls with persistenceCoordinator.persist()
    • Update multi-source update handling

    2. Refactor BaseNodeViewer (~1 day)

    • Replace manual promise tracking with coordinator
    • Update $effect watchers to use declarative dependencies
    • Remove pendingContentSavePromises map
    • Remove waitForNodeSavesIfPending() function

    3. Update Existing Tests (~1 day)

    4. Final Validation

    • Run full test suite
    • Verify FOREIGN KEY race conditions resolved
    • Update architecture documentation if needed

    📁 Files Changed

    • packages/desktop-app/src/lib/services/persistence-coordinator.svelte.ts (NEW)
    • packages/desktop-app/src/tests/services/persistence-coordinator.test.ts (NEW)

    🔗 Branch

    feature/issue-240-persistence-coordinator

    📊 Estimated Time Remaining

    2-3 days of implementation work + testing/validation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

architectureenhancementfoundation

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions