perf(terminal): pool base64 encode buffers to reduce GC churn under heavy PTY output
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)
backend/internal/terminal/attachment.go:195-208—copyOutreuses 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)backend/internal/terminal/manager.go:565-590—outQueue.pushmerges consecutive output for the same terminal into one frame, bounded bymaxMergedData = 256 << 10; on the non-merge path it copies again:msg.raw = append([]byte(nil), msg.raw...) // copy #2 of the same bytesbackend/internal/terminal/manager.go:604-620—outQueue.drainbase64-encodes each drained frame:frames[i].Data = base64.StdEncoding.EncodeToString(frames[i].raw)backend/internal/terminal/manager.go:637-681—writeLoopcallsc.conn.WriteJSON(ctx, msg), implemented aswsjson.Writeinbackend/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.
- Drop the redundant copy in
pushfor callers that already own their bytes (copyOutdoes). Either document thatserverMsg.rawtransfers ownership and remove the copy, or letcopyOuthand over its chunk. Saves one full payload copy per read. - Pool the base64 scratch buffer — borrow a
[]byte,base64.AppendEncodeinto it, build the string, return it. Removes themake([]byte, encodedLen); thestringcopy remains. - Optional larger win: build the whole data frame in one pooled buffer with
base64.AppendEncodeand write it with a newWriteMessage(ctx, []byte)method on thewsConnseam (manager.go:27-32, implemented asa.c.Write(ctx, websocket.MessageText, p)interminal_mux.go:52). That skips both the base64stringand the encoder copy. KeepWriteJSONfor 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
- [ ]
pushno 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, includingoutqueue_test.go's base64 assertions - [ ]
go test -race ./internal/terminal/...passes - [ ]
go test ./internal/httpd/...passes - [ ] a benchmark (
BenchmarkOutQueueDrainor similar) records allocations/op before and after
tested with 100,000 lines. output arrived correctly and the terminal stayed responsive. memory usage still needs benchmarking.