Skip to content

fix(tests): intermittent CI failures when hosted runners are under load - #2129

Merged
bkudiess merged 2 commits into
openclaw:mainfrom
bkudiess:bkudiess-shared-timing-flakes
Nov 12, 2026
Merged

bkudiess merged 2 commits into
openclaw:mainfrom
bkudiess:bkudiess-shared-timing-flakes

Conversation

@bkudiess

@bkudiess bkudiess commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Fixes: Core/CLI, Tray and Tray integration test jobs fail intermittently and need reruns when hosted runners are under load.

User Impact

User impact: no user-visible change. Contributors and maintainers get first-attempt green runs for these tests without reruns. Only test code and test documentation change.

Why This Change Was Made

Each flake had a test-side cause, and no product behavior was wrong:

Test (CI failure) Cause Fix
McpFileTransportTests.RequestDuringBearerRotationCannotAcquireTheReplacementEpoch (5 s TimeoutException) The rotation blocked a shared thread-pool thread while the MCP server under test also needed pool threads. The 5 s limit was an under-budgeted hang guard on event-driven waits. Rotation runs on a dedicated thread. Waits use OPENCLAW_TEST_MCP_STEP_TIMEOUT_SECONDS (30 s).
SettingsChangeCoordinatorTests.Apply_ConcurrentPermissionChanges_PreserveFinalDisabledOrder (Assert.True, line 218) A Task.Run caller was not scheduled within 2 s while the test thread blocked. SettingsChangeCoordinator serializes correctly. Dedicated thread, plus OPENCLAW_TRAY_TEST_CONCURRENCY_TIMEOUT_SECONDS (15 s).
NativeRestartAdmissionTests.InvalidRestartCleanupCannotDeleteNewerCooperatingHandle (Assert.True, line 43) Same pattern, with a 5 s wait. Same fix.
UninstallGatewayCleanupHelperTests.RegistryCleanup_* (30 s TimeoutException) A cold Windows PowerShell 5.1 start on a busy runner took 13 s and more than 30 s. Warm starts take about 0.8 s. 120 s bound via OPENCLAW_UNINSTALL_SCRIPT_TEST_TIMEOUT_SECONDS, matching GatewayPackageCleanupTests.
GatewayFixtureStartupTests.BrowserControlStartup_TransfersLiveResources(foreign: True) (WSAEACCES on rebind) Another host process claimed the freed dynamic port with an exclusive wildcard bind. The fixture's own loopback listeners would produce AddressAlreadyInUse, not WSAEACCES. Release is now proven by listener owner PID, using the production WindowsTcpListenerSnapshot. The test also checks that its own process owns the listener while it is live.
GatewayFixtureStartupTests.ForeignControlReadinessFailure_* (found during the loops; same signature as a Nov 8 CI failure) The foreign child exits with code 1 when another process took gateway port + 2 first. On that exit code only, readiness returns false, so startup retries with a new gateway, as the default path already does. Any other exit still fails. The test also asserts that it reached its injected failure.
OpenClawGatewayClientTests.ChatMessageRead_RejectsInvalidRequestBeforeSending (this PR's first CI run, job) A 2 s guard on the health-probe frame timed out 7 s into the suite, during cold start. Sibling cases took 0.5–1 s instead of about 10 ms. Second commit: 35 literal 2/3/5 s hang guards in this file now use its existing StepTimeout (OPENCLAW_TEST_GATEWAY_STEP_TIMEOUT_SECONDS, 15 s). Assertions and awaited operations are unchanged. The 300 ms negative wait, CloseHandshakeTimeout and SessionRefreshQuietInterval stay as they are.

The GatewayErrorClassifier port-digit flake was already fixed by #2023. A sweep of all 65,535 ports in four refusal formats passes on main and fails on the classifier before #2023, so this PR does not change the classifier.

Evidence

Deterministic RED/GREEN (temporary scaffolding, not committed):

  • Thread-pool saturation. A temporary helper blocked the pool's minimum worker count plus 16 more work items, before each of the 3 tests below ran:

    Test Original code (RED) Fixed code (GREEN)
    SettingsChangeCoordinatorTests Failed at the same assertion as CI (line 218 equivalent) 260 ms
    NativeRestartAdmissionTests Failed at the same assertion as CI (line 43 equivalent) 90 ms
    McpFileTransportTests TimeoutException on a pool-dependent wait Passed (18 s total under saturation)

    With +32 blocked items, all three still passed (the MCP test in 30 s).
    Repeated under the same saturation: Tray 40/40 and Shared 10/10 passed.

  • Foreign port claim. After the fixture released its control port, a temporary socket claimed that port with an exclusive wildcard bind. The old rebind assertion threw AccessDenied, the exact CI error. The new ownership assertion passed.

  • Classifier sweep. All 65,535 ports in 4 formats passed on main. The same sweep failed on the classifier before fix: keep refused Gateway connections classified as network failures #2023 (ports 401, 429 and others).

Repeated runs on the final tree (Shared, Tray and Integration loops ran concurrently, alongside other sessions' test runs on the same host):

Loop Result
Shared targets, 50× (RequestDuringBearerRotation…, RefusedTransport_ReportsNetwork…) 100/100 passed
Tray targets, 50× (SettingsChangeCoordinatorTests, NativeRestartAdmissionTests, UninstallGatewayCleanupHelperTests) 1150/1150 passed
Integration, 50× (GatewayFixtureStartupTests) 350/350 passed
Integration, 50× under concurrent loops 350/350 passed

Before the readiness-retry fix, the same integration loop failed ForeignControlReadinessFailure in 6 of 100 runs.

Review:

  • Dual-model Hanselman review: claude-opus-5.5 (high) and gpt-6-astra (long_context, high), plus two delta rounds on the final diff.
  • No CRITICAL, HIGH or MEDIUM findings. LOW findings in the new code were fixed and confirmed in the final delta round, which found none.

Gaps: Margins under real CI load are inferred from the reproductions.

Second commit (dc64206d, gateway client guards):

  • No local RED. The original 2 s guards passed under thread-pool saturation (up to +256 blocked items), CPU oversubscription, the test class pinned to 1 CPU (5×), and the full Shared suite cold on 2 CPUs (2×). The diagnosis rests on the CI timing and on code analysis:
    • OnConnectedAsync is awaited before ConnectAsync returns.
    • SessionMutationConnectionEpoch!.Value would have thrown one line earlier if the connection were not ready.
  • Loops:
    • OpenClawGatewayClientTests 50×: 22,000/22,000 passed.
    • Pinned to 1 CPU, 10×: 4,400/4,400 passed.
  • Review: a Hanselman delta review by both models found no CRITICAL, HIGH or MEDIUM issues. A LOW follow-up was left out of scope because it changes what is awaited: race the probe against the receive so that a probe that was never sent surfaces its own error.

Change Type

  • Bug fix
  • Feature
  • Refactor
  • Docs or instructions
  • Tests or validation
  • Security hardening
  • Chore or infrastructure

Scope

  • Tray or WinUI UX
  • Windows node capability
  • Local MCP or winnode
  • Gateway, connection, or pairing
  • Setup or onboarding
  • Permissions, privacy, or security
  • Tests, CI, or docs

Required proof pools

  • none: this changes only test code and test documentation, with no product, UI, MCP, Gateway or system.run behavior.

Validation

All runs used the committed tree (diff SHA256 A8231DF8…962DB against 3d5f1427). Tray runs set the isolated OPENCLAW_TRAY_DATA_DIR, OPENCLAW_TRAY_APPDATA_DIR and OPENCLAW_TRAY_LOCALAPPDATA_DIR.

  • ./build.ps1: passed; all projects built.
  • dotnet test ./tests/OpenClaw.Shared.Tests/OpenClaw.Shared.Tests.csproj --no-restore --no-build: 5847 passed, 29 skipped, 0 failed (5876 total).
  • dotnet test ./tests/OpenClaw.Tray.Tests/OpenClaw.Tray.Tests.csproj --no-restore --no-build: 6347 passed, 0 failed.
  • dotnet test ./tests/OpenClaw.Tray.IntegrationTests/OpenClaw.Tray.IntegrationTests.csproj --filter FullyQualifiedName~GatewayFixtureStartupTests: 7 passed per run; 50× twice, all passed.
  • ./scripts/validate-docs.ps1: passed (73 Markdown files).
  • git diff --check: clean.
  • Second commit dc64206d, on that exact tree:
    • dotnet test ./tests/OpenClaw.Shared.Tests/OpenClaw.Shared.Tests.csproj --no-restore --no-build: 5847 passed, 29 skipped, 0 failed.
    • --filter FullyQualifiedName~OpenClaw.Shared.Tests.OpenClawGatewayClientTests, 50×: 22,000 passed.
    • The same filter pinned to 1 CPU, 10×: 4,400 passed.

Real Behavior Proof

  • Environment tested: local Windows 11 developer machine, 32 logical processors, .NET SDK 10.0.403. Other sessions' test runs were active on the same host.
  • PR head or commit tested:
    • First commit: the uncommitted tree on 3d5f14270dd6, whose diff (SHA256 A8231DF8…962DB) is byte-identical to commit 04c83900f108.
    • Second commit: the tree whose diff (SHA256 121995FE…19B6) is byte-identical to dc64206d2b5b.
  • Exact steps or command run: the repeated targeted loops, the starvation and foreign-port RED/GREEN reproductions, and the full suites listed above.
  • Evidence after fix:
    • Shared 100/100.
    • Tray 1150/1150.
    • Integration 350/350, twice.
    • Under thread-pool saturation, the Tray targets passed in under 300 ms.
  • Observed result: no failures in any loop after the fixes. Before the fixes, the reproductions failed at the same assertions as CI, and the readiness test failed 6/100.
  • Screenshot or artifact links verified? (Yes/No/N/A): N/A (test-only change; outputs are summarized above).
  • Not verified or blocked:
    • First CI attempt on 04c83900 (run 43303557148):
      • Tray, setup, and integration tests passed, covering every test the first commit changes.
      • Core failed on the gateway client guard that the second commit fixes.
    • CI on the new head is pending.
    • The gateway client fix has no local RED.
    • FileWorkerManifestTests has the same 30 s Windows PowerShell 5.1 bound but no observed failure, so it is left unchanged.

Security Impact

  • New permissions or capabilities? (Yes/No): No
  • Secrets or tokens handling changed? (Yes/No): No
  • New or changed network calls? (Yes/No): No
  • Command or tool execution surface changed? (Yes/No): No
  • Data access scope changed? (Yes/No): No
  • If any answer is Yes, explain the risk and mitigation: N/A

Compatibility and Migration

  • Backward compatible? (Yes/No): Yes
  • Config or environment changes? (Yes/No): No. The new optional test-only timeout overrides are documented in docs/TEST_COVERAGE.md.
  • Migration needed? (Yes/No): No
  • If yes, list the exact upgrade steps: N/A

Review Conversations

  • I replied to or resolved every bot review conversation addressed by this PR.
  • I left unresolved only conversations that still need maintainer judgment.

Fix the causes of five non-UI test flakes seen on main and PR runs:

- Tests that block a thread on a handoff now start the contending work on
  dedicated (LongRunning) threads instead of Task.Run, so a starved shared
  thread pool cannot miss their 2-5 s waits. Hang guards use named,
  environment-overridable timeouts.
- The MCP bearer-rotation regression keeps its deliberately blocking
  rotation off the thread pool that the server under test needs.
- Windows PowerShell 5.1 uninstall-helper runs get the same 120 s cold-start
  bound already used by the gateway cleanup tests.
- Gateway fixture startup tests prove listener release by owner PID instead
  of rebinding a dynamic-range port another host process may claim, and
  retry readiness when the foreign child loses its port to such a process.

Co-authored-by: Copilot App <[email protected]>
@clawsweeper

clawsweeper Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

🦞👀
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 priority bug or improvement with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Nov 12, 2026
@clawsweeper

clawsweeper Bot commented Nov 12, 2026

Copy link
Copy Markdown

Codex review: needs maintainer review before merge.

What this changes

This PR isolates blocking test work from the shared thread pool, adjusts test deadlines, and checks fixture listener cleanup by process ownership.

Example: The shared thread pool is saturated while the settings-permission concurrency test starts its disabling caller.

  • Before: Task.Run may miss the two-second handoff deadline despite correct settings serialization.
  • After: A dedicated worker performs the handoff with a configurable 15-second hang guard while preserving the final permission-order assertion.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch is focused and source-supported, with substantial reported test validation; the exact-head Shared-test failure still needs classification, and its detailed logs were inaccessible here.
Proof confidence 🦐 gold shrimp (3/6) Test-only changes require no shipped-entry-point proof; the supplied validation describes starvation and port-conflict reproductions, repeated targeted runs, and full-suite results.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Test only · Worth it: Yes · Fix scope: Complete
User problem: Contributors and maintainers encounter intermittent test-job failures and unnecessary reruns on loaded hosted runners.
Reason: The maintainer-authored direction is authorized, and the source supports the reported test-side causes; new environment overrides affect test deadlines only.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR contains useful test stabilization absent from main, and inspection found no introduced defect. The failed Shared-test CI step remains unattributed.

Priority: P2
Reviewed head: 04c83900f10836ac38aa253ca45526d27ad372de

Before merge

None.

Findings

None.

Agent review details

How this fits together

The changed test suites exercise MCP token rotation, settings serialization, restart-file coordination, uninstall helpers, and Gateway fixture resource cleanup; they produce assertions and CI results without changing shipped behavior.

flowchart LR
  A[CI test runner] --> B[Dedicated test workers]
  A --> C[Gateway fixture processes]
  B --> D[Existing production owners]
  C --> E[Loopback listeners]
  E --> F[Process ownership assertions]
  D --> G[Contract assertions]
Loading

Technical review

Best possible solution:

Retain the focused scheduling, deadline, and listener-ownership repairs within the existing tests while preserving their behavioral assertions.

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

Main contains pool-dependent work paired with blocking handoff waits and cleanup assertions that rebind released dynamic ports; the PR reports targeted before/after reproductions, which this read-only review did not execute.

Is this the best way to solve the issue?

The patch addresses test-owned scheduling and observation failures using existing owners, preserves ordering and rejection checks, and limits readiness retries to the fixture child's documented bind-failure result.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • MCP bearer-rotation regression keeps the original intent (932bc0e: Sandbox-backed file transfers require stale bearer requests to remain bound to their original authentication epoch.)
  • Settings concurrency regressions keeps the original intent (17a8b03: SettingsChangeCoordinator owns serialized synchronous effects; the later Ollama change also requires permission revocation to preserve final disabled order.)
  • Native restart admission regression keeps the original intent (3eed1f1: Restart recovery must preserve a newer cooperating writer's valid handle during invalid-file cleanup.)
  • Uninstall script host keeps the original intent (78d08e4: Exercise selected production uninstall functions under Windows PowerShell 5.1 without running destructive top-level uninstall code.)
  • Browser-control fixture startup and disposal keeps the original intent (c25f7ba: Browser-proxy isolation proof needs reliable ownership transfer and cleanup of loopback fixture listeners and foreign children.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Pinned change and unchanged main behavior: The introduced diff changes five test files and one documentation file; main retains the pool-dependent handoffs, shorter deadlines, and port-rebind cleanup assertions. (04c83900f108)
  • Foreign-child retry matches its producer: ListenForControlAsync returns exit code 1 when listener.Start throws SocketException; StartGatewayAsync already retries false readiness results with cleanup and an eight-attempt bound. (tests/OpenClaw.GatewayFixtureHost/Program.cs:292, 04c83900f108)
  • Security regression assertions retained: The bearer-rotation test still rejects the stale request and accepts the replacement bearer; only rotation scheduling and test hang guards change. (tests/OpenClaw.Shared.Tests/FileTransfer/McpFileTransportTests.cs:164, 04c83900f108)
  • Current CI failure is not attributable from available evidence: The exact-head Core and CLI job built successfully, then failed Run Shared Tests; Connection, CLI, and File Worker tests did not run. Its annotation contains only exit code 1. Downloading logs was blocked at GitHub's Azure blob redirect, so neither a patch cause nor an outside cause is established. Job: https://github.com/openclaw/openclaw-windows-node/actions/runs/43303557148/job/131480942309. (04c83900f108)
  • Validation evidence and limits: The PR reports full build, Shared and Tray suite passes, targeted stress loops, and deterministic before/after starvation and foreign-port reproductions. Exact-head Tray/setup/integration CI passed; CI Gate failed and C# security remained in progress at inspection. No builds or tests were run during this read-only review. (04c83900f108)
  • Applicable review policy: The complete root and docs AGENTS.md files were read and applied. No tests subtree AGENTS.md or maintainer-notes directory was found. The user's single-reviewer and read-only instructions supersede helper execution and mutation requirements; no additional reviewer ran, and the checkout remained clean. (AGENTS.md, 04c83900f108)

Likely related people:

  • Scott Hanselman: Raw commit 617d638 adds tests/OpenClaw.Tray.Tests/SettingsChangeCoordinatorTests.cs:193 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 617d63841ba4; files: tests/OpenClaw.Tray.Tests/SettingsChangeCoordinatorTests.cs)
  • Sebastien Tardif: Raw commit c25f7ba adds tests/OpenClaw.Tray.IntegrationTests/GatewayFixtureStartupTests.cs:17 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: c25f7ba06b71; files: tests/OpenClaw.Tray.IntegrationTests/GatewayFixtureStartupTests.cs)
  • Mert Başar: Raw commit 78d08e4 adds tests/OpenClaw.Tray.Tests/UninstallScriptHost.cs:8 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 78d08e401985; files: tests/OpenClaw.Tray.Tests/UninstallScriptHost.cs)

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Change footprint Production +0/-0; tests +118/-28; documentation +9/-1 Growth is confined to existing tests and supports distinct scheduling, process-readiness, and listener-cleanup failures.

Labels

Label changes:

  • add P2: Intermittent shared CI failures burden contributors and maintainers, without changing shipped user behavior.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: Intermittent shared CI failures burden contributors and maintainers, without changing shipped user behavior.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 12, 2026, 3:59 PM ET / 20:59 UTC.

…start

Replace 35 literal 2/3/5 s hang guards on event-driven loopback steps in
OpenClawGatewayClientTests with the file's existing named StepTimeout
(OPENCLAW_TEST_GATEWAY_STEP_TIMEOUT_SECONDS, default 15 s). PR CI failed
ChatMessageRead_RejectsInvalidRequestBeforeSending at a 2 s probe-frame
guard 7 s into the suite, while sibling cases took 0.5-1 s instead of
about 10 ms. Assertions and awaited operations are unchanged; the 300 ms
negative wait, CloseHandshakeTimeout and SessionRefreshQuietInterval stay.

Co-authored-by: Copilot App <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal priority bug or improvement with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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