Skip to content

Fix flaky TerminalWebSocketTests final-output drain: deliver queued producer output before ending - #21471

Merged
David Fowler (davidfowl) merged 1 commit into
mainfrom
agent/fix-terminal-websocket-flake
Nov 10, 2026
Merged

David Fowler (davidfowl) merged 1 commit into
mainfrom
agent/fix-terminal-websocket-flake

Conversation

@davidfowl

Copy link
Copy Markdown
Collaborator

Description

Fixes an intermittent failure in TerminalWebSocketTests.BrowserView_DrainsFinalOutputAndGraphicsBeforeDisconnect. The browser receives Close while it is still waiting for the frame titled Final screen.

Evidence

Dashboard ci.yml first attempts, Oct 16–30 (main push and PR):

  • Ubuntu: 2 failures out of 389 completed attempts, both useGrpc: True:
  • Windows had 0 failures of this test in 383 completed attempts.

Signature: ReadUntilAsync expected Binary but got Close. The server logged no drain timeout, so the dashboard drained successfully, but on a mirror frame that never contained the final output.

No open issue, PR or quarantine covers this test.

Root cause (test fixture)

  1. The test writes the final output, waits for WaitForProducerTextAsync("completed"), then calls EndTerminalAsync(includeHmpExit: true), which disposes the producer's Hmp1PresentationAdapter.
  2. WaitForProducerTextAsync only proves that the producer terminal applied the bytes. In Hex1b 0.173.0, Hmp1PresentationAdapter.WriteOutputAsync only enqueues output on each viewer's channel. A separate write pump delivers it to the transport.
  3. DisposeAsync → DisposeSessionAsync completes the channel and discards queued, undelivered output.
  4. If the write pump hadn't flushed yet, the final lines, OSC title and kitty graphics never reached the dashboard mirror. The mirror then correctly drained a stale frame and closed.

Hex1b's graceful path is TerminalCompleted(exitCode), which queues HMP Exit behind every queued output ("Exit must follow every queued output/replay write on the same pump").

Fix

  • EndTerminalAsync(includeHmpExit: true) now ends the producer like an exited workload:
    1. Call Presentation.TerminalCompleted(0).
    2. Wait until the Exit frame has been written to every viewer transport (or the transport closed).
    3. Then dispose.
  • The producer's server-side output stream tracks HMP frame headers to observe Exit.
  • This replaces the fixture's synthetic gRPC Exit frame: the real Exit now flows through the HMP stream ahead of Ended.
  • includeHmpExit: false still models an abrupt producer end.
  • No product code, assertions or timeouts changed, and there are no sleeps or retries.

Regression check

  • Adds slowProducerDelivery cases. They delay each producer transport write by 500 ms after the initial frame, so output is deterministically still queued when the terminal ends.
  • Results were collected locally on Linux (net11.0 Debug):
slowProducerDelivery cases (both transports) Existing cases
Before (fence bypassed) 20/20 failed (Expected: Binary, Actual: Close) 20/20 passed
After 40/40 passed (20 runs) 40/40 passed
  • Full TerminalWebSocketTests class: 16 runs (2 parallel processes × 8), 0 failures, 67/67 tests each run.
  • Aspire.Dashboard.Playwright.Tests (which shares TerminalTestProducer.cs) builds.

Not addressed here

BrowserView_ProducerDisconnectClosesBrowserWhileWaitingForAcknowledgement failed 3 times in 383 completed Windows first attempts (useGrpc: True).

It has a different signature: the server's 2 s close handshake times out and aborts, and the client's CloseOutputAsync then fails with WSAECONNRESET. It isn't related to producer output delivery. I couldn't attribute it deterministically to a code-level cause, so it is left out of this PR.

Checklist

  • Is this feature complete?
    • Yes. Ready to ship.
    • No. Follow-up changes expected.
  • Are you including unit tests for the changes and scenario tests if relevant?
    • Yes
    • No
  • Did you add public API?
    • Yes
    • No
  • Does the change make any security assumptions or guarantees?
    • Yes
    • No

🤖 Posted by AspireAgent (AI Agent)

TerminalTestHost.EndTerminalAsync disposed the Hex1b HMP producer right after
the producer applied its final output. Hmp1PresentationAdapter only enqueues
output for each viewer's write pump and disposal discards undelivered output,
so the dashboard mirror could miss the final lines, title and graphics and
BrowserView_DrainsFinalOutputAndGraphicsBeforeDisconnect intermittently saw
Close instead of the final frame.

End the producer like an exited workload instead: call TerminalCompleted so
HMP Exit is queued behind all output, wait until Exit reaches every viewer
transport, then dispose. This replaces the fixture's synthetic gRPC Exit.
Add slow-delivery cases that fail deterministically without the fence.

Co-authored-by: Copilot <[email protected]>
@github-actions

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.sh | bash -s -- 21471

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.ps1) } 21471"

@aspire-repo-bot
aspire-repo-bot Bot requested a balanced review from Copilot October 30, 2026 15:47
@github-actions github-actions Bot added the needs-area-label An area label is needed to ensure this gets routed to the appropriate area owners label Oct 30, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Tests selector

1 / 100 PR test projects · 0 PR jobs, from 3 changed files.

Selected PR test projects (1 / 100)

Aspire.Dashboard.Tests

Selected PR jobs (0)

none


How these were chosen — grouped by what changed

🧪 tests/Aspire.Dashboard.Tests/Shared/TerminalTestHost.cs (changed test)
→ 1 directly: Aspire.Dashboard.Tests

🧪 tests/Aspire.Dashboard.Tests/Shared/TerminalTestProducer.cs (changed test)
→ 1 directly: Aspire.Dashboard.Tests

🧪 tests/Aspire.Dashboard.Tests/Terminal/TerminalWebSocketTests.cs (changed test)
→ 1 directly: Aspire.Dashboard.Tests

Job reasons

none


Selection computed for commit 9db0f85.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues are identified for the test-only shutdown and delivery changes.

No open issues 🎉

What changed in this PR

Fixes a flaky dashboard terminal test by making the shared producer fixture deliver queued output before graceful shutdown. No product code changes are included.

Changes:

  • Waits for the real HMP Exit frame to reach viewer transports, or for those transports to close, before disposing the producer.
  • Removes the synthetic gRPC Exit frame while preserving abrupt-shutdown behavior.
  • Adds slow-delivery regression cases for both transports without changing existing assertions or timeouts.
File Description
tests/​Aspire.Dashboard.Tests/​Terminal/​TerminalWebSocketTests.cs Adds slow-delivery cases and passes cancellation tokens to terminal shutdown.
tests/​Aspire.Dashboard.Tests/​Shared/​TerminalTestProducer.cs Tracks HMP Exit delivery and supports delayed transport writes.
tests/​Aspire.Dashboard.Tests/​Shared/​TerminalTestHost.cs Uses graceful producer completion and removes synthetic Exit injection.

Review effort: Balanced

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good. The root cause is in the fixture (disposing the presentation before Hex1b delivered queued output). Waiting for the producer's real HMP Exit (or stream close) before disposal keeps the Exit-then-Ended ordering, and the Exit detection matches the HMP framing (type byte + 4-byte LE length). All 67 TerminalWebSocketTests pass at this head on Linux/Windows CI, and repeated local runs were green.

@davidfowl
David Fowler (davidfowl) merged commit cbb4f01 into main Nov 10, 2026
65 checks passed
@microsoft-github-policy-service microsoft-github-policy-service Bot added this to the 17.1 milestone Nov 10, 2026
@aspire-repo-bot

Copy link
Copy Markdown
Contributor

✅ No documentation update needed.

docs_optional → test_only. No signals triggered (signal_count 0). All 3 changed files match tests/** (tests/Aspire.Dashboard.Tests/Shared/TerminalTestHost.cs, TerminalTestProducer.cs, Terminal/TerminalWebSocketTests.cs); flaky-test fix with no user-facing change.

Ankit Jain (radical) pushed a commit that referenced this pull request Nov 10, 2026
…t test) (#21500)

## Description

Fixes an intermittent Windows failure in
`TerminalWebSocketTests.BrowserView_ProducerDisconnectClosesBrowserWhileWaitingForAcknowledgement(useGrpc:
True)`. The test fails when the browser's `CloseOutputAsync` reply
throws `WebSocketException: The remote party closed the WebSocket
connection without completing the close handshake` (inner error:
`SocketException: An existing connection was forcibly closed`).

No issue tracks this. It is a different test and a different root cause
from #21471, which fixes the producer-side final-output drain in
`BrowserView_DrainsFinalOutputAndGraphicsBeforeDisconnect`.

### Evidence

- Failure: [main push run 41074175594, Dashboard (windows-latest) job
124127031025](https://github.com/microsoft/aspire/actions/runs/41074175594/job/124127031025),
sha 82d064c.
- At 2.689s the server logged `Timed out draining the final terminal
frame` (expected, because this test never acks).
- At 5.305s it logged `Terminal close handshake failed` with
`TaskCanceledException` at the close-reply wait.
- The client's stack shows it called `CloseOutputAsync` as soon as
`ReadCloseAsync` returned, so the browser received the Close after the
server had already aborted.
- Denominators (`ci.yml` attempt 1, Oct 16–30, from a partial survey of
the window): the test failed in 1 of 56 completed Aspire.Dashboard.Tests
Windows jobs and 0 of 56 Ubuntu jobs.
- The test code and `TerminalWebSocketProxy` are unchanged between
82d064c and current main, and the test passes on later main runs. I
also queued a rerun of the failed job on the same head.

### Root cause

`TerminalWebSocketProxy.CloseAsync` sends Close and then waits for the
browser's Close reply. It uses the same 2-second `s_closeTimeout` that
bounds frame drain and sender teardown, and calls `socket.Abort()` when
that expires.

In this test the browser is an in-process `ClientWebSocket` sharing the
test host's thread pool. On a loaded Windows runner its reply can arrive
more than 2 seconds after the server sends Close; the CI log shows about
0.6s of scheduling delay even before `CloseAsync` started. The server
then resets the connection under the browser's in-flight reply.

Waiting for the reply only delays resource cleanup; the browser already
has the authoritative close status. So the short drain budget is the
wrong bound for this step.

**Deterministic repro on main (Linux):** delay the browser's Close reply
by 3 seconds after `ReadCloseAsync`. It fails with the identical
exception:

```
failed ...TerminalWebSocketTests.BrowserView_DelayedCloseReplyCompletesCloseHandshake (5s 869ms)
  WebSocketException : The remote party closed the WebSocket connection without completing the close handshake.
  ---- IOException : Unable to write data to the transport connection: Connection reset by peer.
```

### Fix

- Add a dedicated `s_closeHandshakeTimeout` (10s) for the Close reply
wait in `CloseAsync`.
- The 2-second `s_closeTimeout` still bounds the final-frame drain and
sender teardown, so user-visible close latency is unchanged.
- An unresponsive or disconnected browser is still aborted, and a socket
error ends the wait immediately.

### Validation

- New regression test
`BrowserView_DelayedCloseReplyCompletesCloseHandshake`: fails before the
fix (above) and passes after.
- `Aspire.Dashboard.Tests.Terminal` namespace: 113/113 passed.
- Full `Aspire.Dashboard.Tests`: 2583/2583 passed.

## Checklist

- Is this feature complete?
  - [x] Yes. Ready to ship.
  - [ ] No. Follow-up changes expected.
- Are you including unit tests for the changes and scenario tests if
relevant?
  - [x] Yes
  - [ ] No
- Did you add public API?
  - [ ] Yes
  - [x] No
- Does the change make any security assumptions or guarantees?
  - [ ] Yes
  - [x] No

---
**🤖 Posted by AspireAgent (AI Agent)**

Co-authored-by: davidfowl <[email protected]>
Co-authored-by: Copilot <[email protected]>
Maddy Montaquila (maddymontaquila) added a commit that referenced this pull request Nov 13, 2026
…s, trace log previews, test flakes (#22232)

The remaining dashboard work for `release/17.0`, as one squashable PR:
one commit per change, in this order.

**Backported from `main` (cherry-picked with `-x`):**

1. #21500: Fix flaky terminal
WebSocket close handshake abort (test only)
2. #21503: Fix bUnit JS timeout
flakes in StructuredLogs/Traces/TraceDetails tests (test only)
3. #21471: Fix flaky
TerminalWebSocketTests final-output drain (test only)
4. #21924: Read resource row
state at every density in dashboard browser tests (test only)
5. #22142: Fix inconsistent
dashboard action icon colors. It conflicted with #22188 in
`ResourcesLayout.razor`: the resolution keeps the row menu on every row,
parameters included, with #22142's icon color.

**From open PRs against `main`, applied as they stand:**

6. #22228: Fix resource sidebar
hover state after selection
7. #22229: Keep resource picker
popup width consistent

**New:**

8. Render the trace log preview only for the marker that's hovered or
focused. Each log marker rendered its own hidden preview for the
tooltip, so a span with many logs built over a million hidden elements.
The page now renders one preview, filled on hover or focus. This
addresses Copilot's review on #22230.

9. Center tag group chevrons over the state dot column. In the compact
sidebar at rest, the rows' state dots form a column at the end of the
list, and the group header's chevron sat 13px past it. This replaces
#21996.
10. Fix two resource pane Playwright tests:
- `Rows_KeepDensity` expected parameter rows in the expanded list to
have no overflow menu, but every row has one now.
- `FilterAndGrouping` could hover before the feedback prompt pushed the
page down 40px, leaving the pointer on the brand. It now waits for the
prompt.

When `release/17.0` merges back into `main`, the `Rows_KeepDensity`
change has to come along with it, because #22228's version of that test
expects no menu on parameter rows.

Once this is in `release/17.0`, `release/17.0` merges back into `main`.
#22228 and #22229 can then close on `main`.

## Customer Impact

Fixes and polish to the 17.0 dashboard: icon colors, the resource
sidebar and picker, and trace pages with many logs.

## Testing

- `Aspire.Dashboard.Components.Tests`: 1,447 passed, 0 failed.
- `ResourcePaneResponsiveTests.FilterAndGrouping_*` and
`Rows_KeepDensity*`: 11 passed. `FilterAndGrouping` passed 5 runs in a
row after the fix; before it, the 2000px cases failed in about half the
runs.
- The chevron alignment was checked in the browser at 1440px: the
chevron and the dots are both centered 25px from the list's end.

## Risk

Low. Dashboard-only, and the backports are unchanged apart from the one
conflict described above.

## Regression?

No.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: David Fowler <[email protected]>
Co-authored-by: davidfowl <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: Maddy Montaquila <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: James Newton-King <[email protected]>
Co-authored-by: Sébastien Ros <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-terminal Terminal/PTY support — TerminalHost, WithTerminal, dashboard terminal view flaky-test needs-area-label An area label is needed to ensure this gets routed to the appropriate area owners

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants