feat: structured disconnect attribution for agent logs (#25191)

Implements
[PLAT-60](https://linear.app/codercom/issue/PLAT-60/enhance-disconnect-logs-with-structured-reason-attribution):
adds structured disconnect attribution to disconnect logs throughout the
agent and tailnet packages.

Every disconnect log site now carries structured slog fields. All
existing logs remain; existing messages are preserved with the fields
added alongside.

New fields on disconnect log lines:

- `connect_type` — which layer disconnected: `server_to_agent`,
`agent_to_client`, or `client_to_server`
- `disconnect_reason` — categorical reason: `graceful`, `network_error`,
`server_shutdown`, etc.
- `disconnect_expected` — whether the disconnect is normal operation
(`true`) or should be investigated (`false`)
- `disconnect_initiator` — who started it: `client`, `agent`, `server`,
or `network` (control-plane sites only)
- `disconnect_detail` — free-form supplemental info (where useful)

## What's covered

**Control plane (`server_to_agent`):** coordination RPC, DERP map
subscriber, agent runLoop, agent Close, `BasicCoordination.Close`,
`Controller.run`.

**Data plane (`agent_to_client`):** SSH sessions, reconnecting PTY,
JetBrains port-forwarding.

<details>
<summary>Control-plane sites</summary>

| Site | Reason | Initiator |
|---|---|---|
| `agent/agent.go` `runLoop` EOF | `network_error` | `network` |
| `agent/agent.go` `runCoordinator` deferred exit | `server_shutdown` /
`graceful` / `network_error` | `agent` / `server` / `network` |
| `agent/agent.go` `runDERPMapSubscriber` deferred exit | same (shared
`classifyCoordinatorRPCExit`) | same |
| `agent/agent.go` `Close` shutdown timeout | `server_shutdown` + detail
| `agent` |
| `agent/agent.go` `Close` clean coord disconnect | `server_shutdown` |
`agent` |
| `tailnet/controllers.go` `BasicCoordination.Close` | `graceful` or
`network_error` | `c.initiator` |
| `tailnet/controllers.go` `Controller.run` `net.ErrClosed` |
`network_error` | `network` |

</details>

<details>
<summary>Data-plane sites</summary>

| Site | Reason | Notes |
|---|---|---|
| `agent/agentssh/agentssh.go` SSH session closed | free-form
(`graceful`, `process exited with error status: N`, etc.) | Also sets
`closeCause("normal exit")` for clean exits so coderd's
`connection_log.DisconnectReason` is no longer empty |
| `agent/reconnectingpty/server.go` PTY closed | `server_shutdown`,
error string, or `graceful` | |
| `agent/agentssh/jetbrainstrack.go` channel closed | `normal close` or
error string | Previously passed empty reason |

</details>

<details>
<summary>Bug fix</summary>

The deferred `disconnected from coordination RPC` log no longer fires
when the initial `Coordinate()` RPC call fails before any connection is
established.

</details>

Refs PLAT-60.

---

_This PR was prepared by Coder Agents on behalf of @Emyrk._
**Manually QA'd a lot of common disconnects**

---------

Co-authored-by: Coder Agents <noreply@coder.com>
This commit is contained in:
Steven Masley
2026-05-19 09:47:03 -05:00
committed by GitHub
co-authored by Coder Agents
parent c9c933a300
commit 1afc6d4fd0
10 changed files with 595 additions and 26 deletions
+11 -4
View File
@@ -462,17 +462,23 @@ func (s *Server) sessionHandler(session ssh.Session) {
logger.Warn(ctx, "invalid magic ssh session type specified", slog.F("raw_type", magicTypeRaw))
}
closeCause := func(string) {}
closeCause := func(_ string) {}
if reportSession {
var reason string
closeCause = func(r string) { reason = r }
var reason codersdk.DisconnectReason
closeCause = func(r string) { reason = codersdk.DisconnectReason(r) }
scr := &sessionCloseTracker{Session: session}
session = scr
disconnected := s.config.ReportConnection(id, magicType, remoteAddrString)
defer func() {
disconnected(scr.exitCode(), reason)
logger.Info(ctx, "ssh session closed",
codersdk.ConnectionDirectionAgentToClient.SlogField(),
reason.SlogField(),
reason.SlogExpectedField(),
slog.F("exit_code", scr.exitCode()),
)
disconnected(scr.exitCode(), string(reason))
}()
}
@@ -567,6 +573,7 @@ func (s *Server) sessionHandler(session ssh.Session) {
_ = session.Exit(MagicSessionErrorCode)
return
}
closeCause(string(codersdk.DisconnectReasonGraceful))
logger.Info(ctx, "normal ssh session exit")
_ = session.Exit(0)
}
+7 -2
View File
@@ -11,6 +11,7 @@ import (
gossh "golang.org/x/crypto/ssh"
"cdr.dev/slog/v3"
"github.com/coder/coder/v2/codersdk"
)
// localForwardChannelData is copied from the ssh package.
@@ -85,9 +86,13 @@ func (w *JetbrainsChannelWatcher) Accept() (gossh.Channel, <-chan *gossh.Request
Channel: c,
done: func() {
w.jetbrainsCounter.Add(-1)
disconnected(0, "")
disconnected(0, "normal close")
// nolint: gocritic // JetBrains is a proper noun and should be capitalized
w.logger.Debug(context.Background(), "JetBrains watcher channel closed")
w.logger.Debug(context.Background(), "JetBrains channel closed",
codersdk.ConnectionDirectionAgentToClient.SlogField(),
codersdk.DisconnectReasonGraceful.SlogField(),
codersdk.DisconnectReasonGraceful.SlogExpectedField(),
)
},
}, r, err
}