Skip to content

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

Python

fix(mcp): share one teardown window, and keep the abandon path out of the gpa

Rach Pradhan807462365cce
diff --git a/src/mcp.zig b/src/mcp.zig
index 72b3d923..79af01fa 100644
--- a/src/mcp.zig
+++ b/src/mcp.zig
@@ -196,7 +196,7 @@ pub const Registry = struct {
.protocol_version = "on-demand",
};
var registry_owns_server = false;
- errdefer if (!registry_owns_server) deinitServer(server, reg.io);
+ errdefer if (!registry_owns_server) deinitServer(server, reg.io, .init(reg.io, mcp_teardown.teardown_grace)); // fresh window: not the exit path (#305)
const added = try smolify_manifest.appendTools(Tool, a, &tools, servers.items.len, full_access);
try servers.append(a, server);
const new_servers = try a.dupe(*Server, servers.items);
@@ -377,7 +377,7 @@ pub const Registry = struct {
}
var registry_owns_server = false;
- errdefer if (!registry_owns_server) deinitServer(server, reg.io);
+ errdefer if (!registry_owns_server) deinitServer(server, reg.io, .init(reg.io, mcp_teardown.teardown_grace)); // fresh window: not the exit path (#305)
const server_index = servers.items.len;
const tools_before = tools.items.len;
errdefer tools.shrinkRetainingCapacity(tools_before);
@@ -415,8 +415,11 @@ pub const Registry = struct {
std.debug.print(" [mcp:{s}] connected (mcp {s}) — {d} tool(s)\n", .{ name, server.protocol_version, tools_v.array.items.len });
}
+ /// One shared window bounds the whole teardown: the loop is sequential, so
+ /// a per-server grace cost N graces for N stalled peers (#305).
pub fn deinit(reg: *Registry) void {
- for (reg.servers) |server| deinitServer(server, reg.io);
+ const budget: mcp_teardown.Budget = .init(reg.io, mcp_teardown.teardown_grace);
+ for (reg.servers) |server| deinitServer(server, reg.io, budget);
reg.arena_state.deinit();
}
@@ -516,15 +519,13 @@ pub const Registry = struct {
}
};
-fn deinitServer(server: *Server, io: Io) void {
+fn deinitServer(server: *Server, io: Io, budget: mcp_teardown.Budget) void {
switch (server.transport) {
.stdio => |*stdio| mcp_stdio.stopChild(io, &stdio.child),
- .http => |*http| {
- // Session exit must never wait on a remote peer: teardown is
- // bounded and abandoned past its deadline (#305).
+ .http => |*http| { // never waits on a peer: bounded by `budget` (#305)
if (http.session_id) |session_id| http.client.allocator.free(session_id);
http.session_id = null;
- mcp_teardown.deinitHttpClient(&http.client, io);
+ mcp_teardown.deinitHttpClient(&http.client, io, budget);
},
}
}
diff --git a/src/mcp_teardown.zig b/src/mcp_teardown.zig
index 59a11895..785b9b7d 100644
--- a/src/mcp_teardown.zig
+++ b/src/mcp_teardown.zig
@@ -9,6 +9,18 @@
//! deadline: a transport that outlives the deadline is *abandoned* — its
//! state is deliberately leaked and the exiting process moves on. Nothing
//! useful is lost; the process is exiting.
+//!
+//! Two consequences of abandoning, both deliberate and both bounded to the
+//! stalled-peer path:
+//! - The detached thread still holds the `Io` it was given, and it can
+//! outlive the caller's teardown of that Io. It is parked in the syscall
+//! that made it miss the deadline, so in practice it never returns to touch
+//! Io state before the process dies - but that is a race, not a proof, and
+//! it is why Registry.deinit belongs as late in the exit path as possible.
+//! Nothing here may be reused for mid-session teardown on a live Io.
+//! - The client's pool memory is never freed, so a leak-checking allocator
+//! reports it at exit. That is the trade #305 asks for: a leak line in a
+//! debug build beats a minute of hanging in a user's terminal.
const std = @import("std");
const Io = std.Io;
@@ -21,6 +33,28 @@ pub const teardown_grace = Io.Duration.fromSeconds(1);
const poll_step = Io.Duration.fromMilliseconds(5);
+/// One window shared by every transport in a teardown, rather than one window
+/// each. Registry.deinit tears servers down sequentially, so a per-transport
+/// grace made N stalled peers cost N graces: exit stayed bounded but grew with
+/// the config. The whole exit path now fits inside a single deadline (#305).
+pub const Budget = struct {
+ started: Io.Timestamp,
+ grace: Io.Duration,
+
+ pub fn init(io: Io, grace: Io.Duration) Budget {
+ return .{ .started = Io.Timestamp.now(io, .awake), .grace = grace };
+ }
+
+ /// What is left of the shared window, never negative. Zero means "do not
+ /// wait at all": best-effort teardown still starts, nothing waits for it.
+ pub fn remaining(self: Budget, io: Io) Io.Duration {
+ const elapsed = Io.Timestamp.now(io, .awake).nanoseconds - self.started.nanoseconds;
+ const left = @as(i128, self.grace.nanoseconds) - @as(i128, elapsed);
+ if (left <= 0) return .fromNanoseconds(0);
+ return .fromNanoseconds(@intCast(left));
+ }
+};
+
/// Run `func(args)` on a detached thread and wait at most `grace` for it.
/// Returns true when the task finished within the window. When it does not,
/// the task is abandoned rather than cancelled: cancelling through Io.Select
@@ -75,18 +109,26 @@ fn clientDeinit(client: *std.http.Client) void {
client.deinit();
}
-/// Tear down an MCP HTTP client under `teardown_grace` (#305). The client is
-/// heap-copied first: if teardown is abandoned, the detached thread may
-/// outlive the arena that owns `client`, so it must only ever touch memory
-/// that is deliberately leaked alongside it.
-pub fn deinitHttpClient(client: *std.http.Client, io: Io) void {
- const heap_client = client.allocator.create(std.http.Client) catch {
+/// Tear down an MCP HTTP client inside what is left of the shared teardown
+/// window (#305). The client is heap-copied first: if teardown is abandoned,
+/// the detached thread may outlive the arena that owns `client`, so it must
+/// only ever touch memory that is deliberately leaked alongside it.
+///
+/// The wrapper state comes from the page allocator, NOT from client.allocator
+/// (the session gpa): on the abandon path it is leaked on purpose, and leaking
+/// it out of the gpa put harness-owned bytes into that allocator's leak report
+/// at exit, where they read as a harness bug. The client's own pool memory is
+/// still gpa-owned and still intentionally leaked when a peer stalls - that is
+/// the trade the issue asks for, and it is the only leak left to explain.
+pub fn deinitHttpClient(client: *std.http.Client, io: Io, budget: Budget) void {
+ const wrapper = std.heap.page_allocator;
+ const heap_client = wrapper.create(std.http.Client) catch {
client.deinit();
return;
};
heap_client.* = client.*;
- if (runBounded(client.allocator, io, teardown_grace, clientDeinit, .{heap_client}))
- client.allocator.destroy(heap_client);
+ if (runBounded(wrapper, io, budget.remaining(io), clientDeinit, .{heap_client}))
+ wrapper.destroy(heap_client);
}
test "runBounded completes a prompt task and reports completion" {
@@ -124,5 +166,28 @@ test "deinitHttpClient tears down a pooled client within the grace window" {
// Mirrors the smolify on-demand transport: an HTTP client that was
// connected (handshake done or not) must not hold session exit.
var registry_client: std.http.Client = .{ .allocator = std.testing.allocator, .io = std.testing.io };
- deinitHttpClient(&registry_client, std.testing.io);
+ deinitHttpClient(&registry_client, std.testing.io, .init(std.testing.io, teardown_grace));
+}
+
+test "one Budget bounds the WHOLE teardown, not each transport (#305)" {
+ const io = std.testing.io;
+ const budget: Budget = .init(io, .fromMilliseconds(60));
+ // Three stalled peers in a row, the shape a multi-server .mcp.json makes.
+ // Per-transport graces would cost 3 x 60ms here; the shared window means
+ // the third transport already finds zero left and waits for nothing.
+ const stall = struct {
+ fn run(inner: Io) void {
+ inner.sleep(.fromSeconds(60), .awake) catch {};
+ }
+ }.run;
+ const start = Io.Timestamp.now(io, .awake);
+ var abandoned: usize = 0;
+ for (0..3) |_| {
+ if (!runBounded(std.heap.page_allocator, io, budget.remaining(io), stall, .{io})) abandoned += 1;
+ }
+ const elapsed = Io.Timestamp.now(io, .awake).nanoseconds - start.nanoseconds;
+ try std.testing.expectEqual(@as(usize, 3), abandoned);
+ try std.testing.expect(elapsed < 3 * 60 * std.time.ns_per_ms); // strictly less than the per-transport sum
+ // And the window really is spent: nothing is left for a fourth.
+ try std.testing.expectEqual(@as(u64, 0), budget.remaining(io).nanoseconds);
}