Skip to content

test(chat): await settling tasks instead of wall-clock polling in view model tests - #163792

Merged
steipete merged 2 commits into
mainfrom
steipete/objective-taussig-f93f57
Oct 3, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/objective-taussig-f93f57

Conversation

@steipete

@steipete steipete commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: macos-swift (packages) intermittently fails with timeouts in ChatViewModelTests and ChatViewModelSessionActionTests when the full OpenClawKit package runs its tests in parallel on a loaded runner. A local stress run of the Chat filter hit 21 such waits: question, Swarm, progress-card, and history "request starts" waits, plus branch switch, rewind, and fork start signals.

User Impact

No user-visible change. PRs stop picking up a red macos-swift (packages) job, and its reruns, from these suites.

Why This Change Was Made

This is the follow-up to #163719, for the same flake class. These tests detected product progress with waitUntil, which has a 15 s wall-clock deadline, or with a waitForForkStart race against a 15 s sleep. Under a full parallel package run the MainActor carries a large backlog. Any wait whose condition needs several sequential MainActor hops expires while the product work is still queued, not stuck.

Each listed wait now awaits a deterministic signal instead:

  • Request starts on a test-held gate. The test awaits the fake's own arrival signal. This uses SessionSubscribeGate.waitUntilBlocked(), a new QuestionListGate.waitUntilWaiting(), or SessionActionCompletionGate.waitUntilStarted() without its sleep race. An ungated sessions.list uses a non-blocking stream signal. waitForForkStart, waitForBranchSwitchActivityToClear, and waitForBranchReload are deleted. The waitForForkStart change also converts four non-listed call sites that shared the helper.
  • Completion of owned work. The test awaits the existing handle: bootstrapTask (including the cancelled bootstrap it captured before refresh()), questionRefreshRetryTask until the retry chain settles, or the test's own Task.
  • Completion of unowned work the product spawns. handleTransportEvent now returns the Task that settles the event's transcript or question reconciliation, in the same way the provider wizard actions do. That covers route-change, reconnect, and seqGap recovery, remote rewind and branch-switch reconciliation, and question events. scheduleProgressCardFetch and handleQuestionEvent return their fetch and refresh Tasks. The production event listener discards the value.
  • Two cases no handle can reach use a small Observation-driven wait that resumes on mutation, not on a clock. One is the progress fetch that admitted history schedules internally. The other is listener delivery in event listener does not retain discarded view model. That test now probes delivery with a disconnect instead of a reconnect. The reconnect fan-out legitimately retains the model while its tasks run, so the old test was timing that drain, not listener retention.

No timeouts were lengthened and no retries were added. Several assertions are now stricter, because they run after the owning work has settled instead of racing it. For example, the stale bootstrap is awaited before the "stale history is ignored" check.

Production code is net −8 lines. The return plumbing is funded by folding the three repeated matchesCurrentSessionKey(incoming:agentId:current:) guards in handleSessionsChangedEvent into one local predicate, with identical semantics. Tests are net −132 lines.

Evidence

Deterministic saturation probe. A temporary suite, not committed, floods the MainActor with N yielding tasks that each spin 1 ms. Each MainActor hop then waits about N ms. The probe runs in the same filter as the target tests, with swift test --package-path apps/shared/OpenClawKit --skip-build --disable-sandbox --filter '<tests>|<probe>'. Each run used a private HOME, CFFIXED_USER_HOME, OPENCLAW_STATE_DIR, and TMPDIR.

  • N=2500 and N=5000 expose only 1 and 2 of these waits, because most need fewer sequential hops than the navigation bootstrap did. N=16000 puts a single hop past the 15 s deadline. The probe suite is named so that it starts first, which keeps the backlog in place before the targets enqueue work.
  • Before, at N=16000, on main:
    • ChatViewModelTests: 11 of the 12 listed tests fail with 12 issues; the parameterized route test fails both cases. Each fails at its listed "request starts" wait, for example question get request, older Swarm capability request starts, first bootstrap history request is in flight, health inspected the current progress capability, and event listener receives health. Swarm child lifecycle event still triggers canonical session refresh passed narrowly at 30 s, because its request needs only one hop.
    • ChatViewModelSessionActionTests: remote branch switch refreshes current transcript and branches only fails at unlocked.
  • After, at N=16000, on this head: all 13 ChatViewModelTests cases and all 9 ChatViewModelSessionActionTests cases pass, and every test finishes while the flood is still running. The suites took 297 s and 313 s inside a 420 s flood. The same tests unloaded take about 0.03 s.
  • Known gap. The seven waitForForkStart tests from the stress run do not fail under any probe I could build. I tried the MainActor flood and a global-pool flood with LIBDISPATCH_COOPERATIVE_POOL_STRICT=1 at about 10 s and about 25 s per hop. The helper's TaskGroup children inherit MainActor isolation, so its 15 s sleep starts behind the same backlog as the product path and never wins the race. Only the CPU-starved stress run let the sleep win. The fix removes that race outright; the started stream still controls ordering.

Flake-fix proof bar (writing tests, Flake triage step 4), all on this head with a private HOME, CFFIXED_USER_HOME, OPENCLAW_STATE_DIR, and TMPDIR:

  • 20 of 20 clean standalone runs of each file. ChatViewModelTests ran 339 tests in about 1.2 s, and ChatViewModelSessionActionTests ran 44 tests in about 0.1 s.
  • 3 of 3 clean runs of the stress run's Chat filter, skipping ChatMathBlockViewTests, ChatLinkPreviewRenderingTests, and ChatMarkdownBlockSegmenterTests. Each run passed 1,431 tests in 107 suites in 10–12 s. This is the local stand-in for the original shard.
  • 3 of 3 clean runs of the original shard on this head. These are CI's own macos-swift (packages) full-package swift test --parallel step, in run 37098830253, attempts 1–3, with the two reruns done by maintainer decision. Each run passed 2,167 tests in 183 suites, in 34.7 s, 137.7 s, and 144.8 s. The slower attempts ran on a loaded runner, which is the condition that used to trip these waits. openclaw/ci-gate is green on attempt 3.
  • Owner sibling tests: --filter ChatViewModel covers 10 suites, and 528 of 528 passed.
  • Codex autoreview at the P2 threshold reported no actionable findings.

Checks. swiftformat --lint and swiftlint --strict with the iOS config are clean for the four touched sources. The test files are outside the configured lint scope. git diff --check is clean. I did not run the full OpenClawKit suite locally, because it reaches the Keychain through the GenericPasswordKeychainStore and GatewayTLS fixtures.

Not committed as a regression test. The repro needs a sustained multi-minute MainActor flood, which is far over the test cost budget. The structural guard is that none of the converted waits has a deadline left.

Related: #163719

…w model tests

ChatViewModelTests and ChatViewModelSessionActionTests detected product
progress with 15 s wall-clock waits. Under a full parallel package run the
MainActor backlog makes multi-hop work outlive those deadlines while still
queued, so macos-swift (packages) flaked.

Request-start waits now await the fakes' own arrival signals, completion
waits await bootstrapTask, questionRefreshRetryTask, or a settling Task that
handleTransportEvent, scheduleProgressCardFetch, and handleQuestionEvent now
return, and the two cases no handle reaches use an Observation-driven wait.
The waitForForkStart, waitForBranchSwitchActivityToClear, and
waitForBranchReload deadline helpers are removed. Production code is net
-8 lines: the return plumbing is funded by folding three repeated
current-session guards in handleSessionsChangedEvent into one predicate.
@clawsweeper

clawsweeper Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 2, 2026
@clawsweeper

clawsweeper Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 3, 2026, 2:24 AM ET / 06:24 UTC (Revision 4).

ClawSweeper review

What this changes

The native chat tests await request signals and reconciliation tasks instead of wall-clock polling, with internal completion handles exposed by the chat view model.

Merge readiness

✅ Ready for maintainer review

This remains useful work: current main still contains the affected deadline-based waits. No introduced correctness defect was found, and the supplied mergeability evidence resolves the previous conflict blocker.

Priority: P2
Reviewed head: 2b6b79d9ccfec5099d25369e9483f9076debb60f

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused synchronization changes retain meaningful assertions and have unusually detailed flake evidence with its coverage limits disclosed.
Proof confidence 🦞 diamond lobster (5/6) Not applicable: The repository-state context identifies a MEMBER author, so the external contributor gate does not apply. Captured saturation and shard results directly support the changed native test synchronization; they precede the merge refresh and were not independently rerun. No stored-data contract or material authority boundary changes.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The repository-state context identifies a MEMBER author, so the external contributor gate does not apply. Captured saturation and shard results directly support the changed native test synchronization; they precede the merge refresh and were not independently rerun. No stored-data contract or material authority boundary changes.
Evidence reviewed 9 items Pinned introduced change: The reviewed delta is the supplied merge-base-to-head comparison. Production changes return existing tasks and consolidate equivalent session predicates; they preserve the task bodies, ownership checks, and asynchronous dispatch.
Deterministic test synchronization: Request gates signal their actual suspension points. The revised tests await bootstrap, reconciliation, or retry completion and retain assertions about stale responses, branch state, and request ownership.
Current main still needs this work: Fetched main retains waitForForkStart, waitForBranchReload, and waitForBranchSwitchActivityToClear and their call sites. Its transport event handler also still returns no completion handle, so the central change is not already implemented there.
Findings None None.
Security None None.

How this fits together

OpenClaw's shared Apple chat view model receives Gateway events and updates transcripts, questions, and progress cards. Its tests now synchronize with those operations before checking the resulting state.

flowchart TD
  A[Gateway events] --> B[Native chat view model]
  B --> C[Session and freshness checks]
  C --> D[Reconciliation tasks]
  D --> E[Updated chat state]
  F[Test request gates] --> G[Await completion]
  D --> G
  G --> H[Behavior assertions]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Other -140. Total -140 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 0 0 0 0
Tests 0 0 0 0
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 6 166 306 -140
Total 6 166 306 -140

Review metrics

None.

Technical review

Best possible solution:

Keep synchronization at the existing task and request owners, preserving behavioral assertions without runner-speed deadlines.

Do we have a high-confidence way to reproduce the issue?

Yes, the current-main deadline waits and sequential MainActor work establish a clear source-backed failure mechanism, supported by the captured saturation results. This reviewer did not execute a reproduction.

Is this the best way to solve the issue?

Yes, awaiting existing completion owners and explicit request signals is a focused repair that preserves assertions and avoids extending timeouts or adding retries.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against c9381f9f0faf.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded repair of native test synchronization that causes intermittent package-check failures, with no changed user-facing behavior.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The repository-state context identifies a MEMBER author, so the external contributor gate does not apply. Captured saturation and shard results directly support the changed native test synchronization; they precede the merge refresh and were not independently rerun. No stored-data contract or material authority boundary changes.

Evidence

What I checked:

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (3 earlier review cycles)
  • reviewed 2026-10-02T21:26:44.828Z sha 9ff111b :: blocked before merge. :: none
  • reviewed 2026-10-03T05:12:42.477Z sha 9ff111b :: needs changes before merge. :: none
  • reviewed 2026-10-03T06:09:59.611Z sha 9ff111b :: needs changes before merge. :: none

@steipete
steipete marked this pull request as ready for review October 3, 2026 05:07
@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Oct 3, 2026
@steipete
steipete merged commit 9012bcd into main Oct 3, 2026
72 checks passed
@steipete
steipete deleted the steipete/objective-taussig-f93f57 branch October 3, 2026 06:46
@steipete

steipete commented Oct 3, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 4, 2026
…w model tests (openclaw#163792)

ChatViewModelTests and ChatViewModelSessionActionTests detected product
progress with 15 s wall-clock waits. Under a full parallel package run the
MainActor backlog makes multi-hop work outlive those deadlines while still
queued, so macos-swift (packages) flaked.

Request-start waits now await the fakes' own arrival signals, completion
waits await bootstrapTask, questionRefreshRetryTask, or a settling Task that
handleTransportEvent, scheduleProgressCardFetch, and handleQuestionEvent now
return, and the two cases no handle reaches use an Observation-driven wait.
The waitForForkStart, waitForBranchSwitchActivityToClear, and
waitForBranchReload deadline helpers are removed. Production code is net
-8 lines: the return plumbing is funded by folding three repeated
current-session guards in handleSessionsChangedEvent into one predicate.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal backlog priority with limited blast radius. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant