Skip to content

Preserve structureTree order on sync echoes + fix stale-sibling check (fixes nodespace-sync#77, frontend) - #1215

Merged
mstomar125 merged 4 commits into
NodeSpaceAI:mainfrom
mstomar125:fix/sync-echo-order-preservation
May 27, 2026
Merged

mstomar125 merged 4 commits into
NodeSpaceAI:mainfrom
mstomar125:fix/sync-echo-order-preservation

Conversation

@mstomar125

Copy link
Copy Markdown
Contributor

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

  • `packages/desktop-app/src/lib/services/tauri-sync-listener.ts` — the `has_child` branch of the `relationship:created` handler now preserves the existing structureTree order when `rel.properties?.order` is missing.
  • `packages/desktop-app/src/lib/services/shared-node-store.svelte.ts` — the stale-sibling check (in the CREATE persistence path) now consults `structureTree.getParent` instead of `siblingNode.parentId`.
  • `packages/desktop-app/src/tests/services/shared-node-store-skip-while-editing.test.ts` — 1 new test case for the structureTree-based check.

Test plan

Related PRs

  • #1213 — `setNode` skip-while-editing guard (`nodespace-sync#76`). This PR stacks on it.
  • #1214 — backend half of `nodespace-sync#77`. Independent of this PR; both need to land for the full fix.

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]>
@mstomar125

Copy link
Copy Markdown
Contributor Author

Pragmatic code review — PR #1215

CI: ⏳ No checks reported on fix/sync-echo-order-preservation — verify CI is wired up before merge.
Scope: +337 / -18 across 3 files. Two fixes: tauri-sync-listener preserves existing structureTree order when echo arrives without properties.order; shared-node-store persistence-path stale-sibling check now consults structureTree.getParent instead of the unreliable siblingNode.parentId. Stacked on #1213.
Requirements: Frontend half of nodespace-sync#77. The PR is honest that it's not sufficient alone — both #1214 and this PR need to land.

Findings

🟡 Order-fallback Date.now() lands echoed-brand-new children at the bottom of the visible list, not "somewhere stable" (tauri-sync-listener.ts:200-201)
The comment says "fall back to Date.now() so it lands somewhere stable rather than getting an undefined propagated through the sort comparator." But Date.now() is ~1.7e12, while fractional orders are typically in [0, 2] — so a "stable" fallback is actually a "land far below every other sibling" fallback. For the receive-side of bob's window seeing a brand-new alice-created child for the first time (so structureTree has no entry yet), the child now appears at the bottom of bob's list. PR #1214 is supposed to mitigate this by ensuring the backend appends at end, but if #1215 lands without #1214 the symptom remains. Worth either:

  1. Asserting both PRs ship together (gating merge order).
  2. Asking structureTree for the parent's current last-child order and using last_order + ε instead of Date.now().

🟡 structureTree.getChildrenWithOrder(parentBare).find(c => c.nodeId === childBare) is O(n) (tauri-sync-listener.ts:194-198)
For a parent with many children, every cloud-echoed relationship:created event scans the children list linearly. For a high-cardinality parent (e.g., a date-page with hundreds of nodes) under a burst of sync echoes this multiplies. Worth either:

  1. A direct structureTree.getOrderOf(parentId, childId) primitive.
  2. A Map-backed index inside structureTree.

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 structureTree has no opinion — backend may still reject (shared-node-store.svelte.ts:1349-1359)

if (siblingActualParent !== null && siblingActualParent !== currentNode.parentId) { /* clear */ }

When structureTree.getParent(siblingId) returns null (sibling not yet in tree), the hint is preserved. The PR body says "the backend can still resolve it via its own retry loop" — meaning we rely on NodeService::create_node_with_parent's sibling-validation retry. That retry exists, but its timeout/budget is finite. If structureTree is stale during a fast Enter-key burst, multiple CREATEs hit the retry path in series, each consuming its own budget. The previous (buggy) behavior was to clear the hint and let the backend pick a default; the new behavior is to keep the hint and rely on retry. Net better, but worth quantifying: how often is getParent null at persistence time during the two-window demo? If it's frequent, the change shifts load onto the retry loop. Add a debug log when siblingActualParent === null so the frequency is observable.

🟡 The new test doesn't exercise the persistence-path decision (shared-node-store-skip-while-editing.test.ts:138-160)
The test ends with expect(structureTree.getParent('a')).toBe('D') — a sanity check on the structureTree primitive, not on the fix. The test even acknowledges: "We can't directly observe the persistence-time decision from here without a Tauri mock." But then this is testing structureTree (which is presumably tested elsewhere), not the fix. Either mock tauriCommands.createNode and assert it's called with the preserved insertAfterNodeId, or move this test alongside one that does. As written, this is a test of the assumption underneath the fix, not the fix itself.

🟡 The fix changes the trust hierarchy without naming it in code (shared-node-store.svelte.ts:1340-1349)
Before: siblingNode.parentId was treated as authoritative. After: structureTree.getParent() is authoritative. The comment explains the failure mode of the old approach but not the new model ("structureTree is the authoritative source for has_child hierarchy; the bare Node.parentId field is opportunistically populated and not always reliable"). Documenting this invariant in one place (perhaps on the Node type or structureTree module) prevents the same pattern from being re-introduced in the next persistence path.

Nits

🟢 Nit: typeof incomingOrder === 'number' correctly handles 0 and negative orders (tauri-sync-listener.ts:188)
Good catch over incomingOrder ?? Date.now() which would have miscoerced null. Worth a one-line comment noting why the typeof check is used instead of ??.

🟢 Nit: rel.properties?.order as number | undefined (tauri-sync-listener.ts:187)
The as cast is unchecked — if properties.order is a string "1.5" from some malformed echo, it sneaks through as a number. Use a runtime check or trust the schema; either way, a one-liner saying which.

🟢 Nit: stripNodePrefix called twice (tauri-sync-listener.ts:183-184)
Pre-existing pattern; not your change. Mentioned only because the new block consolidates the two calls into named locals (parentBare, childBare) — already a clean improvement.

🟢 Nit: The test file imports reactive-structure-tree.svelte inline via await import(...) (shared-node-store-skip-while-editing.test.ts:139)
Mixing top-of-file imports and dynamic imports for the same purpose. Move to top of file unless there's a circular-import or initialization-order reason.

🟢 Nit: Test name is very long (shared-node-store-skip-while-editing.test.ts:138)
does NOT clear insertAfterNodeId when the sibling lacks a populated parentId field but IS in structureTree under the same parent (sync#77) — captures the intent precisely but could be split into setup-then-assert with a shorter it() title.

🟢 Nit: existing?.order ?? Date.now() falls through twice silently (tauri-sync-listener.ts:197)
If structureTree has the child but order happens to be 0 (impossible? worth confirming), existing?.order is 0 → falsy under ?? only if it's null/undefined. ?? correctly preserves 0. OK as-is; worth a comment.

🟢 Nit: PR description acknowledges "frontend half alone is not sufficient"
Honest and clearly stated — keep this style. Add a one-line note in the merged commit message naming #1214's commit SHA so future bisects see the dependency.

Summary

Both 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 Date.now() fallback and the preserve-the-hint fallback both have failure modes worth quantifying, and (b) the test for the stale-sibling fix doesn't actually exercise the persistence path it's claiming to harden. None invalidate the fix; each is a small reinforcement.

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]>
@mstomar125

Copy link
Copy Markdown
Contributor Author

Force-pushed to address review feedback. PR is now rebased on top of the updated #1213.

Main behavioral fix

  • 🟡 Date.now() fallback footgun → replaced with three-tier order resolution: (1) incoming order if numeric, (2) preserved existing structureTree order, (3) for genuinely-new children, lastSibling.order + 1 + tiny jitter (true append-at-end). The bob-side receive path now lands new echoes at the bottom of the visible list with a sensible fractional order, not at `~1.7e12`.

Test improvements

  • 🟡 Extracted the stale-sibling decision into SharedNodeStore.shouldClearStaleInsertAfter(siblingId, currentParentId) — a small public helper the persistence closure calls. The new test exercises the helper directly across three cases (structureTree agrees → preserve, disagrees → clear, no opinion → preserve+log). Locks in the production code path without requiring Tauri IPC mocks.
  • Renamed to a shorter intent-focused test name.
  • Moved the dynamic await import to a top-of-file import.

Performance

  • 🟡 Added a comment naming the O(n) siblings.find and pointing at a future Map-backed primitive on structureTree if it ever becomes a hotspot. Not changed structurally in this PR.

Observability

  • 🟡 Added a debug log when structureTree.getParent returns null at decision time, so the frequency of "tree not yet populated at persistence time" is observable.

Documentation

  • 🟡 The new helper's doc comment explicitly names the trust hierarchy: structureTree is authoritative for has_child; Node.parentId is unreliable and must not be consulted alone.

Nits

  • 🟢 typeof === 'number' is now explicitly documented as the runtime check (rel.properties?.order is typed unknown on the wire; the typeof gate IS the validation).
  • 🟢 stripNodePrefix already consolidated into named locals (existing in original PR).

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.

@mstomar125

Copy link
Copy Markdown
Contributor Author

Pragmatic code review (re-review) — PR #1215

Review Type: Re-Review (scope: force-pushed commit d7e4123a, rebased on updated #1213).
CI: ⏳ Still no checks reported on fix/sync-echo-order-preservation. Same flag as round 1.

Previous review summary

  • Previous 🟡: 5 — addressed: 5.
  • Previous 🟢: 7 — addressed: 4, acknowledged with comments: 3.
  • New findings this pass: 0 🔴, 0 🟡, 2 🟢.

Round-1 findings — disposition

✅ Date.now() fallback footgun — replaced with a three-tier resolution:

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 jitter

Brand-new echoed children now land at lastSibling.order + 1 + ε instead of ~1.7e12. The visible-list placement matches the backend's append-at-end semantic from #1214. Stacked correctness is intact.

✅ Stale-sibling test didn't exercise the persistence-path decision — extracted SharedNodeStore.shouldClearStaleInsertAfter(siblingId, currentParentId) as a small public helper that the persistence closure calls. The new test exercises the helper directly across three cases (agrees → preserve, disagrees → clear, no opinion → preserve+log) and the persistence closure routes through it. Lock-in without Tauri IPC mocks.

✅ O(n) siblings.find(...) on a hot path — comment added naming it explicitly and pointing at a future Map-backed getOrderOf(parent, child) primitive on structureTree. Acceptable to defer; flagged for the next iteration.

✅ structureTree.getParent returns null frequency — debug log added on the null branch of shouldClearStaleInsertAfter, so production frequency of "tree not yet populated at persistence time" is observable.

✅ Trust hierarchy invariant — shouldClearStaleInsertAfter's doc comment names it explicitly: "structureTree is authoritative for has_child; Node.parentId is unreliable and must not be consulted alone." That's the right place for the invariant to live — at the helper that enforces it.

✅ Nits addressed — typeof === 'number' runtime check explicitly documented; await import moved to top-of-file; test name shortened.

New findings

🟢 Nit: Math.random() * 0.001 jitter is unseeded (tauri-sync-listener.ts:204)
Two concurrent windows appending brand-new echoed children to the same parent each pick a random jitter in [0, 0.001). Collision probability is low but non-zero; reproducibility of test scenarios is non-existent. For production this is fine — the fractional-order math tolerates near-collisions. For a future test that wants to exercise "two clients append simultaneously and both land in expected order," seeding (or using a monotonically-increasing client-local counter as the sub-fractional component) would help. Style.

🟢 Nit: lastOrder + 1 jumps by a full integer where local creates use fractional steps (tauri-sync-listener.ts:203)
Local optimistic appends typically use lastOrder + (next - lastOrder) / 2-style fractional steps inside FractionalOrderCalculator. The echo-side append uses +1 + jitter. Practically the two streams never compete (echoes arrive after local placement, and the structureTree-existing branch fires for them), so the discrepancy is invisible. But a long-running sequence of echoes-without-local-state could grow the order space faster than the local path expects. Worth a comment naming the asymmetry, or — better — calling into FractionalOrderCalculator::calculate_order so the two paths produce comparable values.

Summary

Every 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

Mayank Tomar and others added 2 commits May 27, 2026 19:30
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]>
@mstomar125
mstomar125 merged commit a7ee9ea into NodeSpaceAI:main May 27, 2026
malibio pushed a commit that referenced this pull request Jun 22, 2026
…tion

Preserve structureTree order on sync echoes + fix stale-sibling check (fixes nodespace-sync#77, frontend)
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.

1 participant