Mathias Fredriksson c7b144cc76 fix(coderd/x/chatd): prevent a chat stream relay deadlock on repeated episode selection (#31187)
Stacked on #31196, which must merge first.

When a chat's worker runs on the same replica as the stream, the chat
stream relay can deadlock with the in-process parts endpoint. Live model
output then stops on that stream until the client reconnects, while
saved messages, status and queue updates keep arriving.

The stream loop configures the relay forwarder after every newer
snapshot, and queueing a message, deleting or promoting a queued one,
interrupting, and recording a retry keep the episode. The forwarder sent
a selection each time, and the endpoint answers each one by sending the
episode again from `seq` 1, so K updates on an N-part episode moved
about K times N parts. While the stream loop reads slowly, the resent
parts fill the buffers and the endpoint's serve loop waits to send.
Three unread selections fill the pipe's one-slot channel, the endpoint's
selection reader and its one-slot channel to the serve loop, and the
forwarder's next `WriteControl` never returns.

- The forwarder sends a selection only on a new connection or when the
target changes. Before #31196, only a repeated selection restarted live
output after the part buffer dropped a slow subscriber.
- The endpoint's selection reader replaces an unread selection instead
of waiting, so the endpoint does not depend on how a client sends
selections. After the first change the forwarder cannot practically
reach the cycle, since it drops other episodes' parts without waiting.
Dropping one loses nothing, because every selection starts again from
`seq` 1.

<details>
<summary>Investigation and decision log</summary>

### Evidence

`TestStreamRelayForwarderSelectsOnlyChangedTargets` configures one
200-part episode 10 times: before the forwarder change it sees 10
selections and 2000 parts, after it 1 selection and 200 parts.
`TestStreamPartsEndpointLatestSelectionWinsWhileBlocked` fails in 10 of
10 runs without the reader change and with a 15-slot queue that replaces
nothing.
`TestStreamRelayForwarderDeliversLivePartsAfterSameEpisodeReconfigures`
stalls the stream loop until the buffers fill, configures the same
episode 1000 times, then requires a new part to arrive; it fails in 20
of 20 runs with both changes reverted and passes with either one alone.
All three pass with `-race -count=20`.

A goroutine dump taken with the world stopped, from a test that used the
real forwarder, local dialer and part buffer with a 2000-part episode,
shows the four goroutines at the waits described above and every buffer
full. The deadlock formed in 20 of 20 runs under `-race`, after 4 to 384
same-episode selections. After the test read every buffered part, added
live parts, configured the relay 11 more times (once for a new episode)
and fired the buffer's send timeout, no part arrived.

```
F goroutine 73 [select]: streamPartsChannelClientTransport.WriteControl stream_parts_transport.go:142 <- (*streamRelayForwarder).loop.func4 stream_relay.go:148 <- loop stream_relay.go:207
R goroutine 74 [select]: streamPartsEndpoint.serve.func1() stream_parts.go:84
E goroutine 83 [select]: streamPartsChannelServerTransport.WriteEvents stream_parts_transport.go:120 <- streamPartsEndpoint.serve stream_parts.go:169
L goroutine 84 [select]: (*streamPartsTransportSession).readLoop stream_parts_transport.go:236
f.parts=128/128 s.parts=128/128 eventsCh=128/128 controlCh=1/1 SelectEpisode started=13 returned=12
```

A test goroutine in place of the stream loop dropped repeated parts and
spent a fixed sync time on each hint before it selected the same episode
again (200 hints, 3 runs per row, real clock):

| Sync time per hint | Hint interval | Deadlock formed |
|--------------------|---------------|-----------------|
| 1 ms               | 1 ms          | 1 of 3          |
| 5 ms               | 5 ms          | 1 of 3          |
| 1 ms               | 2 ms or 5 ms  | 0 of 6          |
| 5 ms               | 10 ms         | 0 of 3          |

The deadlock formed only when selections arrived about as fast as the
stream loop handled them. How often that happens in production is not
measured.

Selecting a new episode every time under the same pressure did not
deadlock in 300 of 300 iterations, because the forwarder drops parts of
other episodes without waiting for the stream loop. Over the WebSocket
transport with the pipeline full, 1263 selections over 2999 iterations
all returned; when the stream loop then stopped reading, the server
heartbeat closed the parts connection about 35 seconds after it opened,
and the forwarder dialed again once the stream loop read again.

### Decisions

- `WriteControl` keeps its waiting send: the reader no longer waits
after reading the pipe, so the send returns, and replacing there changed
no test result.
- Replaced `TestStreamRelayLivePartsAfterSameEpisodeReselects`, which
waited for full buffers before every selection and so relied on the
replays the forwarder change removes, with a test that fills the buffers
once by stalling the stream loop.
- Rejected: having the serve loop read selections while it waits in
`WriteEvents`. The serve loop would have to abandon a send in progress
and drop its part, a larger change with the same result.

</details>

> 🤖 This PR was created with the help of Coder Agents.
2026-11-25 18:28:55 +02:00
2026-11-25 09:53:18 +00:00
2026-11-25 09:53:18 +00:00
…
…

Coder Logo Light Coder Logo Dark

Self-Hosted Cloud Development Environments and AI Agents

Coder Banner Light Coder Banner Dark

Quickstart | Docs | Why Coder | Premium

discord release godoc OpenSSF Best Practices OpenSSF Scorecard license Ask DeepWiki

Coder is a self-hosted platform for cloud development environments and AI coding agents. Workspaces are defined with Terraform, connected through a secure Wireguard® tunnel, and automatically shut down when not used. Coder Agents runs a native AI coding agent whose loop executes in the control plane on your infrastructure, with no API keys in workspaces.

  • Define cloud development environments in Terraform
    • EC2 VMs, Kubernetes Pods, Docker Containers, etc.
  • Automatically shutdown idle resources to save on costs
  • Onboard developers in seconds instead of days
  • Delegate coding work to AI agents on your infrastructure
    • Bring any model (Anthropic, OpenAI, Google, Bedrock, self-hosted)
    • No LLM credentials in workspaces, user identity on every action
    • Centralized model governance, cost tracking, and audit logging

Coder platform showing templates and a running workspace

Quickstart

Check out our install guides for other methods and a complete tutorial.

Try Coder with the install script on Linux and macOS, or grab the latest binary or installer from GitHub Releases on Windows:

curl -fsSL https://coder.com/install.sh | sh

Start the server and open http://localhost:3000 to create your initial user, create a Docker template, and provision your first workspace:

coder server

For a production deployment, add a PostgreSQL database (version 13 or later) and an external access URL, and see our validated architectures for sizing and infrastructure guidance:

coder server --postgres-url <url> --access-url <url>

Without these flags, Coder uses a built-in database and sets up a *.try.coder.app access URL for evaluation. Use coder --help for the full list of flags and environment variables.

Documentation

Browse the documentation or visit a specific section below:

  • Workspaces: Workspaces contain the IDEs, dependencies, and configuration information needed for software development
  • Templates: Templates are written in Terraform and describe the infrastructure for workspaces
  • Coder Agents: Delegate coding work to AI agents running on your self-hosted infrastructure
  • AI Gateway: Centralize authentication, auditing, and cost controls for AI tooling
  • Administration: Learn how to operate Coder
  • Premium: Learn about paid features built for large teams
  • IDEs: Connect your existing editor to a workspace

Support

Open an issue for bugs and feature requests.

For community support, showcasing what you built, and feedback on in-progress features, join our Discord or GitHub Discussions.

Dedicated support is included in Coder Premium. For more information, visit coder.com/pricing.

Integrations

New integrations are always in progress. Open an issue to request one. Contributions are welcome in any official or community repository.

Official

Community

Contributing

New contributors are always welcome. If you are new to the Coder codebase, see the contribution guide to get started.

Hiring

Apply on the careers page if you are interested in joining the team.

S
Description
No description provided
Readme AGPL-3.0
2.3 GiB
0 Stars 1 Watchers 0 Forks
Languages
Go 73.5%
TypeScript 24.3%
Shell 0.9%
PLpgSQL 0.3%
Go Template 0.2%
Other 0.5%