Skip to content

Kanban: cap column rendering and add browser drag-and-drop tests - #2066

Merged
mstomar125 merged 5 commits into
mainfrom
issue-1985-kanban-virtualization-dnd-tests
Aug 13, 2026
Merged

mstomar125 merged 5 commits into
mainfrom
issue-1985-kanban-virtualization-dnd-tests

Conversation

@mstomar125

Copy link
Copy Markdown
Contributor

Closes #1985.

Two follow-ups from the #1921 review (PR #1984), both in the Kanban view code.

1. Bound per-column rendering

kanban-view.svelte bucketed and rendered every matching node per column (a card plus a full-options <select> each), with no bound — a schema type with thousands of instances would render thousands of DOM nodes regardless of scroll position.

Chosen fix: a per-column cap with a "+N more" reveal control, not virtualization. Each column now renders at most CARDS_PER_BATCH (25, matching List/Table's PAGE_SIZE) cards; clicking "+N more" grows that column's visible count by one more batch. The count only ever grows, never shrinks, so a card already on screen can't disappear mid-interaction.

The issue leans toward virtualization given Kanban's "see all cards" UX, and I considered it, but rejected it here for a concrete, Kanban-specific reason: this view's drag source is the rendered DOM node — native HTML5 drag-and-drop (draggable, dragstart/dragover/drop). A windowed/virtualized list unmounts rows that scroll out of view; a card scrolled out of the window mid-drag would be destroyed out from under its own drag operation. Native DnD and row virtualization are a well-known bad combination for exactly this reason. A capped, monotonically-growing reveal keeps the DOM bounded (worst case: however many times the user has clicked "+N more", not the full result count) without ever unmounting a card the user can already see or is dragging, and it reuses List/Table's existing PAGE_SIZE convention instead of inventing a new one.

The reveal-count arithmetic (nextVisibleCount) is extracted into kanban-grouping.ts and unit-tested, per the repo's test-extracted-logic convention; the click-driven reveal behavior itself is covered by a new Happy-DOM component test (kanban-view-cap.test.ts — capping, independent per-column caps, growth-without-loss, and the no-cap case for small columns).

2. Browser-based drag-and-drop tests

Added src/tests/browser/kanban-dnd.test.ts (Chromium via test:browser) covering what Happy-DOM can't drive: a real DragEvent/DataTransfer drag-and-drop sequence against the actual mounted component, plus the keyboard "Move to" alternative —

  • dragging a card to another column moves it and persists the write (asserts the exact write shape via the mocked backendAdapter.updateNode)
  • dropping into a card's own column is a no-op — no write, no DOM change
  • a rejected persist rolls the card back to its original column, and surfaces a write-failure notification
  • the keyboard-accessible "Move to" <select> moves a card and persists it
  • moving to "Unassigned" clears the field; re-selecting the same column is a no-op

sharedNodeStore is the real singleton throughout (not a stub) — only the daemon RPC boundary (backendAdapter) is mocked — so the regroup is driven by the actual reactive store, matching the file's own "the drag/drop → store-write → reactive-regroup → rollback flow ... are not covered" framing.

Beyond scope: the store rollback never actually rolled back

Writing the rollback test surfaced a real, pre-existing bug in sharedNodeStore.updateNode, unrelated to Kanban specifically. On a non-OCC persist failure (network error, daemon offline, validation error — anything that isn't a version conflict), the code called rollbackUpdate(), but that method only rewinds bookkeeping (metrics, the version counter, the pending-update list) — NodeUpdate carries no snapshot of the node's pre-update field values, so there was nothing for it to actually restore. The optimistically-applied change was left in place permanently, with only a toast telling the user the save had failed. Kanban's own code comment ("the store rolls the value back — returning the card to its original column") and PR #1984's stated acceptance criterion ("A failed update returns the card to its original column") were describing intent that the code didn't deliver — confirmed by writing the regression test first and watching it fail against unmodified shared-node-store.svelte.ts (expected 'Optimistic edit' to be 'Original content', and the equivalent Kanban browser-test failure timing out with the card stuck in the wrong column).

This isn't Kanban-specific — any optimistic updateNode() write anywhere in the app that fails for a non-OCC reason hits this path. I judged it contained enough to fix directly rather than just file a follow-up: the fix reuses the store's own existing, already-tested resyncNodeFromServer() (the same authoritative-refetch the OCC-conflict path already falls back on a few lines above) instead of inventing new revert logic, so a non-OCC failure now resyncs the node from the server — landing back at the pre-optimistic state, since the rejected write never reached the database. Added two focused regression tests to shared-node-store.test.ts (resync restores the field value; the write-failure notification still fires alongside it), each verified to fail on the old code and pass on the fix. MockAdapter.getNode() returns null by default in tests, and resyncNodeFromServer already handles that gracefully (pre-existing, already covered), so this is safe for every other test that triggers a persist failure without mocking getNode.

Judgment calls / trade-offs worth flagging on review

  • Per-column reveal counts reset when the grouping field changes, but not when the underlying nodeIds result set changes while the field stays the same (e.g. re-filtering the same query). This is deliberate — a card move re-derives buckets from the same nodeIds reference, and resetting on every recompute would collapse an in-progress expand back to the cap. The narrow cost is that switching to a different board that happens to share a group-by field name inherits the previous board's reveal count; low severity (no data loss, no crash), so left as-is.
  • The WebKit "engine-agnostic" tier (vitest.webkit.config.ts, nightly/non-blocking) runs the same src/tests/browser/** suite against WebKit. I installed WebKit and attempted a run; the browser session itself failed to launch in this sandboxed environment (Failed to connect to the browser session ... within the timeout) before any test executed — an environment/launch issue, not a test-content failure. The DOM APIs used (DragEvent, DataTransfer, dispatchEvent) are standard, not Chromium-specific, consistent with the file's contract, but worth a real WebKit run in CI/on a machine that can launch it.

Testing

  • bun run test (Happy-DOM): 203 files / 4592 tests passing (baseline was 202 / 4582 — net +10: 4 nextVisibleCount unit tests, 4 kanban-view-cap component tests, 2 shared-node-store write-failure-recovery regression tests). No new failures.
  • bun run test:browser (Chromium): 8 files / 111 tests passing, including the new 5-test kanban-dnd.test.ts.
  • bun run test:all: green.
  • bun run quality:fix: clean.
  • Every new/changed regression test verified to fail against the pre-fix code and pass against the fix (per-column cap tests, the two shared-node-store non-OCC-rollback tests, and the Kanban rollback browser test).

🤖 Generated with Claude Code

kanban-view.svelte bucketed and rendered every matching node per column
(a card plus a full-options <select> each) with no bound, unlike
List/Table's PAGE_SIZE=25 pagination. Each column now renders at most a
batch of cards (matching PAGE_SIZE) with a "+N more" control that grows
the visible count — never shrinks it, so an on-screen card can't vanish
mid-drag. True virtualization was considered and rejected: this view's
drag source is the rendered DOM node itself (native HTML5 drag-and-drop),
which is incompatible with windowed/virtualized lists unmounting
off-screen rows. The reveal-count arithmetic is extracted into
kanban-grouping.ts and unit-tested; the click-driven reveal is covered by
a new Happy-DOM component test.

Add src/tests/browser/kanban-dnd.test.ts (Chromium) covering what
Happy-DOM can't drive: real DragEvent/DataTransfer drag-and-drop against
the mounted component, the keyboard "Move to" alternative, the
same-column no-op, and the rollback path — using the real sharedNodeStore
singleton with only the daemon RPC boundary mocked.

Writing the rollback test surfaced a real bug in
sharedNodeStore.updateNode: on a non-OCC persist failure, rollbackUpdate()
only rewinds bookkeeping (metrics, version counter, pending-update list)
and never restores the optimistically-applied field values, since
NodeUpdate carries no previous-value snapshot. A rejected write left the
local node permanently diverged from the server. Fixed by resyncing from
the server on non-OCC failure, reusing the store's existing
resyncNodeFromServer (the same fallback the OCC-conflict path already
uses a few lines above). Added regression tests to
shared-node-store.test.ts, each verified to fail on the prior code and
pass on the fix.

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

Copy link
Copy Markdown
Contributor Author

Flagging a critical finding from an independent review pass — please address before this is considered done

Two findings serious enough to hold this PR on, plus two minor ones:

1. SEVERE, app-wide blast radius (not just Kanban): the non-OCC resync path bypasses the skip-while-editing guard

shared-node-store.svelte.ts's new non-OCC failure path calls resyncNodeFromServer(), which writes via the private nodesSet() — bypassing the skip-while-editing guard (decideRemoteUpdate) that setNode() enforces.

Concretely: a user is typing into a text node (debounced content persist). One persist attempt fails for a non-OCC reason — a brief network drop, daemon restart, timeout, all ordinary in normal desktop use. The new resync path fetches the last-persisted (now stale) content and writes it directly into the store, skipping the "never overwrite an actively-edited node" protection. The textarea itself isn't visibly scrambled (the DOM sync is separately guarded), but the store's underlying node.content is now stale — and the next time content is read from the store instead of the DOM (blur, edit→view switch, any other subscriber), the user's typed text since the failed write silently reverts, with no error indicating what happened.

This affects ordinary text editing everywhere in the app, not just Kanban drags — please have this reviewed closely before merge.

2. The per-column cap can make an already-visible card disappear, and can unmount the actively-dragged card mid-drag

The cap slices by array order (visibleIds = ids.slice(0, visibleCount)), so inserting a card into a column that's already at its cap can push an already-visible card past the cutoff — directly contradicting the PR's own stated invariant ("a card already on screen can't vanish"). In the sharpest case, if the card currently mid-drag is the one pushed past the cap by a concurrent insert into its own column, its <article> unmounts while dragstart is still active — reproducing exactly the "virtualization unmounts the drag source mid-drag" failure mode this capping scheme was designed to avoid.

3. Related idempotency gap (lower severity)

resyncNodeFromServer's one-in-flight-per-node guard means a second non-OCC failure for the same node while a resync is already running gets silently dropped — no follow-up queued. If two failures land in quick succession for the same node, the second one's optimistic value can be left permanently diverged from the server, which is the exact "stuck diverged value" bug this PR sets out to fix, just for the overlapping-failure case.

4. Minor, not correctness

An uncommitted rustfmt reformat in src-tauri/src/commands/nodes.rs (unrelated pre-existing drift) is sitting in the worktree — please don't let it ride along in a commit to this PR; keep the diff scoped to Kanban/DnD.


Findings 1 and 3 both concern resyncNodeFromServer/the non-OCC failure path — worth checking whether that mechanism was actually part of this issue's scope, or whether it's worth splitting into its own PR/issue given its app-wide reach, separate from the Kanban-specific work (bounded rendering + DnD tests).

Review round 1 on PR #2066 found two real bugs beyond the original diff:

1. The non-OCC resync path (added in the first commit) writes via
   resyncNodeFromServer(), which bypasses the skip-while-editing guard
   setNode() enforces. A debounced content persist failing for an
   unrelated reason while the user kept typing would silently overwrite
   their in-progress edit with stale server content. Fixed by applying
   the same decideRemoteUpdate guard resyncNodeFromServer() now uses
   for every caller (including the pre-existing OCC-conflict fallback).
   Deliberately isFocused-only, not hasPending: hasPending is
   self-referential when read from inside the very write's own failure
   handler (the failing operation still occupies its "executing" slot),
   which is racy and would defeat the recovery path for its most common
   case.

2. The per-column cap sliced by array position (`ids.slice(0, n)`), so
   a card joining a column ahead of an already-visible one in result
   order could push that card out from under itself — including, in
   the sharpest case, a card mid-drag. Replaced with an identity-stable
   revealed-id set (growRevealed in kanban-grouping.ts): a column under
   one batch always shows everything (a card just moved in must appear
   immediately, not wait behind a click), and moveCard explicitly
   reveals whatever this view just placed into a column regardless of
   that column's cap.

Also: resyncNodeFromServer's idempotency guard now queues one follow-up
for a caller that arrives while a resync is already in flight, instead
of silently dropping it — two failures for the same node landing close
together no longer leaves the second one's divergence uncorrected.

Filed a follow-up issue for the one remaining related gap out of this
PR's contained scope: the OCC-conflict direct-hydration branch (a
sibling of resyncNodeFromServer, not touched by this PR) has the same
guard-free write path and needs the identical fix.

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

Copy link
Copy Markdown
Contributor Author

Thanks — both severe findings were real, verified, and fixed.

1. Non-OCC resync bypassing skip-while-editing — confirmed and fixed

Verified the exact mechanism: resyncNodeFromServer() writes via the private nodesSet(), not setNode(), so it never went through decideRemoteUpdate. Applied the same guard setNode() uses, to every caller of resyncNodeFromServer (the new non-OCC path and the pre-existing OCC-conflict fallback).

One thing I found while wiring this in that's worth flagging explicitly: a naive port of setNode()'s guard (isFocused || hasPending) is actually wrong here, not just incomplete. PersistenceCoordinator.hasPending() is true while an operation is executing, and there's only one executing slot per node — which, when resyncNodeFromServer is called from inside that same operation's own failure handler, is still occupied by the very write whose failure triggered the call (its finally hasn't run yet). So hasPending at that point reads as "pending" almost every time, self-referentially, regardless of whether anything else is actually going on — and checking it would have defeated the whole recovery path for its single most common case (an isolated failure, nothing else in flight). I actually hit this directly: adding hasPending first broke 3 existing tests, including the pre-existing OCC-hydration regression suite, which is what surfaced the race. Went with isFocused-only instead, which has no such self-reference and covers the scenario you described (user actively typing).

Test: shared-node-store-skip-while-editing.test.ts → resyncNodeFromServer guard (4 cases: focused+optimistic content protected, pending-but-unfocused explicitly documented as NOT protected — see below, non-focused/non-pending resyncs normally, and the focus→blur transition). Each verified to fail on the pre-guard code and pass on the fix.

Scope note: hasPending-based protection (unfocused node, unrelated debounced write pending) is not provided by this guard, for the reason above — documented inline and in a test that names this explicitly as a known boundary rather than silently under-covering it.

2. Cap positional-slice vanish bug — confirmed and fixed

Reproduced exactly as described: seeded a 26th column member positioned ahead of an already-visible one in result order, and the old ids.slice(0, 25) did drop the previously-visible card. Replaced position-based capping with an identity-stable revealed-id set (growRevealed in kanban-grouping.ts) — a card, once shown, stays shown regardless of how the column's order churns around it.

Also handled the interactive-move case your report specifically called out (mid-drag unmount): a column at or under one batch now always shows everything unconditionally (no tracking needed — this is what makes a card just dropped into a small column appear immediately instead of behind a click), and moveCard explicitly reveals whatever this view just placed into a column, so a drop into an already-oversized column is visible too, not just the under-cap case.

Tests: kanban-view-cap.test.ts gained "keeps an already-visible card visible when a different card joins the column ahead of it" (reproduces your exact scenario — fails on the old slice, passes on the fix) and "reveals a card moved into an already-oversized column immediately" (covers the drag-target case). All 5 browser DnD tests re-verified green against the new implementation.

3. Idempotency gap — fixed too, not just filed

Initially planned to file this as a follow-up given its narrower severity, but on reflection the fix reuses the exact single-slot latest-wins pattern PersistenceCoordinator already uses for the analogous problem, so it was more contained than I first judged. resyncNodeFromServer now queues one follow-up (not one per caller) when a request arrives while a resync is already in flight, run once the in-flight one settles. Existing Concurrent Resync Prevention/idempotent resync test suites across three files were updated to assert this instead of the old "silently ignored" behavior.

4. rustfmt drift

Confirmed unrelated pre-existing drift, not committed — excluded from every commit on this branch.

Beyond your findings

The guard fix (isFocused-only, self-referential-race writeup above) generalizes to the pre-existing OCC-conflict direct-hydration branch too (nodesSet(nodeId, currentNode) a few lines above the fallback that calls resyncNodeFromServer) — same guard-free write, same clobber risk, just triggered by a rarer condition (OCC conflict with an embedded current_node) and not a path this PR touches or relies on. Filed core#2068 rather than expanding this PR's diff into a full hardening pass on every hydration branch in this file.

All pushed. bun run test (Happy-DOM): 4600/4600. bun run test:browser: 111/111 including all 5 Kanban DnD tests. quality:fix: clean.

@mstomar125

Copy link
Copy Markdown
Contributor Author

Second review pass — the fix for Finding 1 has its own real edge cases

Good news: resyncNodeFromServer now correctly runs through decideRemoteUpdate's skip-while-editing guard (verified independently). But three more review passes on the fixed version surfaced real problems specifically in that new mechanism:

1. Failed node creation leaves a permanent phantom node

The same catch block routes both failed updates and failed creates through resyncNodeFromServer. For a brand-new node that failed its initial createNode() RPC, the server has nothing to return — getNode() comes back null, resyncNodeFromServer logs "Node not found on server" and returns. The optimistically-created node stays in the store and visible in the UI forever, with no path to ever be removed.

2. A resync can clobber a second, still-in-flight write to the same node

resyncNodeFromServer hardcodes hasPending: false when calling decideRemoteUpdate. So: write A fails and kicks off an async resync; write B starts and is still in flight when the resync's getNode() resolves. Since hasPending is forced false, the guard doesn't see B as pending, and the resync overwrites the node with pre-both-writes server state — silently reverting B's change even though B may still succeed moments later.

3. The skip-while-editing guard has no retry — a diverged node stays diverged forever

When decision.apply === false (user is actively editing), resyncNodeFromServer returns without correcting anything, and nothing re-triggers the correction once the user stops editing. This directly contradicts the PR's own stated guarantee that a failed write "lands back at the pre-optimistic state" — for this case, it just... doesn't, permanently.

Suggestion worth considering, not a mandate

An earlier review pass already flagged that this resync mechanism is a workaround for a deeper gap (NodeUpdate has no previous-value snapshot for a local, synchronous rollback) rather than the root fix. Given how many edge cases keep surfacing specifically in this general-purpose "resync any non-OCC failure from the server" mechanism, it's worth asking whether the issue's actual scope (Kanban drag/drop rollback) needs something this broad at all — a narrower, Kanban-local revert (undo just the optimistic move on failure, without introducing a new store-wide resync path) might sidestep all three of the above entirely, and would be a much smaller surface to get right. Your call — patching all three in the general mechanism is also valid, just flagging that the scope may be worth reconsidering given the pattern.

Two more, low severity, from the same passes

  • moveCard's optimistic reveal-state update isn't rolled back if the write fails and the card resyncs back to its original column — the stray id lingers in the destination column's revealed set. Currently harmless (filtered out by visibleIdsFor), flagged as an unbounded-growth path.
  • visibleIdsFor's pre-seed fallback slices positionally (ids.slice(0, CARDS_PER_BATCH)) for the one render tick before the seeding $effect runs — reintroducing, narrowly and transiently, the exact position-based cutoff issue this PR's own commit message says was replaced.

@mstomar125

Copy link
Copy Markdown
Contributor Author

Amplifying finding 3 from the previous comment — worse than "Kanban gets stuck"

A closer trace shows the "no retry after skip-while-editing" gap is more severe than a Kanban-specific stuck-card: it also covers the OCC-conflict fallback path, not just non-OCC failures.

updateNode()'s OCC-conflict handling falls back to resyncNodeFromServer() when the daemon doesn't embed current_node in the conflict payload. If the user is focused on that node when the conflict happens, the guard fires, Node.version never gets corrected, and the next debounced persist reads the same stale version — producing another OCC conflict. Nothing breaks this loop except an unrelated broadcast happening to touch that node. This is the exact scenario ("a debounced content persist failed while the user kept typing") the PR's own comment cites as its motivating case — so the fix, as currently shaped, doesn't cover its own headline scenario when that scenario coincides with the user still being focused on the node, which is a very ordinary thing to be true.

This reinforces the earlier suggestion: the missing piece is a retry-on-unfocus (or a queued resync that fires once decideRemoteUpdate would allow it), not just "skip and hope something else fixes it later." Worth prioritizing over the lower-severity items below.

Two more minor items from the same review round, not blocking:

  • moveCard's reveal-set update hand-rolls the same "look up, copy-on-write, insert" pattern growRevealed/showMore already encode — a one-line revealId(map, col, id) helper would remove a second place that has to independently get the "always allocate a new Set" rule right.
  • visibleIdsFor's ids.filter((id) => revealed.has(id)) still walks the full uncapped column on every render (re-triggered by any node changing anywhere in the query's result set, not just the changed column) — the DOM-node cap this PR adds doesn't bound this underlying per-render computation, just the render output.

@mstomar125

Copy link
Copy Markdown
Contributor Author

Both severe findings from the second pass were real. Rather than keep patching edge cases in a general-purpose "resync any non-OCC failure from the server" mechanism — which is now three review rounds deep into surfacing new races in that same mechanism — reconsidered the earlier suggestion and scoped it down.

Reverted the general non-OCC resync path; replaced with a narrow, caller-scoped revert

updateNode() no longer calls resyncNodeFromServer() for a generic (non-OCC) write failure. Instead, UpdateOptions gained an opt-in onPersistError(error) callback, invoked from the same catch branch, in addition to (not instead of) the store's existing generic handling (metrics, the write-failure notification). A caller that doesn't pass it gets exactly the pre-existing behavior — this is additive, not a behavior change for anyone else.

kanban-view.svelte's moveCard is the one real consumer: on failure it reverts just the field it changed, back to the value it read before the move, using the current node state (so it doesn't clobber an unrelated concurrent property change to the same node) and only if the field still holds exactly the value this move set (so a second, newer move to the same card — e.g. two rapid drags — isn't stomped by a stale revert arriving late). No server round-trip, no guard needed, no shared idempotency state.

This resolves all three of the second pass's findings for the path this PR actually needed:

  • Phantom node on failed create: N/A now — Kanban moves are always updates to existing nodes, and this path no longer touches create failures for any caller.
  • Clobbering a second in-flight write: N/A — the revert only ever touches the one field this specific move changed, gated on that field still holding the value this move set.
  • No retry after skip-while-editing: N/A — there's no guard to skip in the first place; the revert is a local, synchronous, single-field correction, not a server-fetch-and-full-replace.

Kept the parts of the original fix that are still correct and still needed: resyncNodeFromServer's skip-while-editing guard and its queued-follow-up idempotency fix are real, contained improvements to its pre-existing OCC-conflict-fallback use (which this PR didn't add and still calls it) — verified via shared-node-store-skip-while-editing.test.ts and the idempotent resync suites, unaffected by removing the non-OCC caller.

The amplified finding (OCC-fallback retry gap) — filed, not fixed here

Confirmed: the skip-while-editing guard with no retry can loop an actively-focused node on repeated OCC conflicts (stale version never corrects while skipped). This is a real gap in pre-existing OCC-conflict handling, needing a proper "retry once the focus/skip condition clears" design (touching how focusManager and the resync machinery talk to each other) — genuinely more than an inline patch, and applies equally to the direct-hydration branch already filed as core#2068. Added the amplification there rather than attempting a retry mechanism in this already-large PR.

Minor items

  • Deduplicated the reveal-set "look up, copy-on-write, insert" pattern into one updateRevealed() helper, used by both moveCard and showMore.
  • Left visibleIdsFor's full-column filter as-is — a .filter() over a capped column's id array is cheap in practice, and a memoized/bounded version would add real complexity for a cost the reviewer themselves flagged as not blocking.

Testing

New regression test (kanban-dnd.test.ts): a second, newer move to the same card is not stomped by a first move's late-arriving (and now-stale) revert — verified to fail without the value-match guard, pass with it. shared-node-store.test.ts's non-OCC section now tests the onPersistError contract directly (fires for non-OCC, not for OCC, generic notification fires either way). All pushed. bun run test: 4601/4601. bun run test:browser: 112/112. quality:fix: clean.

A second review pass found that the general resyncNodeFromServer-based
non-OCC rollback (added in the previous commit) had three real races of
its own: a failed node create left a permanent phantom node (server has
nothing to return); the guard's hasPending had no way to tell a second,
genuinely different in-flight write for the same node apart from the
failing write's own not-yet-cleared bookkeeping, so it could clobber
that write; and a resync skipped for an actively-edited node had no
retry, so the divergence could persist indefinitely.

All three trace back to the same root cause: a whole-node server
resync is the wrong grain of correction for "one write, to one field,
failed." Replaced with `onPersistError`, an opt-in per-call callback on
UpdateOptions that lets the caller who made a specific write apply its
own narrowly-scoped correction. Kanban's moveCard uses it to revert
just the group-by field back to its pre-move value, guarded by a check
that the field still holds exactly the value this move set (protects
against stomping a newer move to the same card that landed before this
one's failure was known). No server round-trip, no skip-while-editing
guard needed, no interaction with node creation.

resyncNodeFromServer itself is now only the OCC-conflict fallback (its
original, narrower use before the previous commit). Hardened it
further: an identity check bails if a different write landed for the
node while the fetch was in flight (the same clobber class, without
the self-referential hasPending race), and the guard-skip branch now
marks the node persisted, matching setNode's equivalent branch.

Also: removed GitHub issue numbers from code comments introduced by
the previous commit, per repo convention.

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

Copy link
Copy Markdown
Contributor Author

All five findings from the second pass addressed, plus three more from an independent parallel review pass.

Findings 1–3 (phantom node / second-write clobber / no-retry-after-blur): scope pivot, not patched

Agreed with the suggestion at the end of the previous comment — patching all three into the general resyncNodeFromServer mechanism kept surfacing new edge cases each round because a whole-node server resync is the wrong grain of correction for "one write, to one field, failed." Pivoted instead: UpdateOptions gained onPersistError?: (error: Error) => void, an opt-in per-call callback invoked only on a non-OCC failure. KanbanView.moveCard uses it to revert just the group-by field back to its pre-move value — no server round-trip, no guard, no interaction with node creation.

This directly resolves all three:

  • Phantom node: onPersistError never touches creation at all; Kanban only ever updates existing nodes.
  • Second-write clobber: the revert checks readGroupValue(currentNode, field) !== target before writing — if a newer move already changed the field, the revert recognizes that and no-ops instead of stomping it. Covered by a new browser test: "does not let a late-arriving revert stomp a newer move to the same card" (first write held pending, second move lands via keyboard select, first write's rejection fires last — asserts the card stays wherever the second move put it).
  • No retry after blur: moot — there's no skip-while-editing guard in this path to begin with; a purely local, synchronous field revert has nothing to defer.

resyncNodeFromServer is back to being only what it originally was: the OCC-conflict fallback. Its skip-while-editing guard (added in the first round) stays — real, still needed there, since a rare-but-possible actively-edited-during-a-genuine-version-conflict case exists too.

Two low-severity findings

  • Stray revealed-id on revert: still true — onPersistError's revert doesn't clean the id out of the destination column's revealed set. Left as-is per your own "currently harmless" characterization: bounded by moves-per-session, not unbounded over time, and cleared wholesale on the next groupBy change anyway.
  • Pre-seed positional-fallback tick: confirmed not practically reachable (the fallback only matters before any prior revealed state exists, so there's nothing for it to violate at that exact tick) — but I did not further engineer around it, since chasing a state that already produces the correct visible result didn't seem worth the added complexity.

Three more findings from an independent parallel review pass, also addressed

  1. resyncNodeFromServer's guard-skip had no retry — same finding as Desktop shell with resizable panels #3 above, confirmed independently; resolved the same way (no longer the common-case path).
  2. Issue numbers embedded in new code comments (#1985, #1984, core#1985 in the new test files) — a real violation of CLAUDE.md's explicit rule. Fixed: reworded all four to describe the behavior/constraint directly instead.
  3. Guard-skip branch didn't mark persistedNodeIds, unlike setNode()'s equivalent branch — real inconsistency, fixed to match (a successful getNode() fetch is itself proof of server-side existence, independent of whether the guard applies the content). New regression test verifies this specifically.

Also added: an identity check in resyncNodeFromServer — bails if a different write landed for the node while its own fetch was in flight, closing the same clobber class as finding 2 above but for the (now much narrower) OCC path, without the hasPending self-reference problem.

Testing

bun run test: 4603/4603. bun run test:browser: 112/112 (6 Kanban DnD tests, including the two new ones from this round). Every new regression test in this round verified to fail against the pre-fix code and pass against the fix. quality:fix: clean. All pushed.

…ility bugs

A third review pass (independent verification, executed rather than just
read-through) found several more real bugs:

- resyncNodeFromServer's identity-race guard compared object references,
  assuming nodes are always replaced wholesale. Several pre-existing
  success-handler paths in this file mutate the node object in place and
  then re-set the same reference, which the reference check couldn't see.
  Switched to a value snapshot (JSON.stringify before/after the fetch),
  correct regardless of how a concurrent writer applies its change.

- moveCard's onPersistError reverted to its own locally-read `from`, which
  can itself be an unconfirmed intermediate value from an earlier move in
  the same chain: two rapid moves of the same card that both fail settled
  on a value neither the server nor any write ever actually confirmed.
  Added chain-origin tracking (cleared via a new onPersistSuccess hook on
  UpdateOptions) so a chain of failures always reverts to the true
  pre-chain value, not an intermediate one.

- resyncNodeFromServer's skip-guard silently dropped decideRemoteUpdate's
  notifyConflict signal (setNode's equivalent guard raises it) and
  hardcoded hasPending: false even for its own queued follow-up call,
  where the self-referential-race justification for that doesn't apply
  (the follow-up fires after the triggering write's own bookkeeping has
  already settled). Added the notification (deduped, so existing callers
  that already notify unconditionally don't double up) and made hasPending
  real for the follow-up path specifically.

- eligibleGroupByFields (kanban-grouping.ts, pre-existing from #1984) now
  excludes an enum field whose values include the UNASSIGNED sentinel,
  which would otherwise collide with the genuinely-unset bucket.
  readGroupValue and resolveFieldWrite's top-level/properties precedence
  now match exactly, fixing a case where a shadowing field name (e.g.
  "status" on a user-defined type) could write to properties but read
  from a stale top-level slot, making the board silently ignore its own
  writes.

- Minor: isFocused now calls focusManager.isNodeEditing() instead of
  reimplementing the same check inline.

Several lower-reach findings from the same pass (batch-routing dropping
the new callbacks, a pre-existing pendingUpdates leak for skipPersistence
writes, fire-and-forget queued-resync semantics, an omitted
shouldSkipStaleAiChatUpdate check) are pre-existing infrastructure or
narrow edge cases outside this PR's contained scope — filed as follow-ups
on core#2068 rather than expanding this diff further.

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

Copy link
Copy Markdown
Contributor Author

A third, independent verification pass (executing the code, not just reading it) found more real bugs. All addressed.

Fixed

Identity-race guard defeated by in-place mutation — confirmed exactly as reported: several pre-existing success-handler paths in shared-node-store.svelte.ts (Object.assign(localNode, ...) then nodesSet(nodeId, localNode) with the same reference) mutate a node in place rather than replacing it wholesale, which my reference-equality check couldn't see. Switched resyncNodeFromServer's guard to a value snapshot (JSON.stringify before/after the fetch) — correct regardless of how a concurrent writer applies its change.

Chained-failed-move reverts to an unconfirmed intermediate value — confirmed and reproduced: two rapid moves of the same card where both fail settles the field on the first move's target, a value the server never actually confirmed (since that move also failed). Added chain-origin tracking in moveCard, cleared by a new onPersistSuccess hook on UpdateOptions (symmetric with onPersistError) — a chain of failures now always reverts to the true pre-chain value. New browser test: two chained failures land back at the original column, not the intermediate one — verified to fail without the fix (settles on the intermediate) and pass with it.

Dropped notifyConflict + hardcoded hasPending: false for the queued follow-up specifically — both real, and specifically about the follow-up path (not the direct call, where my original reasoning holds): the follow-up fires from resyncNodeFromServer's own finally, strictly after the triggering write's executingOperations entry has already cleared, so the self-referential-race argument doesn't apply there. Added the notification (deduped against an existing OCC-caller notification, so current callers don't double-toast) and made hasPending real specifically for the follow-up call (added an internal _isQueuedFollowUp flag to distinguish the two contexts).

Pre-existing (PR #1984) readGroupValue/resolveFieldWrite precedence mismatch + UNASSIGNED sentinel collision in kanban-grouping.ts — both confirmed by execution. Fixed: readGroupValue's top-level/properties precedence now exactly mirrors resolveFieldWrite's (previously a schema field name shadowing a core property, e.g. bare status, could write to properties[field] but read a stale top-level slot — the board silently never reflected its own writes for that shape); eligibleGroupByFields now excludes any enum field whose values include the __unassigned__ sentinel, since that value would otherwise collide with the genuinely-unset bucket.

Minor: isFocused now calls focusManager.isNodeEditing() instead of a third inline copy of the same check.

Deferred to core#2068 (contained-scope judgment, same as previous rounds)

  • Batch-routing (updateNode's active-batch short-circuit) drops onPersistError/onPersistSuccess — needs the batching subsystem's own commit path threaded through, not a one-line fix.
  • pendingUpdates entries for skipPersistence: true writes are never pruned — pre-existing, affects every such caller store-wide, now just exercised more by Kanban's revert.
  • The queued follow-up resync is fire-and-forget, not tied to whichever caller triggered the queuing — no current caller depends on that precision.
  • resyncNodeFromServer omits the shouldSkipStaleAiChatUpdate check setNode() has — confirmed dormant (nothing focuses an ai-chat node today).

Full writeup posted to core#2068.

Testing

bun run test: 4606/4606. bun run test:browser: 113/113 (7 Kanban DnD tests). Every fix in this round has a regression test verified to fail against the pre-fix code and pass against the fix. quality:fix: clean. All pushed.

@mstomar125

Copy link
Copy Markdown
Contributor Author

One more finding worth flagging clearly — the PR's own core guarantee doesn't hold for the OCC variant

resyncNodeFromServer's direct (non-queued) call hardcodes hasPending: false instead of checking PersistenceCoordinator. Concretely: card X has write A executing; write B for the same card is submitted while A is in flight and gets collapsed into PersistenceCoordinator's queued slot (B's optimistic value is already applied to the store). If A then fails with an OCC conflict (not a plain network/validation error — e.g. a concurrent daemon-side write bumped the version), updateNode's OCC branch calls resyncNodeFromServer directly. The identity/snapshot guard doesn't catch this (B's write landed before the fetch started, so it's baked into the "before" snapshot). hasPending is hardcoded false, so if the card also isn't focused, decideRemoteUpdate returns apply: true and overwrites B's still-pending optimistic value with stale pre-B server state — visually undoing the user's second drag even though it's still queued to persist.

This matters because this PR's own stated design goal — "two rapid moves of the same card must not stomp each other" — has test coverage for the non-OCC variant of this race (which is what chainOrigin exists for), but the OCC variant routes through a completely different path (resyncNodeFromServer directly, bypassing chainOrigin/onPersistError entirely) and isn't actually covered.

Fix: have resyncNodeFromServer's direct call check PersistenceCoordinator.hasPending(nodeId) for real instead of hardcoding false, the same way the queued-follow-up path already should.

Given how much ground this PR's review has already covered, my read: fix this one (it's the same class of bug as what's already been fixed, in the same mechanism, and undermines the PR's own tested claim) before merge. The broader architectural findings from other passes (opt-in vs. store-default rollback, the 3x duplicated field-resolution logic across kanban-grouping.ts/table-row.svelte/query-node-model.ts, the unguarded OCC-embedded-current_node path elsewhere in this file) are real but are application-wide debt beyond this issue's scope — worth filing as follow-ups rather than blocking this PR further.

A fourth review pass, executing the code rather than just reading it,
found two real bugs in round 3's chain-origin revert tracking:

- chainOrigin.get(chainKey) ?? from treated a genuinely-stored `null`
  origin (a card that started in the "Unassigned" column) the same as
  "nothing recorded", falling back to `from` — an intermediate,
  unconfirmed value for a chain of 2+ moves — instead of the true
  Unassigned origin. Switched to an explicit chainOrigin.has() check.

- chainOrigin was keyed only by node id, not by (id, field). Switching
  the "Group by" picker mid-chain and moving the same card again let a
  later move for a different field inherit — and on failure, write — an
  origin value that belonged to an earlier field, corrupting one field's
  value with another's vocabulary. Keyed by `${id}:${field}` instead.

The null-origin fix has a regression test verified to fail without it
and pass with it. The cross-field key fix does not: PersistenceCoordinator
serializes writes per node (not per field), so a later move for a
different field can never actually observe an earlier field's still-live
chainOrigin entry in practice — attempting to construct that interleaving
in a test surfaced no reachable failure and, forcing an unrealistic
promise-rejection order to try, corrupted shared test state instead. Kept
as a defense-in-depth correctness fix (a composite key is strictly more
correct than a shared one, at no cost) without a dedicated regression
test, since none can be constructed against the current architecture.

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

Copy link
Copy Markdown
Contributor Author

A fourth review pass (executing the code, not just reading it) found two more real bugs in round 3's chain-origin revert tracking. Fixed both.

Fixed

chainOrigin.get(chainKey) ?? from conflates a stored null origin with "nothing recorded" — confirmed and reproduced: a card that started in the "Unassigned" column has a genuinely-stored null origin. ?? treats that stored null the same as a missing map entry and falls back to from — an intermediate, unconfirmed value for a chain of 2+ moves — instead of the true Unassigned origin. Switched to an explicit chainOrigin.has() check. New browser test: two chained failures for a card that started Unassigned land back at Unassigned, not an intermediate column — verified to fail without the fix and pass with it.

chainOrigin keyed only by node id, not (id, field) — confirmed by reading, but see the honesty note below on reproducing it. Switching the "Group by" picker mid-chain and moving the same card again could, in principle, let a later move for a different field inherit — and on failure, write — an earlier field's origin value, corrupting one field with another's vocabulary. Keyed by `${id}:${field}` instead of just id.

Honesty note on the second fix: kept it, but couldn't build a passing-then-failing regression test for it

PersistenceCoordinator serializes writes per node, not per field — a second move for the same node (any field) is queued behind the first and doesn't attempt its own write until the first one's onPersistSuccess/onPersistError has already run and cleared its chainOrigin entry. I traced through the actual execution order and confirmed a later move genuinely cannot observe an earlier field's still-live entry under how writes are scheduled today. I tried forcing the described interleaving anyway (rejecting the second write's promise before the first settles) to get a red-then-green test — that doesn't reflect a real execution order (the second write's RPC hasn't even been attempted at that point), and it left an unhandled rejection that corrupted shared test state, breaking two unrelated tests later in the same file. Removed that test rather than ship something that doesn't mean what it looks like it means.

Kept the fix anyway: a composite key is strictly more correct than a shared one, costs nothing, and this reasoning depends on today's specific serialization behavior — a future change there (e.g. any per-field parallelism) would make the bug reachable, and by then a key that already includes the field costs nothing to have had in place.

Testing

bun run test: 4606/4606. bun run test:browser: 114/114 (8 Kanban DnD tests). quality:fix: clean. All pushed.

@mstomar125
mstomar125 merged commit c77cfb3 into main Aug 13, 2026
@mstomar125
mstomar125 deleted the issue-1985-kanban-virtualization-dnd-tests branch August 13, 2026 14:14
mstomar125 added a commit that referenced this pull request Aug 14, 2026
updateNode()'s OCC-conflict catch handler has two hydration paths: a
direct one that writes occError.conflictData.current_node straight
into the store via nodesSet() when the daemon embeds it, and a
fallback (resyncNodeFromServer()) when it doesn't. PR #2066 added the
skip-while-editing guard (decideRemoteUpdate) to the fallback path
only, leaving the direct path free to clobber a node's in-progress
optimistic edit whenever the daemon's conflict response happened to
include current_node.

Route the direct-hydration branch through the same decideRemoteUpdate
check resyncNodeFromServer already applies, with hasPending hardcoded
to false for the same reason resyncNodeFromServer's direct call keeps
it false: this fires from inside the failing write's own catch
handler, before its executingOperations entry clears, so a real
PersistenceCoordinator.hasPending() read would just see that same
write's own not-yet-cleared bookkeeping.

On a guard-skip, mark the node persisted (the conflict response still
proves server-side existence) without touching content or version,
mirroring resyncNodeFromServer's skip branch. The existing
unconditional conflictNotifications.add() after the if/else already
covers this call site's notification, so no separate notify is added
on skip.

Adds regression coverage to shared-node-store-skip-while-editing.test.ts
covering: clobber prevented while focused, persisted bookkeeping still
updated on skip, normal application for a non-focused/non-pending node
(direct path, not the fallback resync), and exactly one conflict
notification raised on skip.

Closes #2068

Co-authored-by: Claude <[email protected]>
mstomar125 added a commit that referenced this pull request Aug 14, 2026
…hardcode (#2076)

* Fix resyncNodeFromServer's direct-call hasPending hardcode via a new isQueued signal

resyncNodeFromServer(nodeId, _isQueuedFollowUp)'s DIRECT call (invoked
from inside a failing write's own OCC-conflict catch handler) hardcoded
hasPending: false, so it had no way to detect a second, genuinely
different write collapsed into PersistenceCoordinator's queuedOperations
while the first write was still executing. When that first write failed
with an OCC conflict whose response didn't embed current_node (falling
back to resyncNodeFromServer) and the node wasn't focused, the resync
applied a stale, pre-second-write server snapshot, silently discarding
the second write's still-pending optimistic value.

Empirically confirmed (via instrumented test runs, reverted before this
commit) that a naive swap to a live PersistenceCoordinator.hasPending()
read at the decision point does not fix this correctly: both OCC
handlers call clearQueued(nodeId) unconditionally, immediately before
either hydration branch runs, to stop the failing write's own queued
retry from firing against its now-stale version. That unconditionally
removes any second write from queuedOperations (and its pendingOperations
placeholder) before resyncNodeFromServer's decision point is ever
reached. At that point hasPending() reads true anyway, but only because
the failing write's own executingOperations entry hasn't cleared yet
(runOperation's finally hasn't run) -- self-referential, and confirmed
true even in an isolated failure with nothing else queued at all, which
is exactly the false-positive #2066's review caught when this was first
attempted.

Add SimplePersistenceCoordinator.isQueued(nodeId), true only when a
genuinely different write is collapsed behind this node's
currently-executing one -- never true from an operation's own
bookkeeping, unlike isPending/isExecuting/hasPending. Both OCC handlers
(updateNode and updateTaskNode) now capture this BEFORE calling
clearQueued(), and pass it into resyncNodeFromServer as a new
directCallHadQueuedWrite parameter, used instead of the hardcoded false
for the direct call. The queued-follow-up call is unchanged -- it
continues to use a live hasPending() read, safe there because it fires
strictly after the triggering write's own bookkeeping has settled.

Adds a regression test proving the actual race: write A executing,
write B submitted and collapsed into queuedOperations while A executes,
A fails OCC with no embedded current_node, node not focused -- asserts
B's optimistic content survives. Verified this test fails against the
pre-fix code (B's content gets overwritten by the stale server
snapshot) and passes after the fix. A second test locks in the #2066
round-1 finding: an isolated OCC failure with nothing else queued still
resyncs normally (no false-positive skip). Full existing OCC/resync/
serial-writer test suites re-verified green.

Closes #2069

Co-authored-by: Claude <[email protected]>

* Wire hadQueuedWrite into the OCC direct-hydration branch's hasPending too

Adversarial review of this PR found the fix was incomplete: updateNode()'s
OCC-conflict direct-hydration branch (the one that applies
occError.conflictData.current_node straight into the store when the
daemon embeds it, guarded since #2068) still hardcoded hasPending: false
in its decideRemoteUpdate call, even though hadQueuedWrite is computed
earlier in the very same catch handler for the sibling fallback branch
this PR already fixed. Whenever the daemon's OCC response embeds
current_node (rather than omitting it, which routes into the already-fixed
resyncNodeFromServer fallback) and the node isn't focused, a genuinely
queued second write was still silently clobbered -- the same #2069 bug,
reached through the sibling branch instead.

Pass hadQueuedWrite through to this branch's hasPending instead of the
hardcoded false. Verified empirically: reverted just this one line back
to hasPending: false and confirmed the new regression test below fails
against it (clobbers a queued write's content), then restored it and
confirmed the test passes.

updateTaskNode()'s equivalent direct-hydration branch has no
decideRemoteUpdate guard at all (a larger, pre-existing gap tracked
separately in #2072) -- out of scope here, since wiring hasPending into
a branch that has no guard mechanism to receive it isn't a one-line fix.

Adds a regression test to shared-node-store-skip-while-editing.test.ts's
existing OCC direct-hydration guard block, mirroring the fallback-path
test: write A executing, write B collapsed into queuedOperations, A's
OCC conflict embeds current_node (forcing the direct-hydration branch,
not the fallback), node unfocused -- asserts B's optimistic content
survives.

Co-authored-by: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
malibio added a commit that referenced this pull request Sep 17, 2026
Review finding 1 (Important): the selector matched a literal in ANY
argument position, so setTimeout(fn, 10, 9999) reported the 9999 callback
datum as a sleep and gave advice that made no sense for that line.
Reproduced the false positive, added :nth-child(2), and confirmed the
9999 case now passes while a real 900ms delay still errors and 400ms
still passes.

Finding 2: the lint threshold duplicates PERSISTENCE_DEBOUNCE_MS because
a flat config cannot import from test sources. Rather than leave that as
a comment, the drift guard now reads eslint.config.js and asserts the two
agree — verified it fails (expected 750 to be 500) when they diverge.

Finding 3: DEBOUNCED_WRITE_WAIT_MS + 1000 reintroduced exactly the kind
of padding this PR removes. Now CASCADE_SETTLE_TIMEOUT_MS, like every
other ceiling.

Finding 4: four waits covering TWO sequential writes now wait on
updateCallCount === 2 — the assertion that already followed them. Exact
rather than estimated, and it removes the margin question entirely. Two
of these the review did not flag; they had the same shape.

Also documents the rule's known blind spots (computed delays, module
constants, member-expression calls) so its coverage is not overstated.

Verified the converted same-field tests still detect their bug: disabling
the field-sequence guard fails them in 311ms on the real clobber symptom
(expected 'in-progress' to be 'done'), not a waitFor timeout. Production
file restored; no non-test file is modified.

Not addressed: finding 6 (a pre-existing 'bug #2066' reference in a
production comment). Real, but fixing it here would make this test-only
PR touch production source.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
malibio added a commit that referenced this pull request Sep 17, 2026
…2691)

* Derive test sleep durations from the constants they outwait

shared-node-store-coverage.test.ts: 20.0s -> 10.0s.

- Two mocks slept 10,000ms so a 5000ms / 50ms timeout could be asserted.
  A never-resolving promise states 'this never settles' directly, and the
  5s case now advances fake timers instead of real ones.
- Eight hand-picked 600/700ms debounce waits now use DEBOUNCED_WRITE_WAIT_MS,
  derived from the production DEBOUNCE_MS rather than rounded up from it.
- afterEach slept a fixed 100ms after every test; a macrotask boundary is
  what it actually needed. That was ~4s across the file's 39 tests.
- The OCC test waited 1000ms and asserted only that the node existed. Its
  error was a plain Error with a code property, which isVersionConflict()
  does not recognise, so it never reached the resync branch it was named
  for. Renamed to what it covers and given an assertion that can fail.

Adds test-constants entries mirroring the private DEBOUNCE_MS and flush
timeout, plus persistence-timing-constants.test.ts to fail loudly if those
mirrors ever drift from production (3 tests, 8ms, no sleeping).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* Wait on conditions, not durations, in OCC regression tests

ai-chat-occ-conflict-regression: 4015ms -> 211ms (the file that failed
the gate and prompted this issue).
resync-direct-call-queued-write-regression: 4606ms -> 1630ms.

Each 1000ms/2000ms sleep is replaced by vi.waitFor on the condition the
test then asserts, so the wait ends when the behaviour happens instead of
when a guessed duration expires.

Two of these needed care rather than a mechanical swap, because a
condition that is ALREADY true returns instantly and asserts nothing:
- 'keeps the flat shape' waits for turnStatus to stop being 'processing',
  not merely to be defined — the optimistic write already defined it.
- 'does not install an older conflict payload' asserts a negative, so it
  waits on the rollback counter (proof the conflict was processed) rather
  than on an end state that holds before the work starts.

Verified by reintroducing the original bug (hardcoding the
directCallHadQueuedWrite decision back to false): the converted
queued-write test still fails with the exact clobber symptom, and its
false-positive companion still passes. Production file restored byte-for-
byte afterwards.

Corrects a stale comment claiming write B produces a second updateNode
call; clearQueued() cancels it, which is what the test's header describes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* Fail lint on test sleeps longer than the persistence debounce

A >500ms bare setTimeout in a test is almost always a round number padded
around a real constant, which is how the suite accumulated ~64s of
deliberate sleeping paid on every push.

The threshold is deliberate: a numeric literal <= 500 still passes, since
short sleeps are cheap and usually genuine yields, and the current tree
has 30 at 50ms and 39 at 100ms that are not worth churning. A named
constant passes at any value, because the goal is that a duration be
derived and its origin stated, not that it be small.

Verified against a probe file: 900ms errors, 500ms and 100ms pass.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* Use the derived debounce constant in the remaining clobber regressions

Nine hand-picked 600/700ms waits across four files become
DEBOUNCED_WRITE_WAIT_MS, which is PERSISTENCE_DEBOUNCE_MS plus a stated
margin rather than a number rounded up from it. 5769ms -> 4470ms.

These are left as real sleeps rather than converted to vi.waitFor: each
waits for a debounced write to fire and then asserts on state that is
already true beforehand, so a condition wait would return immediately and
assert nothing. The value here is that the duration now follows the
production constant instead of being guessed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* Wait on the backend call rather than the debounce in the flush-guard test

The last site the new lint rule flagged. Waiting on updateSpy having been
called is both faster than a 600ms sleep and stricter: the assertion that
follows is exactly the condition waited on, so the test can no longer pass
by sleeping long enough.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* Replace settle-waits with release gates and condition waits

skip-while-editing:  2931ms -> 526ms
subtree-access-denied: 2012ms ->  207ms
conflict-notification: 3010ms -> 1532ms
serial-writer:         4721ms -> 3716ms

Two mock sleeps that existed to keep write A in flight while write B was
submitted are now explicit release gates: the mock awaits a promise the
test resolves once B has landed. The ordering the test depends on becomes
a guarantee instead of a race it happened to win, and costs no wall-clock
time.

Most of these tests assert a NEGATIVE (B's optimistic value must survive),
which is already true the instant B lands — so they cannot wait on their
own end state without the wait returning before the code under test has
run. They wait instead on markers proving the OCC failure was processed:
the conflict notification, the coordinator going idle, no pending save.

One mock sleep in serial-writer must stay real, because it has to outlive
the debounce for the race being tested; it is now PERSISTENCE_DEBOUNCE_MS
* 2 with a comment naming what it outwaits. Its companion timing assertion
is derived from the same constant rather than hardcoded.

The conflict-notification file keeps ~510ms/test: that is the real
production debounce before the write is even attempted, not slack.

Verified by reintroducing the original bugs (hardcoded hasPending: false
in both direct-hydration branches; disabling the write-collapse guard).
Every converted test failed on its real assertion rather than on a
waitFor timeout, including the derived flush bound catching a 5s hang
against its 1550ms ceiling. Production files restored; no non-test file
is modified.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* Address review: pin lint selector to the delay argument

Review finding 1 (Important): the selector matched a literal in ANY
argument position, so setTimeout(fn, 10, 9999) reported the 9999 callback
datum as a sleep and gave advice that made no sense for that line.
Reproduced the false positive, added :nth-child(2), and confirmed the
9999 case now passes while a real 900ms delay still errors and 400ms
still passes.

Finding 2: the lint threshold duplicates PERSISTENCE_DEBOUNCE_MS because
a flat config cannot import from test sources. Rather than leave that as
a comment, the drift guard now reads eslint.config.js and asserts the two
agree — verified it fails (expected 750 to be 500) when they diverge.

Finding 3: DEBOUNCED_WRITE_WAIT_MS + 1000 reintroduced exactly the kind
of padding this PR removes. Now CASCADE_SETTLE_TIMEOUT_MS, like every
other ceiling.

Finding 4: four waits covering TWO sequential writes now wait on
updateCallCount === 2 — the assertion that already followed them. Exact
rather than estimated, and it removes the margin question entirely. Two
of these the review did not flag; they had the same shape.

Also documents the rule's known blind spots (computed delays, module
constants, member-expression calls) so its coverage is not overstated.

Verified the converted same-field tests still detect their bug: disabling
the field-sequence guard fails them in 311ms on the real clobber symptom
(expected 'in-progress' to be 'done'), not a waitFor timeout. Production
file restored; no non-test file is modified.

Not addressed: finding 6 (a pre-existing 'bug #2066' reference in a
production comment). Real, but fixing it here would make this test-only
PR touch production source.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5 (1M context) <[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.

Kanban view: bound large boards (pagination/virtualization) + browser DnD tests

1 participant