Skip to content

Implement PersistenceCoordinator for Dependency-Based Persistence - #243

Merged
malibio merged 4 commits into
mainfrom
feature/issue-240-persistence-coordinator
Oct 12, 2025
Merged

malibio merged 4 commits into
mainfrom
feature/issue-240-persistence-coordinator

Conversation

@malibio

@malibio malibio commented Oct 12, 2025 •

Copy link
Copy Markdown
Collaborator

Summary

Refactors SharedNodeStore to delegate all persistence operations to PersistenceCoordinator, completing a major milestone for issue #240.

Changes

Core Refactoring

  • Removed deprecated methods: saveNodeImmediately(), updateNodeContentDebounced(), ensureAncestorChainPersisted()
  • Removed internal state: pendingContentSaves map, contentDebounceTimers, queueDatabaseWrite()
  • Delegated persistence: All database operations now go through PersistenceCoordinator.getInstance().persist()
  • Automatic debouncing: Content changes (typing) use 500ms debounce automatically
  • Dependency management: Structural changes wait for parent dependencies via declarative dependencies array

Integration

  • Updated BaseNodeViewer: Fixed 3 call sites to use new API (setNode(), updateNode())
  • Test mode support: PersistenceCoordinator skips database operations in test mode
  • Refactored tests: 52 SharedNodeStore tests passing, removed tests for deprecated methods

Architecture Benefits

  • Separation of concerns: SharedNodeStore = state, PersistenceCoordinator = persistence
  • Declarative dependencies: FOREIGN KEY constraints enforced automatically
  • Better testability: Clear test mode API for unit tests
  • Reduced code: 563 lines removed (221 additions, 784 deletions)

Testing

✅ Passing Tests

  • SharedNodeStore tests: 52 passing
  • PersistenceCoordinator tests: 36 passing
  • Total passing: 919 tests across 47 test files

⚠️ Known Test Failures (Documented in #245)

  • 16 test files failing with database initialization errors
  • Root cause: Tests using SharedNodeStore need to enable PersistenceCoordinator test mode
  • Impact: Test infrastructure only, no production code affected
  • Fix: Simple pattern to add in test setup (see issue Fix test failures after PersistenceCoordinator integration #245)
  • Estimated effort: 1-2 hours

Related Issues

Breaking Changes

API Changes

  • ❌ Removed SharedNodeStore.saveNodeImmediately() → Use setNode() instead
  • ❌ Removed SharedNodeStore.updateNodeContentDebounced() → Use updateNode() (automatic debouncing)
  • ❌ Removed SharedNodeStore.ensureAncestorChainPersisted() → Dependencies handled automatically
  • ✅ Kept hasPendingSave() and waitForNodeSaves() (delegate to coordinator)

Test Infrastructure

  • All tests using SharedNodeStore must enable PersistenceCoordinator.enableTestMode()
  • See src/tests/services/shared-node-store.test.ts (lines 43-65) for pattern

Migration Guide

For Application Code

// Before
await sharedNodeStore.saveNodeImmediately(id, content, type, parent, container, sibling, false, source);

// After
const node: Node = { id, nodeType: type, content, parentId: parent, ... };
sharedNodeStore.setNode(node, source);

For Tests

import { PersistenceCoordinator } from '$lib/services/persistence-coordinator.svelte';

beforeEach(() => {
  // Enable test mode to skip database operations
  PersistenceCoordinator.resetInstance();
  const coordinator = PersistenceCoordinator.getInstance();
  coordinator.enableTestMode();
  coordinator.resetTestState();
});

afterEach(() => {
  const coordinator = PersistenceCoordinator.getInstance();
  coordinator.reset();
  PersistenceCoordinator.resetInstance();
});

Next Steps

  1. Merge this PR (core functionality complete)
  2. Address issue Fix test failures after PersistenceCoordinator integration #245 (fix 16 failing test files)
  3. Continue with BaseNodeViewer refactoring (separate session as planned)

Files Changed

  • src/lib/services/shared-node-store.ts - Core refactoring
  • src/lib/services/persistence-coordinator.svelte.ts - Test mode support
  • src/tests/services/shared-node-store.test.ts - Refactored tests
  • src/lib/design/components/base-node-viewer.svelte - Updated to new API

Quality Checks


🤖 Generated with Claude Code

Co-Authored-By: Claude [email protected]

This implements the core PersistenceCoordinator service that provides
declarative dependency-based persistence for node operations.

Key Features:
- Declarative dependency management (node IDs, lambdas, batches, handles)
- Configurable debouncing (immediate vs. debounced persistence)
- Reactive state tracking using Svelte 5 $state
- Test mode support for testing without database
- Topological dependency resolution
- Performance metrics and monitoring
- Comprehensive error handling and rollback

Architecture:
- Singleton pattern ensures single coordinator instance
- Supports multiple dependency types for flexibility
- Automatic retry and cleanup on errors
- 36 comprehensive tests covering all functionality

This is Step 2 of Issue #240. Next steps:
- Refactor SharedNodeStore to delegate to coordinator
- Refactor BaseNodeViewer to use declarative dependencies
- Update existing tests for new architecture

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

Co-Authored-By: Claude <[email protected]>
…nator (#240)

BREAKING CHANGES:
- Removed saveNodeImmediately() - use setNode() instead
- Removed updateNodeContentDebounced() - use updateNode() (automatic debouncing)
- Removed ensureAncestorChainPersisted() - dependencies handled automatically
- Removed pendingContentSaves map - managed by PersistenceCoordinator

CHANGES:
- All persistence delegates to PersistenceCoordinator.getInstance().persist()
- Content changes use debounced mode (500ms) automatically
- Structural changes use immediate mode with parent dependencies
- hasPendingSave() and waitForNodeSaves() delegate to coordinator
- hasPendingWrites() checks coordinator metrics
- Added test mode support to PersistenceCoordinator (skips DB operations)
- Refactored SharedNodeStore tests to test new persistence delegation
- Updated BaseNodeViewer to use new API (setNode/updateNode)

ARCHITECTURE:
- SharedNodeStore focuses on in-memory state management
- PersistenceCoordinator handles all async persistence coordination
- FOREIGN KEY dependencies declared declaratively
- Proper separation between state and persistence layers

TESTING:
- 52 SharedNodeStore tests passing
- 36 PersistenceCoordinator tests passing
- All quality checks passing (lint, format, type-check)

Co-Authored-By: Claude <[email protected]>
🤖 Generated with [Claude Code](https://claude.com/claude-code)
malibio and others added 2 commits October 12, 2025 12:12
CRITICAL FIXES:
- Fix reactivity: Use .clear() instead of reassignment for Svelte 5 reactive state
  * Preserves reactive proxy in persistenceStatus and persistedNodes Maps/Sets
  * Prevents broken reactivity in production UI components

- Add ancestor chain dependencies in SharedNodeStore
  * Ensure ENTIRE parent chain is persisted, not just immediate parent
  * Prevents FOREIGN KEY constraint violations with nested placeholder nodes
  * Use lambda dependencies to call ensureAncestorChainPersisted()

- Fix test mode to execute user operations while catching DB errors
  * Operations execute normally (allows test callbacks to run)
  * DatabaseInitializationError silently ignored (no DB setup required)
  * Other errors properly propagated (error-handling tests work)
  * Maintains backward compatibility with existing tests

IMPORTANT IMPROVEMENTS:
- Remove unused maxConcurrentOperations variable (YAGNI principle)
- Remove unimplemented priority option from PersistenceOptions interface
- Add memory cleanup strategy for completed operations
  * Schedule cleanup 5 minutes after completion
  * Prevents unbounded memory growth in long-running sessions
  * Keep persistedNodes Set (needed for existence checks)

- Add comprehensive error recovery documentation to persist() JSDoc
  * Explain dependency failure propagation
  * Document retry patterns
  * Include error handling examples

- Fix inconsistent error logging to use structured format
  * All console.error calls now use object parameter
  * Better for log parsing and monitoring tools

TESTING:
- All 88 tests passing (36 PersistenceCoordinator + 52 SharedNodeStore)
- Quality checks passing (0 warnings, 0 errors)
- Test mode properly handles both test operations and real service calls

NOTES:
- Test mode implementation is temporary - proper solution is to mock
  tauriNodeService in all tests and remove test mode entirely
- Memory cleanup uses simple time-based eviction (5min) - could be
  enhanced with LRU cache if needed
- Ancestor chain dependency adds small overhead but prevents critical
  FOREIGN KEY violations

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

Co-Authored-By: Claude <[email protected]>
Resolved conflicts by:
- Keeping PersistenceCoordinator delegation from our branch
- Incorporating shouldPersist logic from main (PR #244)
- Combining both isEmptyTextNode checks and viewer source filtering
- Maintaining ancestor chain dependency resolution

Changes from main (PR #244):
- Added shouldPersist check for viewer source filtering
- Added isNewNode tracking for setNode
- Better comments explaining viewer persistence behavior

Our changes preserved:
- PersistenceCoordinator delegation for all persistence
- Ancestor chain dependency resolution via lambda
- Structured error handling and test error tracking
@malibio
malibio merged commit c81998c into main Oct 12, 2025
@malibio
malibio deleted the feature/issue-240-persistence-coordinator branch October 12, 2025 10:16
malibio added a commit that referenced this pull request Oct 12, 2025
This commit fixes a critical race condition in the combineNodes() function
where node deletion could occur before sibling chain repairs completed,
causing database locking errors and FOREIGN KEY constraint violations.

Changes:
- Made combineNodes() async to properly await sibling chain repairs
- Identify affected nodes BEFORE calling removeFromSiblingChain()
- Wait for all sibling chain updates to persist before deleting node
- Updated all call sites to properly await combineNodes()
- Updated event handlers in base-node-viewer.svelte to be async

Technical Details:
The issue was that removeFromSiblingChain() queues an async database
operation via PersistenceCoordinator, but the original code immediately
proceeded to delete the node without waiting. The fix:

1. Identifies nodes that will be affected (next sibling, children)
2. Calls removeFromSiblingChain() to queue the updates
3. Waits for those specific nodes to persist
4. Then safely deletes the node

This ensures proper ordering: sibling chain repair → wait → deletion

Files Modified:
- reactive-node-service.svelte.ts: Made combineNodes() async
- base-node-viewer.svelte: Made event handlers async
- sibling-chain-integrity.test.ts: Updated test calls to await

Related:
- Issue #230: Fix Sibling Chain Integrity
- PR #243: PersistenceCoordinator implementation
- Rebased onto main to leverage new PersistenceCoordinator architecture

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

Co-Authored-By: Claude <[email protected]>
malibio added a commit that referenced this pull request Oct 12, 2025
* Fix sibling chain integrity with unified child promotion logic (#230)

## Changes

### Core Refactoring
- **Extract shared `promoteChildren()` helper** with depth-aware parent selection
- **Simplify `deleteNode()`** to be internal helper (no child handling)
- **Unified logic in `combineNodes()`** handles all deletion scenarios

### Key Improvements
1. **Depth-Aware Child Promotion**: Children promoted to nearest ancestor at same depth
2. **Consistent Behavior**: Both empty and non-empty node deletion use same path
3. **Sibling Chain Integrity**: `removeFromSiblingChain()` repairs chain before deletion
4. **Single Source of Truth**: All child promotion logic in `promoteChildren()`

### Files Changed
- `reactive-node-service.svelte.ts`: Refactored deletion and child promotion
- `base-node-viewer.svelte`: Updated to always use `combineNodes()`

## Testing
- All cases verified: empty nodes, nodes with content, nodes with children
- Sibling chain repair logic consolidated
- UI now consistently uses `combineNodes()` for all deletion scenarios

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

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

* Fix sibling chain integrity in combineNodes operation

This commit fixes a critical race condition in the combineNodes() function
where node deletion could occur before sibling chain repairs completed,
causing database locking errors and FOREIGN KEY constraint violations.

Changes:
- Made combineNodes() async to properly await sibling chain repairs
- Identify affected nodes BEFORE calling removeFromSiblingChain()
- Wait for all sibling chain updates to persist before deleting node
- Updated all call sites to properly await combineNodes()
- Updated event handlers in base-node-viewer.svelte to be async

Technical Details:
The issue was that removeFromSiblingChain() queues an async database
operation via PersistenceCoordinator, but the original code immediately
proceeded to delete the node without waiting. The fix:

1. Identifies nodes that will be affected (next sibling, children)
2. Calls removeFromSiblingChain() to queue the updates
3. Waits for those specific nodes to persist
4. Then safely deletes the node

This ensures proper ordering: sibling chain repair → wait → deletion

Files Modified:
- reactive-node-service.svelte.ts: Made combineNodes() async
- base-node-viewer.svelte: Made event handlers async
- sibling-chain-integrity.test.ts: Updated test calls to await

Related:
- Issue #230: Fix Sibling Chain Integrity
- PR #243: PersistenceCoordinator implementation
- Rebased onto main to leverage new PersistenceCoordinator architecture

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

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

* Address code review feedback: improve defensive programming and documentation

This commit implements the suggested improvements from the code review:

1. **Timeout Fallback Validation in combineNodes()**: Added defensive check
   to validate that all expected nodes were persisted before deletion. If
   timeout occurs, logs detailed error but continues operation to avoid
   leaving UI in inconsistent state.

2. **Enhanced deleteNode() Documentation**: Clarified API contract with
   explicit warnings about child handling. Documents when direct deleteNode()
   usage is appropriate vs combineNodes(). Addresses reviewer concern about
   "internal helper" terminology for public API.

3. **Documented Batch Update Decision**: Added comment explaining why
   individual child updates are preferred over batch API. PersistenceCoordinator
   already handles batching at lower level, typical nodes have <10 children,
   and added complexity wouldn't justify minimal performance gain.

Technical Details:
- combineNodes() now captures return value from waitForNodeSaves()
- Validates persistedNodes.size matches expected nodesToWaitFor.length
- Logs failed node IDs for debugging if timeout occurs
- deleteNode() JSDoc now includes use cases and explicit API guidance

Related: Issue #230, PR #234 code review feedback

🤖 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 4, 2026
* Implement PersistenceCoordinator with dependency tracking (#240)

This implements the core PersistenceCoordinator service that provides
declarative dependency-based persistence for node operations.

Key Features:
- Declarative dependency management (node IDs, lambdas, batches, handles)
- Configurable debouncing (immediate vs. debounced persistence)
- Reactive state tracking using Svelte 5 $state
- Test mode support for testing without database
- Topological dependency resolution
- Performance metrics and monitoring
- Comprehensive error handling and rollback

Architecture:
- Singleton pattern ensures single coordinator instance
- Supports multiple dependency types for flexibility
- Automatic retry and cleanup on errors
- 36 comprehensive tests covering all functionality

This is Step 2 of Issue #240. Next steps:
- Refactor SharedNodeStore to delegate to coordinator
- Refactor BaseNodeViewer to use declarative dependencies
- Update existing tests for new architecture

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

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

* Refactor SharedNodeStore to delegate persistence to PersistenceCoordinator (#240)

BREAKING CHANGES:
- Removed saveNodeImmediately() - use setNode() instead
- Removed updateNodeContentDebounced() - use updateNode() (automatic debouncing)
- Removed ensureAncestorChainPersisted() - dependencies handled automatically
- Removed pendingContentSaves map - managed by PersistenceCoordinator

CHANGES:
- All persistence delegates to PersistenceCoordinator.getInstance().persist()
- Content changes use debounced mode (500ms) automatically
- Structural changes use immediate mode with parent dependencies
- hasPendingSave() and waitForNodeSaves() delegate to coordinator
- hasPendingWrites() checks coordinator metrics
- Added test mode support to PersistenceCoordinator (skips DB operations)
- Refactored SharedNodeStore tests to test new persistence delegation
- Updated BaseNodeViewer to use new API (setNode/updateNode)

ARCHITECTURE:
- SharedNodeStore focuses on in-memory state management
- PersistenceCoordinator handles all async persistence coordination
- FOREIGN KEY dependencies declared declaratively
- Proper separation between state and persistence layers

TESTING:
- 52 SharedNodeStore tests passing
- 36 PersistenceCoordinator tests passing
- All quality checks passing (lint, format, type-check)

Co-Authored-By: Claude <[email protected]>
🤖 Generated with [Claude Code](https://claude.com/claude-code)

* Apply code review fixes for PersistenceCoordinator (#240)

CRITICAL FIXES:
- Fix reactivity: Use .clear() instead of reassignment for Svelte 5 reactive state
  * Preserves reactive proxy in persistenceStatus and persistedNodes Maps/Sets
  * Prevents broken reactivity in production UI components

- Add ancestor chain dependencies in SharedNodeStore
  * Ensure ENTIRE parent chain is persisted, not just immediate parent
  * Prevents FOREIGN KEY constraint violations with nested placeholder nodes
  * Use lambda dependencies to call ensureAncestorChainPersisted()

- Fix test mode to execute user operations while catching DB errors
  * Operations execute normally (allows test callbacks to run)
  * DatabaseInitializationError silently ignored (no DB setup required)
  * Other errors properly propagated (error-handling tests work)
  * Maintains backward compatibility with existing tests

IMPORTANT IMPROVEMENTS:
- Remove unused maxConcurrentOperations variable (YAGNI principle)
- Remove unimplemented priority option from PersistenceOptions interface
- Add memory cleanup strategy for completed operations
  * Schedule cleanup 5 minutes after completion
  * Prevents unbounded memory growth in long-running sessions
  * Keep persistedNodes Set (needed for existence checks)

- Add comprehensive error recovery documentation to persist() JSDoc
  * Explain dependency failure propagation
  * Document retry patterns
  * Include error handling examples

- Fix inconsistent error logging to use structured format
  * All console.error calls now use object parameter
  * Better for log parsing and monitoring tools

TESTING:
- All 88 tests passing (36 PersistenceCoordinator + 52 SharedNodeStore)
- Quality checks passing (0 warnings, 0 errors)
- Test mode properly handles both test operations and real service calls

NOTES:
- Test mode implementation is temporary - proper solution is to mock
  tauriNodeService in all tests and remove test mode entirely
- Memory cleanup uses simple time-based eviction (5min) - could be
  enhanced with LRU cache if needed
- Ancestor chain dependency adds small overhead but prevents critical
  FOREIGN KEY violations

🤖 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 4, 2026
* Fix sibling chain integrity with unified child promotion logic (#230)

## Changes

### Core Refactoring
- **Extract shared `promoteChildren()` helper** with depth-aware parent selection
- **Simplify `deleteNode()`** to be internal helper (no child handling)
- **Unified logic in `combineNodes()`** handles all deletion scenarios

### Key Improvements
1. **Depth-Aware Child Promotion**: Children promoted to nearest ancestor at same depth
2. **Consistent Behavior**: Both empty and non-empty node deletion use same path
3. **Sibling Chain Integrity**: `removeFromSiblingChain()` repairs chain before deletion
4. **Single Source of Truth**: All child promotion logic in `promoteChildren()`

### Files Changed
- `reactive-node-service.svelte.ts`: Refactored deletion and child promotion
- `base-node-viewer.svelte`: Updated to always use `combineNodes()`

## Testing
- All cases verified: empty nodes, nodes with content, nodes with children
- Sibling chain repair logic consolidated
- UI now consistently uses `combineNodes()` for all deletion scenarios

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

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

* Fix sibling chain integrity in combineNodes operation

This commit fixes a critical race condition in the combineNodes() function
where node deletion could occur before sibling chain repairs completed,
causing database locking errors and FOREIGN KEY constraint violations.

Changes:
- Made combineNodes() async to properly await sibling chain repairs
- Identify affected nodes BEFORE calling removeFromSiblingChain()
- Wait for all sibling chain updates to persist before deleting node
- Updated all call sites to properly await combineNodes()
- Updated event handlers in base-node-viewer.svelte to be async

Technical Details:
The issue was that removeFromSiblingChain() queues an async database
operation via PersistenceCoordinator, but the original code immediately
proceeded to delete the node without waiting. The fix:

1. Identifies nodes that will be affected (next sibling, children)
2. Calls removeFromSiblingChain() to queue the updates
3. Waits for those specific nodes to persist
4. Then safely deletes the node

This ensures proper ordering: sibling chain repair → wait → deletion

Files Modified:
- reactive-node-service.svelte.ts: Made combineNodes() async
- base-node-viewer.svelte: Made event handlers async
- sibling-chain-integrity.test.ts: Updated test calls to await

Related:
- Issue #230: Fix Sibling Chain Integrity
- PR #243: PersistenceCoordinator implementation
- Rebased onto main to leverage new PersistenceCoordinator architecture

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

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

* Address code review feedback: improve defensive programming and documentation

This commit implements the suggested improvements from the code review:

1. **Timeout Fallback Validation in combineNodes()**: Added defensive check
   to validate that all expected nodes were persisted before deletion. If
   timeout occurs, logs detailed error but continues operation to avoid
   leaving UI in inconsistent state.

2. **Enhanced deleteNode() Documentation**: Clarified API contract with
   explicit warnings about child handling. Documents when direct deleteNode()
   usage is appropriate vs combineNodes(). Addresses reviewer concern about
   "internal helper" terminology for public API.

3. **Documented Batch Update Decision**: Added comment explaining why
   individual child updates are preferred over batch API. PersistenceCoordinator
   already handles batching at lower level, typical nodes have <10 children,
   and added complexity wouldn't justify minimal performance gain.

Technical Details:
- combineNodes() now captures return value from waitForNodeSaves()
- Validates persistedNodes.size matches expected nodesToWaitFor.length
- Logs failed node IDs for debugging if timeout occurs
- deleteNode() JSDoc now includes use cases and explicit API guidance

Related: Issue #230, PR #234 code review feedback

🤖 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
* Implement PersistenceCoordinator with dependency tracking (#240)

This implements the core PersistenceCoordinator service that provides
declarative dependency-based persistence for node operations.

Key Features:
- Declarative dependency management (node IDs, lambdas, batches, handles)
- Configurable debouncing (immediate vs. debounced persistence)
- Reactive state tracking using Svelte 5 $state
- Test mode support for testing without database
- Topological dependency resolution
- Performance metrics and monitoring
- Comprehensive error handling and rollback

Architecture:
- Singleton pattern ensures single coordinator instance
- Supports multiple dependency types for flexibility
- Automatic retry and cleanup on errors
- 36 comprehensive tests covering all functionality

This is Step 2 of Issue #240. Next steps:
- Refactor SharedNodeStore to delegate to coordinator
- Refactor BaseNodeViewer to use declarative dependencies
- Update existing tests for new architecture

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

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

* Refactor SharedNodeStore to delegate persistence to PersistenceCoordinator (#240)

BREAKING CHANGES:
- Removed saveNodeImmediately() - use setNode() instead
- Removed updateNodeContentDebounced() - use updateNode() (automatic debouncing)
- Removed ensureAncestorChainPersisted() - dependencies handled automatically
- Removed pendingContentSaves map - managed by PersistenceCoordinator

CHANGES:
- All persistence delegates to PersistenceCoordinator.getInstance().persist()
- Content changes use debounced mode (500ms) automatically
- Structural changes use immediate mode with parent dependencies
- hasPendingSave() and waitForNodeSaves() delegate to coordinator
- hasPendingWrites() checks coordinator metrics
- Added test mode support to PersistenceCoordinator (skips DB operations)
- Refactored SharedNodeStore tests to test new persistence delegation
- Updated BaseNodeViewer to use new API (setNode/updateNode)

ARCHITECTURE:
- SharedNodeStore focuses on in-memory state management
- PersistenceCoordinator handles all async persistence coordination
- FOREIGN KEY dependencies declared declaratively
- Proper separation between state and persistence layers

TESTING:
- 52 SharedNodeStore tests passing
- 36 PersistenceCoordinator tests passing
- All quality checks passing (lint, format, type-check)

Co-Authored-By: Claude <[email protected]>
🤖 Generated with [Claude Code](https://claude.com/claude-code)

* Apply code review fixes for PersistenceCoordinator (#240)

CRITICAL FIXES:
- Fix reactivity: Use .clear() instead of reassignment for Svelte 5 reactive state
  * Preserves reactive proxy in persistenceStatus and persistedNodes Maps/Sets
  * Prevents broken reactivity in production UI components

- Add ancestor chain dependencies in SharedNodeStore
  * Ensure ENTIRE parent chain is persisted, not just immediate parent
  * Prevents FOREIGN KEY constraint violations with nested placeholder nodes
  * Use lambda dependencies to call ensureAncestorChainPersisted()

- Fix test mode to execute user operations while catching DB errors
  * Operations execute normally (allows test callbacks to run)
  * DatabaseInitializationError silently ignored (no DB setup required)
  * Other errors properly propagated (error-handling tests work)
  * Maintains backward compatibility with existing tests

IMPORTANT IMPROVEMENTS:
- Remove unused maxConcurrentOperations variable (YAGNI principle)
- Remove unimplemented priority option from PersistenceOptions interface
- Add memory cleanup strategy for completed operations
  * Schedule cleanup 5 minutes after completion
  * Prevents unbounded memory growth in long-running sessions
  * Keep persistedNodes Set (needed for existence checks)

- Add comprehensive error recovery documentation to persist() JSDoc
  * Explain dependency failure propagation
  * Document retry patterns
  * Include error handling examples

- Fix inconsistent error logging to use structured format
  * All console.error calls now use object parameter
  * Better for log parsing and monitoring tools

TESTING:
- All 88 tests passing (36 PersistenceCoordinator + 52 SharedNodeStore)
- Quality checks passing (0 warnings, 0 errors)
- Test mode properly handles both test operations and real service calls

NOTES:
- Test mode implementation is temporary - proper solution is to mock
  tauriNodeService in all tests and remove test mode entirely
- Memory cleanup uses simple time-based eviction (5min) - could be
  enhanced with LRU cache if needed
- Ancestor chain dependency adds small overhead but prevents critical
  FOREIGN KEY violations

🤖 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
* Fix sibling chain integrity with unified child promotion logic (#230)

## Changes

### Core Refactoring
- **Extract shared `promoteChildren()` helper** with depth-aware parent selection
- **Simplify `deleteNode()`** to be internal helper (no child handling)
- **Unified logic in `combineNodes()`** handles all deletion scenarios

### Key Improvements
1. **Depth-Aware Child Promotion**: Children promoted to nearest ancestor at same depth
2. **Consistent Behavior**: Both empty and non-empty node deletion use same path
3. **Sibling Chain Integrity**: `removeFromSiblingChain()` repairs chain before deletion
4. **Single Source of Truth**: All child promotion logic in `promoteChildren()`

### Files Changed
- `reactive-node-service.svelte.ts`: Refactored deletion and child promotion
- `base-node-viewer.svelte`: Updated to always use `combineNodes()`

## Testing
- All cases verified: empty nodes, nodes with content, nodes with children
- Sibling chain repair logic consolidated
- UI now consistently uses `combineNodes()` for all deletion scenarios

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

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

* Fix sibling chain integrity in combineNodes operation

This commit fixes a critical race condition in the combineNodes() function
where node deletion could occur before sibling chain repairs completed,
causing database locking errors and FOREIGN KEY constraint violations.

Changes:
- Made combineNodes() async to properly await sibling chain repairs
- Identify affected nodes BEFORE calling removeFromSiblingChain()
- Wait for all sibling chain updates to persist before deleting node
- Updated all call sites to properly await combineNodes()
- Updated event handlers in base-node-viewer.svelte to be async

Technical Details:
The issue was that removeFromSiblingChain() queues an async database
operation via PersistenceCoordinator, but the original code immediately
proceeded to delete the node without waiting. The fix:

1. Identifies nodes that will be affected (next sibling, children)
2. Calls removeFromSiblingChain() to queue the updates
3. Waits for those specific nodes to persist
4. Then safely deletes the node

This ensures proper ordering: sibling chain repair → wait → deletion

Files Modified:
- reactive-node-service.svelte.ts: Made combineNodes() async
- base-node-viewer.svelte: Made event handlers async
- sibling-chain-integrity.test.ts: Updated test calls to await

Related:
- Issue #230: Fix Sibling Chain Integrity
- PR #243: PersistenceCoordinator implementation
- Rebased onto main to leverage new PersistenceCoordinator architecture

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

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

* Address code review feedback: improve defensive programming and documentation

This commit implements the suggested improvements from the code review:

1. **Timeout Fallback Validation in combineNodes()**: Added defensive check
   to validate that all expected nodes were persisted before deletion. If
   timeout occurs, logs detailed error but continues operation to avoid
   leaving UI in inconsistent state.

2. **Enhanced deleteNode() Documentation**: Clarified API contract with
   explicit warnings about child handling. Documents when direct deleteNode()
   usage is appropriate vs combineNodes(). Addresses reviewer concern about
   "internal helper" terminology for public API.

3. **Documented Batch Update Decision**: Added comment explaining why
   individual child updates are preferred over batch API. PersistenceCoordinator
   already handles batching at lower level, typical nodes have <10 children,
   and added complexity wouldn't justify minimal performance gain.

Technical Details:
- combineNodes() now captures return value from waitForNodeSaves()
- Validates persistedNodes.size matches expected nodesToWaitFor.length
- Logs failed node IDs for debugging if timeout occurs
- deleteNode() JSDoc now includes use cases and explicit API guidance

Related: Issue #230, PR #234 code review feedback

🤖 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
* Implement PersistenceCoordinator with dependency tracking (#240)

This implements the core PersistenceCoordinator service that provides
declarative dependency-based persistence for node operations.

Key Features:
- Declarative dependency management (node IDs, lambdas, batches, handles)
- Configurable debouncing (immediate vs. debounced persistence)
- Reactive state tracking using Svelte 5 $state
- Test mode support for testing without database
- Topological dependency resolution
- Performance metrics and monitoring
- Comprehensive error handling and rollback

Architecture:
- Singleton pattern ensures single coordinator instance
- Supports multiple dependency types for flexibility
- Automatic retry and cleanup on errors
- 36 comprehensive tests covering all functionality

This is Step 2 of Issue #240. Next steps:
- Refactor SharedNodeStore to delegate to coordinator
- Refactor BaseNodeViewer to use declarative dependencies
- Update existing tests for new architecture

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

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

* Refactor SharedNodeStore to delegate persistence to PersistenceCoordinator (#240)

BREAKING CHANGES:
- Removed saveNodeImmediately() - use setNode() instead
- Removed updateNodeContentDebounced() - use updateNode() (automatic debouncing)
- Removed ensureAncestorChainPersisted() - dependencies handled automatically
- Removed pendingContentSaves map - managed by PersistenceCoordinator

CHANGES:
- All persistence delegates to PersistenceCoordinator.getInstance().persist()
- Content changes use debounced mode (500ms) automatically
- Structural changes use immediate mode with parent dependencies
- hasPendingSave() and waitForNodeSaves() delegate to coordinator
- hasPendingWrites() checks coordinator metrics
- Added test mode support to PersistenceCoordinator (skips DB operations)
- Refactored SharedNodeStore tests to test new persistence delegation
- Updated BaseNodeViewer to use new API (setNode/updateNode)

ARCHITECTURE:
- SharedNodeStore focuses on in-memory state management
- PersistenceCoordinator handles all async persistence coordination
- FOREIGN KEY dependencies declared declaratively
- Proper separation between state and persistence layers

TESTING:
- 52 SharedNodeStore tests passing
- 36 PersistenceCoordinator tests passing
- All quality checks passing (lint, format, type-check)

Co-Authored-By: Claude <[email protected]>
🤖 Generated with [Claude Code](https://claude.com/claude-code)

* Apply code review fixes for PersistenceCoordinator (#240)

CRITICAL FIXES:
- Fix reactivity: Use .clear() instead of reassignment for Svelte 5 reactive state
  * Preserves reactive proxy in persistenceStatus and persistedNodes Maps/Sets
  * Prevents broken reactivity in production UI components

- Add ancestor chain dependencies in SharedNodeStore
  * Ensure ENTIRE parent chain is persisted, not just immediate parent
  * Prevents FOREIGN KEY constraint violations with nested placeholder nodes
  * Use lambda dependencies to call ensureAncestorChainPersisted()

- Fix test mode to execute user operations while catching DB errors
  * Operations execute normally (allows test callbacks to run)
  * DatabaseInitializationError silently ignored (no DB setup required)
  * Other errors properly propagated (error-handling tests work)
  * Maintains backward compatibility with existing tests

IMPORTANT IMPROVEMENTS:
- Remove unused maxConcurrentOperations variable (YAGNI principle)
- Remove unimplemented priority option from PersistenceOptions interface
- Add memory cleanup strategy for completed operations
  * Schedule cleanup 5 minutes after completion
  * Prevents unbounded memory growth in long-running sessions
  * Keep persistedNodes Set (needed for existence checks)

- Add comprehensive error recovery documentation to persist() JSDoc
  * Explain dependency failure propagation
  * Document retry patterns
  * Include error handling examples

- Fix inconsistent error logging to use structured format
  * All console.error calls now use object parameter
  * Better for log parsing and monitoring tools

TESTING:
- All 88 tests passing (36 PersistenceCoordinator + 52 SharedNodeStore)
- Quality checks passing (0 warnings, 0 errors)
- Test mode properly handles both test operations and real service calls

NOTES:
- Test mode implementation is temporary - proper solution is to mock
  tauriNodeService in all tests and remove test mode entirely
- Memory cleanup uses simple time-based eviction (5min) - could be
  enhanced with LRU cache if needed
- Ancestor chain dependency adds small overhead but prevents critical
  FOREIGN KEY violations

🤖 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
* Fix sibling chain integrity with unified child promotion logic (#230)

## Changes

### Core Refactoring
- **Extract shared `promoteChildren()` helper** with depth-aware parent selection
- **Simplify `deleteNode()`** to be internal helper (no child handling)
- **Unified logic in `combineNodes()`** handles all deletion scenarios

### Key Improvements
1. **Depth-Aware Child Promotion**: Children promoted to nearest ancestor at same depth
2. **Consistent Behavior**: Both empty and non-empty node deletion use same path
3. **Sibling Chain Integrity**: `removeFromSiblingChain()` repairs chain before deletion
4. **Single Source of Truth**: All child promotion logic in `promoteChildren()`

### Files Changed
- `reactive-node-service.svelte.ts`: Refactored deletion and child promotion
- `base-node-viewer.svelte`: Updated to always use `combineNodes()`

## Testing
- All cases verified: empty nodes, nodes with content, nodes with children
- Sibling chain repair logic consolidated
- UI now consistently uses `combineNodes()` for all deletion scenarios

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

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

* Fix sibling chain integrity in combineNodes operation

This commit fixes a critical race condition in the combineNodes() function
where node deletion could occur before sibling chain repairs completed,
causing database locking errors and FOREIGN KEY constraint violations.

Changes:
- Made combineNodes() async to properly await sibling chain repairs
- Identify affected nodes BEFORE calling removeFromSiblingChain()
- Wait for all sibling chain updates to persist before deleting node
- Updated all call sites to properly await combineNodes()
- Updated event handlers in base-node-viewer.svelte to be async

Technical Details:
The issue was that removeFromSiblingChain() queues an async database
operation via PersistenceCoordinator, but the original code immediately
proceeded to delete the node without waiting. The fix:

1. Identifies nodes that will be affected (next sibling, children)
2. Calls removeFromSiblingChain() to queue the updates
3. Waits for those specific nodes to persist
4. Then safely deletes the node

This ensures proper ordering: sibling chain repair → wait → deletion

Files Modified:
- reactive-node-service.svelte.ts: Made combineNodes() async
- base-node-viewer.svelte: Made event handlers async
- sibling-chain-integrity.test.ts: Updated test calls to await

Related:
- Issue #230: Fix Sibling Chain Integrity
- PR #243: PersistenceCoordinator implementation
- Rebased onto main to leverage new PersistenceCoordinator architecture

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

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

* Address code review feedback: improve defensive programming and documentation

This commit implements the suggested improvements from the code review:

1. **Timeout Fallback Validation in combineNodes()**: Added defensive check
   to validate that all expected nodes were persisted before deletion. If
   timeout occurs, logs detailed error but continues operation to avoid
   leaving UI in inconsistent state.

2. **Enhanced deleteNode() Documentation**: Clarified API contract with
   explicit warnings about child handling. Documents when direct deleteNode()
   usage is appropriate vs combineNodes(). Addresses reviewer concern about
   "internal helper" terminology for public API.

3. **Documented Batch Update Decision**: Added comment explaining why
   individual child updates are preferred over batch API. PersistenceCoordinator
   already handles batching at lower level, typical nodes have <10 children,
   and added complexity wouldn't justify minimal performance gain.

Technical Details:
- combineNodes() now captures return value from waitForNodeSaves()
- Validates persistedNodes.size matches expected nodesToWaitFor.length
- Logs failed node IDs for debugging if timeout occurs
- deleteNode() JSDoc now includes use cases and explicit API guidance

Related: Issue #230, PR #234 code review feedback

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

Implement PersistenceCoordinator for Dependency-Based Persistence

1 participant