Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

47.5 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 BoxLite AI

package controllers

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log/slog"
	"net"
	"net/http"
	"net/http/httptest"
	"os"
	"strings"
	"sync"
	"sync/atomic"
	"testing"
	"time"

	"github.com/boxlite-ai/runner/pkg/boxlite"
	"github.com/boxlite-ai/runner/pkg/common"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"github.com/prometheus/client_golang/prometheus"
	dto "github.com/prometheus/client_model/go"
)

// stubAttachExec is a substitutable attachExec for unit-testing the
// /attach handler without a live VM. Behavior is recorded into atomics
// and channels so assertions can read them after the handler returns.
type stubAttachExec struct {
	stdoutR    *io.PipeReader
	stdoutW    *io.PipeWriter
	stderrR    *io.PipeReader
	stderrW    *io.PipeWriter
	stdinR     *io.PipeReader
	stdinW     *io.PipeWriter
	done       chan struct{}
	exitCode   int
	tty        bool
	connected  atomic.Bool
	disconnect atomic.Int32

	// Slot bookkeeping the production ManagedExec keeps: when the current
	// occupant claimed the slot and how many sessions there have been.
	stateMu     sync.Mutex
	connectedAt time.Time
	sessions    int

	mu             sync.Mutex
	resizeRows     int
	resizeCols     int
	resizeCalls    atomic.Int32
	signalCalls    atomic.Int32
	signaledWith   []int
	stdinClosed    atomic.Bool
	signalErrToRet error

	// allowSecondAttach: when false, MarkConnected returns false on second call.
	allowSecondAttach bool

	// panicOnExitCode makes ExitCodeValue panic, to exercise the attach
	// loop's recover path.
	panicOnExitCode bool

	// Subscriber fan-out: mirrors the production broadcaster so tests
	// exercise the same channel-based path the real /attach handler uses.
	subMu        sync.Mutex
	subs         []stubSubscriber
	broadcasting bool
}

type stubSubscriber struct {
	stdout *stubStream
	stderr *stubStream
}

// stubStream is the test-side attachStream: the fan-out channel plus the
// drop counter. The stub never replays a backlog.
type stubStream struct {
	ch      chan []byte
	dropped atomic.Uint64
}

func (s *stubStream) Chan() <-chan []byte { return s.ch }
func (s *stubStream) Dropped() uint64     { return s.dropped.Load() }
func (s *stubStream) Replayed() uint64    { return 0 }

func newStubAttachExec() *stubAttachExec {
	stdoutR, stdoutW := io.Pipe()
	stderrR, stderrW := io.Pipe()
	stdinR, stdinW := io.Pipe()
	return &stubAttachExec{
		stdoutR: stdoutR, stdoutW: stdoutW,
		stderrR: stderrR, stderrW: stderrW,
		stdinR: stdinR, stdinW: stdinW,
		done: make(chan struct{}),
	}
}

// Subscribe spawns a stdout/stderr pump that fan-outs to the returned
// channels. Calling Subscribe more than once is supported (mirrors the
// production fan-out broadcaster); each subscriber gets its own channels and
// sees all subsequent bytes. The pump goroutines exit when the stdout/stderr
// pipes EOF or when the subscriber is cancelled.
func (s *stubAttachExec) Subscribe(bufSize int) (stdout, stderr attachStream, cancel func()) {
	if bufSize <= 0 {
		bufSize = 256
	}
	outCh := &stubStream{ch: make(chan []byte, bufSize)}
	errCh := &stubStream{ch: make(chan []byte, bufSize)}

	s.subMu.Lock()
	s.subs = append(s.subs, stubSubscriber{stdout: outCh, stderr: errCh})
	if !s.broadcasting {
		s.broadcasting = true
		go s.broadcastPipe(s.stdoutR, true)
		go s.broadcastPipe(s.stderrR, false)
	}
	s.subMu.Unlock()

	once := sync.Once{}
	cancel = func() {
		once.Do(func() {
			s.subMu.Lock()
			for i, sub := range s.subs {
				if sub.stdout == outCh {
					s.subs = append(s.subs[:i], s.subs[i+1:]...)
					break
				}
			}
			s.subMu.Unlock()
			close(outCh.ch)
			close(errCh.ch)
		})
	}
	return outCh, errCh, cancel
}

// broadcastPipe is the test-side analog of ManagedExec.broadcastPipe. Same
// invariants: single reader per pipe, non-blocking fan-out, drop on slow
// subscriber.
func (s *stubAttachExec) broadcastPipe(r *io.PipeReader, isStdout bool) {
	buf := make([]byte, 4096)
	for {
		n, err := r.Read(buf)
		if n > 0 {
			chunk := make([]byte, n)
			copy(chunk, buf[:n])
			s.subMu.Lock()
			for _, sub := range s.subs {
				st := sub.stdout
				if !isStdout {
					st = sub.stderr
				}
				select {
				case st.ch <- chunk:
				default:
					st.dropped.Add(uint64(n))
				}
			}
			s.subMu.Unlock()
		}
		if err != nil {
			return
		}
	}
}

func (s *stubAttachExec) WriteStdin(data []byte) (int, error) {
	if s.stdinW == nil {
		return 0, fmt.Errorf("stdin is closed")
	}
	select {
	case <-s.done:
		return 0, fmt.Errorf("stdin is closed")
	default:
	}
	return s.stdinW.Write(data)
}
func (s *stubAttachExec) DoneCh() <-chan struct{} { return s.done }
func (s *stubAttachExec) ExitCodeValue() int {
	if s.panicOnExitCode {
		panic("exit code stub panic")
	}
	return s.exitCode
}
func (s *stubAttachExec) IsTTY() bool { return s.tty }
func (s *stubAttachExec) Resize(rows, cols int) error {
	s.mu.Lock()
	s.resizeRows = rows
	s.resizeCols = cols
	s.mu.Unlock()
	s.resizeCalls.Add(1)
	return nil
}
func (s *stubAttachExec) Signal(sig int) error {
	s.mu.Lock()
	s.signaledWith = append(s.signaledWith, sig)
	s.mu.Unlock()
	s.signalCalls.Add(1)
	return s.signalErrToRet
}
func (s *stubAttachExec) CloseStdin() error {
	s.stdinClosed.Store(true)
	return s.stdinW.Close()
}

func (s *stubAttachExec) MarkConnected() bool {
	if s.connected.CompareAndSwap(false, true) {
		s.stateMu.Lock()
		s.connectedAt = time.Now()
		s.sessions++
		s.stateMu.Unlock()
		return true
	}
	return s.allowSecondAttach
}

func (s *stubAttachExec) AttachState() boxlite.AttachState {
	s.stateMu.Lock()
	defer s.stateMu.Unlock()
	return boxlite.AttachState{
		Connected:   s.connected.Load(),
		ConnectedAt: s.connectedAt,
		Sessions:    s.sessions,
	}
}

func (s *stubAttachExec) MarkDisconnected() {
	s.connected.Store(false)
	s.disconnect.Add(1)
}

// withStubExec installs target as the resolveAttachExec result for execId
// for the duration of the test. Returns a cleanup func.
func withStubExec(t *testing.T, execId string, target attachExec) func() {
	t.Helper()
	prev := resolveAttachExec
	resolveAttachExec = func(ctx *gin.Context, id, boxID string) (attachExec, error) {
		if id == execId {
			return target, nil
		}
		return prev(ctx, id, boxID)
	}
	return func() { resolveAttachExec = prev }
}

// newAttachServer returns an httptest.Server that routes
// /v1/boxes/:boxId/executions/:execId/attach to BoxliteExecAttach.
func newAttachServer(t *testing.T) *httptest.Server {
	t.Helper()
	gin.SetMode(gin.TestMode)
	r := gin.New()
	r.GET("/v1/boxes/:boxId/executions/:execId/attach", BoxliteExecAttach)
	return httptest.NewServer(r)
}

// dialAttach opens a WS connection to /v1/boxes/box/executions/<execId>/attach
// on the given httptest server.
func dialAttach(t *testing.T, srv *httptest.Server, execId string) (*websocket.Conn, *http.Response, error) {
	t.Helper()
	wsURL := strings.Replace(srv.URL, "http://", "ws://", 1) +
		"/v1/boxes/box/executions/" + execId + "/attach"
	dialer := *websocket.DefaultDialer
	dialer.HandshakeTimeout = 5 * time.Second
	return dialer.Dial(wsURL, nil)
}

// readNextNonPongFrame reads frames, ignoring control pongs. Returns the
// first data frame.
func readNextDataFrame(t *testing.T, conn *websocket.Conn, deadline time.Duration) (int, []byte, error) {
	t.Helper()
	_ = conn.SetReadDeadline(time.Now().Add(deadline))
	mt, payload, err := conn.ReadMessage()
	return mt, payload, err
}

func TestBoxliteExecAttach_StdinAndExit(t *testing.T) {
	stub := newStubAttachExec()
	stub.exitCode = 42
	cleanup := withStubExec(t, "exec-1", stub)
	defer cleanup()

	srv := newAttachServer(t)
	defer srv.Close()

	conn, resp, err := dialAttach(t, srv, "exec-1")
	if err != nil {
		t.Fatalf("dial attach: %v (resp=%v)", err, resp)
	}
	defer conn.Close()

	// Goroutine: drain just enough stdin to confirm the pump delivered.
	// io.ReadAll would deadlock — the handler never closes stdinW.
	stdinDone := make(chan []byte, 1)
	go func() {
		buf := make([]byte, 64)
		n, _ := stub.stdinR.Read(buf)
		stdinDone <- buf[:n]
	}()

	// Send binary stdin frame.
	if err := conn.WriteMessage(websocket.BinaryMessage, []byte("ls\n")); err != nil {
		t.Fatalf("write stdin: %v", err)
	}

	// Confirm the forward here, while the session is still live. Past the exit
	// the server has sent its Close and the reader only drains, so whether a
	// frame still reaches stdin then depends on which goroutine the scheduler
	// runs first — and on a finished exec the production stdin writer refuses
	// the write anyway (ManagedExec.AttachWriteStdin).
	select {
	case got := <-stdinDone:
		if string(got) != "ls\n" {
			t.Fatalf("expected stdin %q, got %q", "ls\n", got)
		}
	case <-time.After(2 * time.Second):
		t.Fatal("stdin pump did not deliver bytes")
	}

	// Push some stdout, expect to read back a binary frame with 0x01 prefix.
	go func() {
		_, _ = stub.stdoutW.Write([]byte("hello"))
	}()

	mt, payload, err := readNextDataFrame(t, conn, 2*time.Second)
	if err != nil {
		t.Fatalf("read stdout frame: %v", err)
	}
	if mt != websocket.BinaryMessage {
		t.Fatalf("expected BinaryMessage, got %d", mt)
	}
	if len(payload) < 1 || payload[0] != 0x01 {
		t.Fatalf("expected 0x01 stdout prefix, got payload=% x", payload)
	}
	if string(payload[1:]) != "hello" {
		t.Fatalf("expected payload 'hello', got %q", string(payload[1:]))
	}

	// Fire Done. Handler should emit text exit frame then close.
	stub.stdoutW.Close()
	stub.stderrW.Close()
	close(stub.done)

	// Read frames until we see exit JSON or close.
	deadline := time.Now().Add(3 * time.Second)
	gotExit := false
	for time.Now().Before(deadline) {
		_ = conn.SetReadDeadline(time.Now().Add(2 * time.Second))
		mt, payload, err := conn.ReadMessage()
		if err != nil {
			// Close error is acceptable AFTER we've seen exit.
			if gotExit {
				break
			}
			if ce, ok := err.(*websocket.CloseError); ok {
				t.Fatalf("got close before exit frame: %v", ce)
			}
			t.Fatalf("unexpected read err: %v", err)
		}
		if mt == websocket.TextMessage {
			var ev map[string]interface{}
			if err := json.Unmarshal(payload, &ev); err != nil {
				t.Fatalf("bad exit json: %v", err)
			}
			if ev["type"] == "exit" {
				if got, want := int(ev["exit_code"].(float64)), 42; got != want {
					t.Fatalf("expected exit_code %d, got %d", want, got)
				}
				gotExit = true
				continue
			}
		}
	}
	if !gotExit {
		t.Fatal("did not receive exit text frame within deadline")
	}

	// Confirm disconnect was marked. The handler runs MarkDisconnected
	// in a deferred block after wg.Wait, so allow a brief settle window.
	deadline = time.Now().Add(2 * time.Second)
	for time.Now().Before(deadline) && stub.disconnect.Load() == 0 {
		time.Sleep(10 * time.Millisecond)
	}
	if stub.disconnect.Load() == 0 {
		t.Fatal("expected MarkDisconnected to be called")
	}
}

func TestBoxliteExecAttach_SingleAttach409(t *testing.T) {
	stub := newStubAttachExec()
	cleanup := withStubExec(t, "exec-busy", stub)
	defer cleanup()

	srv := newAttachServer(t)
	defer srv.Close()

	// First attach succeeds.
	conn1, resp1, err := dialAttach(t, srv, "exec-busy")
	if err != nil {
		t.Fatalf("first dial failed: %v (resp=%v)", err, resp1)
	}
	defer conn1.Close()

	// Second attach must return 409 BEFORE upgrade.
	wsURL := strings.Replace(srv.URL, "http://", "ws://", 1) +
		"/v1/boxes/box/executions/exec-busy/attach"
	dialer := *websocket.DefaultDialer
	dialer.HandshakeTimeout = 2 * time.Second
	conn2, resp2, err := dialer.Dial(wsURL, nil)
	if err == nil {
		conn2.Close()
		t.Fatal("expected second dial to fail with 409")
	}
	if resp2 == nil {
		t.Fatalf("expected http response on second dial, got nil (err=%v)", err)
	}
	if resp2.StatusCode != http.StatusConflict {
		t.Fatalf("expected status 409, got %d", resp2.StatusCode)
	}
}

func TestBoxliteExecAttach_ResizeFrame(t *testing.T) {
	stub := newStubAttachExec()
	stub.tty = true
	cleanup := withStubExec(t, "exec-resize", stub)
	defer cleanup()

	srv := newAttachServer(t)
	defer srv.Close()

	conn, _, err := dialAttach(t, srv, "exec-resize")
	if err != nil {
		t.Fatalf("dial: %v", err)
	}
	defer conn.Close()

	resizeFrame := `{"type":"resize","cols":120,"rows":40}`
	if err := conn.WriteMessage(websocket.TextMessage, []byte(resizeFrame)); err != nil {
		t.Fatalf("write resize: %v", err)
	}

	// Wait until the resize call is observed.
	deadline := time.Now().Add(2 * time.Second)
	for time.Now().Before(deadline) {
		if stub.resizeCalls.Load() > 0 {
			break
		}
		time.Sleep(10 * time.Millisecond)
	}
	if stub.resizeCalls.Load() == 0 {
		t.Fatal("Resize was not called")
	}
	stub.mu.Lock()
	rows, cols := stub.resizeRows, stub.resizeCols
	stub.mu.Unlock()
	if rows != 40 || cols != 120 {
		t.Fatalf("expected rows=40 cols=120, got rows=%d cols=%d", rows, cols)
	}
}

func TestBoxliteExecAttach_StdinEofClosesStdin(t *testing.T) {
	stub := newStubAttachExec()
	cleanup := withStubExec(t, "exec-eof", stub)
	defer cleanup()

	srv := newAttachServer(t)
	defer srv.Close()

	conn, _, err := dialAttach(t, srv, "exec-eof")
	if err != nil {
		t.Fatalf("dial: %v", err)
	}
	defer conn.Close()

	// Drain stdin in background — we need the writer to actually flush
	// before the close is observable, but the pipe blocks until read.
	stdinDone := make(chan struct{})
	go func() {
		_, _ = io.Copy(io.Discard, stub.stdinR)
		close(stdinDone)
	}()

	if err := conn.WriteMessage(websocket.TextMessage, []byte(`{"type":"stdin_eof"}`)); err != nil {
		t.Fatalf("write eof: %v", err)
	}

	// stdin pipe closes once handler invokes CloseStdin.
	select {
	case <-stdinDone:
	case <-time.After(2 * time.Second):
		t.Fatal("stdin pipe did not close after stdin_eof frame")
	}

	if !stub.stdinClosed.Load() {
		t.Fatal("CloseStdin was not called")
	}
}

func TestBoxliteExecAttach_KeepalivePing(t *testing.T) {
	// Speed the keepalive interval up.
	restore := setKeepaliveIntervalForTest(50 * time.Millisecond)
	defer restore()

	stub := newStubAttachExec()
	cleanup := withStubExec(t, "exec-ping", stub)
	defer cleanup()

	srv := newAttachServer(t)
	defer srv.Close()

	conn, _, err := dialAttach(t, srv, "exec-ping")
	if err != nil {
		t.Fatalf("dial: %v", err)
	}
	defer conn.Close()

	pingSeen := make(chan struct{}, 1)
	conn.SetPingHandler(func(appData string) error {
		select {
		case pingSeen <- struct{}{}:
		default:
		}
		// Standard pong reply.
		return conn.WriteControl(websocket.PongMessage, []byte(appData), time.Now().Add(time.Second))
	})

	// We need to drive ReadMessage to dispatch the control frame handler.
	readErr := make(chan error, 1)
	go func() {
		_ = conn.SetReadDeadline(time.Now().Add(2 * time.Second))
		_, _, err := conn.ReadMessage()
		readErr <- err
	}()

	select {
	case <-pingSeen:
		// good
	case err := <-readErr:
		t.Fatalf("read returned before ping observed: %v", err)
	case <-time.After(1 * time.Second):
		t.Fatal("did not observe a server ping within 1s (interval=50ms)")
	}
}

func TestValidateInbandSignal_RejectsKillStopCont(t *testing.T) {
	for _, sig := range []int{9, 17, 18, 19, 23} {
		if err := validateInbandSignal(sig); err == nil {
			t.Fatalf("expected sig %d to be rejected", sig)
		}
	}
	for _, sig := range []int{1, 2, 3, 6, 10, 12, 15, 28} {
		if err := validateInbandSignal(sig); err != nil {
			t.Fatalf("expected sig %d allowed, got err: %v", sig, err)
		}
	}
}

func TestBoxliteExecAttach_SignalFrameRejectedSendsError(t *testing.T) {
	stub := newStubAttachExec()
	cleanup := withStubExec(t, "exec-sig-bad", stub)
	defer cleanup()

	srv := newAttachServer(t)
	defer srv.Close()

	conn, _, err := dialAttach(t, srv, "exec-sig-bad")
	if err != nil {
		t.Fatalf("dial: %v", err)
	}
	defer conn.Close()

	// 9 (KILL) is rejected by the in-band validator.
	if err := conn.WriteMessage(websocket.TextMessage, []byte(`{"type":"signal","sig":9}`)); err != nil {
		t.Fatalf("write signal: %v", err)
	}

	_ = conn.SetReadDeadline(time.Now().Add(2 * time.Second))
	mt, payload, err := conn.ReadMessage()
	if err != nil {
		t.Fatalf("read err: %v", err)
	}
	if mt != websocket.TextMessage {
		t.Fatalf("expected text frame, got mt=%d", mt)
	}
	var ev map[string]interface{}
	if err := json.Unmarshal(payload, &ev); err != nil {
		t.Fatalf("bad json: %v", err)
	}
	if ev["type"] != "error" {
		t.Fatalf("expected type=error, got %v", ev["type"])
	}
	if stub.signalCalls.Load() != 0 {
		t.Fatal("Signal must NOT be called for rejected sig")
	}
}

func TestBoxliteExecAttach_SignalFrameAllowedDelivered(t *testing.T) {
	stub := newStubAttachExec()
	cleanup := withStubExec(t, "exec-sig-ok", stub)
	defer cleanup()

	srv := newAttachServer(t)
	defer srv.Close()

	conn, _, err := dialAttach(t, srv, "exec-sig-ok")
	if err != nil {
		t.Fatalf("dial: %v", err)
	}
	defer conn.Close()

	// 2 (INT) is allowed.
	if err := conn.WriteMessage(websocket.TextMessage, []byte(`{"type":"signal","sig":2}`)); err != nil {
		t.Fatalf("write signal: %v", err)
	}

	deadline := time.Now().Add(2 * time.Second)
	for time.Now().Before(deadline) {
		if stub.signalCalls.Load() > 0 {
			break
		}
		time.Sleep(10 * time.Millisecond)
	}
	if stub.signalCalls.Load() == 0 {
		t.Fatal("Signal was not delivered for allowed sig")
	}
	stub.mu.Lock()
	got := append([]int(nil), stub.signaledWith...)
	stub.mu.Unlock()
	if len(got) != 1 || got[0] != 2 {
		t.Fatalf("expected delivered sig=[2], got %v", got)
	}
}

// A client that never pongs (suppressed via SetPingHandler that swallows
// pings) must be evicted within ~3 keepalive intervals so the single-attach
// slot is released. Without pong-based liveness the server's tiny ping write
// fits in the kernel send buffer indefinitely on a half-open TCP and the slot
// is held for 10-15 minutes.
func TestBoxliteExecAttach_PongTimeoutEvictsDeadClient(t *testing.T) {
	restore := setKeepaliveIntervalForTest(50 * time.Millisecond)
	defer restore()

	stub := newStubAttachExec()
	cleanup := withStubExec(t, "exec-deadpong", stub)
	defer cleanup()

	srv := newAttachServer(t)
	defer srv.Close()

	conn, _, err := dialAttach(t, srv, "exec-deadpong")
	if err != nil {
		t.Fatalf("dial: %v", err)
	}
	defer conn.Close()

	// Suppress the client-side auto-pong so the server never sees a Pong.
	// Returning nil from the handler tells gorilla to drop the ping silently.
	conn.SetPingHandler(func(string) error { return nil })

	// Drive ReadMessage so gorilla's internal control-frame dispatch runs
	// (pings would otherwise queue). Read frames until the server gives up.
	readErr := make(chan error, 1)
	go func() {
		_ = conn.SetReadDeadline(time.Now().Add(2 * time.Second))
		for {
			if _, _, err := conn.ReadMessage(); err != nil {
				readErr <- err
				return
			}
		}
	}()

	// pongWait = 3 * 50ms = 150ms; expect MarkDisconnected within ~500ms.
	deadline := time.After(1500 * time.Millisecond)
	for {
		if stub.disconnect.Load() > 0 {
			return // success: handler tore down and released the slot
		}
		select {
		case <-deadline:
			t.Fatalf("server did not detect dead client within 1.5s (disconnect=%d, readErr=%v)",
				stub.disconnect.Load(), tryReceive(readErr))
		case <-time.After(20 * time.Millisecond):
		}
	}
}

// tryReceive returns the channel value if available, otherwise nil — used to
// avoid blocking when surfacing context in a failure message.
func tryReceive(ch <-chan error) error {
	select {
	case v := <-ch:
		return v
	default:
		return nil
	}
}

// Sanity guard: handler returns 404 if the guest execution is unknown.
func TestBoxliteExecAttach_NotFound(t *testing.T) {
	prev := resolveAttachExec
	resolveAttachExec = func(_ *gin.Context, _, _ string) (attachExec, error) { return nil, boxlite.ErrExecNotFound }
	defer func() { resolveAttachExec = prev }()

	srv := newAttachServer(t)
	defer srv.Close()

	wsURL := strings.Replace(srv.URL, "http://", "ws://", 1) +
		"/v1/boxes/box/executions/missing/attach"
	dialer := *websocket.DefaultDialer
	dialer.HandshakeTimeout = 2 * time.Second
	conn, resp, err := dialer.Dial(wsURL, nil)
	if err == nil {
		conn.Close()
		t.Fatal("expected dial to fail for unknown exec")
	}
	if resp == nil || resp.StatusCode != http.StatusNotFound {
		t.Fatalf("expected 404, got %v err=%v", resp, err)
	}
}

// A command that exits before its client attaches puts the whole session —
// upgrade, backlog replay, exit frame, Close — inside a single round trip. The
// server must still hold the TCP connection open for the peer's Close: an
// intermediary mid-handshake with the client reads an immediate teardown as an
// upgrade that never completed, and answers the client 502 (Google's external
// ALB logs it as `websocket_handshake_failed`).
func TestBoxliteExecAttach_HoldsConnectionForPeerClose(t *testing.T) {
	stub := newStubAttachExec()
	stub.exitCode = 0
	// Finished before anyone attaches — the case that loses the race.
	close(stub.done)
	cleanup := withStubExec(t, "exec-already-done", stub)
	defer cleanup()

	srv := newAttachServer(t)
	defer srv.Close()

	conn, resp, err := dialAttach(t, srv, "exec-already-done")
	if err != nil {
		t.Fatalf("dial attach: %v (resp=%v)", err, resp)
	}
	defer conn.Close()

	// Say nothing back. gorilla answers a Close frame with its own by
	// default, which would complete the handshake for us and hide what the
	// server does when the peer stays silent.
	conn.SetCloseHandler(func(int, string) error { return nil })

	// Drain to the server's Close frame — everything this session will say.
	_ = conn.SetReadDeadline(time.Now().Add(2 * time.Second))
	for {
		_, _, rerr := conn.ReadMessage()
		if rerr == nil {
			continue
		}
		if !websocket.IsCloseError(rerr, websocket.CloseNormalClosure) {
			t.Fatalf("expected a normal Close frame, got %v", rerr)
		}
		break
	}

	// Reading a Close leaves the socket alone, so the raw connection now
	// reports only what the server does with it: still open at the deadline
	// means the server is waiting for the Close we never sent.
	raw := conn.UnderlyingConn()
	_ = raw.SetReadDeadline(time.Now().Add(500 * time.Millisecond))
	_, rerr := raw.Read(make([]byte, 1))
	var netErr net.Error
	if !errors.As(rerr, &netErr) || !netErr.Timeout() {
		t.Fatalf("server tore down the TCP connection without waiting for the peer's Close: raw read returned %v", rerr)
	}
}

// The wait is worth nothing if the first frame a client sends ends it. A client
// that still has stdin in flight when its command exits would otherwise get the
// same instant teardown — the reader would return, close readerDone, and release
// the wait before the peer ever answered.
func TestBoxliteExecAttach_ClientFramesDoNotEndTheCloseWait(t *testing.T) {
	stub := newStubAttachExec()
	close(stub.done)
	cleanup := withStubExec(t, "exec-chatty", stub)
	defer cleanup()

	srv := newAttachServer(t)
	defer srv.Close()

	conn, resp, err := dialAttach(t, srv, "exec-chatty")
	if err != nil {
		t.Fatalf("dial attach: %v (resp=%v)", err, resp)
	}
	defer conn.Close()
	conn.SetCloseHandler(func(int, string) error { return nil })

	_ = conn.SetReadDeadline(time.Now().Add(2 * time.Second))
	for {
		_, _, rerr := conn.ReadMessage()
		if rerr == nil {
			continue
		}
		if !websocket.IsCloseError(rerr, websocket.CloseNormalClosure) {
			t.Fatalf("expected a normal Close frame, got %v", rerr)
		}
		break
	}

	// Keep talking, the way a client mid-upload would. None of it is answered —
	// answering after a Close is what §5.5.1 forbids — but none of it may end
	// the wait either.
	for i := 0; i < 3; i++ {
		if werr := conn.WriteMessage(websocket.BinaryMessage, []byte("more stdin\n")); werr != nil {
			t.Fatalf("write stdin after close: %v", werr)
		}
	}

	raw := conn.UnderlyingConn()
	_ = raw.SetReadDeadline(time.Now().Add(500 * time.Millisecond))
	_, rerr := raw.Read(make([]byte, 1))
	var netErr net.Error
	if !errors.As(rerr, &netErr) || !netErr.Timeout() {
		t.Fatalf("client frames ended the close wait: raw read returned %v", rerr)
	}
}

// The peer answering is what the wait is for, so it has to end promptly when it
// does — a client that closes cleanly must not pay the wsPeerCloseWait bound.
func TestBoxliteExecAttach_PeerCloseEndsTheWaitPromptly(t *testing.T) {
	stub := newStubAttachExec()
	close(stub.done)
	cleanup := withStubExec(t, "exec-polite", stub)
	defer cleanup()

	srv := newAttachServer(t)
	defer srv.Close()

	conn, resp, err := dialAttach(t, srv, "exec-polite")
	if err != nil {
		t.Fatalf("dial attach: %v (resp=%v)", err, resp)
	}
	defer conn.Close()
	conn.SetCloseHandler(func(int, string) error { return nil })

	_ = conn.SetReadDeadline(time.Now().Add(2 * time.Second))
	for {
		_, _, rerr := conn.ReadMessage()
		if rerr == nil {
			continue
		}
		if !websocket.IsCloseError(rerr, websocket.CloseNormalClosure) {
			t.Fatalf("expected a normal Close frame, got %v", rerr)
		}
		break
	}

	started := time.Now()
	if werr := conn.WriteControl(
		websocket.CloseMessage,
		websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""),
		time.Now().Add(time.Second),
	); werr != nil {
		t.Fatalf("answer the close: %v", werr)
	}

	raw := conn.UnderlyingConn()
	_ = raw.SetReadDeadline(time.Now().Add(2 * time.Second))
	if _, rerr := raw.Read(make([]byte, 1)); rerr == nil {
		t.Fatal("expected the server to close the connection once answered")
	}
	// Far below wsPeerCloseWait: the bound covers a peer that never answers,
	// and one that does must not wait it out.
	if waited := time.Since(started); waited > time.Second {
		t.Fatalf("server took %s to close after the peer answered", waited)
	}
}

// The bound is the whole reason the wait is safe to have: a peer that answers
// nothing must not hold the connection, the handler goroutine, or the
// single-attach slot behind it for longer than wsPeerCloseWait.
func TestBoxliteExecAttach_SilentPeerIsDroppedAtTheBound(t *testing.T) {
	restore := setPeerCloseWaitForTest(300 * time.Millisecond)
	defer restore()

	stub := newStubAttachExec()
	close(stub.done)
	cleanup := withStubExec(t, "exec-silent", stub)
	defer cleanup()

	srv := newAttachServer(t)
	defer srv.Close()

	conn, resp, err := dialAttach(t, srv, "exec-silent")
	if err != nil {
		t.Fatalf("dial attach: %v (resp=%v)", err, resp)
	}
	defer conn.Close()
	conn.SetCloseHandler(func(int, string) error { return nil })

	_ = conn.SetReadDeadline(time.Now().Add(2 * time.Second))
	for {
		_, _, rerr := conn.ReadMessage()
		if rerr == nil {
			continue
		}
		if !websocket.IsCloseError(rerr, websocket.CloseNormalClosure) {
			t.Fatalf("expected a normal Close frame, got %v", rerr)
		}
		break
	}

	// Say nothing at all. The server owes us no more frames, so the only thing
	// that can end this read is the server dropping the connection.
	raw := conn.UnderlyingConn()
	_ = raw.SetReadDeadline(time.Now().Add(3 * time.Second))
	started := time.Now()
	if _, rerr := raw.Read(make([]byte, 1)); rerr == nil {
		t.Fatal("expected the server to drop the connection at the bound")
	}
	if waited := time.Since(started); waited > 2*time.Second {
		t.Fatalf("server held a silent peer for %s, well past the bound", waited)
	}
	// The slot is released in the deferred cleanup, after conn.Close() — so the
	// drop we just observed strictly precedes it. Poll the same settle window
	// the other disconnect assertions in this file use.
	settle := time.Now().Add(2 * time.Second)
	for time.Now().Before(settle) && stub.connected.Load() {
		time.Sleep(10 * time.Millisecond)
	}
	if stub.connected.Load() {
		t.Fatal("the single-attach slot was still held after the bound elapsed")
	}
}

// A client that keeps talking must not be able to hold the connection open
// indefinitely.
//
// What this pins is the outcome, not the mechanism: awaitPeerClose's timer
// enforces the bound on its own, so this still passes if the reader starts
// pushing its read deadline again. That ordering is a race the teardown
// usually wins, and no test here can fail for it — it is removed by
// construction rather than proved.
func TestBoxliteExecAttach_ChattyPeerStillHitsTheBound(t *testing.T) {
	restore := setPeerCloseWaitForTest(300 * time.Millisecond)
	defer restore()

	stub := newStubAttachExec()
	close(stub.done)
	cleanup := withStubExec(t, "exec-chatty-bound", stub)
	defer cleanup()

	srv := newAttachServer(t)
	defer srv.Close()

	conn, resp, err := dialAttach(t, srv, "exec-chatty-bound")
	if err != nil {
		t.Fatalf("dial attach: %v (resp=%v)", err, resp)
	}
	defer conn.Close()
	conn.SetCloseHandler(func(int, string) error { return nil })

	_ = conn.SetReadDeadline(time.Now().Add(2 * time.Second))
	for {
		_, _, rerr := conn.ReadMessage()
		if rerr == nil {
			continue
		}
		if !websocket.IsCloseError(rerr, websocket.CloseNormalClosure) {
			t.Fatalf("expected a normal Close frame, got %v", rerr)
		}
		break
	}

	// Keep sending past the Close, the way a client mid-upload would. Writing is
	// not the assertion — a write to a socket whose peer is gone succeeds until
	// a reset comes back — it is only what keeps the server's reader busy.
	chatting := make(chan struct{})
	defer close(chatting)
	go func() {
		for {
			select {
			case <-chatting:
				return
			default:
			}
			if werr := conn.WriteMessage(websocket.BinaryMessage, []byte("x")); werr != nil {
				return
			}
			time.Sleep(time.Millisecond)
		}
	}()

	// The server dropping the connection is the signal, and it has to come from
	// the bound rather than from anything this client does.
	raw := conn.UnderlyingConn()
	_ = raw.SetReadDeadline(time.Now().Add(3 * time.Second))
	started := time.Now()
	if _, rerr := raw.Read(make([]byte, 1)); rerr != nil {
		var netErr net.Error
		if errors.As(rerr, &netErr) && netErr.Timeout() {
			t.Fatal("a talking peer kept the connection open past the bound")
		}
	}
	if waited := time.Since(started); waited > 2*time.Second {
		t.Fatalf("a talking peer held the connection for %s, past the bound", waited)
	}
}

// The same outcome for the one frame that reaches a handler of its own: gorilla
// calls the pong handler for every Pong, the drain after our own Close
// included.
//
// Read this the way the chatty case above reads. The timer bounds the wait
// whether or not the pong handler still pushes the read deadline, so this
// passes with that guard removed too. The guard is there because the deadline
// is what ends the reader after the wait, and a Pong arriving in the window
// between the teardown's near deadline and sideWg.Wait() could otherwise push
// it out by pongWait — a race, not something a test can land on.
func TestBoxliteExecAttach_PongingPeerStillHitsTheBound(t *testing.T) {
	restore := setPeerCloseWaitForTest(300 * time.Millisecond)
	defer restore()

	stub := newStubAttachExec()
	close(stub.done)
	cleanup := withStubExec(t, "exec-ponging", stub)
	defer cleanup()

	srv := newAttachServer(t)
	defer srv.Close()

	conn, resp, err := dialAttach(t, srv, "exec-ponging")
	if err != nil {
		t.Fatalf("dial attach: %v (resp=%v)", err, resp)
	}
	defer conn.Close()
	conn.SetCloseHandler(func(int, string) error { return nil })

	_ = conn.SetReadDeadline(time.Now().Add(2 * time.Second))
	for {
		_, _, rerr := conn.ReadMessage()
		if rerr == nil {
			continue
		}
		if !websocket.IsCloseError(rerr, websocket.CloseNormalClosure) {
			t.Fatalf("expected a normal Close frame, got %v", rerr)
		}
		break
	}

	ponging := make(chan struct{})
	defer close(ponging)
	go func() {
		for {
			select {
			case <-ponging:
				return
			default:
			}
			if werr := conn.WriteControl(websocket.PongMessage, nil, time.Now().Add(time.Second)); werr != nil {
				return
			}
			time.Sleep(time.Millisecond)
		}
	}()

	raw := conn.UnderlyingConn()
	_ = raw.SetReadDeadline(time.Now().Add(3 * time.Second))
	started := time.Now()
	if _, rerr := raw.Read(make([]byte, 1)); rerr != nil {
		var netErr net.Error
		if errors.As(rerr, &netErr) && netErr.Timeout() {
			t.Fatal("a ponging peer kept the connection open past the bound")
		}
	}
	if waited := time.Since(started); waited > 2*time.Second {
		t.Fatalf("a ponging peer held the connection for %s, past the bound", waited)
	}
}

// ─── attach session logging ──────────────────────────────────────────────
//
// The runner used to leave no trace of an attach session: a 409 and a silent
// disconnect were both invisible, and the only evidence of a reconnect hang
// was one SDK WARN line. These tests pin the session-end and refusal lines:
// the reason must classify correctly, the first failure must survive the
// later ones, and nothing from the request or the streams may leak into the
// log.

// syncBuffer is a bytes.Buffer that a slog handler on the server goroutine
// may write to while the test goroutine polls its contents.
type syncBuffer struct {
	mu sync.Mutex
	b  bytes.Buffer
}

func (s *syncBuffer) Write(p []byte) (int, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	return s.b.Write(p)
}

func (s *syncBuffer) String() string {
	s.mu.Lock()
	defer s.mu.Unlock()
	return s.b.String()
}

// captureAttachLogs points the default slog logger at a buffer for the
// duration of the test, at DEBUG so the normal-end lines show up too. Safe
// because no test in this package calls t.Parallel.
func captureAttachLogs(t *testing.T) *syncBuffer {
	t.Helper()
	buf := &syncBuffer{}
	prev := slog.Default()
	slog.SetDefault(slog.New(slog.NewJSONHandler(buf, &slog.HandlerOptions{Level: slog.LevelDebug})))
	t.Cleanup(func() { slog.SetDefault(prev) })
	return buf
}

// logLine waits for the one line holding every substring and returns it.
// A session's end is logged from the server goroutine, so a line from an
// earlier test's server can land in a later test's buffer; naming the exec
// id as well as the message keeps the match on this test's line.
func logLine(t *testing.T, logs *syncBuffer, substrs ...string) string {
	t.Helper()
	deadline := time.Now().Add(5 * time.Second)
	for time.Now().Before(deadline) {
		for _, l := range strings.Split(logs.String(), "\n") {
			if containsAll(l, substrs) {
				return l
			}
		}
		time.Sleep(20 * time.Millisecond)
	}
	t.Fatalf("log line with %q never appeared; captured:\n%s", substrs, logs.String())
	return ""
}

func containsAll(line string, substrs []string) bool {
	for _, s := range substrs {
		if !strings.Contains(line, s) {
			return false
		}
	}
	return true
}

// assertLogHas waits for the line holding every substring of `match` and
// checks that it carries every wanted field and none of the forbidden
// substrings, naming what is wrong in the failure.
func assertLogHas(t *testing.T, logs *syncBuffer, match []string, want []string, forbid ...string) {
	t.Helper()
	line := logLine(t, logs, match...)
	for _, w := range want {
		if !strings.Contains(line, w) {
			t.Errorf("log line lacks %q; got:\n%s", w, line)
		}
	}
	for _, f := range forbid {
		if strings.Contains(line, f) {
			t.Errorf("log line leaks %q; got:\n%s", f, line)
		}
	}
}

// counterValue reads a Prometheus counter without the testutil package, so
// the test adds no module requirement.
func counterValue(t *testing.T, c prometheus.Counter) float64 {
	t.Helper()
	var m dto.Metric
	if err := c.Write(&m); err != nil {
		t.Fatalf("read counter: %v", err)
	}
	return m.GetCounter().GetValue()
}

func TestClassifyAttachEnd(t *testing.T) {
	cases := []struct {
		name string
		err  error
		want attachEndReason
	}{
		{"nothing reported", nil, attachEndServerShutdown},
		{"client close frame",
			fmt.Errorf("read client frame: %w", &websocket.CloseError{Code: websocket.CloseNormalClosure, Text: "bye"}),
			attachEndClientClose},
		{"close frame without a status code",
			fmt.Errorf("read client frame: %w", &websocket.CloseError{Code: websocket.CloseNoStatusReceived}),
			attachEndClientClose},
		{"socket dropped without a close frame (gorilla's 1006)",
			fmt.Errorf("read client frame: %w", &websocket.CloseError{Code: websocket.CloseAbnormalClosure, Text: "unexpected EOF"}),
			attachEndReadError},
		{"output write failure",
			attachWriteError{fmt.Errorf("write stdout frame: %w", errors.New("broken pipe"))},
			attachEndWriteFailed},
		{"read deadline as net error",
			fmt.Errorf("read client frame: %w", &net.OpError{Op: "read", Net: "tcp", Err: os.ErrDeadlineExceeded}),
			attachEndPongTimeout},
		{"read deadline sentinel",
			fmt.Errorf("read client frame: %w", os.ErrDeadlineExceeded),
			attachEndPongTimeout},
		{"socket reset",
			fmt.Errorf("read client frame: %w", errors.New("connection reset by peer")),
			attachEndReadError},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			if got := classifyAttachEnd(tc.err); got != tc.want {
				t.Fatalf("classifyAttachEnd(%v) = %q, want %q", tc.err, got, tc.want)
			}
		})
	}
}

// The first failure names the cause; the ones that follow are consequences
// of the teardown it started.
func TestAttachEndRecordKeepsFirstError(t *testing.T) {
	var r attachEndRecord
	if r.get() != nil {
		t.Fatalf("empty record holds %v", r.get())
	}
	first := errors.New("first")
	r.fail(first)
	r.fail(errors.New("second"))
	r.fail(nil)
	if r.get() != first {
		t.Fatalf("record kept %v, want the first error %v", r.get(), first)
	}
}

func TestBoxliteExecAttach_RefusalIsLoggedWithoutRequestDetails(t *testing.T) {
	logs := captureAttachLogs(t)
	before := counterValue(t, common.ExecAttachRefusals.WithLabelValues("slot_occupied"))

	stub := newStubAttachExec()
	cleanup := withStubExec(t, "exec-busy", stub)
	defer cleanup()

	srv := newAttachServer(t)
	defer srv.Close()

	conn1, resp1, err := dialAttach(t, srv, "exec-busy")
	if err != nil {
		t.Fatalf("first dial failed: %v (resp=%v)", err, resp1)
	}
	defer conn1.Close()

	// Credentials ride in the query string on some deployments, so it is the
	// part of the URL that must never reach a log.
	conn2, resp2, err := dialAttachQuery(t, srv, "exec-busy", "?token=secret-query-value")
	if err == nil {
		conn2.Close()
		t.Fatal("expected second dial to fail with 409")
	}
	if resp2 == nil || resp2.StatusCode != http.StatusConflict {
		t.Fatalf("expected status 409, got resp=%v err=%v", resp2, err)
	}

	assertLogHas(t, logs, []string{"exec attach refused", `"execId":"exec-busy"`}, []string{
		`"level":"WARN"`, `"boxId":"box"`, `"execId":"exec-busy"`,
		`"reason":"slot_occupied"`, `"execDone":false`, `"occupantConnectedForMs":`,
	}, "secret-query-value")
	if counterValue(t, common.ExecAttachRefusals.WithLabelValues("slot_occupied"))-before < 1 {
		t.Error("refusal counter did not move")
	}
}

// dialAttachQuery is dialAttach with a query string appended to the path.
func dialAttachQuery(t *testing.T, srv *httptest.Server, execId, query string) (*websocket.Conn, *http.Response, error) {
	t.Helper()
	wsURL := strings.Replace(srv.URL, "http://", "ws://", 1) +
		"/v1/boxes/box/executions/" + execId + "/attach" + query
	dialer := *websocket.DefaultDialer
	dialer.HandshakeTimeout = 5 * time.Second
	return dialer.Dial(wsURL, nil)
}

// A session that ends with the exec must report what it sent per stream,
// and must not repeat the output in the log.
func TestBoxliteExecAttach_SessionEndLog_ExecDone(t *testing.T) {
	logs := captureAttachLogs(t)
	before := counterValue(t, common.ExecAttachSessions.WithLabelValues("exec_done"))

	stub := newStubAttachExec()
	stub.exitCode = 3
	cleanup := withStubExec(t, "exec-done", stub)
	defer cleanup()

	srv := newAttachServer(t)
	defer srv.Close()

	conn, _, err := dialAttachQuery(t, srv, "exec-done", "?stdin=1&token=secret-query-value")
	if err != nil {
		t.Fatalf("dial attach: %v", err)
	}
	defer conn.Close()

	// The reader goroutine starts after Subscribe, so stdin round-tripping
	// proves the pump is live before output is written into a stub that has
	// no backlog to replay it from.
	stdinDone := make(chan []byte, 1)
	go func() {
		buf := make([]byte, 8)
		n, _ := stub.stdinR.Read(buf)
		stdinDone <- buf[:n]
	}()
	if err := conn.WriteMessage(websocket.BinaryMessage, []byte("go")); err != nil {
		t.Fatalf("write stdin: %v", err)
	}
	select {
	case <-stdinDone:
	case <-time.After(2 * time.Second):
		t.Fatal("stdin pump did not deliver bytes")
	}
	if _, err := stub.stdoutW.Write([]byte("hello-secret-output")); err != nil {
		t.Fatalf("write stub stdout: %v", err)
	}
	mt, payload, err := readNextDataFrame(t, conn, 2*time.Second)
	if err != nil || mt != websocket.BinaryMessage || string(payload) != "\x01hello-secret-output" {
		t.Fatalf("expected stdout frame, got mt=%d payload=%q err=%v", mt, payload, err)
	}

	close(stub.done)

	// Read up to the exit frame, then answer the server's Close so the
	// handshake completes and the session-end line is written promptly.
	sawExit := false
	_ = conn.SetReadDeadline(time.Now().Add(3 * time.Second))
	for {
		mt, payload, err := conn.ReadMessage()
		if err != nil {
			if !sawExit {
				t.Fatalf("connection ended before the exit frame: %v", err)
			}
			break
		}
		if mt == websocket.TextMessage {
			var ev struct {
				Type     string `json:"type"`
				ExitCode int    `json:"exit_code"`
			}
			if err := json.Unmarshal(payload, &ev); err != nil {
				t.Fatalf("bad exit json: %v", err)
			}
			if ev.Type == "exit" {
				if ev.ExitCode != 3 {
					t.Fatalf("expected exit_code 3, got %d", ev.ExitCode)
				}
				sawExit = true
				_ = conn.WriteControl(websocket.CloseMessage,
					websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""),
					time.Now().Add(2*time.Second))
			}
		}
	}

	assertLogHas(t, logs, []string{"exec attach session ended", `"execId":"exec-done"`}, []string{
		`"level":"DEBUG"`, `"boxId":"box"`, `"execId":"exec-done"`, `"reason":"exec_done"`,
		`"execDone":true`, `"exitFrameSent":true`, `"execAttachSessions":1`,
		`"stdoutReplayedBytes":0`, `"stdoutSentBytes":20`, `"stdoutDroppedBytes":0`,
		`"stderrReplayedBytes":0`, `"stderrSentBytes":0`, `"stderrDroppedBytes":0`,
	}, "hello-secret-output", "secret-query-value", "firstError")
	if counterValue(t, common.ExecAttachSessions.WithLabelValues("exec_done"))-before < 1 {
		t.Error("exec_done counter did not move")
	}
}

func TestBoxliteExecAttach_SessionEndLog_PeerCloseAtExit(t *testing.T) {
	for _, tc := range []struct {
		name        string
		exitSent    bool
		peerCode    int
		wantFailure bool
	}{
		{"normal close after exit", true, websocket.CloseNormalClosure, false},
		{"exit frame unsent", false, websocket.CloseNormalClosure, true},
		{"protocol error after exit", true, websocket.CloseProtocolError, true},
	} {
		t.Run(tc.name, func(t *testing.T) {
			logs := captureAttachLogs(t)
			logAttachSessionEnd(attachSessionReport{
				execId:        tc.name,
				reason:        attachEndExecDone,
				execDone:      true,
				exitFrameSent: tc.exitSent,
				firstErr:      fmt.Errorf("read client frame: %w", &websocket.CloseError{Code: tc.peerCode}),
				outputs: [2]*attachOutput{
					{stream: &stubStream{}, channel: chanStdout},
					{stream: &stubStream{}, channel: chanStderr},
				},
			})
			match := []string{`"reason":"exec_done"`, fmt.Sprintf(`"execId":%q`, tc.name)}
			if tc.wantFailure {
				assertLogHas(t, logs, match, []string{`"firstError":`, fmt.Sprintf(`"clientCloseCode":%d`, tc.peerCode)})
			} else {
				assertLogHas(t, logs, match, nil, `"firstError":`, `"clientCloseCode":`)
			}
		})
	}
}

// A client Close frame is the normal end of a session that the client ends
// itself — what the SDK does before it reconnects.
func TestBoxliteExecAttach_SessionEndLog_ClientClose(t *testing.T) {
	logs := captureAttachLogs(t)
	stub := newStubAttachExec()
	cleanup := withStubExec(t, "exec-close", stub)
	defer cleanup()

	srv := newAttachServer(t)
	defer srv.Close()

	conn, _, err := dialAttach(t, srv, "exec-close")
	if err != nil {
		t.Fatalf("dial attach: %v", err)
	}
	defer conn.Close()

	if err := conn.WriteControl(websocket.CloseMessage,
		websocket.FormatCloseMessage(websocket.CloseNormalClosure, "reconnecting"),
		time.Now().Add(2*time.Second)); err != nil {
		t.Fatalf("send close: %v", err)
	}
	_ = conn.SetReadDeadline(time.Now().Add(3 * time.Second))
	for {
		if _, _, err := conn.ReadMessage(); err != nil {
			break
		}
	}

	assertLogHas(t, logs, []string{"exec attach session ended", `"execId":"exec-close"`}, []string{
		`"level":"DEBUG"`, `"execId":"exec-close"`, `"reason":"client_close"`,
		`"clientCloseCode":1000`, `"execDone":false`, `"exitFrameSent":false`,
		`"firstError":"read client frame: websocket: close 1000 (normal): reconnecting"`,
	})
}

// A client that keeps the socket but stops answering pings is evicted at
// pongWait; the line must say so, at WARN.
func TestBoxliteExecAttach_SessionEndLog_PongTimeout(t *testing.T) {
	logs := captureAttachLogs(t)
	restore := setKeepaliveIntervalForTest(50 * time.Millisecond)
	defer restore()

	stub := newStubAttachExec()
	cleanup := withStubExec(t, "exec-pong", stub)
	defer cleanup()

	srv := newAttachServer(t)
	defer srv.Close()

	conn, _, err := dialAttach(t, srv, "exec-pong")
	if err != nil {
		t.Fatalf("dial attach: %v", err)
	}
	defer conn.Close()
	conn.SetPingHandler(func(string) error { return nil })
	go func() {
		_ = conn.SetReadDeadline(time.Now().Add(3 * time.Second))
		for {
			if _, _, err := conn.ReadMessage(); err != nil {
				return
			}
		}
	}()

	assertLogHas(t, logs, []string{"exec attach session ended", `"execId":"exec-pong"`}, []string{
		`"level":"WARN"`, `"execId":"exec-pong"`, `"reason":"pong_timeout"`,
		`"firstError":"read client frame: read tcp`, `i/o timeout`,
	})
}

// A socket dropped without a Close frame — a killed client process or a cut
// network — reads as an error on our side and cannot be told apart, so it
// is WARN too.
func TestBoxliteExecAttach_SessionEndLog_ReadError(t *testing.T) {
	logs := captureAttachLogs(t)
	stub := newStubAttachExec()
	cleanup := withStubExec(t, "exec-reset", stub)
	defer cleanup()

	srv := newAttachServer(t)
	defer srv.Close()

	conn, _, err := dialAttach(t, srv, "exec-reset")
	if err != nil {
		t.Fatalf("dial attach: %v", err)
	}
	if err := conn.UnderlyingConn().Close(); err != nil {
		t.Fatalf("close socket: %v", err)
	}

	// gorilla surfaces the dropped socket as a 1006 CloseError; the line must
	// still call it a read error and must not report a client close code.
	assertLogHas(t, logs, []string{"exec attach session ended", `"execId":"exec-reset"`}, []string{
		`"level":"WARN"`, `"execId":"exec-reset"`, `"reason":"read_error"`,
		`"firstError":"read client frame: websocket: close 1006 (abnormal closure): unexpected EOF"`,
	}, `"clientCloseCode"`, `"reason":"client_close"`)
}

// A panic in the loop is ERROR, and the slot is still released.
func TestBoxliteExecAttach_SessionEndLog_Panic(t *testing.T) {
	logs := captureAttachLogs(t)
	// The test client never answers the server's Close, so bound the wait.
	restore := setPeerCloseWaitForTest(200 * time.Millisecond)
	defer restore()

	stub := newStubAttachExec()
	stub.panicOnExitCode = true
	cleanup := withStubExec(t, "exec-panic", stub)
	defer cleanup()

	srv := newAttachServer(t)
	defer srv.Close()

	conn, _, err := dialAttach(t, srv, "exec-panic")
	if err != nil {
		t.Fatalf("dial attach: %v", err)
	}
	defer conn.Close()
	close(stub.done)

	assertLogHas(t, logs, []string{"exec attach session ended", `"execId":"exec-panic"`}, []string{
		`"level":"ERROR"`, `"execId":"exec-panic"`, `"reason":"panic"`,
		`"firstError":"attach loop panic: exit code stub panic"`,
	})
	if stub.connected.Load() {
		t.Error("attach slot still held after the panic")
	}
}

// A request that is not a WebSocket upgrade fails after the slot was
// claimed; it is logged as upgrade_failed and the slot is released.
func TestBoxliteExecAttach_SessionEndLog_UpgradeFailed(t *testing.T) {
	logs := captureAttachLogs(t)
	before := counterValue(t, common.ExecAttachSessions.WithLabelValues("upgrade_failed"))

	stub := newStubAttachExec()
	cleanup := withStubExec(t, "exec-up", stub)
	defer cleanup()

	srv := newAttachServer(t)
	defer srv.Close()

	resp, err := http.Get(srv.URL + "/v1/boxes/box/executions/exec-up/attach?token=secret-query-value")
	if err != nil {
		t.Fatalf("plain GET: %v", err)
	}
	resp.Body.Close()
	if resp.StatusCode != http.StatusBadRequest {
		t.Fatalf("expected 400 from the upgrader, got %d", resp.StatusCode)
	}

	assertLogHas(t, logs, []string{"exec attach upgrade failed", `"execId":"exec-up"`}, []string{
		`"level":"WARN"`, `"boxId":"box"`, `"execId":"exec-up"`, `"reason":"upgrade_failed"`, `"error":`,
	}, "secret-query-value")
	if stub.connected.Load() {
		t.Error("attach slot still held after the failed upgrade")
	}
	if counterValue(t, common.ExecAttachSessions.WithLabelValues("upgrade_failed"))-before < 1 {
		t.Error("upgrade_failed counter did not move")
	}
}