agent-orchestrator icon indicating copy to clipboard operation
agent-orchestrator copied to clipboard

perf(terminal): pool base64 encode buffers to reduce GC churn under heavy PTY output

Open ApexYash11 opened this issue 3 weeks ago • 1 comments

Summary

Streaming a heavy command (npm install, cargo build, go test -v, seq 1 100000) makes the daemon allocate and copy every PTY output byte several times before it reaches the renderer. Previous work reduced the number of frames; the per-frame allocation and copying cost is still there. This issue tracks removing it, with the wire format unchanged.

Current code path (verified on main)

  1. backend/internal/terminal/attachment.go:195-208 — copyOut reuses one 32 KiB read buffer but allocates a fresh chunk per read:
    buf := make([]byte, 32*1024)
    n, err := p.Read(buf)
    chunk := make([]byte, n)
    copy(chunk, buf[:n])   // copy #1: caller now owns chunk
    a.onData(chunk)
    
  2. backend/internal/terminal/manager.go:565-590 — outQueue.push merges consecutive output for the same terminal into one frame, bounded by maxMergedData = 256 << 10; on the non-merge path it copies again:
    msg.raw = append([]byte(nil), msg.raw...)   // copy #2 of the same bytes
    
  3. backend/internal/terminal/manager.go:604-620 — outQueue.drain base64-encodes each drained frame:
    frames[i].Data = base64.StdEncoding.EncodeToString(frames[i].raw)
    
  4. backend/internal/terminal/manager.go:637-681 — writeLoop calls c.conn.WriteJSON(ctx, msg), implemented as wsjson.Write in backend/internal/httpd/terminal_mux.go:55.

Allocation cost per data frame

Measured against Go 1.27.1 and github.com/coder/websocket v1.8.14:

Step Allocation
copyOut chunk n bytes
push copy n bytes — redundant on this path, the chunk is already owned
merge append amortized growth, up to 256 KiB
EncodeToString make([]byte, encodedLen) plus a string copy of encodedLen, where encodedLen = 4*ceil(n/3)
wsjson.Write not a full json.Marshal: it streams through json.Encoder straight into c.Write(ctx, MessageText, p), and encoding/json pools its encodeState

Correction to an earlier draft of this issue: the JSON step is not a third large allocation. The avoidable cost is the double copy of the payload plus the two base64 allocations.

Fix

Three independent, additive changes; each is safe on its own.

  1. Drop the redundant copy in push for callers that already own their bytes (copyOut does). Either document that serverMsg.raw transfers ownership and remove the copy, or let copyOut hand over its chunk. Saves one full payload copy per read.
  2. Pool the base64 scratch buffer — borrow a []byte, base64.AppendEncode into it, build the string, return it. Removes the make([]byte, encodedLen); the string copy remains.
  3. Optional larger win: build the whole data frame in one pooled buffer with base64.AppendEncode and write it with a new WriteMessage(ctx, []byte) method on the wsConn seam (manager.go:27-32, implemented as a.c.Write(ctx, websocket.MessageText, p) in terminal_mux.go:52). That skips both the base64 string and the encoder copy. Keep WriteJSON for every other frame type.

The wire format is identical in all three cases: same JSON object, same base64 Data. No client, protocol, or migration change.

Files: backend/internal/terminal/manager.go; for option 3 also backend/internal/httpd/terminal_mux.go and the wsConn fake in the tests.

Prior work (complementary, not this fix)

Commit What it changed What remains
65748f32b5 Merged consecutive PTY chunks so base64 runs once per merged frame Each merged frame still encodes and copies
b06a3a4058 4 ms burst pacing: ~2,900 messages to ~23 for seq 1 100000 Each of those frames still pays the cost above
ca9a083036 (#6232) Moved VT emulation off the PTY read loop (asyncSurface) Unrelated to encoding
7a142e5658 (#6465) WebGL context pool, batched frames, faster terminal open Renderer side only

There is exactly one sync.Pool in the backend today (previewGzipWriters, backend/internal/httpd/controllers/sessions.go:604), so pooling here is consistent with existing practice rather than new machinery.

Why it matters

Allocation and copy cost scales with output volume times open panes. It lands as GC work in the daemon and as decode work in the renderer, and it is the part that remains after the frame-count work: fewer, larger frames still carry every byte through two copies and two base64 allocations. Option 1 alone removes a full copy of every PTY byte.

Definition of done

  • [ ] push no longer copies payload bytes it already owns (ownership documented)
  • [ ] base64 encoding reuses a pooled buffer
  • [ ] optionally, data frames are written from a pooled buffer via WriteMessage
  • [ ] go test ./internal/terminal/... passes, including outqueue_test.go's base64 assertions
  • [ ] go test -race ./internal/terminal/... passes
  • [ ] go test ./internal/httpd/... passes
  • [ ] a benchmark (BenchmarkOutQueueDrain or similar) records allocations/op before and after

ApexYash11 avatar Nov 10 '26 13:11 ApexYash11

tested with 100,000 lines. output arrived correctly and the terminal stayed responsive. memory usage still needs benchmarking.

image

codebanditssss avatar Nov 11 '26 16:11 codebanditssss