Repository navigation
Derive test sleep durations instead of guessing them (closes #2679) - #2691
Conversation
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]>
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]>
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]>
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]>
…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]>
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]>
Code Review — PR #2691 (
|
| Check | Method | Result |
|---|---|---|
| Sleep budget | Regex-summed setTimeout(ident, N) across src/tests on origin/main vs HEAD |
65,605ms → 12,005ms (−82%). Corroborates the PR's 64,105 → 11,905 (delta is regex-counting variance, not a discrepancy). |
| All converted files green | bun run test -- on all 12 touched test files |
12 files / 105 tests, 0 failures, 24.2s |
| Drift guard fails when prod RAISED | Set DEBOUNCE_MS = 800, ran guard |
Fails: expected "updateNode" to be called 1 times, but got 0 at :82 |
| Drift guard fails when prod LOWERED | Set DEBOUNCE_MS = 300, ran guard |
Fails: expected "updateNode" to not be called at :67 |
| Bug injection #1 | directCallHadQueuedWrite → false (shared-node-store.svelte.ts:4006) |
Real assertion failure: expected 'server-state-before-B' to be 'B-edit-still-queued'. Companion false-positive test stayed green. |
| Bug injection #2 | hasPending: hadQueuedWrite → false in both hydration branches (:2120, :3277) |
Both skip-while-editing tests failed on real assertions, in 1.43s |
| Release-gate deadlock | Forced the pre-gate assertion to throw so releaseWriteA() never runs |
Fails cleanly in 515ms with a real assertion error — no hang |
| Flush-bound headroom | Instrumented flushDuration |
996ms measured against a 1550ms bound (~55% headroom) |
afterEach 100ms → 0ms isolation |
5 consecutive runs of shared-node-store-coverage |
Stable: 9.91 / 9.96 / 9.95 / 9.95 / 9.95s, all passing |
| Lint rule behavior | ESLint probe file with 12 shapes | See Finding 1 |
| Lint clean on current tree | bunx eslint 'src/tests/**/*.ts' from packages/desktop-app |
0 errors; no numeric sleep >500ms remains |
| Production untouched | shasum before/after every probe + git status --porcelain |
777912754afc… unchanged; tree clean, no production file modified |
Findings
🟡 Important
1. The lint selector matches any argument, not the delay argument — a real false positive on setTimeout's 3rd argument
📁 packages/desktop-app/eslint.config.js:322
selector: "CallExpression[callee.name='setTimeout'] > Literal.arguments[value>500]"
Literal.arguments matches a literal in any argument position. Verified by probe: setTimeout((n: number) => n, 10, 9999) errors at column 38 — that 9999 is callback data passed through to the handler, not a delay. The message then tells the author to "prefer vi.waitFor", which is nonsense advice for that line, and there is no suppression escape hatch under this repo's no-lint-suppression standard.
Principle — a guard that misfires trains people to work around it. The selector should pin the position:
selector: "CallExpression[callee.name='setTimeout'] > Literal.arguments:nth-child(2)[value>500]"Worth confirming the :nth-child indexing against a probe before adopting; esquery indexes children 1-based over the node's own child list.
Also verified false negatives, all of which slip past silently: setTimeout(fn, 400 + 500) (BinaryExpression), setTimeout(fn, D) where const D = 9000, setTimeout(fn, Number(9000)), and both globalThis.setTimeout(fn, 4000) / window.setTimeout(fn, 4000) (the callee.name form only matches a bare identifier). These are acceptable for a heuristic ratchet — the common shape is caught (setTimeout(resolve, 900) and setTimeout(done, 5000) both error) — but the config comment currently reads as though the rule's only deliberate exemption is "a named constant." One line noting that member-expression and computed forms are out of reach of this selector would stop a future reader assuming coverage the rule does not have.
Correctly verified as a non-issue: obj.setTimeout(() => {}, 30000) on a local object does not trigger — good.
🟢 Suggestions
2. The >500 threshold is coherent, but sits exactly on a boundary the constants can cross
📁 packages/desktop-app/eslint.config.js:322, packages/desktop-app/src/tests/utils/test-constants.ts:26
PERSISTENCE_DEBOUNCE_MS = 500 and the threshold is >500, so a literal 500 passes. That is intentional and stated. But note the ratchet's own asymmetry: if production's DEBOUNCE_MS were lowered, the drift guard fires (good); if it were raised, every derived constant grows while the lint threshold stays pinned at 500 — and the threshold would no longer mean "the debounce." Consider deriving the threshold from the same source of truth, or at minimum noting in the comment that it tracks PERSISTENCE_DEBOUNCE_MS by hand. Principle: two constants meaning the same thing in two files is precisely the duplication this PR's own drift guard exists to catch.
3. DEBOUNCED_WRITE_WAIT_MS + 1000 reintroduces the magic number the PR removes
📁 packages/desktop-app/src/tests/services/shared-node-store-coverage.test.ts:817
Every other converted wait uses CASCADE_SETTLE_TIMEOUT_MS as its ceiling; this one uses DEBOUNCED_WRITE_WAIT_MS + 1000. The + 1000 is undocumented and is exactly the "round number padded around a real constant" the PR sets out to eliminate. Since this is a vi.waitFor ceiling (costs nothing when the condition holds early), just use CASCADE_SETTLE_TIMEOUT_MS for consistency. Nit-adjacent, but it is the one place the new convention is not followed.
4. Two waits were shortened from 700ms to 550ms — a real reduction in margin, not just a rename
📁 packages/desktop-app/src/tests/services/updatetasknode-samefield-clobber-regression.test.ts:211, packages/desktop-app/src/tests/services/updatetasknode-success-clobber-regression.test.ts:220
These 700 → DEBOUNCED_WRITE_WAIT_MS (=550) changes read as pure derivation in the diff, but they also cut ~21% of margin on a wait that must cover debounce (500) plus two sequential write settlements (expect(updateCallCount).toBe(2)). The other sites converted 600 → 550, a much smaller step. They passed in my runs, and 550 is defensible as "debounce + settle." But the assertion here is on two writes having completed, so DEBOUNCED_WRITE_WAIT_MS is arguably the wrong constant — it names the wait for one debounced write. The file already has a stronger idiom available (the coordinator-idle wait used well at shared-node-store-skip-while-editing.test.ts:660); a vi.waitFor on updateCallCount === 2 would be both faster and strictly stronger than any duration here. Low priority — worth doing the next time this file is touched rather than now.
5. Flush-duration bound is tighter than before; still adequate, recorded here so it need not be re-derived
📁 packages/desktop-app/src/tests/services/persistence-serial-writer-regression.test.ts:217
Old: RPC 2000ms, bound 3000ms. New: RPC 1000ms (PERSISTENCE_DEBOUNCE_MS * 2), bound 1550ms. Measured: 996ms against 1550ms, so ~554ms absolute headroom versus ~1600ms before. The ratio is comparable and the assertion still discriminates sharply against the failure mode it exists for — a hung promise burning the full 5000ms internal timeout sits 3.2x above the bound. Verdict: PERSISTENCE_DEBOUNCE_MS * 2 is sufficient for the race, since the mock latency only needs to outlive one debounce window while the second edit lands. No change needed.
6. Pre-existing: an embedded issue number in a production code comment
📁 packages/desktop-app/src/lib/services/shared-node-store.svelte.ts:2101 — "exactly the class of bug #2066 closed for the fallback"
CLAUDE.md prohibits embedding GitHub issue numbers in code comments. Not introduced by this PR and out of scope — noting it only so it is not mistaken for something this change added. (Same pattern in a test name at shared-node-store-skip-while-editing.test.ts:810, also pre-existing.)
Acceptance criteria
- 35 sleeps ≥600ms converted — verified: zero numeric sleeps >500ms remain anywhere in
src/tests; ESLint clean. - Sleep time materially below 64.1s — independently measured 65,605ms → 12,005ms.
- Remaining real sleeps name their constant — all surviving long waits are named imports with doc comments; the two deliberate mock latencies (
300,PERSISTENCE_DEBOUNCE_MS * 2) carry explicit "this must STAY" rationale. ai-chat-occ-conflict-regression+shared-node-store-coverageno longer wall-clock-dependent — the former is now 207ms (4 tests, allvi.waitFor); the latter's remaining time is real production debounce, not padding.test:allpasses — the pre-push gate ran green; I re-ran all 12 touched files (105/105).- No behavioral change to code under test — verified by checksum after every probe;
git statusclean.
Behavior-preservation review
The renamed test ('should trigger resync on VERSION_CONFLICT error' → 'rolls back and tracks the error when a write fails') is correctly reasoned. isVersionConflict() requires structured conflictData, which the test's plain Error + .code never carried — so the original never reached the resync branch and its only assertion was expect(node).toBeTruthy(), which is tautological. The replacement asserts getTestErrors()[0].message contains VERSION_CONFLICT and that the local edit is not discarded — both can fail, and the second encodes a real product invariant (don't drop what the user typed because a write failed). A strict improvement in coverage, not a weakening; the real OCC path remains covered elsewhere.
The afterEach 100ms → setTimeout(resolve, 0) reduction is sound: a 0ms timer still yields a full macrotask boundary, which is what draining already-scheduled microtasks and 0ms timers requires; the preceding flushAllPending() race, clearAll(), resetInstance() and clearAllMocks() do the actual isolation work. Adding vi.useRealTimers() as the first teardown statement is a genuine robustness improvement that did not exist before — without it, a test leaving fake timers installed would freeze the clock the teardown races. Verified stable across 5 consecutive runs. Residual risk is low and now bounded by an explicit ceiling constant rather than a guess.
On the release gates: no deadlock is reachable. Only one assertion sits between gate creation and releaseWriteA(), and I confirmed empirically that when it throws, the test fails cleanly in 515ms with a real assertion error. The unreleased gate leaks a dangling promise, but Vitest is not blocked on it.
Leaving ~153 short sleeps (≤500ms, 11.9s) alone is the right scope call: they are 18% of the cost, mostly 10/50/100ms yields, and churning them would add regression risk disproportionate to the saving. YAGNI applies to test refactors too. The new lint rule prevents the budget from regrowing, which is the durable part.
Standards
No lint suppressions, no any, no {@html}, no new embedded issue numbers, bun run test used throughout. unicorn/filename-case satisfied by the new file.
Automated pragmatic code review. Production source was restored and checksum-verified after every bug-injection probe; the working tree is clean.
malibio
left a comment
There was a problem hiding this comment.
Automated pragmatic-code-review: APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.
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]>
Address Review —
|
Summary
Frontend tests waited on real wall-clock time with durations picked as "comfortably large" rather than derived from what was being awaited. That cost 64.1s of deliberate sleeping on every push — the pre-push gate (ADR-047) is the sole CI here — and left the suite with no headroom under parallel load, which is how it surfaced.
Literal sleep time: 64,105ms → 11,905ms (-81%).
testsexecution timesrc/testsMeasured per-file on the 18 sleep-heavy service tests: 56.7s → 32.2s, 416 tests, 0 failures.
shared-node-store-coverageai-chat-occ-conflict-regressionresync-direct-call-queued-writepersistence-serial-writerconflict-notification-integrationshared-node-store-skip-while-editingsubtree-access-denied-restoreWhat changed
Durations are now derived. New constants in
tests/utils/test-constants.tsmirror the private production values (DEBOUNCE_MS = 500, the 5s internal flush timeout). Waits arePERSISTENCE_DEBOUNCE_MS + DEBOUNCE_SETTLE_MS, not a round number rounded up from it.A drift guard, because a mirror nothing checks will drift.
persistence-timing-constants.test.tsfails loudly — and names the file to edit — if the production debounce or flush timeout ever moves away from the test-side copy. 3 tests, 8ms, no sleeping.Mocks say what they mean. Two mocks slept 10,000ms so a 5000ms (and a 50ms) timeout could be asserted. A never-resolving promise states "this never settles" directly and costs nothing.
Ordering is guaranteed, not raced. Two mock sleeps existed to keep write A in flight while write B was submitted. They are now explicit release gates: the mock awaits a promise the test resolves once B has landed.
Waits are on conditions, not the clock.
vi.waitForon the condition the test then asserts, so a passing test costs only as long as the behaviour actually takes.A lint rule so this does not come back.
no-restricted-syntaxfails any test sleeping >500ms with a numeric literal. A named constant passes at any value — the point is that a duration be derived and stated, not that it be small. Verified against a probe: 900ms errors, 500ms and 100ms pass.Two traps worth knowing about
Both bit during this work and are called out in comments at each site:
turnStatusto be defined passed immediately — an optimistic write had already defined it. The correct wait was for it to stop being'processing'.Verification
Beyond "the tests pass", each converted regression test was checked to still detect its original bug:
directCallHadQueuedWriteback tofalse→ the queued-write test failed with the exact clobber symptom, and its false-positive companion stayed green.hasPending: falsein both direct-hydration branches → both skip-while-editing tests failed on real assertions.onRefused?.()outside the refusal branch → the negative-assertion test failed in 58ms.Every failure was a real assertion, never a
waitFortimeout on an unrelated condition. No production file is modified — verified byte-for-byte after each probe.Full gate passed (
test:all+cargo build+test:e2e) with three other sessions building concurrently — the load condition that caused the original failure.quality:fixclean: 0 errors, design-token baseline unchanged at 137.Notes for the reviewer
persistence-serial-writer, mock RPC latency): it must outlive the debounce for the race under test. It is nowPERSISTENCE_DEBOUNCE_MS * 2with a comment naming what it outwaits.conflict-notificationkeeps ~510ms/test — that is the real production debounce before the write is attempted, not slack.'should trigger resync on VERSION_CONFLICT error'built a plainErrorwith acodeproperty, whichisVersionConflict()does not recognise — so it never reached the resync branch, slept 1s, and asserted only that the node existed. Renamed to what it covers, with an assertion that can fail. The real OCC resync path is covered byai-chat-occ-conflict-regressionandconflict-notification-integration.Closes #2679
🤖 Generated with Claude Code