Skip to content

test(monetization): make ToastController auto-dismiss deterministic via a sleep seam - #1098

Merged
wei18 merged 2 commits into
mainfrom
test/1087-toast-sleep-seam
Sep 22, 2026
Merged

wei18 merged 2 commits into
mainfrom
test/1087-toast-sleep-seam

Conversation

@wei18

@wei18 wei18 commented Sep 21, 2026 •

Copy link
Copy Markdown
Owner

Closes #1087

What

ToastController.show() hard-coded Task.sleep, so autoDismiss_firesAfterDuration was a wall-clock test (200 ms toast, 5 s poll) that ended red 5 of 5 inside the SudokuKit board --filter batch under local load. Per the PM ruling on the issue: no wider timeout, no moving rows out of the batch.

  • MonetizationUI/ToastView.swift: ToastController.init(sleep:), defaulting to { try await Task.sleep(for: $0) }; show() awaits the injected sleeper. Nothing else in the file changes.
  • ToastControllerBehaviorTests.swift: a file-private ManualSleeper (@MainActor, continuation FIFO, waitUntilParked(_:) / releaseNext()). It deliberately ignores cancellation, so the Task.isCancelled guard is the only thing standing between a stale sleeper and the new toast. The tests wait for dismissal by awaiting the dismiss Task itself (controller.dismissTask?.value), never by yielding or polling; waitUntilParked has a 5 s failure-path bound so a bypassed seam fails instead of hanging.
    • autoDismiss_firesAfterDuration: current != nil while parked, current == nil after release.
    • new show_replacesPreviousToast_staleSleeperDoesNotClearNewToast: releasing the old sleeper after a replacing show() leaves "second" on screen; releasing the new one clears it.
  • SudokuKit ToastTests.swift: the four byte-for-byte copies of the behaviour tests are deleted (they exercised another package's type). The three ToastView snapshot tests are untouched; no baseline changed.

Evidence

Red first (swift test --package-path Packages/AppMonetizationKit --filter ToastControllerBehaviorTests):

  • remove self?.current = nil → autoDismiss_firesAfterDuration() recorded an issue at ToastControllerBehaviorTests.swift:101:9: Expectation failed: (controller.current → Toast(… message: "pop" …)) == nil — Test run with 5 tests in 1 suite failed … with 2 issues (the second is the stale-sleeper test's final current == nil, which also depends on the clear)
  • remove guard !Task.isCancelled else { return } → show_replacesPreviousToast_staleSleeperDoesNotClearNewToast() recorded an issue at ToastControllerBehaviorTests.swift:116:9: Expectation failed: (controller.current?.message → nil) == "second" — failed … with 1 issue
  • restored → Test run with 5 tests in 1 suite passed; looped 10 times, 10 of 10 passed.

Green:

  • swift test --package-path Packages/AppMonetizationKit → Test run with 182 tests in 32 suites passed after 1.712 seconds.
  • rg -n "Task.sleep|Date\(\).addingTimeInterval" …/ToastControllerBehaviorTests.swift → exactly one hit, the ManualSleeper 5 s failure-path bound (try? await Task.sleep(for: .seconds(5))). Nothing on any pass path waits on a clock: a passing run returns the moment the sleeper parks and cancels that bound (done-when 3 as amended by the PM on test(sudoku): ToastTests.autoDismiss_firesAfterDuration flakes inside the board --filter batch — wall-clock, pre-existing #1087).
  • swiftlint --strict on the three files → 0 violations.
  • Production ToastController() call sites, all unchanged: GameAppKit/MakeGameApp.swift:169, SudokuAppComposition/Preview.swift:45, MinesweeperAppComposition/Preview.swift:43. Test call sites outside this PR (unchanged, still compile): EntitlementHookOrderingTests ×3, PurchaseFlowStateTests ×2, SudokuKit MonetizationStateControllerUpdatesTests ×1, SettingsViewTests ×1.
  • iOS Simulator build (build-only, xcodebuild build -workspace Game.xcworkspace -scheme <app> -configuration Debug -destination 'generic/platform=iOS Simulator' CODE_SIGNING_ALLOWED=NO): Sudoku ** BUILD SUCCEEDED ** (exit 0), Minesweeper ** BUILD SUCCEEDED ** (exit 0).

Follow-up cec92125 (review findings)

  • ManualSleeper.waitUntilParked(_:) is bounded (5 s, failure path only) and returns Bool; callers try #require it; releaseNext() on nothing parked records an issue. Seam-bypass mutation (show() calling Task.sleep directly) now fails in ~5 s with ManualSleeper: fewer than 1 sleep() calls parked within 5 s — did ToastController.show() bypass the injected sleep? instead of hanging.
  • settle() (one Task.yield()) is gone: yield has no ordering guarantee against the dismiss job, and under 8-core CPU load it lost ~1 in 200 runs. The tests now await controller.dismissTask?.value (and await stale?.value for the superseded task); dismissTask is private(set) for that. Loaded 200× loop: fixed 200/200 green; yield-based mutant red at run 65 (autoDismiss_firesAfterDuration … == nil failed). M1/M2 mutations still red. AMK full 182/182; GameAppKit swift build clean; both iOS Simulator builds BUILD SUCCEEDED.

Board batch (exact filter from #1062 (comment)), macOS 27.0 (26A428):

tree result
clean 331b4de7 188 tests / 43 suites, 39 issues = 38 snapshot mismatches + autoDismiss_firesAfterDuration at ToastTests.swift:57 (the bug, reproduced)
this branch, run 1 184 tests / 43 suites, 38 issues — all snapshot mismatches
this branch, run 2 same 38
this branch, run 3 same 38

Failing-test set on this branch minus the base set = empty. Base set minus this branch = exactly autoDismiss_firesAfterDuration. So this change contributes 0 issues, and removes the one it targets. 184 = 188 minus the four deleted duplicates.

#1097 (environment)

Not counted above as this PR's issues. These 38 strict-.image snapshot tests fail identically on a clean 331b4de7 under macOS 27.0 (renderer drift after the 2026-09-16 OS upgrade; e.g. ToastView-success-light: 1246 of 153600 px differ, max channel delta 44, visually identical). Nothing was re-recorded.

ToastTests 3 (snapshotSuccessLight, snapshotFailureLight, snapshotInfoLight) · BoardViewTests 12 · CompletionOverlayScaffoldTests 5 · BoardControlClusterSnapshotTests 4 · BoardViewPencilNotesTests 4 · BoardFullBleedBreakpointTests 3 · CompletionViewTests 3 · BoardViewDigitFirstTests 2 · BannerSlotDarkBandRegressionTests 1 · BoardLoaderViewFailedExitTests 1

swift test --package-path Packages/SudokuKit --filter ToastTests therefore runs exactly 3 tests and shows those 3 mismatches, on base and on this branch alike.

Review

Production change in MonetizationUI → Code Reviewer required. Merge is the PM's; auto-merge is not armed.

🤖 Generated with Claude Code

…ia a sleep seam (#1087)

ToastController.show() hard-coded Task.sleep, so autoDismiss_firesAfterDuration
was a wall-clock test: a 200 ms toast polled for up to 5 s. Inside the SudokuKit
board --filter batch it ended red 5 of 5 under local load.

- ToastController.init gains a `sleep` parameter defaulting to Task.sleep(for:);
  every production ToastController() call site compiles unchanged.
- ToastControllerBehaviorTests drives dismissal with a manually released
  sleeper: no deadline, no polling. A new test pins the Task.isCancelled guard:
  a stale sleeper released after a replacing show() must not clear the new toast.
- SudokuKit ToastTests drops its four byte-for-byte copies of those behaviour
  tests (they exercised another package's type); its three ToastView snapshot
  tests stay, baselines untouched.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@wei18

wei18 commented Sep 21, 2026

Copy link
Copy Markdown
Owner Author

T6 acceptance (fresh-context, sonnet; read-only; head 8599a8f3, base 331b4de7)

The checker did not author the change. Evidence was taken from git show 8599a8f3:<path> and the three-dot diff, not from the working tree.

# Check Result
1 Scope: exactly the 3 files, +99/−57, no PNG/baseline change PASS
2 Seam: init(sleep:) with Task.sleep(for:) default; show() uses it; Task.isCancelled guard, self?.current = nil, dismiss() intact; rest of ToastView.swift byte-identical to base PASS
3 Determinism: 0 hits for Task.sleep / Date().addingTimeInterval in the behaviour tests; autoDismiss asserts non-nil while parked and nil after release; stale-sleeper test present PASS (1 MINOR below)
4 Red first: red-M1 2 issues incl. autoDismiss_firesAfterDuration; red-M2 1 issue on the stale-sleeper test; checker's own run of --filter ToastControllerBehaviorTests → 5 tests passed PASS
5 SudokuKit ToastTests.swift: single hunk removing the 4 behaviour tests; the 3 snapshot tests untouched PASS
6 Numbers, rebuilt from the raw logs (not from my .fails files): AMK 182 tests in 32 suites passed; base 39 issues, branch 38/38/38; branch − base = ∅, base − branch = {autoDismiss_firesAfterDuration}; three branch runs identical; all 38 are snapshot mismatches; both iOS builds BUILD SUCCEEDED, exit 0 PASS
7 PR hygiene: title ^[a-z0-9]; only close-word hit is Closes #1087; #1087 / #1097 / the #1062 filter comment exist and match; autoMergeRequest null PASS
8 Production ToastController() call sites at head = the 3 listed, none touched; 7 other test call sites use the default init PASS
9 `TODO FIXME

MINOR (non-blocking) — ToastControllerBehaviorTests.swift, settle(): a single Task.yield() relies on the MainActor's FIFO job ordering (resume → guard → assignment has no suspension point and the injected closure is @MainActor), which is how the runtime behaves but not a language guarantee. Low risk; 10/10 loop plus the checker's run were green. Recorded as the first place to look if this ever goes red.

Not verified by the checker: swiftlint --strict (no evidence file; it ran in the pre-commit hook and by hand, 0 violations); iOS builds, the board batch and the AMK full suite were checked from the log files, not re-run (one-heavy-job-at-a-time constraint).

總判定:ACCEPT

…s task instead of yielding (#1087)

Two findings from the PR #1098 review.

- ManualSleeper.waitUntilParked had no bound: if show() ever bypassed the
  injected sleep, the test hung instead of failing (the reviewer's mutation
  run sat for 9 hours). It now returns false after 5 s with an Issue.record;
  callers use #require. That bound is failure-path only: a passing run
  returns the moment the sleeper parks and cancels it. The waiter continuation
  is taken exactly once by whichever of park / timeout wins, all on MainActor.
  releaseNext() with nothing parked records an issue instead of returning.

- settle() = a single Task.yield() was a bet on job ordering: yield
  re-enqueues on the global executor, so it has no ordering guarantee against
  the dismiss job resumed by releaseNext(). Under CPU load it lost about once
  in 200 runs (and 1 in 6 with a non-isolated seam). The tests now await the
  dismiss Task itself (`controller.dismissTask?.value`), whose completion
  happens-after `current = nil` by construction: no yield, no polling, no
  ordering assumption. dismissTask becomes internal-readable
  (`private(set)`) for that; nothing outside the module should rely on it.

Evidence (8 cores of `yes > /dev/null`, 200 runs each): fixed 200/200 green;
yield-based mutant red at run 65; seam-bypass mutation fails in ~5 s instead
of hanging; drop-clear and drop-guard mutations still red.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@wei18

wei18 commented Sep 22, 2026

Copy link
Copy Markdown
Owner Author

PM merge record, head cec92125. Gate satisfied:

  • Fresh-context T6 at 8599a8f3: ACCEPT (9/9; see the comment above).
  • Code review, retry with bounded runs: mutations (a) and (b) red as designed; full AppMonetizationKit green; the default sleep is exactly Task.sleep(for:); production call sites unchanged; Swift 6 isolation sound. It found one required issue: with show() bypassing the injected sleep (mutation 4(c)), the suite hung instead of failing (killed at 181 s), because ManualSleeper.waitUntilParked had no bound. The first reviewer stalled on that hang for about 9 hours.
  • Fixes in cec92125:
    • waitUntilParked is bounded at 5 s. On timeout it records an issue and returns false, and callers use try #require. Its continuation resumes exactly once, by whichever of park or timeout wins. releaseNext() with nothing parked records an issue instead of trapping.
    • The stale-sleeper test's single Task.yield() raced the dismiss job. That race was observed under load, and typing the seam @MainActor did not fix it (a loaded loop went red again). The tests now await controller.dismissTask?.value, which completes after current = nil by construction. dismissTask is internal-readable (private(set), still @ObservationIgnored). The seam type is the original non-isolated @Sendable.
  • Verified from the ref: the production diff is the seam, one access-control keyword and one comment. The test file has one Task.sleep, the documented failure-path bound at :72, and no Task.yield on any path; the only mention is inside a comment. No nonisolated(unsafe) or @unchecked Sendable added. CI 21/21 green.
  • Evidence:
    • The fixed build ran 200 times under CPU load (8 × yes) with 0 red.
    • The race-regression mutant (the yield-based settle restored) went red at run 65 under the same load, so the loop does detect the race.
    • 4(c) now fails in 5.3 s with a clear message.
    • M1 and M2 are red.
    • Full AppMonetizationKit is 182/182, and the GameAppKit build and both iOS builds succeed.

Snapshot failures in the SudokuKit board batch are #1097 environment drift (macOS 27), identical on main; not from this PR.

@wei18
wei18 merged commit 73f76b4 into main Sep 22, 2026
21 checks passed
@wei18
wei18 deleted the test/1087-toast-sleep-seam branch September 22, 2026 02:10
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.

test(sudoku): ToastTests.autoDismiss_firesAfterDuration flakes inside the board --filter batch — wall-clock, pre-existing

1 participant