graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(subagent): stream subagent requests on the stall-watched path (#682)
justrachd4cb048e725e
diff --git a/architecture.md b/architecture.mdindex 413c4950..ab419629 100644--- a/architecture.md+++ b/architecture.md@@ -120,10 +120,11 @@ as codex).### Streaming-Root-agent requests stream on **all three** wire formats. `request()` decides-per call: `live = !sub` (`Agent.usesLiveTransport`). `-p` and compaction set+Agent requests stream on **all three** wire formats, root and subagent alike+(`Agent.usesLiveTransport`, #682). `-p`, compaction and subagents set`out=null` / `stream_quiet` to mute paint, not to leave the stall-watched-path; subagents always take the buffered `postWatched()` path. When live,+path; the buffered `postWatched()` path serves only the remaining+non-turn callers (compaction summary, rlm queries). When live,`buildBody` adds `stream:true` (openai also gets`stream_options:{include_usage:true}` so token counts survive — dropped andretried once if a provider rejects it, same pattern as the soft-strictdiff --git a/src/agent.zig b/src/agent.zigindex 0c7e8489..47a5bdb1 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -269,9 +269,9 @@ pub const Agent = struct {return true;}- /// Root streams even on `-p`; `out`/`stream_quiet` only mute paint.- pub fn usesLiveTransport(self: *const Agent) bool {- return !self.sub;+ /// Every agent streams — root even on `-p`, subagents too (#682): the stall-watched path, never the 5-minute POST. `out`/`stream_quiet` only mute paint.+ pub fn usesLiveTransport(_: *const Agent) bool {+ return true;}pub fn toolsJson(self: *const Agent) []const u8 {diff --git a/src/agent_stream_stall_test.zig b/src/agent_stream_stall_test.zigindex 511832fb..5aa44ced 100644--- a/src/agent_stream_stall_test.zig+++ b/src/agent_stream_stall_test.zig@@ -23,11 +23,31 @@ const nowMs = @import("agent_ws_mock.zig").nowMs;/// between-lines budget. After it, the socket stays open and silent.const prose_line = "data: {\"choices\":[{\"delta\":{\"content\":\"hi\"}}]}\n\n";+/// The provider's terminal event: with it the response is complete and the+/// reader returns; without it the socket is a stream that went quiet.+const done_line = "data: [DONE]\n\n";+const Srv = struct {- /// Answer `conns` requests in turn: drain the request head, send the SSE- /// head plus one prose delta, then hold the socket open without another- /// byte until the test is over. Every accepted socket is kept, so a- /// client that gave up sees silence (a stall), never EOF (a drop).+ /// Drain the request head, send the SSE head plus one prose delta (plus+ /// the terminal event when `finish`). The socket then stays open with no+ /// further byte, so a client that gives up sees silence (a stall), never+ /// EOF (a drop).+ fn answer(io: Io, c: std.Io.net.Stream, finish: bool) void {+ var rbuf: [8192]u8 = undefined;+ var sr = std.Io.net.Stream.Reader.init(c, io, &rbuf);+ while (true) {+ const l = (sr.interface.takeDelimiter('\n') catch return) orelse return;+ if (l.len == 0 or (l.len == 1 and l[0] == '\r')) break; // end of headers+ }+ var wbuf: [1024]u8 = undefined;+ var sw = std.Io.net.Stream.Writer.init(c, io, &wbuf);+ sw.interface.writeAll("HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n" ++ prose_line) catch return;+ if (finish) sw.interface.writeAll(done_line) catch return;+ sw.interface.flush() catch return;+ }++ /// `conns` streams that go quiet, in turn (the #680 ladder). Every+ /// accepted socket is kept until the test is over.fn run(io: Io, server: *std.Io.net.Server, conns: usize, done: *std.atomic.Value(bool)) void {var held: [3]?std.Io.net.Stream = @splat(null);defer for (held) |h| if (h) |c| c.close(io);@@ -35,21 +55,91 @@ const Srv = struct {while (i < conns) : (i += 1) {const c = server.accept(io) catch return;held[i] = c;- var rbuf: [8192]u8 = undefined;- var sr = std.Io.net.Stream.Reader.init(c, io, &rbuf);- while (true) {- const l = (sr.interface.takeDelimiter('\n') catch return) orelse return;- if (l.len == 0 or (l.len == 1 and l[0] == '\r')) break; // end of headers- }- var wbuf: [1024]u8 = undefined;- var sw = std.Io.net.Stream.Writer.init(c, io, &wbuf);- sw.interface.writeAll("HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n" ++ prose_line) catch return;- sw.interface.flush() catch return;+ answer(io, c, false);+ }+ while (!done.load(.acquire)) io.sleep(.fromMilliseconds(20), .awake) catch return;+ }++ /// One complete stream, then one that goes quiet (#682).+ fn runTwo(io: Io, server: *std.Io.net.Server, done: *std.atomic.Value(bool)) void {+ var held: [2]?std.Io.net.Stream = @splat(null);+ defer for (held) |h| if (h) |c| c.close(io);+ for (0..2) |i| {+ const c = server.accept(io) catch return;+ held[i] = c;+ answer(io, c, i == 0);}while (!done.load(.acquire)) io.sleep(.fromMilliseconds(20), .awake) catch return;}};+fn testProvider(url: []const u8) @import("provider.zig").Provider {+ return .{ .id = "test", .kind = .openai, .auth = .bearer, .url = url, .api_key = "k", .model = "m", .context = 0 };+}++// #682: a subagent (`sub`, no paint) used to take the buffered 5-minute POST,+// so a provider that goes quiet — or an edge that times a long non-streaming+// generation out — cost it 250s+ per attempt. It now streams like the root:+// a complete stream returns, and a silent one trips the stream watchdog at+// the pre-prose budget (nothing grows partial_text with no frontend), not+// post_deadline_ms.+test "#682: a subagent-shaped agent streams — completes on the terminal event, stalls on the stream budget" {+ if (builtin.os.tag == .windows) return error.SkipZigTest;+ const gpa = std.testing.allocator;+ const io = std.testing.io;++ var addr = try std.Io.net.IpAddress.parseLiteral("127.0.0.1:0");+ var server = try std.Io.net.IpAddress.listen(&addr, io, .{});+ defer server.deinit(io);+ var done: std.atomic.Value(bool) = .init(false);+ // Connection 1 finishes its stream; connection 2 goes quiet after the prose.+ var fut = io.async(Srv.runTwo, .{ io, &server, &done });+ defer fut.await(io);+ defer done.store(true, .release);++ const saved_stream = http.stream_stall_ms;+ const saved_post = http.post_deadline_ms;+ http.stream_stall_ms = 1200; // protocol-seen budget: what a no-paint stream arms after its first line+ http.post_deadline_ms = 60 * 1000; // the buffered path's ceiling — must NOT be what bounds this+ defer http.stream_stall_ms = saved_stream;+ defer http.post_deadline_ms = saved_post;++ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var client: std.http.Client = .{ .allocator = gpa, .io = io };+ defer client.deinit();+ var url_buf: [64]u8 = undefined;+ const url = try std.fmt.bufPrint(&url_buf, "http://127.0.0.1:{d}/v1/chat/completions", .{server.socket.address.getPort()});+ var child: Agent = .{+ .gpa = gpa,+ .arena = arena,+ .io = io,+ .client = &client,+ .provider = testProvider(url),+ .messages = std.json.Array.init(arena),+ .sub = true,+ .label = "child",+ .out = null,+ };+ try std.testing.expect(child.usesLiveTransport());++ const t0 = nowMs(io);+ const first = agent_stream.postStreamWithClient(&child, &client, "{}");+ const t1 = nowMs(io);+ const second = agent_stream.postStreamWithClient(&child, &client, "{}");+ const t2 = nowMs(io);++ const body = try first;+ defer gpa.free(body);+ try std.testing.expect(std.mem.indexOf(u8, body, "\"content\":\"hi\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, body, "[DONE]") != null);+ try std.testing.expect(t1 - t0 < 1000); // returned on the terminal event, no wait+ try std.testing.expectError(error.StreamStalled, second);+ try std.testing.expect(t2 - t1 >= 1150 and t2 - t1 < 2400); // the stream budget, not the 60s POST deadline+ try std.testing.expectEqual(@as(u64, 1200), child.stall.tripped_ms);+}+test "#680: each stall reconnect widens the between-lines wait the SSE reader arms" {if (builtin.os.tag == .windows) return error.SkipZigTest;const gpa = std.testing.allocator;diff --git a/src/agent_tests.zig b/src/agent_tests.zigindex 2c4c93a9..4f961763 100644--- a/src/agent_tests.zig+++ b/src/agent_tests.zig@@ -85,6 +85,9 @@ pub fn lazyRootTools(comptime Agent: type) !void {/// `-p` sets `out=null` and `stream_quiet` so stdout stays the answer, but/// the root still takes postLive (head/stream stall) instead of the 5-minute/// watched POST that burned json-stream / cookie-store to a 300s SIGKILL.+/// #682: a subagent is the same shape (no paint, same silent POST) and takes+/// the same path — two of its calls once sat 4-8 minutes in postWatched+/// waiting for a 5xx the stream watchdog would have caught inside a minute.pub fn oneshotUsesLiveTransport(comptime Agent: type) !void {var root: Agent = undefined;root.sub = false;@@ -96,5 +99,5 @@ pub fn oneshotUsesLiveTransport(comptime Agent: type) !void {child.sub = true;child.out = null;child.stream_quiet = true;- try std.testing.expect(!child.usesLiveTransport());+ try std.testing.expect(child.usesLiveTransport());}diff --git a/src/http.zig b/src/http.zigindex 42ddc650..a6438ef0 100644--- a/src/http.zig+++ b/src/http.zig@@ -191,10 +191,10 @@ fn post(gpa: Allocator, client: *std.http.Client, provider: Provider, body: []co/// Hard ceiling on one non-streaming request. The legitimate worst case/// observed (a 160k-token subagent context) completed in ~134s; anything/// past this is a hung response, not a slow one. Tunable via-/// GRAFF_POST_DEADLINE_SECS (#544): non-streaming callers (subagents)+/// GRAFF_POST_DEADLINE_SECS (#544): the remaining non-streaming callers/// have no inter-chunk stall signal, so this deadline is their only hang-/// detector — a harness with a tighter task timeout lowers it. Root `-p`-/// streams (ADR 0046); this ceiling is not that path's hang detector.+/// detector — a harness with a tighter task timeout lowers it. Agent turns+/// stream, root `-p` (ADR 0046) and subagents (#682) included: not this path.pub var post_deadline_ms: u64 = 5 * 60 * 1000;pub const WatchdogFired = enum { esc, deadline };