Repository navigation
Preserve structureTree order on sync echoes + fix stale-sibling check (fixes nodespace-sync#77, frontend) - #1215
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 #1215CI: ⏳ No checks reported on Findings🟡 Order-fallback
🟡
Not a blocker for correctness, but the sync echo path is one of the hotter paths in the receive side. 🟡 Stale-sibling check now preserves the hint when if (siblingActualParent !== null && siblingActualParent !== currentNode.parentId) { /* clear */ }When 🟡 The new test doesn't exercise the persistence-path decision ( 🟡 The fix changes the trust hierarchy without naming it in code ( Nits🟢 Nit: 🟢 Nit: 🟢 Nit: 🟢 Nit: The test file imports 🟢 Nit: Test name is very long ( 🟢 Nit: 🟢 Nit: PR description acknowledges "frontend half alone is not sufficient" SummaryBoth fixes target the right primitives (structureTree as the order-of-record, structureTree as the parent-of-record). The blockers are about (a) what happens when structureTree has no data — the 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]>
|
Force-pushed to address review feedback. PR is now rebased on top of the updated #1213. Main behavioral fix
Test improvements
Performance
Observability
Documentation
Nits
Test deltas
Re-verified manually against the two-window same-device demo: both windows correctly place new siblings below the typed line in the same position. |
Pragmatic code review (re-review) — PR #1215Review Type: Re-Review (scope: force-pushed commit Previous review summary
Round-1 findings — disposition✅ if (typeof incomingOrder === 'number') { order = incomingOrder; }
else if (existing) { order = existing.order; } // tier 2: preserve structureTree order
else { order = lastOrder + 1 + Math.random() * 0.001; } // tier 3: append-at-end with jitterBrand-new echoed children now land at ✅ Stale-sibling test didn't exercise the persistence-path decision — extracted ✅ O(n) ✅ ✅ Trust hierarchy invariant — ✅ Nits addressed — New findings🟢 Nit: 🟢 Nit: SummaryEvery round-1 🟡 is resolved with code + test (the helper extraction is particularly clean — production code path now matches what the test exercises). Tier 3 of the order fallback is the right shape: append-at-end with a sub-integer jitter is a sensible "stable" default that doesn't drag echoed children to absurd positions. The two remaining nits are about long-tail consistency between the echo path and the local optimistic path — not blockers. Verdict: APPROVE |
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]>
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]>
…tion Preserve structureTree order on sync echoes + fix stale-sibling check (fixes nodespace-sync#77, frontend)
Summary
Frontend resilience half of
nodespace-sync#77. Companion to #1214 (`fix/create-parent-edge-idempotent`) — each PR removes one piece of the "new node lands at the top of the list" failure mode.Bug 1 — `tauri-sync-listener` clobbers the local order on cloud echo
The cloud LIVE-SELECT echo of a freshly-created `has_child` edge arrives with `properties.order = undefined` because the sync layer's `RELATE ... SET rel_type = $rt` doesn't push the order field to cloud. The previous fallback `?? Date.now()` overwrote the correct local fractional order (set by the local optimistic path and the preceding local domain event) with a value 11 orders of magnitude larger — relocating the just-created sibling out of position.
Fix: when the incoming order is missing, look up the existing entry in `structureTree` and preserve its order. If the child is brand-new and we genuinely have nothing better, fall back to `Date.now()` so it lands somewhere stable.
Bug 2 — stale-sibling check uses an unreliable field
The persistence-time check that decides whether to clear `insertAfterNodeId` before firing a CREATE compared `siblingNode.parentId` against `currentNode.parentId`. Nodes loaded via `getChildrenTree` come back without `parentId` populated on the wire, so every Enter-key insertion looked "stale" — the hint got cleared and the backend received `None`, falling into the wrong default branch.
Fix: use `structureTree.getParent` (the authoritative source for hierarchy via `has_child` edges) instead. Preserves the hint when `structureTree` has no opinion (sibling not yet in tree) so the backend can still resolve it via its own retry loop.
Stacking note
This PR is stacked on top of #1213 (`fix/setnode-skip-while-editing`) — both PRs touch `shared-node-store.svelte.ts` in non-overlapping regions, but stacking keeps the review diff legible. Once #1213 merges, this PR rebases trivially against main.
What changed
Test plan
Related PRs