szn

Bug 482 — Full-frame heap copy into dc.out_buf per render per client

482. Render frame duplicated into out_buf before socket write

Severity: LOW (performance) Status: ✅ FIXED Files: src/server/server.zig:2806-2815

Problem

appendClientOut (the path render frames flow through after #431) does:

if (hdr.len > 0) {
    dc.out_buf.appendSlice(self.allocator, hdr) catch return false;
}
if (body.len > 0) {
    dc.out_buf.appendSlice(self.allocator, body) catch {
        dc.out_buf.shrinkRetainingCapacity(prev_len);
        return false;
    };
}

body here is self.render_buf.items — a serialized frame up to ~768 KiB (RENDER_HIGH_WATERMARK). Every frame is heap-allocated into dc.out_buf and memcpy’d before flushDisplayClient writes it to the socket. With N display clients each render does N full-frame heap copies.

This duplicates the #431 flow-control fix at the cost of one extra per-frame allocation + memcpy per client.

Proposed Fix

Write render_buf directly to the display socket with a non-blocking partial-write loop; only fall back to queueing in out_buf on EAGAIN (the socket is O_NONBLOCK, and writeAll/EINTR handling already exist on the client side — see main.zig:51-82). The RENDER_HIGH_WATERMARK / behind backpressure from #298/#431 is preserved: on EAGAIN the frame queues, watermark still applies, and no frame is dropped.

Resolution

Added Server.writeFrameToClient (src/server/server.zig) and routed the display render path through it. With no earlier frame draining, the frame is written straight to the socket (header then body, c.write loop with INTR/EAGAIN handling). out_buf.ensureTotalCapacity(total_len) is reserved first, so a partial write can always queue its remainder with appendSliceAssumeCapacity — a half-written frame is never abandoned on allocation failure. Only the unsent remainder is copied into out_buf and POLLOUT is armed; the watermark/behind accounting is preserved (a single oversized frame sets behind once queued, further frames are skipped). appendClientOutFrame remains the fallback while a previous frame is pending; flushDisplayClient is unchanged.

Tests: a socketpair frame lands on the peer with out_buf empty, and a filled/non-blocking socket EAGAIN path queues exactly hdr + body for POLLOUT.

Verified: zig build test -Doptimize=ReleaseFast — 1012/1012 tests pass.