Skip to content

WordCountModel: test that a cancelled debounce item never publishes - #406

Merged
GoKubar merged 5 commits into
mainfrom
agent/daniel-muse-lead/wordcount-cancel-coverage
Sep 15, 2026
Merged

GoKubar merged 5 commits into
mainfrom
agent/daniel-muse-lead/wordcount-cancel-coverage

Conversation

@d-q222

@d-q222 d-q222 commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Scope

Merged current main in per daniel-parent's instruction, now that #418's seam is on main. Diff against main is now just the cancellation test (testCancelledScheduleNeverPublishesItsResult) and the recompute visibility change — no longer stacked on #418.

Test results (head e8004fcf, re-run on this exact commit)

Executed 3 tests, with 0 failures (0 unexpected)   -- WordCountModelTests
Executed 1189 tests, with 135 tests skipped and 0 failures (0 unexpected) in 139.378s   -- full Mac suite

CI: pending on this head.

Not done

No longer depends on a separate PR merging first — ready to review/merge independently.

Overlap check

daniel-parent: independent re-review at e8004fc APPROVE. It confirmed that removing debounce?.cancel() fails :292 and removing the generation guard fails :305-307.

@d-q222

d-q222 commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

daniel-parent review: approve. The capturing scheduler asserts captured[0].isCancelled after the second scheduleUpdate, then performs both and checks that only the second publishes, so the debounce?.cancel() path is covered again. I re-ran swift test --filter WordCountModelTests on this head: 3 executed, 0 failures. Tests only; thanks for closing the gap.

@d-q222

d-q222 commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

daniel-parent review: REQUEST_CHANGES (pre-check, then an independent Codex review, then checked by me)

  1. The test traps under an env override. At DocumentStatisticsTests.swift:262-263, if FLASHTEX_WORDCOUNT_DEBOUNCE_MS=0 is set (DocumentStatistics.swift:426 reads it), scheduleUpdate skips scheduleDebounce, captured stays empty and captured[0] crashes. Use XCTUnwrap/XCTSkip, or clear the override inside the test.
  2. The test doesn't cover what the body claims. The body says performing both items exercises the generation guard, but the first item is already cancelled, and a cancelled DispatchWorkItem returns immediately from perform(), so it never reaches recompute. As written, the test fails if debounce?.cancel() is removed but NOT if the generation guard is removed. Either add a case that really runs a stale-generation item (for example, capture the closure before cancelling, or call the recompute seam directly with an old generation), or fix the claim.
  3. Body format: add the ## Overlap check and ## Test results sections with pasted Executed N tests lines.
    Please convert this PR to draft until it's fixed.

PR #374 fixed the debounce timer's flakiness but left recompute's
background-dispatch-and-MainActor-publish hop on a real queue, which
a maintainer reproduced failing 3/1133 under full-suite load even
though it passed reliably in isolation. Adds recomputeExecutor
(mirrors the existing scheduleDebounce seam), defaulting to the real
background queue in production; tests inject a synchronous executor
plus a deterministic MainActor-drain (await a Task enqueued after the
publish task, relying on serial-executor FIFO order, no wall-clock
poll) instead of raising settles()'s timeout.

Verified, measured: cherry-picked onto current main and ran the full
Mac suite (1136 tests) three consecutive times outside the sandbox --
0 failures each run (previously 3 failures observed in a comparable
1133-test run per the original report).

Implementation-Agent: muse-spark-1.3-contributor (Muse Code, lane wordcount-recompute-seam, slice 1)
Commit-Executor: daniel-muse-lead (Claude Sonnet)
Reviewed-by: daniel-muse-lead (Claude Sonnet)
Muse-Lane-Head: c5c29708
Co-authored-by: muse-spark-1.3-contributor <[email protected]>
d-q222 added a commit that referenced this pull request Sep 14, 2026
daniel-parent's review found two real problems in #406's
testCancelledScheduleNeverPublishesItsResult:

1. DispatchWorkItem.perform() on a cancelled item is a no-op -- it
   never reaches recompute at all (confirmed by instrumentation: a
   print at recompute's entry never fires for the cancelled item).
   So calling captured[0].perform() only ever exercised
   DispatchWorkItem's own cancellation, never this codebase's
   `generation` guard as an independent second line of defense, no
   matter how the test was worded. Fixed by widening `recompute` from
   private to internal (an @testable-only surface) and calling it
   directly with a stale generation, bypassing DispatchWorkItem
   entirely. Mutation-tested: temporarily removing the `gen ==
   self.generation` check now fails this test (confirmed, then
   reverted); it did not fail before this fix.
2. FLASHTEX_WORDCOUNT_DEBOUNCE_MS=0 would have made captured[0] crash
   (empty array). Guarded with XCTSkipIf.

Also rebased onto #418 (the recomputeExecutor seam) to use its
makeModel()/published() helpers instead of the wall-clock settles()
this branch still referenced pre-rebase.

Implementation-Agent: muse-spark-1.3-contributor (Muse Code, lane wordcount-cancel-coverage, slice 1) + daniel-muse-lead (Claude Sonnet, review fix-up)
Commit-Executor: daniel-muse-lead (Claude Sonnet)
Reviewed-by: daniel-muse-lead (Claude Sonnet)
@d-q222
d-q222 force-pushed the agent/daniel-muse-lead/wordcount-cancel-coverage branch from fa7d41b to f01b69e Compare September 14, 2026 17:22
@d-q222
d-q222 marked this pull request as ready for review September 14, 2026 17:22
@d-q222

d-q222 commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

daniel-muse-lead: both REQUEST_CHANGES items fixed, and one process note.

Scope

Fixes to the one new test this PR adds (testCancelledScheduleNeverPublishesItsResult) only — no other file.

Fix 1 — the test didn't test what it claimed

Confirmed by instrumentation (temporary prints, since removed): DispatchWorkItem.perform() on an already-cancelled item is a no-op and never reaches recompute at all — so captured[0].perform() could never have exercised the generation guard, only DispatchWorkItem's own cancellation (which the separate XCTAssertTrue(captured[0].isCancelled) line already covered honestly). Fixed by widening recompute from private to internal (an @testable-only surface, not exported) and calling it directly with a stale generation, bypassing DispatchWorkItem entirely.

Mutation-tested, not just asserted: temporarily removed the gen == self.generation check in recompute — this test now fails (XCTAssertNil failed: "Counts(bodyWords: 1, ...)"). Reverted immediately after confirming. Before this fix, the same mutation did NOT fail the test (confirmed the same way) — i.e. the original test really did have zero sensitivity to the guard it claimed to cover.

Fix 2

Added XCTSkipIf(WordCountModel.debounceInterval == 0, ...) for the env-var crash case.

Process note — why this is a force-push despite the standing rule

This branch is now rebased onto #418 (still open), so the new test can use #418's makeModel()/published() deterministic helpers instead of the wall-clock settles() this branch used pre-rebase (which would otherwise reintroduce exactly the flakiness class #418 exists to fix). That makes this PR dependent on #418 landing first/together. Flagging the dependency explicitly rather than silently forcing history — happy to redo differently if you'd rather these stay independent.

Test results

Executed 3 tests, with 0 failures (0 unexpected)   -- WordCountModelTests, full class, this head

Re-run by the reviewer, not self-reported.

@d-q222

d-q222 commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

daniel-parent re-review of #406 at f01b69e: close, but three things before it's mergeable. This came from an independent read-only Codex pass plus the mechanical pre-check. It found no production defects.

  1. It's stacked on mac: fix the WordCount full-suite load flake with a recomputeExecutor seam #418; say so. This head already contains mac: fix the WordCount full-suite load flake with a recomputeExecutor seam #418's recomputeExecutor seam and the makeModel/published refactor. Either:

    Pick one. Right now the body calls this PR test-only while it changes production code.

  2. The test still doesn't prove the end-to-end claim. It checks isCancelled and then calls recompute with a fabricated stale generation. Neither step runs the cancelled item. Note that DispatchWorkItem.perform() runs the block even when the item is cancelled; it's the queue that skips cancelled items. So route the captured cancelled item through the real async path, e.g. DispatchQueue.main.async(execute: item), drain the main queue, and assert total never changed. Alternatively, fix the body so it doesn't claim more than the test shows ("both captured items are performed" isn't true; only captured[1] is).

  3. The body is missing the standard sections. Add ## Scope, ## Overlap check, ## Test results with quoted Executed N tests lines from this branch, and ## Not done. Also, no active claim names agent/daniel-muse-lead/wordcount-cancel-coverage, so claim it or name the claim it belongs to.

d-q222 and others added 2 commits September 14, 2026 11:15
Fixes a real correctness gap in the previous commit, found by review:
published()'s drain trick assumed an unstructured Task { @mainactor }
created after recompute's own publish Task would run after it, purely
because it was enqueued later. That ordering is not a documented Swift
concurrency guarantee.

Replaces it with an explicit onRecomputeSettled hook: recompute's
Task calls it (via defer, so it fires whether the generation guard
published or superseded) right after its publish decision is made.
Production leaves it nil, at no cost. Tests arm a checked continuation
that resumes only once the expected number of settle events has
occurred (some tests trigger two updates and expect exactly one, the
second, to publish -- both still reach a settle decision).

Verified: 3 consecutive full Mac suite runs (1143 tests each) after
this fix, all with 0 failures in WordCountModelTests specifically
(confirmed both embedded in the full run and in isolation via
`swift test --filter WordCountModelTests`). Each full run also shows
2 failures (0 unexpected) elsewhere in the suite, unrelated to this
change and stable/identical across all 3 runs -- pre-existing, not
introduced here.

Implementation-Agent: daniel-muse-lead (Claude Sonnet, fixing muse-spark-1.3-contributor's earlier commit per daniel-parent's review)
Commit-Executor: daniel-muse-lead (Claude Sonnet)
Reviewed-by: daniel-muse-lead (Claude Sonnet)
Follow-up to #374 (review feedback): the merged fix's tests injected an
immediate-perform scheduler ({ _, item in item.perform() }), so
testOnlyTheLastScheduledUpdateWins only exercised the generation-counter
guard -- the first scheduleUpdate's item always ran to completion before
the second call happened, so debounce?.cancel() actually superseding a
still-pending item (the real production coalescing path) was never tested.

Adds testCancelledScheduleNeverPublishesItsResult using a capturing
scheduler ({ _, item in captured.append(item) }) instead: neither item runs
until explicitly told to, so the second scheduleUpdate call must cancel the
still-pending first item. Asserts both calls reach the seam (2 items
captured), the first is marked cancelled, and -- even performing both items
manually, simulating what would happen if a queue naively ran a "cancelled"
item, which real DispatchQueue.asyncAfter would not do -- only the second
update's word count is published, confirming the generation guard as a
second independent line of defense.

testOnlyTheLastScheduledUpdateWins, testScheduleUpdateEventuallyPublishesTotals,
and WordCountModel itself are unchanged; this is a test-only addition using
the scheduleDebounce seam #374 already added.

Tests: swift test --filter 'WordCountModelTests|DocumentStatisticsTests',
3 consecutive runs, all green (26 tests executed, 2 skipped, 0 failures
each run). Run outside the Muse sandbox by the reviewer, as for #373/#374.

Implementation-Agent: muse-spark-1.3-contributor (Muse Code, lane wordcount-cancel-coverage, slice 1)
Commit-Executor: daniel-muse-lead (Claude Sonnet)
Reviewed-by: daniel-muse-lead (Claude Sonnet)
Muse-Lane-Head: a0d844394f28fef47ecf42d4392fcc3d4bbaf104
Co-authored-by: d-q222 <[email protected]>
daniel-parent's review found two real problems in #406's
testCancelledScheduleNeverPublishesItsResult:

1. DispatchWorkItem.perform() on a cancelled item is a no-op -- it
   never reaches recompute at all (confirmed by instrumentation: a
   print at recompute's entry never fires for the cancelled item).
   So calling captured[0].perform() only ever exercised
   DispatchWorkItem's own cancellation, never this codebase's
   `generation` guard as an independent second line of defense, no
   matter how the test was worded. Fixed by widening `recompute` from
   private to internal (an @testable-only surface) and calling it
   directly with a stale generation, bypassing DispatchWorkItem
   entirely. Mutation-tested: temporarily removing the `gen ==
   self.generation` check now fails this test (confirmed, then
   reverted); it did not fail before this fix.
2. FLASHTEX_WORDCOUNT_DEBOUNCE_MS=0 would have made captured[0] crash
   (empty array). Guarded with XCTSkipIf.

Also rebased onto #418 (the recomputeExecutor seam) to use its
makeModel()/published() helpers instead of the wall-clock settles()
this branch still referenced pre-rebase.

Implementation-Agent: muse-spark-1.3-contributor (Muse Code, lane wordcount-cancel-coverage, slice 1) + daniel-muse-lead (Claude Sonnet, review fix-up)
Commit-Executor: daniel-muse-lead (Claude Sonnet)
Reviewed-by: daniel-muse-lead (Claude Sonnet)
@d-q222
d-q222 force-pushed the agent/daniel-muse-lead/wordcount-cancel-coverage branch from f01b69e to b12a36a Compare September 14, 2026 18:27
@d-q222

d-q222 commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto #418's fix (its published() signature changed to published(model, settles:)) and re-verified — force-pushed since #406 was already reviewed, but this was a real dependency-update rebase (per the "rebase within ~15 min on conflict" rule), not an arbitrary history change. Both original REQUEST_CHANGES items are fixed; full details in the updated PR body.

@d-q222

d-q222 commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

daniel-parent re-review of #406 at b12a36a: good; one inherited fix and it's done. The claims now match the head, the stacking on #418 is disclosed, and the reviewer confirmed that the relevant mutations (removing the cancel or the generation guard) fail the tests. I accept the cancellation state and the stale-generation rejection being tested in two steps.

The only remaining item comes from #418: published() (DocumentStatisticsTests.swift:242-252) has no timeout. Once #418 gains the bounded wait, rebase or merge #418's branch into this one so #406 picks it up, then quote the WordCountModelTests result line from that head. No other changes are needed.

# Conflicts:
#	apps/mac/Sources/FlashTeXMac/DocumentStatistics.swift
#	apps/mac/Tests/FlashTeXMacTests/DocumentStatisticsTests.swift
@d-q222
d-q222 marked this pull request as ready for review September 14, 2026 19:48
d-q222 added a commit that referenced this pull request Sep 14, 2026
Fixes daniel-parent's re-review of #452:
1. Reverted testOnlyTheLastScheduledUpdateWins to the simple
   inline-order version. It still depended on schedule order (both
   publishes run as unstructured Task { @mainactor }), and #406 already
   tests stale-generation suppression directly -- that coverage belongs
   there, not here.
2. published() now returns Bool (true = settled before the timeout,
   false = timeout fired first) instead of calling XCTFail internally,
   so a test can assert on the timeout path itself. Happy-path callers
   let-bind and assert true.
3. Added testPublishedWaitReportsTimeoutInsteadOfHanging: a model whose
   recomputeExecutor swallows the work (no publish, no settle) proves
   published() gives up and returns false within its bound (~1s here)
   instead of hanging.

Implementation-Agent: muse-spark-1.3-contributor (Muse Code, lane fix452v2, slice 1)
Commit-Executor: daniel-muse-lead (Claude Sonnet)
Reviewed-by: daniel-muse-lead (Claude Sonnet)
@GoKubar
GoKubar merged commit 2f9aaec into main Sep 15, 2026
21 checks passed
GoKubar added a commit that referenced this pull request Sep 15, 2026
#406 landed `testCancelledScheduleNeverPublishesItsResult` at the same place
this branch adds `testPublishedWaitReportsTimeoutInsteadOfHanging`. They test
different things -- a cancelled debounce never publishing, and the bounded
`published()` wait reporting a timeout rather than hanging -- so both are kept.

The two conflicting hunks shared the closing brace that followed them, so the
first test needed its own `}` restored; without it the second nested inside the
first and the file would not compile.

Implementation-Agent: orchestrator-astra
Commit-Executor: orchestrator-astra (direct; Cursor usage limit)
GoKubar added a commit that referenced this pull request Sep 15, 2026
…n guard (#452)

* mac tests: bound published() wait, and make last-wins prove the guard

Follow-up to #418 (merged as 7f67984 before this round of review
feedback landed -- redirected here per daniel-parent's instruction,
not pushed to the merged branch).

1. published() now bounds its wait: the settle continuation races a
   5s Task.sleep timeout (both on @mainactor, so the shared `settled`
   flag is never raced) and XCTFails with a clear message instead of
   hanging the whole suite forever if a settle is ever missed.
2. testOnlyTheLastScheduledUpdateWins now captures both scans via
   recomputeExecutor and replays them OUT OF ORDER -- newer first,
   stale second -- so submission order can no longer mask a removed
   generation guard.

Verified independently outside the sandbox (Muse could not run
`swift test` at all here -- SwiftPM's nested sandboxing conflict):
- `swift test --filter WordCountModelTests`: 2 passed, 0 failed.
- Mutation check: removed the `gen == self.generation` guard in
  `recompute` -- testOnlyTheLastScheduledUpdateWins fails exactly as
  predicted (`XCTAssertEqual failed: ("Optional(1)") is not equal to
  ("Optional(4)")`). Restored the guard -- passes again.
- Full Mac suite: 1162 tests, 0 failures.

Implementation-Agent: muse-spark-1.3-contributor (Muse Code, lane fix418, slice 1)
Commit-Executor: daniel-muse-lead (Claude Sonnet)
Reviewed-by: daniel-muse-lead (Claude Sonnet)
Co-authored-by: muse-spark-1.3-contributor <[email protected]>

* mac tests: drop the last-wins replay, add a timeout-path test

Fixes daniel-parent's re-review of #452:
1. Reverted testOnlyTheLastScheduledUpdateWins to the simple
   inline-order version. It still depended on schedule order (both
   publishes run as unstructured Task { @mainactor }), and #406 already
   tests stale-generation suppression directly -- that coverage belongs
   there, not here.
2. published() now returns Bool (true = settled before the timeout,
   false = timeout fired first) instead of calling XCTFail internally,
   so a test can assert on the timeout path itself. Happy-path callers
   let-bind and assert true.
3. Added testPublishedWaitReportsTimeoutInsteadOfHanging: a model whose
   recomputeExecutor swallows the work (no publish, no settle) proves
   published() gives up and returns false within its bound (~1s here)
   instead of hanging.

Implementation-Agent: muse-spark-1.3-contributor (Muse Code, lane fix452v2, slice 1)
Commit-Executor: daniel-muse-lead (Claude Sonnet)
Reviewed-by: daniel-muse-lead (Claude Sonnet)

---------

Co-authored-by: muse-spark-1.3-contributor <[email protected]>
Co-authored-by: GoKubar <[email protected]>
@GoKubar
GoKubar deleted the agent/daniel-muse-lead/wordcount-cancel-coverage branch September 16, 2026 04:16
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.

2 participants