Repository navigation
Skip-while-editing guard in SharedNodeStore.setNode (fixes nodespace-sync#76) - #1213
Conversation
Daemon-broadcast events arrive on the gRPC WatchNodes stream after every
local UpdateNode RPC confirms. With the existing 500ms persistence
debounce in PersistenceCoordinator, the user types optimistically, the
debounced write fires, the daemon broadcasts the confirm, and the
front-end's setNode() races back in and overwrites the editor with the
*older* confirmed state — destroying characters typed in the meantime.
Add a guard: when source.type === 'database' and the incoming node is
either focused (focusManager.editingNodeId === node.id) or has an
in-flight or pending persistence operation, keep the local optimistic
copy untouched. Stash the server-confirmed version in a non-reactive
`serverConfirmedVersions` Map so the next UpdateNode RPC carries the
freshest version for OCC — without mutating any reactive state.
Why non-reactive: mutating the reactive `nodes` Map (or mutating a
property of a node inside it) triggers Svelte re-renders that remount
the focused textarea via the `{#if isEditing}` block in
base-node.svelte. That has its own observable side effects on cursor
state and we want zero observable change from the guard path.
Adds PersistenceCoordinator.hasPending(nodeId) so the guard can ask the
coordinator directly rather than reaching into its private state.
Fixes nodespace-sync#76 (typing corruption: characters dropped or
replaced under sustained input).
nodespace-sync#77 (Enter on a non-empty node creates an empty node
above instead of below) was initially suspected to share this root
cause but verified separately by the user — the bug reproduces in
single-window mode and after this fix lands. Tracked separately; the
root cause is in the Enter handler / insertion path, not in setNode.
Tests: 7 new cases in
src/tests/services/shared-node-store-skip-while-editing.test.ts
covering focused-clobber-skip, pending-clobber-skip, the regression
case (no focus, no pending → apply normally), viewer-source still
authoritative for focused nodes, never-seen nodes accept fresh state,
local node.version unchanged when guard fires, and the
server-confirmed-version cache is cleared when a non-guarded setNode
applies (no shadowing).
Test deltas vs origin/main:
- shared-node-store family: 245 → 252 passing (+7 new)
- full frontend suite: 3832 → 3839 passing, same 93 pre-existing
localStorage-env failures unchanged
Manually verified end-to-end against the two-window same-device demo
(scripts/run-two-daemons.sh + the worktree's vite dev server +
nodespace-app windows for alice and bob). Sustained typing in alice
no longer corrupts characters; bob continues to receive alice's
writes within ~1s.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Pragmatic code review — PR #1213CI: ⏳ No checks reported on Findings🟡 Idempotency check shadows the OCC contract for concurrent writers ( 🟡 hasPending(nodeId: string): boolean {
return this.pendingOperations.has(nodeId) ||
this.executingOperations.has(nodeId) ||
this.queuedOperations.has(nodeId);
}The coordinator transitions a node between these three Maps. Between 🟡 🟡 🟡 No test exercises the persistence path consuming the stashed version ( Nits🟢 Nit: The 'database' source assumption is implicit ( 🟢 Nit: 🟢 Nit: 🟢 Nit: Comment names 🟢 Nit: 🟢 Nit: The new test file's SummaryThe shape of the fix is correct and the test coverage is honest about what it tests. The blocker is the concurrent-writer interaction: stashing whatever-version-the-daemon-sends and replaying it as OCC works for the same-client loopback case but breaks the cross-client conflict-detection that OCC exists to provide. Worth resolving before this lands as the foundation for #77 frontend resilience (#1215) and the broader sync UX story. Verdict: REQUEST CHANGES |
- Foreign-write OCC defeat: the guard previously stashed `node.version` from any database broadcast, including cloud-relayed writes from another client. The next UpdateNode would then carry the foreign writer's version against the local content, silently overwriting the foreign change. Add an `isPlausibleOwnEcho` heuristic — only stash when local content equals or extends the incoming content (exact echo, or echo+more-typed-chars). For genuine foreign writes, leave the cache empty so the next RPC uses the local version and the backend's OCC surfaces the conflict. - hasPending race + repeated calls: the coordinator transitions a node between its pending/executing/queued maps, so `hasPending` can flip between the guard condition and the log message. Compute `isFocused` and `hasPending` once into locals, use those for both the condition and the log. - Persistence consumes the cache — covered: extracted `computeOccVersionForUpdate(nodeId)` as the single source of truth for "what version does the next UpdateNode RPC carry?". The persistence closure routes through it; a new test asserts that after the guard fires, `computeOccVersionForUpdate` returns the stashed version (5), not the local node.version (1). Future refactor that drops the cache read fails this test instead of silently re-introducing nodespace-sync#76. - Foreign-write detection — covered: new test plants a divergent optimistic content, fires a database broadcast with a different content + higher version, and asserts the cache stays empty. - `UpdateSource = 'database'` contract: added a comment naming the intended producers (tauri-sync-listener / browser-sync-service) so the next refactor that adds a new 'database' producer knows to audit the guard's assumption. - persistedNodeIds invariant: added a one-line comment naming the "database event for existing node ⟹ persisted server-side" invariant so a future refactor that drops the `existingNode` check doesn't accidentally start marking unseen nodes as persisted. - Fixed an issue cross-reference (#77 → #76) in setNode's doc comment. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Pushed review-feedback addressed in Real concerns
Comments
Nits skipped
Test deltas
|
Pragmatic code review (re-review) — PR #1213Review Type: Re-Review (scope: commit Previous review summary
Round-1 findings — disposition✅ Foreign-write OCC defeat — ✅ ✅ Persistence-path consumption uncovered — ✅ ✅ ✅ #77 → #76 cross-reference — fixed on the New findings🟡 private isPlausibleOwnEcho(local: Node, incoming: Node): boolean {
if (localContent === incomingContent) return true;
return localContent.startsWith(incomingContent); // own-extension case
}The startsWith branch covers the legitimate case where the user has typed more characters since the broadcast was generated. But it also covers an unintended case: alice's local content is Tighter heuristic options:
(2) is the cleanest if the broadcast envelope already carries enough info; this is the same kind of L1-origin-tag pattern used in 🟢 Nit: SummarySubstantial improvement. Four of five round-1 🟡s are cleanly resolved with code + tests that lock the contract. The OCC-defeat concern is mitigated for the common shapes (exact echo, user-typed extension, divergent edit) but the prefix-overlap edge case still slips through the heuristic. That's a real silent-data-loss hole, even if narrow — worth either the origin-tag fix above or an explicit "known limitation" note in code + a tracking issue, so it's not silently inherited by the next reviewer. Verdict: REQUEST CHANGES (one residual 🟡) |
The previous heuristic compared `local.content.startsWith(incoming.content)`,
which covered legitimate own-write echoes with newer-typed-chars-on-top
but also mis-classified a class of foreign writes as own-echoes:
alice optimistic: "hello world"
bob writes: "hello" (broadcast hits alice)
→ "hello world".startsWith("hello") is true
→ bob's version stashed
→ alice's next UpdateNode carries bob's version against "hello world"
→ backend silently overwrites bob
Replace with own-write history tracking: maintain a
`lastPersistedContent: Map<string, string>` populated by the
persistence path (`tauriCommands.updateNode` / `tauriCommands.createNode`
call sites) right before each RPC, and gate the cache stash on
`incoming.content === lastPersistedContent[nodeId]`.
This is the conservative direction:
- False positives are eliminated (the bob-prefix race above).
- False negatives just defer to OCC — a client that has never
persisted this node before (initial-load path) won't classify
the daemon's first echo as own, will use the local version on
the next RPC, and the OCC layer handles the rest. No content
loss; at worst a single conflict-retry cycle.
Test deltas:
- New `does NOT mis-classify a prefix-compatible foreign write
as an own-echo` test as the explicit regression check for the
startsWith hole.
- Updated two existing tests that depended on the old heuristic's
behavior to seed the `lastPersistedContent` cache via the new
`__test_setLastPersistedContent` helper.
- shared-node-store-skip-while-editing.test.ts: 9 → 10 passing.
- shared-node-store family: 248 → 249.
- `bun run --cwd packages/desktop-app quality:fix` — clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Pushed 🟡 `isPlausibleOwnEcho` startsWith hole — fixed. The previous heuristic compared `local.content.startsWith(incoming.content)` which mis-classified a class of foreign writes as own-echoes (alice's optimistic "hello world" + bob's broadcast "hello" → falsely true → bob's version stashed → next RPC silently overwrites bob). Replaced with an own-write history check: maintain a `lastPersistedContent: Map<string, string>` populated by the persistence path right before each `tauriCommands.updateNode` / `tauriCommands.createNode` RPC, and gate the cache stash on `incoming.content === lastPersistedContent[nodeId]`. Conservative direction — false positives eliminated; false negatives just defer to OCC. The reviewer's three options:
Trade-off: a client that has never persisted a node yet (initial load, no edits) reports false for all broadcasts including the daemon's first own-confirm. That's fine — with no last-sent record, local Test additions
Test deltas
|
- Foreign-write OCC defeat: the guard previously stashed `node.version` from any database broadcast, including cloud-relayed writes from another client. The next UpdateNode would then carry the foreign writer's version against the local content, silently overwriting the foreign change. Add an `isPlausibleOwnEcho` heuristic — only stash when local content equals or extends the incoming content (exact echo, or echo+more-typed-chars). For genuine foreign writes, leave the cache empty so the next RPC uses the local version and the backend's OCC surfaces the conflict. - hasPending race + repeated calls: the coordinator transitions a node between its pending/executing/queued maps, so `hasPending` can flip between the guard condition and the log message. Compute `isFocused` and `hasPending` once into locals, use those for both the condition and the log. - Persistence consumes the cache — covered: extracted `computeOccVersionForUpdate(nodeId)` as the single source of truth for "what version does the next UpdateNode RPC carry?". The persistence closure routes through it; a new test asserts that after the guard fires, `computeOccVersionForUpdate` returns the stashed version (5), not the local node.version (1). Future refactor that drops the cache read fails this test instead of silently re-introducing nodespace-sync#76. - Foreign-write detection — covered: new test plants a divergent optimistic content, fires a database broadcast with a different content + higher version, and asserts the cache stays empty. - `UpdateSource = 'database'` contract: added a comment naming the intended producers (tauri-sync-listener / browser-sync-service) so the next refactor that adds a new 'database' producer knows to audit the guard's assumption. - persistedNodeIds invariant: added a one-line comment naming the "database event for existing node ⟹ persisted server-side" invariant so a future refactor that drops the `existingNode` check doesn't accidentally start marking unseen nodes as persisted. - Fixed an issue cross-reference (#77 → #76) in setNode's doc comment. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The previous heuristic compared `local.content.startsWith(incoming.content)`,
which covered legitimate own-write echoes with newer-typed-chars-on-top
but also mis-classified a class of foreign writes as own-echoes:
alice optimistic: "hello world"
bob writes: "hello" (broadcast hits alice)
→ "hello world".startsWith("hello") is true
→ bob's version stashed
→ alice's next UpdateNode carries bob's version against "hello world"
→ backend silently overwrites bob
Replace with own-write history tracking: maintain a
`lastPersistedContent: Map<string, string>` populated by the
persistence path (`tauriCommands.updateNode` / `tauriCommands.createNode`
call sites) right before each RPC, and gate the cache stash on
`incoming.content === lastPersistedContent[nodeId]`.
This is the conservative direction:
- False positives are eliminated (the bob-prefix race above).
- False negatives just defer to OCC — a client that has never
persisted this node before (initial-load path) won't classify
the daemon's first echo as own, will use the local version on
the next RPC, and the OCC layer handles the rest. No content
loss; at worst a single conflict-retry cycle.
Test deltas:
- New `does NOT mis-classify a prefix-compatible foreign write
as an own-echo` test as the explicit regression check for the
startsWith hole.
- Updated two existing tests that depended on the old heuristic's
behavior to seed the `lastPersistedContent` cache via the new
`__test_setLastPersistedContent` helper.
- shared-node-store-skip-while-editing.test.ts: 9 → 10 passing.
- shared-node-store family: 248 → 249.
- `bun run --cwd packages/desktop-app quality:fix` — clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Skip-while-editing guard in SharedNodeStore.setNode (fixes nodespace-sync#76)
Frontend resilience half of nodespace-sync#77 — pairs with the backend
fix at NodeSpaceAI/nodespace-core PR fix/create-parent-edge-idempotent
to restore correct ordering across the cloud round-trip in both
windows.
## tauri-sync-listener: order fallback rewritten
Three tiers of fallback for `relationship:created has_child` events
when `properties.order` is missing:
1. Incoming order is a number (incl. 0, negatives) → use it. The
typeof gate IS the runtime check; `properties.order` is typed
`unknown` on the wire.
2. Incoming order missing AND we already have an entry for this
child in structureTree → preserve the existing order. This is
the alice-side echo case — the local optimistic path or the
preceding domain event already placed the child correctly.
3. Incoming order missing AND no existing entry → append after the
parent's current last child (order = last.order + 1 + tiny
jitter). This is the bob-side path for a brand-new sync-echoed
child. The previous fallback `Date.now()` was a "stable" but
wrong location — children landed at ~1.7e12 order, far below
every sibling.
Performance note: the `siblings.find` is O(n) per echo. Adequate for
the present, worth a Map-backed primitive on structureTree if a
high-cardinality parent under sync burst becomes a hotspot.
## shared-node-store: stale-sibling check extracted
The decision logic that gates `insertAfterNodeId` clearing was
inlined in the persistence closure. Extracted as
`SharedNodeStore.shouldClearStaleInsertAfter(siblingId,
currentParentId)` — single source of truth, directly unit-testable
without mocking the Tauri IPC.
Documents the **trust hierarchy** explicitly on the helper:
`structureTree` is authoritative for has_child relationships; the
bare `Node.parentId` field is opportunistically populated by some
load paths and reliably `null` for nodes returned via
`getChildrenTree` (the wire shape strips it). Hierarchy decisions
must always consult structureTree.
Adds a debug log when structureTree has no opinion at decision time
(`siblingActualParent === null`) so the frequency of "tree not yet
populated at persistence time" is observable — a high rate would
indicate a race in a different code path, not this one.
## Tests
- New `shouldClearStaleInsertAfter` covers three cases: structureTree
agrees (preserve), structureTree disagrees (clear), structureTree
has no opinion (preserve, log).
- Rebased the test file on top of PR #1213's foreign-write and
persistence-path tests so this PR's tests stack cleanly.
- Test file's reactive-structure-tree import moved to top-of-file
(was inline `await import(...)`).
- Renamed the test to a shorter, intent-focused name.
## Stacking
Stacked on top of PR fix/setnode-skip-while-editing (#1213). Both
PRs touch `shared-node-store.svelte.ts` in non-overlapping regions;
stacking keeps each PR's diff legible. Once #1213 merges, this PR
rebases trivially against main.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Summary
Daemon-broadcast events arrive on the gRPC
WatchNodesstream after every localUpdateNodeRPC confirms. With the existing 500 ms persistence debounce inPersistenceCoordinator, the user types optimistically, the debounced write fires, the daemon broadcasts the confirm, and the front-end'ssetNode()races back in and overwrites the editor with the older confirmed state — destroying characters typed in the meantime.Add a guard: when
source.type === 'database'and the incoming node is either focused (focusManager.editingNodeId === node.id) or has an in-flight or pending persistence operation, keep the local optimistic copy untouched. Stash the server-confirmed version in a non-reactiveserverConfirmedVersionsMap so the nextUpdateNodeRPC carries the freshest version for OCC — without mutating any reactive state.Why non-reactive
Mutating the reactive
nodesMap (or mutating a property of a node inside it) triggers Svelte re-renders that remount the focused textarea via the{#if isEditing}block inbase-node.svelte. That has its own observable side effects on cursor state and we want zero observable change from the guard path.What this fixes
NodeSpaceAI/nodespace-sync#76— typing corruption: characters dropped or replaced under sustained input.What changed
packages/desktop-app/src/lib/services/shared-node-store.svelte.tssetNodeguard before the unconditional Map mutationserverConfirmedVersions: Map<string, number>(non-reactive)serverConfirmedVersionsovercurrentNode.versionat OCC timePersistenceCoordinator.hasPending(nodeId)so the guard can ask the coordinator directly rather than reaching into its private statepackages/desktop-app/src/tests/services/shared-node-store-skip-while-editing.test.ts— 7 new test casesTest plan
cargo test -p nodespace-core --lib— 1191 passed / 0 failedcargo clippy -p nodespace-core --lib -- -D warnings— cleanRelated PRs
Two parallel PRs for the companion bug
nodespace-sync#77(Enter relocates new node to top of list) will follow shortly:create_parent_edgeidempotency +None-translationtauri-sync-listenerorder preservation + persistence-time stale-sibling check