Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

transport: bound the upload by its progress, not the head deadline (#1785)

justrachc03c26926830
diff --git a/src/agent_stream.zig b/src/agent_stream.zig
index 1aa551ff..b98cb5f2 100644
--- a/src/agent_stream.zig
+++ b/src/agent_stream.zig
@@ -29,10 +29,9 @@ const http_headers = @import("http_headers.zig");
const providerUserAgent = http.providerUserAgent;
const capture5xxBodyStream = http.capture5xxBodyStream;
const WatchdogFired = http.WatchdogFired;
-const sendHeadTask = http.sendHeadTask;
+const http_send = @import("http_send.zig");
const stream_progress = @import("stream_read_progress.zig");
const streamLineTask = stream_progress.lineTask;
-const deadlineStallTask = http.deadlineStallTask;
const watchdogError = http.watchdogError;
const http_stall = @import("http_stall.zig");
@@ -121,74 +120,33 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []cons
// HTTP/2 first, under the same raw-stdin window so Esc and steering work
// there too; null means "not sent, use HTTP/1.1".
if (try @import("agent_stream_h2.zig").postStream(self, body, orig_tio != null)) |full| return full;
- var req = transport.request(.POST, try std.Uri.parse(provider.url), .{
+ var head: http_send.H1 = .{ .client = transport, .uri = try std.Uri.parse(provider.url), .body = body, .options = .{
.redirect_behavior = .unhandled,
.headers = .{
.content_type = .{ .override = "application/json" },
.user_agent = providerUserAgent(provider),
},
.extra_headers = extra,
- }) catch |err| {
- if (http_client.constructionTlsFailure(err, provider.url)) return http_client.constructionTlsError(transport);
- return err;
- };
- defer req.deinit();
+ } };
+ defer if (head.req) |*r| r.deinit();
// A failed SEND leaves reader.state == .ready, which Request.deinit
// reads as "connection still clean" and returns it to the keep-alive
// pool — every retry (and every later turn) then pulls the same dead
// connection back out: HttpConnectionClosing once, WriteFailed
// forever after (observed in the wild). Poison it on any error so
// deinit discards it and the retry dials fresh.
- errdefer if (req.connection) |conn| {
+ errdefer if (head.req) |*r| if (r.connection) |conn| {
conn.closing = true;
};
- // Race the send + head receive against a stall watchdog so a
- // freshly-redialed connection that the server accepts but never
- // answers can't hang the turn (issue #54: "retrying (1/3)" then
- // "thinking… forever"). Mirrors the SSE line-loop and postWatched
- // patterns. Falls back to a bare send+receiveHead (the old behavior)
- // when no spare concurrency exists.
- var response: std.http.Client.Response = undefined;
- head: {
- const HeadDone = union(enum) { sent: anyerror!void, stall: WatchdogFired };
- var hd_buf: [2]HeadDone = undefined;
- var hsel: Io.Select(HeadDone) = .init(self.io, &hd_buf);
- hsel.concurrent(.sent, sendHeadTask, .{ &req, body, &response }) catch {
- // #56 Fix-B: Io pool exhausted (deep subagent fan-out saturated the
- // thread pool) — we can't spawn the head-stall watchdog. A bare
- // send+receiveHead here could hang forever on a half-open socket with
- // nothing to trip it. Nothing has streamed yet, so fail safe: poison the
- // connection and return a retryable HungRequest so request() backs off
- // and redials once a pool slot frees, instead of blocking the turn.
- if (req.connection) |conn| conn.closing = true;
- return error.HungRequest;
- };
- hsel.concurrent(.stall, deadlineStallTask, .{ self.io, orig_tio != null, http_stall.headBudgetMs(provider.url, http.head_stall_ms, http_stall.streamPolicy(provider.model, provider.url, http.stream_stall_ms)) }) catch {
- const r = hsel.await() catch |e| {
- hsel.cancelDiscard();
- return e;
- };
- hsel.cancelDiscard();
- r.sent catch |e| {
- return e;
- };
- break :head;
- };
- const first = hsel.await() catch |e| {
- hsel.cancelDiscard();
- return e;
- };
- hsel.cancelDiscard();
- switch (first) {
- .sent => |s| s catch |e| {
- return e;
- },
- .stall => |w| {
- if (req.connection) |conn| conn.closing = true;
- return watchdogError(w, error.HungRequest);
- },
- }
- }
+ // Connect, upload and head wait race a staged watchdog, so a server that
+ // accepts and never answers can't hang the turn (#54) and a large body
+ // still draining isn't killed by the head deadline (#1785).
+ http_send.raceH1(self.io, &head, orig_tio != null, http_send.Budget.forRequest(body.len, provider.url, provider.model)) catch |err| {
+ if (head.req == null and http_client.constructionTlsFailure(err, provider.url)) return http_client.constructionTlsError(transport);
+ return err;
+ };
+ const req = &head.req.?;
+ const response = &head.response;
// 429/5xx before any body: a retryable throttle — request() backs
// off and retries (surfaced in the trace as a "retry" note).
@@ -198,17 +156,17 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []cons
return err;
}
if (status_code == 429 or status_code >= 500) {
- http.captureRetryAfter(&response); // #retry-after: honor the provider's requested backoff
+ http.captureRetryAfter(response); // #retry-after: honor the provider's requested backoff
// Drain a snippet for quota classifiers. Do not echo it on the REPL
// retry line — vendor envelopes include user ids and routing docs.
- capture5xxBodyStream(self.gpa, &response);
+ capture5xxBodyStream(self.gpa, response);
if (req.connection) |conn| conn.closing = true;
return if (status_code == 429) error.RateLimited else error.ServerError;
}
// #opencode-parity: OpenAI proper spuriously 404s available models — retry a
// 404 from an openai-* provider like a 5xx instead of hard-failing the turn.
if (status_code == 404 and std.mem.startsWith(u8, self.provider.id, "openai")) {
- capture5xxBodyStream(self.gpa, &response);
+ capture5xxBodyStream(self.gpa, response);
if (req.connection) |conn| conn.closing = true;
return error.OpenAiFlaky404;
}
diff --git a/src/agent_stream_h2.zig b/src/agent_stream_h2.zig
index f5416d66..1afa0ad4 100644
--- a/src/agent_stream_h2.zig
+++ b/src/agent_stream_h2.zig
@@ -17,7 +17,7 @@ const engine_sink = @import("engine_sink.zig");
const http_zig = @import("http_zig");
const WatchdogFired = http.WatchdogFired;
const watchdogError = http.watchdogError;
-const deadlineStallTask = http.deadlineStallTask;
+const http_send = @import("http_send.zig");
const stream_progress = @import("stream_read_progress.zig");
const ssePayload = Agent.ssePayload;
@@ -86,10 +86,11 @@ pub fn postStream(self: *Agent, body: []const u8, poll_stdin: bool) !?[]u8 {
var keep = false;
defer head.deinit(keep);
- // Dial, send and time-to-first-HEADERS race the head-stall watchdog, as
- // the HTTP/1.1 send + receiveHead do (issue #54): a half-open socket or a
- // server that accepts the stream and goes silent must not hang the turn.
- switch (try raceHead(self.io, &head, poll_stdin, http_stall.headBudgetMs(provider.url, http.head_stall_ms, http_stall.streamPolicy(provider.model, provider.url, http.stream_stall_ms)))) {
+ // Dial, send and time-to-first-HEADERS race the staged watchdog, as on
+ // HTTP/1.1 (#54, #1785): a half-open socket or a server that accepts the
+ // stream and goes silent must not hang the turn. http-zig reports no DATA
+ // progress, so the upload gets only its size-scaled total.
+ switch (try raceHead(self.io, &head, poll_stdin, http_send.Budget.forRequest(body.len, provider.url, provider.model).blind())) {
.ok => {},
.fallback => return null,
}
@@ -209,14 +210,15 @@ const Head = struct {
const HeadResult = enum { ok, fallback };
-fn raceHead(io: Io, head: *Head, poll_stdin: bool, budget_ms: u64) !HeadResult {
+fn raceHead(io: Io, head: *Head, poll_stdin: bool, budget: http_send.Budget) !HeadResult {
+ var watch: http_send.Watch = .init(io, budget);
const HeadDone = union(enum) { done: anyerror!void, stall: WatchdogFired };
var hd_buf: [2]HeadDone = undefined;
var hsel: Io.Select(HeadDone) = .init(io, &hd_buf);
// #56 Fix-B: no slot for the task means no watchdog either. Nothing has
// been sent, so fail retryable instead of blocking the turn.
- hsel.concurrent(.done, headTask, .{head}) catch return error.HungRequest;
- hsel.concurrent(.stall, deadlineStallTask, .{ io, poll_stdin, budget_ms }) catch {};
+ hsel.concurrent(.done, headTask, .{ head, &watch }) catch return error.HungRequest;
+ hsel.concurrent(.stall, http_send.Watch.watch, .{ &watch, poll_stdin }) catch {};
const first = hsel.await() catch |e| {
hsel.cancelDiscard();
return e;
@@ -267,14 +269,16 @@ test "HTTP/1.1 fallback only when the request provably never reached the server"
try std.testing.expect(!mayResendOnH1(.send, error.Canceled));
}
-fn headTask(head: *Head) anyerror!void {
+fn headTask(head: *Head, watch: *http_send.Watch) anyerror!void {
head.phase = .dial;
head.lease = try http2_pool.acquire(head.gpa, head.io, head.origin.host, head.origin.port);
const sess = head.lease.?.session;
if (sess.h1_only) return error.H1NoStream;
head.phase = .send;
+ watch.enter(.upload);
head.lines = try sess.startLines(head.req);
head.phase = .wait;
+ watch.enter(.head);
const lines = &head.lines.?;
head.status = try lines.waitStatus();
// Error bodies are read here, still under the head watchdog: request()
diff --git a/src/http_send.zig b/src/http_send.zig
new file mode 100644
index 00000000..666296b0
--- /dev/null
+++ b/src/http_send.zig
@@ -0,0 +1,209 @@
+//! The request half of a streaming POST (#1785): connection setup, the body
+//! upload and the wait for the response head each get their own budget. One
+//! flat head deadline over all three killed large bodies still draining to a
+//! live peer, and the retry only re-sent the same upload into the same wall.
+
+const std = @import("std");
+const Io = std.Io;
+const http = @import("http.zig");
+const http_stall = @import("http_stall.zig");
+const Agent = @import("agent.zig").Agent;
+const cancel_source = @import("cancel_source.zig");
+const sendDeadlineMs = @import("agent_ws_signal.zig").sendDeadlineMs;
+
+pub const Stage = enum(u8) { connect, upload, head };
+
+/// Body bytes per socket write; each completed write is upload progress.
+const chunk_len: usize = 16 * 1024;
+/// Upload floor of 128 kbit/s: a peer accepting a byte at a time still ends.
+const floor_bytes_per_s: usize = 16 * 1024;
+/// The unfinished-event cap stream_read_progress uses for the read side.
+const max_upload_ms: u64 = 15 * 60 * 1000;
+
+pub const Budget = struct {
+ connect_ms: u64,
+ /// No body byte taken by the socket for this long is a stalled peer.
+ upload_idle_ms: u64,
+ upload_total_ms: u64,
+ /// From the last body byte to the response head. Grows with the body as
+ /// the WebSocket send deadline does: its tail can still sit in socket
+ /// buffers, clamped to the read budget.
+ head_ms: u64,
+
+ pub fn init(body_len: usize, setup_ms: u64, head_ms: u64, stream_ms: u64) Budget {
+ const floor_ms = @as(u64, @intCast(body_len / floor_bytes_per_s)) *| 1000;
+ return .{
+ .connect_ms = setup_ms,
+ .upload_idle_ms = setup_ms,
+ .upload_total_ms = @min(setup_ms +| floor_ms, @max(setup_ms, max_upload_ms)),
+ .head_ms = sendDeadlineMs(body_len, head_ms, stream_ms),
+ };
+ }
+
+ /// The configured budgets for one request. The loopback-inference head
+ /// exception (http_stall.headBudgetMs) widens only the head wait.
+ pub fn forRequest(body_len: usize, url: []const u8, model: []const u8) Budget {
+ const policy = http_stall.streamPolicy(model, url, http.stream_stall_ms);
+ return init(body_len, http.head_stall_ms, http_stall.headBudgetMs(url, http.head_stall_ms, policy), http.stream_stall_ms);
+ }
+
+ /// A transport that reports no upload progress (http-zig writes DATA
+ /// internally) gets only the size-scaled total.
+ pub fn blind(self: Budget) Budget {
+ var b = self;
+ b.upload_idle_ms = b.upload_total_ms;
+ return b;
+ }
+};
+
+/// `since_ms`: time in this stage; `idle_ms`: time since the last progress.
+pub fn expired(b: Budget, stage: Stage, since_ms: u64, idle_ms: u64) bool {
+ return switch (stage) {
+ .connect => since_ms >= b.connect_ms,
+ .upload => idle_ms >= b.upload_idle_ms or since_ms >= b.upload_total_ms,
+ .head => since_ms >= b.head_ms,
+ };
+}
+
+fn nowMs(io: Io) i64 {
+ return @intCast(@divTrunc(Io.Timestamp.now(io, .awake).nanoseconds, std.time.ns_per_ms));
+}
+
+fn elapsed(from: i64, now: i64) u64 {
+ return @intCast(@max(now - from, 0));
+}
+
+/// The request task advances the stage and notes progress; the watchdog arm
+/// reads only these atomics.
+pub const Watch = struct {
+ io: Io,
+ budget: Budget,
+ stage: std.atomic.Value(Stage) = .init(.connect),
+ stage_ms: std.atomic.Value(i64),
+ last_ms: std.atomic.Value(i64),
+
+ pub fn init(io: Io, budget: Budget) Watch {
+ const now = nowMs(io);
+ return .{ .io = io, .budget = budget, .stage_ms = .init(now), .last_ms = .init(now) };
+ }
+
+ pub fn enter(self: *Watch, stage: Stage) void {
+ const now = nowMs(self.io);
+ self.stage_ms.store(now, .monotonic);
+ self.last_ms.store(now, .monotonic);
+ self.stage.store(stage, .release);
+ }
+
+ pub fn note(self: *Watch) void {
+ self.last_ms.store(nowMs(self.io), .monotonic);
+ }
+
+ /// Select arm: fires when the current stage's budget runs out, or on Esc.
+ pub fn watch(self: *Watch, poll_stdin: bool) http.WatchdogFired {
+ while (true) {
+ const stage = self.stage.load(.acquire);
+ const now = nowMs(self.io);
+ if (expired(self.budget, stage, elapsed(self.stage_ms.load(.monotonic), now), elapsed(self.last_ms.load(.monotonic), now))) return .deadline;
+ self.io.sleep(.fromMilliseconds(10), .awake) catch return .deadline; // canceled: the request finished
+ if (poll_stdin and Agent.drainSteerStdin(true)) {
+ cancel_source.cancelFromStdin();
+ return .esc;
+ }
+ if (Agent.esc_cancel.load(.acquire)) return .esc;
+ }
+ }
+};
+
+/// Write the body in chunks; each one the connection took is progress.
+pub fn sendBody(req: *std.http.Client.Request, body: []const u8, watch: *Watch) !void {
+ req.transfer_encoding = .{ .content_length = body.len };
+ var bw = try req.sendBodyUnflushed(&.{});
+ var off: usize = 0;
+ while (off < body.len) {
+ const n = @min(chunk_len, body.len - off);
+ try bw.writer.writeAll(body[off..][0..n]);
+ off += n;
+ watch.note();
+ }
+ try bw.end();
+ try req.connection.?.flush();
+}
+
+/// HTTP/1.1 request state the task fills and the caller owns. `req` stays
+/// null until the connection is up, so the caller knows what to tear down.
+pub const H1 = struct {
+ client: *std.http.Client,
+ uri: std.Uri,
+ options: std.http.Client.RequestOptions,
+ body: []const u8,
+ req: ?std.http.Client.Request = null,
+ response: std.http.Client.Response = undefined,
+};
+
+fn h1Task(h: *H1, w: *Watch) anyerror!void {
+ h.req = try h.client.request(.POST, h.uri, h.options);
+ w.enter(.upload);
+ try sendBody(&h.req.?, h.body, w);
+ w.enter(.head);
+ h.response = try h.req.?.receiveHead(&.{});
+}
+
+/// Connect, upload and receive the head against the staged watchdog. A
+/// deadline is HungRequest (retryable), Esc is Interrupted.
+pub fn raceH1(io: Io, h: *H1, poll_stdin: bool, budget: Budget) !void {
+ var w: Watch = .init(io, budget);
+ const Done = union(enum) { sent: anyerror!void, stall: http.WatchdogFired };
+ var buf: [2]Done = undefined;
+ var sel: Io.Select(Done) = .init(io, &buf);
+ // #56 Fix-B: no slot for the request means no watchdog either. Nothing
+ // is on the wire, so fail retryable instead of blocking the turn.
+ sel.concurrent(.sent, h1Task, .{ h, &w }) catch return error.HungRequest;
+ sel.concurrent(.stall, Watch.watch, .{ &w, poll_stdin }) catch {
+ const r = sel.await() catch |e| {
+ sel.cancelDiscard();
+ return e;
+ };
+ sel.cancelDiscard();
+ return r.sent;
+ };
+ const first = sel.await() catch |e| {
+ sel.cancelDiscard();
+ return e;
+ };
+ sel.cancelDiscard();
+ switch (first) {
+ .sent => |s| return s,
+ .stall => |f| return http.watchdogError(f, error.HungRequest),
+ }
+}
+
+test "staged budgets: defaults, body scaling and their caps (#1785)" {
+ const small = Budget.init(4 * 1024, 30_000, 30_000, 120_000);
+ try std.testing.expectEqual(@as(u64, 30_000), small.connect_ms);
+ try std.testing.expectEqual(@as(u64, 30_000), small.upload_idle_ms);
+ try std.testing.expectEqual(@as(u64, 30_000), small.upload_total_ms);
+ try std.testing.expectEqual(@as(u64, 30_000), small.head_ms);
+ // 1 MiB: 64 s of floor-rate upload, 16 s of queued tail for the head.
+ const mib = Budget.init(1024 * 1024, 30_000, 30_000, 120_000);
+ try std.testing.expectEqual(@as(u64, 30_000), mib.upload_idle_ms);
+ try std.testing.expectEqual(@as(u64, 94_000), mib.upload_total_ms);
+ try std.testing.expectEqual(@as(u64, 46_000), mib.head_ms);
+ const huge = Budget.init(std.math.maxInt(usize), 30_000, 30_000, 120_000);
+ try std.testing.expectEqual(max_upload_ms, huge.upload_total_ms);
+ try std.testing.expectEqual(@as(u64, 120_000), huge.head_ms);
+ // A widened loopback head wait is kept, not clamped to the read budget.
+ try std.testing.expectEqual(@as(u64, 600_000), Budget.init(1024 * 1024, 30_000, 600_000, 120_000).head_ms);
+ try std.testing.expectEqual(mib.upload_total_ms, mib.blind().upload_idle_ms);
+}
+
+test "staged expiry: upload ends on silence or its total, never on the head deadline (#1785)" {
+ const b = Budget.init(1024 * 1024, 30_000, 30_000, 120_000);
+ try std.testing.expect(!expired(b, .connect, 29_999, 29_999));
+ try std.testing.expect(expired(b, .connect, 30_000, 0));
+ // Still draining well past the head deadline: alive.
+ try std.testing.expect(!expired(b, .upload, 80_000, 50));
+ try std.testing.expect(expired(b, .upload, 1_000, 30_000));
+ try std.testing.expect(expired(b, .upload, 94_000, 50));
+ try std.testing.expect(!expired(b, .head, 45_999, 45_999));
+ try std.testing.expect(expired(b, .head, 46_000, 0));
+}
diff --git a/src/http_send_test.zig b/src/http_send_test.zig
new file mode 100644
index 00000000..9cf3b349
--- /dev/null
+++ b/src/http_send_test.zig
@@ -0,0 +1,132 @@
+//! A body still draining to the peer is not a hung request (#1785).
+//! Synthetic loopback peer drives the production HTTP/1 SSE entry point.
+const std = @import("std");
+const builtin = @import("builtin");
+const Io = std.Io;
+const Agent = @import("agent.zig").Agent;
+const http = @import("http.zig");
+const agent_stream = @import("agent_stream.zig");
+
+const head_ms: u64 = 150; // not 30_000: the loopback head exception stays off
+const paced_len: usize = 2 * 1024 * 1024;
+
+const Peer = struct {
+ const Mode = enum { paced, stopped };
+
+ fn run(io: Io, listener: *Io.net.Server, mode: Mode, got: *std.atomic.Value(usize), done: *std.atomic.Value(bool)) void {
+ const conn = listener.accept(io) catch return;
+ defer conn.close(io);
+ if (mode == .stopped) {
+ while (!done.load(.acquire)) io.sleep(.fromMilliseconds(10), .awake) catch return;
+ return;
+ }
+ var input_buf: [8192]u8 = undefined;
+ var input = Io.net.Stream.Reader.init(conn, io, &input_buf);
+ var len: usize = 0;
+ while (true) {
+ const line = (input.interface.takeDelimiter('\n') catch return) orelse return;
+ if (line.len == 0 or (line.len == 1 and line[0] == '\r')) break;
+ const name = "content-length:";
+ if (line.len > name.len and std.ascii.eqlIgnoreCase(line[0..name.len], name))
+ len = std.fmt.parseInt(usize, std.mem.trim(u8, line[name.len..], " \r"), 10) catch return;
+ }
+ // 32 KiB per 10 ms: the whole body takes several head budgets.
+ var since_pause: usize = 0;
+ while (got.load(.monotonic) < len) {
+ const n = @min(len - got.load(.monotonic), 8192);
+ input.interface.discardAll(n) catch return;
+ _ = got.fetchAdd(n, .monotonic);
+ since_pause += n;
+ if (since_pause >= 32 * 1024) {
+ since_pause = 0;
+ io.sleep(.fromMilliseconds(10), .awake) catch return;
+ }
+ }
+ var output_buf: [1024]u8 = undefined;
+ var output = Io.net.Stream.Writer.init(conn, io, &output_buf);
+ output.interface.writeAll("HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n" ++
+ "data: {\"choices\":[{\"delta\":{\"content\":\"ok\"}}]}\n\ndata: [DONE]\n\n") catch return;
+ output.interface.flush() catch return;
+ while (!done.load(.acquire)) io.sleep(.fromMilliseconds(10), .awake) catch return;
+ }
+};
+
+fn nowMs(io: Io) i64 {
+ return @intCast(@divTrunc(Io.Timestamp.now(io, .awake).nanoseconds, std.time.ns_per_ms));
+}
+
+fn exercise(mode: Peer.Mode, body_len: usize) !void {
+ if (builtin.os.tag == .windows) return error.SkipZigTest; // loopback buffer sizing is not deterministic there
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var addr = try Io.net.IpAddress.parseLiteral("127.0.0.1:0");
+ var listener = try Io.net.IpAddress.listen(&addr, io, .{});
+ defer listener.deinit(io);
+ // A small receive buffer keeps the peer's pace, not the kernel, in charge.
+ const rcvbuf: c_int = 16 * 1024;
+ if (builtin.os.tag != .windows) std.posix.setsockopt(listener.socket.handle, std.posix.SOL.SOCKET, std.posix.SO.RCVBUF, std.mem.asBytes(&rcvbuf)) catch {};
+ var got: std.atomic.Value(usize) = .init(0);
+ var done: std.atomic.Value(bool) = .init(false);
+ var peer = io.async(Peer.run, .{ io, &listener, mode, &got, &done });
+ defer peer.await(io);
+ defer done.store(true, .release);
+
+ const saved_head = http.head_stall_ms;
+ const saved_stream = http.stream_stall_ms;
+ http.head_stall_ms = head_ms;
+ http.stream_stall_ms = 1000;
+ defer http.head_stall_ms = saved_head;
+ defer http.stream_stall_ms = saved_stream;
+
+ const body = try gpa.alloc(u8, body_len);
+ defer gpa.free(body);
+ @memset(body, ' ');
+ body[0] = '{';
+ body[body.len - 1] = '}';
+
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ var client: std.http.Client = .{ .allocator = gpa, .io = io };
+ defer client.deinit();
+ var url_buf: [96]u8 = undefined;
+ const url = try std.fmt.bufPrint(&url_buf, "http://127.0.0.1:{d}/v1/chat/completions", .{listener.socket.address.getPort()});
+ var agent: Agent = .{
+ .gpa = gpa,
+ .arena = arena_state.allocator(),
+ .io = io,
+ .client = &client,
+ .provider = .{ .id = "test", .kind = .openai, .auth = .bearer, .url = url, .api_key = "synthetic", .model = "fixture", .context = 0 },
+ .messages = std.json.Array.init(arena_state.allocator()),
+ .sub = true,
+ .label = "fixture",
+ .out = null,
+ };
+ const t0 = nowMs(io);
+ const response = agent_stream.postStreamWithClient(&agent, &client, body);
+ const ms: u64 = @intCast(nowMs(io) - t0);
+ switch (mode) {
+ .paced => {
+ const reply = try response;
+ defer gpa.free(reply);
+ try std.testing.expect(std.mem.indexOf(u8, reply, "data: [DONE]") != null);
+ try std.testing.expectEqual(body_len, got.load(.monotonic));
+ try std.testing.expect(ms > 2 * head_ms); // the old flat head deadline would have fired
+ },
+ .stopped => {
+ if (response) |reply| gpa.free(reply) else |_| {}
+ try std.testing.expectError(error.HungRequest, response);
+ try std.testing.expect(ms >= head_ms);
+ try std.testing.expect(ms < 3000);
+ },
+ }
+}
+
+test "#1785: a paced upload longer than the head budget completes" {
+ try exercise(.paced, paced_len);
+}
+
+test "#1785: a peer that stops reading the body still fails within a bound" {
+ // Larger than any plausible loopback send+receive buffer pair, so the
+ // write genuinely blocks.
+ try exercise(.stopped, 16 * 1024 * 1024);
+}
diff --git a/src/main.zig b/src/main.zig
index 53a9f39b..196d2dbd 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -577,7 +577,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu
_ = @import("agent_ws_steer.zig");
_ = @import("agent_ws_signal.zig");
_ = .{ @import("agent_ws_prewarm.zig"), @import("agent_ws_headers.zig") };
- _ = .{ @import("http2_pool.zig"), @import("agent_stream_h2.zig"), @import("agent_stream_h2_transport_test.zig"), @import("agent_stream_progress_test.zig"), @import("agent_stream_h2_progress_test.zig"), @import("stream_read_progress.zig") }; // transport contracts and partial-event byte progress
+ _ = .{ @import("http2_pool.zig"), @import("agent_stream_h2.zig"), @import("agent_stream_h2_transport_test.zig"), @import("agent_stream_progress_test.zig"), @import("agent_stream_h2_progress_test.zig"), @import("stream_read_progress.zig"), @import("http_send.zig"), @import("http_send_test.zig") }; // transport contracts, partial-event byte progress, staged send budgets
_ = @import("acp_preauth.zig"); // credential-free ACP loop must stay in the test root
_ = .{ @import("acp_protocol.zig"), @import("acp_v2.zig"), @import("acp_v2_prompt.zig"), @import("acp_session_load.zig"), @import("acp_session_fork.zig"), @import("session_fork.zig"), @import("acp_elicit.zig"), @import("hot_context.zig"), @import("history_translate.zig"), @import("mcp_notify.zig"), @import("mcp_wait.zig"), @import("mcp_pages.zig"), @import("mcp_mrtr.zig"), @import("ask_user_args.zig"), @import("mcp_add.zig"), @import("mcp_lazy.zig"), @import("mcp_share.zig"), @import("acp_room.zig"), @import("mcp_catalog.zig"), @import("mcp_watch.zig"), @import("acp_engine_test.zig"), @import("subagent_mimo_tests.zig"), @import("mimo_effort_tests.zig"), @import("gateway_picker_catalog.zig"), @import("ask_user_answers.zig"), @import("job_class.zig"), @import("startup_claim.zig") };
_ = @import("task_outcome.zig"); // goal-outcome telemetry events