Skip to content

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

Python

fix(#364): stop dropping a Ctrl-D the tty converted to a NUL EOF marker

justrach7e55a95abff5
diff --git a/scripts/test-pty-parallel-cancel.py b/scripts/test-pty-parallel-cancel.py
index 8017dbef..0122bc48 100755
--- a/scripts/test-pty-parallel-cancel.py
+++ b/scripts/test-pty-parallel-cancel.py
@@ -138,6 +138,11 @@ def main() -> None:
"LMSTUDIO_API_KEY": "local-pty-test",
"GRAFF_FLEET": "off",
"GRAFF_NO_TELEMETRY": "1",
+ # #364: stamp every teardown phase onto the terminal, so the
+ # transcript dumped below names the phase that stalled instead
+ # of ending at the prompt with nothing to go on. No marks at
+ # all means the quit keystroke itself never landed.
+ "GRAFF_SHUTDOWN_DEBUG": "1",
}
with PtySession(GRAFF, ["--model", "lmstudio", "--no-telemetry"], cwd=tmp, env=env, timeout=20) as session:
session.wait_for_literal("] ›")
@@ -153,12 +158,15 @@ def main() -> None:
session.wait_for_literal("interrupted (esc)", start=cursor)
assert_processes_gone(pid_paths)
session.send_key("ctrl-d")
- # #364: every cancel assertion above already PASSED when CI
- # failed here — only the exit was slow. Shutdown drains the
- # session writer, reaps jobs, and joins the fleet worker; on a
- # loaded ubuntu runner 5s was not enough. Give it headroom and,
- # when it still fails, dump the transcript so the next
- # occurrence is diagnosable instead of a bare exit code.
+ # #364: the exit was never SLOW, it was infinite. This ctrl-d
+ # lands in the sliver between the interrupted turn restoring
+ # the terminal and the next prompt claiming it, so Linux's line
+ # discipline handled it as a canonical-mode VEOF and delivered
+ # it as NUL; readLine had no case for that byte and waited at
+ # the prompt forever (input_util.typeAheadByte now maps it
+ # back). The window stays generous and the transcript is still
+ # dumped: with GRAFF_SHUTDOWN_DEBUG on, a future stall names
+ # its phase rather than leaving a bare exit code.
result = session.read_until_exit(30)
if result.timed_out or result.exit_code != 0:
raw = session.raw
diff --git a/src/behavior_trace.zig b/src/behavior_trace.zig
index 773f56f3..6d5889a7 100644
--- a/src/behavior_trace.zig
+++ b/src/behavior_trace.zig
@@ -13,6 +13,7 @@ const types = @import("behavior_trace_types.zig");
const session_start = @import("session_start.zig");
const scoring = @import("scoring.zig");
const trace = @import("trace.zig");
+const shutdown_trace = @import("shutdown_trace.zig"); // #364: teardown phase stamps
test {
_ = @import("behavior_trace_tests.zig");
@@ -531,6 +532,7 @@ pub const Boot = struct {
/// clean return is not a task success verdict; finish() is idempotent and
/// keeps an earlier error-unwind status terminal.
pub fn finishAndClose(self: *Boot, tracer: ?*trace.Tracer, status: BehaviorRunStatus) void {
+ shutdown_trace.mark("behavior-finish + upload"); // #364: this phase can make a network call
self.behavior.finish(status);
if (tracer) |tr| tr.behavior = null;
if (self.open.file) |f| f.close(self.io);
diff --git a/src/input_util.zig b/src/input_util.zig
index 163ee720..18512a0d 100644
--- a/src/input_util.zig
+++ b/src/input_util.zig
@@ -90,6 +90,43 @@ pub fn parseDsrCol(seq: []const u8) ?usize {
return if (col == 0) null else col;
}
+/// Ctrl-D, the byte `readLine` reads as EOF-on-an-empty-line.
+pub const eof_key: u8 = 0x04;
+
+/// Translate one byte of type-ahead — input that was already queued on the tty
+/// when `readLine` switched it into raw mode, so the LINE DISCIPLINE, not the
+/// editor, decided what those bytes look like (#364).
+///
+/// Linux's n_tty does not deliver a canonical-mode VEOF (Ctrl-D) verbatim: it
+/// substitutes `__DISABLED_CHAR` (NUL) into the read buffer and uses it as an
+/// end-of-line marker. Read back in canonical mode that surfaces as a 0-byte
+/// read (EOF); read back in RAW mode — which is what happens when a Ctrl-D
+/// lands in the sliver between a turn restoring the terminal and the next
+/// prompt claiming it — it surfaces as a literal 0x00. readLine had no case
+/// for that byte, so the keystroke was dropped and the REPL sat at the prompt
+/// forever waiting for a quit that had already been typed. macOS/BSD hand the
+/// 0x04 back unchanged, which is why the pty regression only ever hung on
+/// Linux. Mapping the marker back to the key it stands for makes the race
+/// harmless instead of fatal: whichever side of the mode switch the byte lands
+/// on, Ctrl-D means Ctrl-D.
+///
+/// Scoped to type-ahead deliberately. A NUL typed at a live prompt (Ctrl-@ /
+/// Ctrl-Space) is not an EOF request and keeps its current do-nothing
+/// behavior; only bytes the canonical line discipline already processed are
+/// reinterpreted.
+pub fn typeAheadByte(b: u8) u8 {
+ return if (b == 0) eof_key else b;
+}
+
+test "type-ahead NUL is the line discipline's Ctrl-D, everything else is itself" {
+ try std.testing.expectEqual(eof_key, typeAheadByte(0));
+ try std.testing.expectEqual(eof_key, typeAheadByte(eof_key));
+ try std.testing.expectEqual(@as(u8, 'a'), typeAheadByte('a'));
+ try std.testing.expectEqual(@as(u8, '\r'), typeAheadByte('\r'));
+ try std.testing.expectEqual(@as(u8, 0x03), typeAheadByte(0x03)); // Ctrl-C still cancels the line
+ try std.testing.expectEqual(@as(u8, 0x1b), typeAheadByte(0x1b));
+}
+
/// Sumi-rust → Codegraff coral → warm-gold stops for the ultracode ember wave.
const ultracode_rgb = [_]struct { r: u8, g: u8, b: u8 }{
.{ .r = 168, .g = 99, .b = 67 },
diff --git a/src/main.zig b/src/main.zig
index 01b28b0c..5c22abce 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -236,11 +236,11 @@ const cli = @import("cli.zig");
const args = @import("args.zig");
// Post-arg-parse setup (resolveKeys, buildSystemPrompt, early subcommand dispatch) lives in startup.zig; everything after credentials/http.Client exist lives in sibling session_start.zig.
const startup = @import("startup.zig");
-const startup_timing = @import("startup_timing.zig");
+const startup_timing = @import("startup_timing.zig"); // .shutdown_trace re-exports #364's teardown-phase stamps (this file is at the 600-line cap and cannot spare an import line)
const session_start = @import("session_start.zig");
const session_run = @import("session_run.zig");
pub fn main(init: std.process.Init) !void {
- var boot = startup_timing.Tracker.init(init.io, init.environ_map.get("GRAFF_BOOT_DEBUG") != null);
+ var boot = startup_timing.Tracker.init(startup_timing.shutdown_trace.arm(init.io, init.environ_map), init.environ_map.get("GRAFF_BOOT_DEBUG") != null); // #364: arm() passes io through, so the teardown below stamps phases without a line of its own
const gpa = init.gpa;
const io = init.io;
const arena = init.arena.allocator();
@@ -253,7 +253,7 @@ pub fn main(init: std.process.Init) !void {
// reset each request() so a long REPL/--json/serve session's RSS stays flat.
var scratch_state = std.heap.ArenaAllocator.init(gpa);
defer scratch_state.deinit();
- defer hooks.deinitCodedbCache(gpa, io);
+ defer hooks.deinitCodedbCache(gpa, startup_timing.shutdown_trace.at(io, "codedb-cache + arena (last)"));
g_session_arena = init.arena;
g_mem_debug = init.environ_map.get("GRAFF_MEM_DEBUG") != null;
g_no_browser = init.environ_map.get("GRAFF_NO_BROWSER") != null;
@@ -295,7 +295,7 @@ pub fn main(init: std.process.Init) !void {
var client_warm_fut = io.async(prewarmCaBundleTask, .{ &client, gpa, io, &client_ready });
boot.mark(io, "CA warm scheduled");
defer {
- _ = client_warm_fut.await(io);
+ _ = client_warm_fut.await(startup_timing.shutdown_trace.at(io, "ca-warm-await"));
http.g_client_ready = null;
}
var stdin_buf: [64 * 1024]u8 = undefined;
@@ -458,14 +458,14 @@ pub fn main(init: std.process.Init) !void {
// earlier fallbacks remain for failures that occur before these defers
// are registered.
defer if (!jobs_reaped) {
- jobsReap(gpa, io);
+ jobsReap(gpa, startup_timing.shutdown_trace.at(io, "jobs-reap"));
jobs_reaped = true;
};
defer if (!agent_jobs_reaped) {
- agentJobsReap(gpa, io);
+ agentJobsReap(gpa, startup_timing.shutdown_trace.at(io, "agent-jobs-reap"));
agent_jobs_reaped = true;
};
- defer joinElites(io); // reap if the session quits before any turn joins it
+ defer joinElites(startup_timing.shutdown_trace.at(io, "join-elites")); // reap if the session quits before any turn joins it
session_run.saveOrResumeSession(&root, &keys, arena, flags);
// Load restored configuration before run_started, but defer any model-backed
@@ -481,7 +481,7 @@ pub fn main(init: std.process.Init) !void {
session_run.compactResumedSession(&root);
// Closing the learning loop: this session counts toward the next trial.
- defer session_run.startBackgroundLearning(gpa, arena, io, init.environ_map, &invocation_budget, !flags.no_telemetry_flag);
+ defer session_run.startBackgroundLearning(gpa, arena, startup_timing.shutdown_trace.at(io, "background-learning"), init.environ_map, &invocation_budget, !flags.no_telemetry_flag);
// `graff repl`: interactive chat REPL on the zigzag TUI, backed by the REAL agent loop — each prompt runs a full root turn (tools + MCP) via
// replTurnCb. `graff acp` (acp.zig) is the same idea over Zed's stdio Agent Client Protocol. Both self-contained — each exits after.
@@ -526,7 +526,7 @@ pub fn main(init: std.process.Init) !void {
.sys_normal = sys_normal,
};
try mainloop.run(&loop_ctx);
- try session_run.finalizeSession(gpa, io, arena, out, &root, json_mode);
+ try session_run.finalizeSession(gpa, startup_timing.shutdown_trace.at(io, "final-save"), arena, out, &root, json_mode);
}
// The `graff mcp` CLI (list/add servers in .mcp.json) + the trusted-companion check live in mcp_cli.zig.
const mcp_cli = @import("mcp_cli.zig");
diff --git a/src/mainloop.zig b/src/mainloop.zig
index 6b0b9143..2a0844b1 100644
--- a/src/mainloop.zig
+++ b/src/mainloop.zig
@@ -60,7 +60,7 @@ pub const Ctx = struct {
pub fn run(ctx: *Ctx) !void {
var title_jobs: mainloop_title.Jobs = .{};
defer title_jobs.deinit(ctx);
- defer session.flushSaves(); // #273: the turn-path autosaves write in the background — no queued one may outlive this loop, on ANY exit
+ defer session.flushSavesAtExit(); // #273: the turn-path autosaves write in the background — no queued one may outlive this loop, on ANY exit (#364 stamps this teardown phase)
// Trajectory spine state: each turn's parent is the previous turn, and a
// changed prompt fingerprint marks a set_system_prompt mutation edge.
var prev_turn_id: u64 = 0;
diff --git a/src/mcp.zig b/src/mcp.zig
index 5c790b2b..06c4b4db 100644
--- a/src/mcp.zig
+++ b/src/mcp.zig
@@ -21,6 +21,7 @@ const mcp_http = @import("mcp_http.zig");
const mcp_protocol = @import("mcp_protocol.zig");
const mcp_stdio = @import("mcp_stdio.zig");
const mcp_teardown = @import("mcp_teardown.zig");
+const shutdown_trace = @import("shutdown_trace.zig"); // #364: teardown phase stamps
const mcp_rpc = @import("mcp_rpc.zig");
const smolify_manifest = @import("smolify_manifest.zig");
const vision = @import("vision.zig"); // #249: MCP image results become staged vision blocks
@@ -480,6 +481,7 @@ pub const Registry = struct {
/// a later defer tear that Io down underneath it (#325). Kept separate from
/// `deinit` because tests and mid-session callers must never exit.
pub fn deinitAtExit(reg: *Registry) void {
+ shutdown_trace.mark("mcp-teardown"); // #364
reg.deinit();
mcp_teardown.exitIfAbandoned();
}
diff --git a/src/readline.zig b/src/readline.zig
index e2ddfe6f..4d45c7ad 100644
--- a/src/readline.zig
+++ b/src/readline.zig
@@ -34,6 +34,7 @@ const input_util = @import("input_util.zig");
const fillCompletions = input_util.fillCompletions;
const LineRender = input_util.LineRender;
const parseDsrCol = input_util.parseDsrCol;
+const typeAheadByte = input_util.typeAheadByte;
const cleanDroppedPath = input_util.cleanDroppedPath;
const collectRepoFiles = input_util.collectRepoFiles;
const isImagePath = input_util.isImagePath;
@@ -50,6 +51,7 @@ const agent_mod = @import("agent.zig");
const session = @import("session.zig");
const Agent = agent_mod.Agent;
const saveSession = session.saveSession;
+const shutdown_trace = @import("shutdown_trace.zig"); // #364: the quit path's first phase stamp
const rl_history = @import("readline_history.zig");
const HistoryNav = rl_history.HistoryNav;
@@ -85,6 +87,9 @@ pub fn readLine(
// shifts the whole block together and never strands the prompt. Typed-
// ahead text bytes that race the reply are replayed into the edit loop
// below; a typed-ahead escape sequence inside that ~ms window is dropped.
+ // Those replayed bytes went through the tty's CANONICAL line discipline
+ // (they were queued before enterRaw above), so each is normalized by
+ // input_util.typeAheadByte first — see #364.
var prompt_col: usize = 1; // 1-based column where the buffer renders
var rstate: LineRender = .{}; // rows used + cursor row of the last redraw
var pending: std.ArrayList(u8) = .empty;
@@ -108,7 +113,7 @@ pub fn readLine(
n = 0;
continue;
}
- pending.append(gpa, b) catch {};
+ pending.append(gpa, typeAheadByte(b)) catch {}; // #364: a canonical-mode Ctrl-D reaches us as NUL on Linux
if (pending.items.len > 64) break :dsr;
continue;
}
@@ -316,6 +321,7 @@ pub fn readLine(
},
0x04 => { // Ctrl-D: EOF on empty line, else forward-delete
if (buf.items.len == 0) {
+ shutdown_trace.mark("readline-eof (ctrl-d)"); // #364: proves the quit key was SEEN, not just sent
out.writeAll("\n") catch {};
return null;
}
diff --git a/src/session.zig b/src/session.zig
index be9a75b2..6605d8a0 100644
--- a/src/session.zig
+++ b/src/session.zig
@@ -24,6 +24,7 @@ const provider_mod = @import("provider.zig");
const util = @import("util.zig");
const goal_state = @import("goal_state.zig");
const session_writer = @import("session_writer.zig"); // #273: the fingerprint + the background write
+const shutdown_trace = @import("shutdown_trace.zig"); // #364: teardown phase stamps
const protocol_seq = @import("protocol_seq.zig"); // #330: the --json event sequence survives a resume
const Agent = agent_mod.Agent;
const Keys = provider_mod.Keys;
@@ -206,6 +207,16 @@ pub fn flushSaves() void {
session_writer.drain();
}
+/// The same drain, named for the one caller that is a TEARDOWN step: the defer
+/// mainloop.run registers, and therefore the first thing the quit path does.
+/// Separate from `flushSaves` only so the #364 phase stamp marks that drain and
+/// not the dozen mid-session ones `saveSession` performs (a teardown log that
+/// also fires during the conversation cannot answer "did the loop exit?").
+pub fn flushSavesAtExit() void {
+ shutdown_trace.mark("loop-exit: draining queued autosaves");
+ flushSaves();
+}
+
/// The save itself, against an explicit base directory. Production always
/// passes the cwd (through saveSessionAsync/saveSession); the parameter exists
/// so the tests can exercise the real path against a tmp dir.
diff --git a/src/shutdown_trace.zig b/src/shutdown_trace.zig
new file mode 100644
index 00000000..68d17437
--- /dev/null
+++ b/src/shutdown_trace.zig
@@ -0,0 +1,112 @@
+//! Per-phase shutdown timings (#364).
+//!
+//! A REPL that does not exit used to be a silent 30s and a bare `exit=-15` in
+//! CI: the transcript ended at the prompt, and nothing distinguished "the quit
+//! key never arrived" from "teardown stalled" — let alone WHICH teardown step
+//! stalled. Every phase of the quit path now stamps a line, so the next hang
+//! names itself.
+//!
+//! Off unless `GRAFF_SHUTDOWN_DEBUG` is set (mirrors `GRAFF_BOOT_DEBUG` /
+//! startup_timing.zig). Output goes to stderr rather than the trace file so it
+//! survives a hang — nothing is buffered, nothing needs a clean close — and so
+//! a pty harness capturing the terminal sees it in the transcript it dumps.
+//! scripts/test-pty-parallel-cancel.py turns it on for exactly that reason.
+//!
+//! READING THE OUTPUT. A mark is written when a phase BEGINS and carries how
+//! long the PREVIOUS phase took. On a hang the last line printed names the
+//! phase that is stuck, and the lines before it are a clean teardown profile.
+//! NO lines at all means the loop never reached its exit — the quit keystroke
+//! itself was lost, which is what #364 turned out to be.
+//!
+//! WHY `arm`/`at` RETURN `Io`. main.zig, mainloop.zig and session_run.zig are
+//! all at the 600-line ceiling, so the teardown they own cannot afford a
+//! statement per phase. Both helpers pass their `io` straight through, so a
+//! call site instruments itself inside an expression it already has:
+//!
+//! defer joinElites(shutdown_trace.at(io, "join-elites"));
+//!
+//! State is process-global on purpose: teardown runs across a dozen modules
+//! and there is no shutdown object to thread through them. `arm` also stores
+//! the Io, so the phases that are marked from inside a callee (session.zig,
+//! jobs.zig, …) need no new parameter to reach the clock.
+
+const std = @import("std");
+const Io = std.Io;
+
+/// Set (to anything) to print the phase lines.
+pub const env_var = "GRAFF_SHUTDOWN_DEBUG";
+
+var enabled = false;
+var clock: ?Io = null;
+var started: Io.Timestamp = undefined;
+var last_ms: i64 = 0;
+
+/// Read the opt-in, keep the Io, and start the clock. Returns `io` so main()
+/// can arm this inside a call it already makes (see the header). Re-arming
+/// restarts the clock, which is what a re-entered process wants.
+pub fn arm(io: Io, environ_map: *const std.process.Environ.Map) Io {
+ enabled = environ_map.get(env_var) != null;
+ clock = io;
+ started = Io.Timestamp.now(io, .awake);
+ last_ms = 0;
+ return io;
+}
+
+/// Stamp the beginning of one teardown phase. A no-op when unarmed (unit
+/// tests, `graff repl`, any path that never called `arm`) or when the opt-in
+/// is off, so a normal exit pays one bool load per phase.
+pub fn mark(phase: []const u8) void {
+ if (!enabled) return;
+ const io = clock orelse return;
+ const cumulative: i64 = @intCast(@max(0, started.untilNow(io, .awake).toMilliseconds()));
+ var buf: [160]u8 = undefined;
+ std.debug.print("{s}", .{render(&buf, phase, cumulative, @max(0, cumulative - last_ms))});
+ last_ms = cumulative;
+}
+
+/// `mark`, passing `io` through — the form call sites at the line ceiling use.
+pub fn at(io: Io, phase: []const u8) Io {
+ mark(phase);
+ return io;
+}
+
+/// The rendered line. Split out so its shape is testable without a terminal:
+/// the numbers are the whole point of the feature, and a silently truncated
+/// line would report nothing at all.
+pub fn render(buf: []u8, phase: []const u8, cumulative_ms: i64, phase_ms: i64) []const u8 {
+ return std.fmt.bufPrint(buf, "[shutdown +{d}ms, prev {d}ms] {s}\n", .{ cumulative_ms, phase_ms, phase }) catch phase;
+}
+
+/// Test seam: the tests below must neither depend on whether this process was
+/// armed nor leave the flag on for a later test.
+pub fn setEnabledForTest(on: bool) void {
+ enabled = on;
+}
+
+test "render names the phase and both durations" {
+ var buf: [160]u8 = undefined;
+ try std.testing.expectEqualStrings(
+ "[shutdown +1234ms, prev 56ms] jobs-reap\n",
+ render(&buf, "jobs-reap", 1234, 56),
+ );
+}
+
+test "render degrades to the bare phase name rather than dropping it" {
+ var tiny: [4]u8 = undefined;
+ try std.testing.expectEqualStrings("join-elites", render(&tiny, "join-elites", 1, 1));
+}
+
+test "an unarmed process prints nothing and `at` stays a pass-through" {
+ setEnabledForTest(false);
+ mark("never-printed");
+ // `at` is what call sites embed in an existing expression, so it must hand
+ // back exactly the io it was given whether or not tracing is on.
+ _ = at(std.testing.io, "also-never-printed");
+ try std.testing.expect(!enabled);
+ // Armed but with no clock (no `arm` in this process) must also stay silent
+ // rather than read the undefined timestamp.
+ setEnabledForTest(true);
+ clock = null;
+ mark("no-clock-no-output");
+ setEnabledForTest(false);
+}
diff --git a/src/startup_timing.zig b/src/startup_timing.zig
index 217d4792..e1f068c7 100644
--- a/src/startup_timing.zig
+++ b/src/startup_timing.zig
@@ -6,6 +6,13 @@ const std = @import("std");
const Io = std.Io;
const trace = @import("trace.zig");
+/// #364's teardown-side mirror of this module: `GRAFF_SHUTDOWN_DEBUG` phase
+/// stamps for the quit path. Re-exported here — rather than imported directly
+/// — because its only arming call site is main.zig, which sits exactly at the
+/// 600-line ceiling and has no room for an import of its own. `arm`/`at`
+/// return their `Io` for the same reason; see shutdown_trace.zig's header.
+pub const shutdown_trace = @import("shutdown_trace.zig");
+
pub const Tracker = struct {
const max_phases = 16;
const Phase = struct { label: []const u8, cumulative_ms: i64, phase_ms: i64 };
diff --git a/src/telemetry.zig b/src/telemetry.zig
index 195b1dd8..b0c444aa 100644
--- a/src/telemetry.zig
+++ b/src/telemetry.zig
@@ -21,6 +21,7 @@ const util = @import("util.zig");
const utf8Prefix = util.utf8Prefix;
const unixMs = util.unixMs;
const http = @import("http.zig");
+const shutdown_trace = @import("shutdown_trace.zig"); // #364: teardown phase stamps
// For the session run id (score/run join key) and the propose-site
// fingerprint check. No cycle: scoring imports only std + pricing.
@@ -340,6 +341,7 @@ pub const Telemetry = struct {
/// Final flush at session end: the session summary plus any events not
/// already shipped by a mid-session batch.
pub fn flush(self: *Telemetry) void {
+ shutdown_trace.mark("telemetry-flush"); // #364: fires mid-session too, but the LAST one is the exit flush
self.sendBatch(self.events.items, true);
}
diff --git a/src/test_hooks.zig b/src/test_hooks.zig
index 75e491f0..3b3ac4a7 100644
--- a/src/test_hooks.zig
+++ b/src/test_hooks.zig
@@ -84,6 +84,11 @@ const agent_eval_control_tests = @import("agent_eval_control_tests.zig");
// that staying true.
const mcp_config = @import("mcp_config.zig");
+// #364: shutdown-phase timings. Production reaches it from readline.zig,
+// session.zig, mcp.zig, telemetry.zig and startup_timing.zig, so its coverage
+// is contingent on those call sites staying — pinned here instead.
+const shutdown_trace = @import("shutdown_trace.zig");
+
test {
_ = learn_holdout;
_ = learn_receipt;
@@ -117,4 +122,5 @@ test {
_ = mcp_config;
_ = acp;
_ = agent_eval_control_tests;
+ _ = shutdown_trace;
}