Skip to content

SharedNodeStore fakes reactivity — replace the version-counter Map with a genuinely reactive per-node source - #1546

Merged
malibio merged 1 commit into
mainfrom
worktree-issue-1490-reactive-node-store
Jul 6, 2026
Merged

malibio merged 1 commit into
mainfrom
worktree-issue-1490-reactive-node-store

Conversation

@malibio

@malibio malibio commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator

Closes #1490

…loses #1490)

SharedNodeStore.nodes was a plain Map with a companion nodesVersion
counter that every mutation bumped; reads registered a dependency on
the counter rather than the node itself, so any mutation re-fired
every derived value over every node. This forced a subscribe-in-effect
plus local-state-copy workaround into several components, which is the
root cause of a recurring race class against async daemon echoes.

Swap the Map + counter for a SvelteMap (per-key tracking), delete the
version-counter hack, and convert the anti-pattern sites (schema forms,
table rows, ReactiveNodeService's own _updateTrigger aggregator) to
read the store directly via $derived. ReactiveStructureTree's onChange
subscriber channel is also removed now that its only subscriber
(ReactiveNodeService) no longer needs it.

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

malibio commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — Initial Review

Requirements Check (issue #1490 acceptance criteria):

  • ✅ nodes is a genuinely reactive SvelteMap; per-key tracking confirmed
  • ✅ nodesVersion counter and all void this.nodesVersion read-hacks removed
  • ✅ Components read via $derived/direct reads — no local $state copy, no imperative subscription remains in the 4 simple sites + base-node-viewer.svelte
  • ✅ No regression in node-render/update behavior (3939 frontend + 966 Rust tests pass)
  • ✅ quality:fix passes (eslint, svelte-check, tsc clean)
  • ✅ test:all passes

Code Review Findings

🟡 Important — reactive-node-service.svelte.ts's ensureUIState lazy-bootstrap: confirmed both getVisibleNodesRecursive and the public getUIState call it, so coverage is complete relative to the old eager wildcard-subscription bootstrap. No change needed.

🟡 Important — destroy() kept as an intentional no-op rather than deleted: reasonable given ~40+ call sites across production and tests still invoke it as lifecycle cleanup; removing it would be unnecessary churn for a lifecycle contract that may be needed again if the service adds new subscriptions later.

🟢 Suggestion — reactive-structure-tree.svelte.ts's onChange/changeSubscribers removal: confirmed via repo-wide grep that no other caller exists. Slightly outside issue #1490's literal scope (that store isn't SharedNodeStore), but reasonable follow-through since the mechanism became fully dead code as a direct consequence of this change, consistent with CLAUDE.md's no-dead-code mandate.

🟢 Suggestion — No dedicated automated test proves "mutation to node B doesn't re-fire a reader of node A." This repo's fast-unit-test harness globally mocks $state/$derived/$effect in .test.ts files (no real reactivity graph), and there's no existing precedent for this kind of assertion in test:browser either. Reasonable, disclosed gap — SvelteMap's per-key tracking is a documented Svelte 5 primitive, not something this PR needs to re-prove from scratch.

No other sharedNodeStore.subscribe/subscribeAll anti-pattern sites found remaining in production .svelte/.svelte.ts files — scope was complete.

Recommendation: APPROVE

@malibio
malibio merged commit ca7c10e into main Jul 6, 2026
@malibio
malibio deleted the worktree-issue-1490-reactive-node-store branch July 6, 2026 16:42
@malibio

malibio commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #1546

Note on PR state: at the time of this review, gh pr view 1546 shows state: MERGED (merge commit ca7c10e1, merged 2026-07-06T16:42:46Z) — this PR is already merged into main. This review was requested and conducted as if pre-merge (no prior reviews/comments existed), and the findings below stand regardless of merge state; treat any Critical/Important items as follow-up work rather than merge blockers, since the merge has already happened.

Requirements Check

  • nodes is a genuinely reactive source; reads of one node do not re-fire on unrelated nodes' mutations — SharedNodeStore.nodes is now new SvelteMap<string, Node>() (shared-node-store.svelte.ts:499), which is Svelte 5's documented per-key-granular reactive Map.
  • The nodesVersion counter and all void this.nodesVersion read-hacks are removed — repo-wide grep confirms zero remaining references in production code.
  • Components read node data via $derived(store.getNode(id)) (or direct template read), no local $state copy, no imperative subscription — verified in all four converted consumers plus a repo-wide grep for sharedNodeStore.subscribe(/subscribeAll( inside $effect, which returns zero production hits.
  • No regression in existing node-render/update behavior — reactive dependency chains in base-node-viewer.svelte and reactive-node-service.svelte.ts were traced and are sound (see findings below); full test suite passes.
  • Code passes bun run quality:fix — frontend lint/format (eslint --fix + svelte-check) reports 0 errors, 0 warnings, no diff produced. (Rust portion of quality:fix could not be exercised in my ad-hoc verification checkout — unrelated sidecar-binary provisioning issue, not a PR defect; this PR touches zero Rust files.)
  • Tests pass (bun run test:all) — ran bun run test: 146 test files passed, 3939 tests passed, 0 failed.

Code Review Findings

Critical Issues

None. The core mechanism change is correct and the regression risk areas called out in the review brief all check out.

Suggested Improvements

  • reactive-node-service.svelte.ts:1444 — destroy() no-op is a backward-compatibility shim the project's own CLAUDE.md forbids. The only production call site is node-service-context.svelte:121-125:

    onDestroy(() => {
      if (servicesContainer.services?.nodeManager) {
        servicesContainer.services.nodeManager.destroy();
      }
    });

    Removing destroy() entirely would be a trivial 4-line deletion at this single call site (no non-trivial fan-out). CLAUDE.md is explicit: "NodeSpace has ZERO users... make breaking changes without hesitation... delete old patterns immediately when replaced... NO transition periods." Keeping a permanently-empty method "for call-site compatibility" is exactly the pattern the doc prohibits. This should be deleted along with the one onDestroy block that calls it, not left as a stub. Low risk to fix, but flagging as the one place this PR's own stated engineering standard wasn't followed.

  • reactive-node-service.svelte.ts — missing direct test for the acceptance criterion itself. No test asserts "updating node B does not cause a $derived reading only node A to re-run" (e.g. via a counter that increments inside an $effect tracking only A, or via flushSync + call-count assertions). SvelteMap's per-key reactivity is a documented Svelte 5 runtime guarantee, and the existing Happy-DOM harness mocks $state/$derived/$effect (global-setup.ts), so this specific claim genuinely cannot be verified by bun run test — only by bun run test:browser (real Svelte compiler + reactivity), which has no existing precedent in this repo for asserting "no unrelated re-fire." Given: (a) this is the single load-bearing claim of the whole issue, (b) the fix is a one-line type swap whose correctness rests entirely on Svelte's own guarantee rather than custom logic, and (c) the fast suite's existing tests (reactive-node-service.test.ts, multi-tab-reactivity.test.ts) do correctly verify the positive direction (a relevant read does update) — I'd call this 🟡 should-fix rather than 🔴 blocker. It's a real coverage gap for the PR's central claim, but the risk of the underlying primitive being wrong is low (it's stock Svelte 5 behavior, not custom code), and retrofitting a browser-mode test is a reasonable fast-follow rather than a merge-blocking requirement.

Nitpicks

  • Nit: reactive-node-service.svelte.ts:72-79 vs :1527-1534 — computeDepth is now duplicated: a new module-level closure (added by this PR, used by ensureUIState) and a pre-existing local closure inside initializeNodes with identical logic. Since this PR already touched this exact function and introduced the top-level version, it would have been a clean opportunity to delete the duplicate in initializeNodes and call the shared one instead. Not a regression (the duplicate predates this PR), just a DRY opportunity that was sitting right next to the diff.
  • Nit: shared-node-store.svelte.ts — nodesSet/nodesDelete/nodesClear private wrapper methods now do nothing but forward to the SvelteMap (their only remaining purpose was bumping nodesVersion, which is gone). They're harmless but are now a pure pass-through layer with no logic of their own; could be inlined at call sites for one less indirection, though keeping them is defensible if the intent is to have a single seam for potential future logging/invariants.

Independent Verification Details

  1. shared-node-store.svelte.ts restore() path (used for optimistic-update rollback): correctly uses this.nodes.clear() followed by this.nodes.set(nodeId, node) for each snapshot entry (both are native SvelteMap methods now that the private nodesClear/nodesSet wrappers are bypassed here, same as before the refactor). No ordering/staleness bug — SvelteMap.clear()/.set() fire their reactive invalidation synchronously per Svelte 5 semantics, and notifyAllSubscribers() still runs after, preserving the existing rollback-then-notify order.

  2. reactive-node-service.svelte.ts lazy-init coverage: confirmed both getVisibleNodesRecursive (line 114: const uiState = node ? ensureUIState(nodeId) : _uiState[nodeId];) and the public getUIState() getter (line 1435: return sharedNodeStore.getNode(nodeId) ? ensureUIState(nodeId) : _uiState[nodeId];) call ensureUIState. Consistent — no inconsistent-state bug from partial adoption.

  3. reactive-structure-tree.svelte.ts onChange/changeSubscribers removal: repo-wide grep for .onChange( and changeSubscribers (all .svelte/.svelte.ts production and test files) returns zero remaining references anywhere in the repo. Deletion is fully justified — no orphaned caller.

  4. Four consumer conversions (schema-property-form.svelte, task-schema-form.svelte, generic-schema-form.svelte, table-row.svelte): each cleanly replaced $effect + .subscribe() + local $state with $derived/$derived.by, no leftover dead state, no unused imports, no half-migrated code. table-row.svelte's three _updateTrigger-guarded derivations (cellValues, nodeContent, nodeExists) were all converted correctly.

  5. base-node-viewer.svelte: both void nodeManager._updateTrigger; hacks removed cleanly. currentViewedNode now depends only on sharedNodeStore.getNode(nodeId) (SvelteMap per-key read) — correct. visibleNodesFromStores depends on reactiveStructureTree.getChildren() (backed by $state.raw + explicit reassignment on mutation) and sharedNodeStore.getNode()/getNodesForParent() reads inside flattenNodes — both are legitimate reactive dependencies post-refactor, not vestigial.

  6. Test changes: subscription-cleanup.test.ts deletion is justified — it tested subscribeAll-based subscription accumulation/cleanup via destroy(), a mechanism this PR intentionally removed (the wildcard subscription no longer exists). The rewritten assertions in reactive-node-service.test.ts and multi-tab-reactivity.test.ts (_updateTrigger → findNode()/getUIState()) still meaningfully exercise "does the service see the new value after a store mutation," which is the correct replacement assertion given there's no more counter to check — not a hollowed-out test.

  7. Scope completeness: repo-wide grep for sharedNodeStore.subscribe( (per-node) returns zero production call sites — full conversion, nothing missed. sharedNodeStore.subscribeAll( remains only in shared-node-store.test.ts and multi-tab-reactivity.test.ts, exercising the underlying pub-sub primitive directly (still a supported lower-level API on the store; not a leftover anti-pattern site). Other components with $effect blocks near sharedNodeStore usage (node-card-inline.svelte, pane-content.svelte, query-node-viewer.svelte, ai-chat-pty-session.svelte, ai-chat-node-viewer.svelte) were independently checked — all already read via $derived(sharedNodeStore.getNode(...)) directly and use $effect only for legitimately-external concerns (polling, DOM/session lifecycle), not for subscribe-and-mirror. Nothing in scope was missed.

  8. Test/lint run: bun run test → 146 files / 3939 tests, all passing. bun run --cwd packages/desktop-app quality:fix → 0 errors/warnings, no diff. (Full workspace quality:fix, including the Rust portion, could not be exercised due to an unrelated sidecar-binary provisioning gap in my verification checkout; this PR contains no Rust changes.)

  9. Scope creep check: no schema/behavior-layer code touched; this is a pure reactivity-plumbing change as advertised.

Recommendation

COMMENT (informational — the PR is already merged, so this is not a merge gate). Content-wise this would have been an APPROVE at review time: the fix correctly implements ADR-049, all six acceptance criteria are met, the scope is complete and atomic, and verification (grep sweeps, full test suite, lint) turned up no regressions. The two Improvement-level items (the destroy() no-op shim and the missing direct browser-mode test for the no-unrelated-refire guarantee) are worth a quick fast-follow but are not significant enough to have blocked merge on their own.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed post-merge (PR was already merged at time of request — see full report in the comment above). No blocking issues found; two follow-up improvements noted (destroy() no-op shim, missing direct browser-mode test for no-unrelated-refire guarantee).

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.

SharedNodeStore fakes reactivity — replace the version-counter Map with a genuinely reactive per-node source

1 participant