From 8cccce138323e119484269b66f4c6cfa1e6f8934 Mon Sep 17 00:00:00 2001 From: Daniel Samson Date: Sat, 17 Oct 2026 13:22:26 +0100 Subject: [PATCH] feat: job runner with heartbeat, timeout, kill and retry (M3 part 2) Co-Authored-By: Claude Sonnet 5.5 --- src/root.zig | 1 + src/runner.zig | 358 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 359 insertions(+) create mode 100644 src/runner.zig diff --git a/src/root.zig b/src/root.zig index 427bbf6..5d5d8e2 100644 --- a/src/root.zig +++ b/src/root.zig @@ -16,6 +16,7 @@ pub const config = @import("config.zig"); pub const loadclass = @import("loadclass.zig"); pub const retry = @import("retry.zig"); pub const proc = @import("proc.zig"); +pub const runner = @import("runner.zig"); test { @import("std").testing.refAllDecls(@This()); diff --git a/src/runner.zig b/src/runner.zig new file mode 100644 index 0000000..c74c5ba --- /dev/null +++ b/src/runner.zig @@ -0,0 +1,358 @@ +//! Runs one job to completion: spawn, heartbeat, timeout and kill handling, final state, retry. +//! Port of barn's `JobRunner`, with the documented behaviour (see AGENTS.md): retries are +//! actually scheduled on failure, timeouts are enforced, and a job that was already moved to +//! a terminal state by someone else is left alone instead of raising an invalid transition. +const std = @import("std"); +const Io = std.Io; +const Allocator = std.mem.Allocator; +const Repository = @import("repository.zig").Repository; +const proc = @import("proc.zig"); +const retry = @import("retry.zig"); +const timestamp = @import("timestamp.zig"); +const State = @import("state.zig").State; + +/// Shared between the runner, its monitor thread and whoever may kill the job. +pub const Control = struct { + kill_requested: std.atomic.Value(bool) = .init(false), + /// Skip SIGTERM and go straight to SIGKILL. + force: std.atomic.Value(bool) = .init(false), + pid: std.atomic.Value(i64) = .init(0), + + pub fn requestKill(self: *Control, force: bool) void { + if (force) self.force.store(true, .release); + self.kill_requested.store(true, .release); + } +}; + +pub const Options = struct { + heartbeat_interval_ms: u64 = 5_000, + /// 0 disables the timeout. + timeout_seconds: u64 = 0, + retry_codes: []const i32 = &.{}, + /// How often the monitor wakes to check for kill/timeout/heartbeat. + tick_ms: u64 = 100, + /// Time between SIGTERM and SIGKILL. + kill_grace_ms: u64 = 5_000, + /// Jitter source for retry delays; null disables jitter. + random: ?std.Random = null, +}; + +pub const Outcome = enum { + succeeded, + failed, + /// Failed and re-queued for another attempt. + retried, + canceled, + timed_out, + start_failed, + /// The job vanished, was not queued, or persistence failed. + aborted, +}; + +const Monitor = struct { + io: Io, + repo: Repository, + id: []const u8, + ctl: *Control, + opts: Options, + pid: proc.Pid, + done: std.atomic.Value(bool) = .init(false), + timed_out: std.atomic.Value(bool) = .init(false), + + fn monoNow(self: *Monitor) i128 { + return Io.Timestamp.now(self.io, .awake).nanoseconds; + } + + fn loop(self: *Monitor) void { + const ms = std.time.ns_per_ms; + const started = self.monoNow(); + var last_heartbeat = started; + var term_sent_at: ?i128 = null; + var kill_sent = false; + + while (!self.done.load(.acquire)) { + self.io.sleep(.fromMilliseconds(@intCast(self.opts.tick_ms)), .real) catch return; + const now = self.monoNow(); + + if (now - last_heartbeat >= @as(i128, self.opts.heartbeat_interval_ms) * ms) { + self.repo.updateHeartbeat(self.id, timestamp.now(self.io)) catch {}; + last_heartbeat = now; + } + + const killed = self.ctl.kill_requested.load(.acquire); + const timed_out = self.opts.timeout_seconds > 0 and + now - started >= @as(i128, self.opts.timeout_seconds) * std.time.ns_per_s; + if (timed_out and !killed) self.timed_out.store(true, .release); + + if ((killed or timed_out) and term_sent_at == null) { + if (self.ctl.force.load(.acquire)) { + proc.signalTree(self.pid, .kill); + kill_sent = true; + } else { + proc.signalTree(self.pid, .term); + } + term_sent_at = now; + } else if (term_sent_at) |t| { + if (!kill_sent and now - t >= @as(i128, self.opts.kill_grace_ms) * ms) { + proc.signalTree(self.pid, .kill); + kill_sent = true; + } + } + } + } +}; + +/// Executes the (queued) job `id` and blocks until it finishes. Never returns an error: +/// persistence problems are logged and reported as `.aborted`. +pub fn run(gpa: Allocator, io: Io, repo: Repository, id: []const u8, ctl: *Control, opts: Options) Outcome { + return runInner(gpa, io, repo, id, ctl, opts) catch |err| { + std.log.err("job {s}: runner failed: {s}", .{ id, @errorName(err) }); + return .aborted; + }; +} + +fn runInner(gpa: Allocator, io: Io, repo: Repository, id: []const u8, ctl: *Control, opts: Options) !Outcome { + var arena_state = std.heap.ArenaAllocator.init(gpa); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + + const manifest = try repo.loadManifest(arena, id); + var job_dir = try repo.dirs.openJob(io, id); + defer job_dir.close(io); + + // A kill that arrived before the process even started. + if (ctl.kill_requested.load(.acquire)) { + repo.markCanceled(id) catch {}; + return .canceled; + } + + var child = proc.spawnJob(io, job_dir, manifest.command) catch |err| { + const msg = try std.fmt.allocPrint(arena, "Failed to start process: {s}", .{@errorName(err)}); + proc.appendLog(io, job_dir, "logs/stderr.log", msg) catch {}; + // queued -> failed is a valid transition; no pid was ever assigned. + repo.markFailed(id, "start_failed", msg) catch {}; + return .start_failed; + }; + const pid = child.id.?; + ctl.pid.store(pid, .release); + repo.markStarted(id, pid) catch |err| { + proc.signalTree(pid, .kill); + _ = child.wait(io) catch {}; + return err; + }; + + var monitor: Monitor = .{ .io = io, .repo = repo, .id = id, .ctl = ctl, .opts = opts, .pid = pid }; + const thread = std.Thread.spawn(.{}, Monitor.loop, .{&monitor}) catch null; + const term = child.wait(io); + monitor.done.store(true, .release); + if (thread) |t| t.join(); + ctl.pid.store(0, .release); + + const code = proc.exitCodeOf(term catch .{ .unknown = 255 }); + + if (ctl.kill_requested.load(.acquire)) { + repo.markCanceled(id) catch {}; + return .canceled; + } + if (monitor.timed_out.load(.acquire)) { + const msg = try std.fmt.allocPrint(arena, "Job exceeded timeout of {d} seconds", .{opts.timeout_seconds}); + repo.markFailed(id, "timeout", msg) catch {}; + return .timed_out; + } + + const err_msg: ?[]const u8 = if (code == 0) null else try std.fmt.allocPrint(arena, "Process exited with code {d}", .{code}); + repo.markCompleted(id, code, err_msg) catch |e| switch (e) { + error.InvalidTransition => return .aborted, // someone else already finalised it + else => return e, + }; + if (code == 0) return .succeeded; + + const current = (try repo.findById(arena, id)) orelse return .aborted; + if (retry.shouldRetry(current.retry_count, manifest.max_retries, code, opts.retry_codes)) { + const delay = retry.delaySeconds(current.retry_count, manifest.retry_delay_seconds, manifest.retry_backoff_multiplier, opts.random); + const retry_at = timestamp.now(io) + @as(i128, delay) * std.time.ns_per_s; + try repo.scheduleRetry(gpa, id, retry_at, code, err_msg); + return .retried; + } + return .failed; +} + +// -- tests ----------------------------------------------------------------------------- + +const Dirs = @import("dirs.zig").Dirs; +const repository = @import("repository.zig"); + +const TestEnv = struct { + tmp: std.testing.TmpDir, + arena: std.heap.ArenaAllocator, + dirs: Dirs, + + fn init() !*TestEnv { + const self = try std.testing.allocator.create(TestEnv); + self.tmp = std.testing.tmpDir(.{}); + self.arena = std.heap.ArenaAllocator.init(std.testing.allocator); + const base = try std.fmt.allocPrint(self.arena.allocator(), ".zig-cache/tmp/{s}/zag", .{self.tmp.sub_path}); + self.dirs = try Dirs.open(std.testing.io, base); + return self; + } + + fn deinit(self: *TestEnv) void { + self.dirs.close(std.testing.io); + self.arena.deinit(); + self.tmp.cleanup(); + std.testing.allocator.destroy(self); + } + + fn repo(self: *TestEnv) Repository { + return Repository.init(std.testing.io, &self.dirs); + } + + fn create(self: *TestEnv, command: []const []const u8, opts: repository.CreateOptions) ![]const u8 { + const j = try self.repo().create(self.arena.allocator(), command, opts); + return j.id; + } + + fn job(self: *TestEnv, id: []const u8) !@import("job.zig").Job { + return (try self.repo().findById(self.arena.allocator(), id)).?; + } +}; + +const fast: Options = .{ .tick_ms = 10, .heartbeat_interval_ms = 20, .kill_grace_ms = 300 }; + +test "successful job" { + const env = try TestEnv.init(); + defer env.deinit(); + const id = try env.create(&.{ "sh", "-c", "echo hello" }, .{}); + var ctl: Control = .{}; + try std.testing.expectEqual(Outcome.succeeded, run(std.testing.allocator, std.testing.io, env.repo(), id, &ctl, fast)); + const j = try env.job(id); + try std.testing.expectEqual(State.succeeded, j.state); + try std.testing.expectEqual(@as(i32, 0), j.exit_code.?.code); + try std.testing.expect(j.pid != null and j.started_at != null and j.finished_at != null); + var jd = try env.dirs.openJob(std.testing.io, id); + defer jd.close(std.testing.io); + const out = try jd.readFileAlloc(std.testing.io, "logs/stdout.log", std.testing.allocator, .limited(1024)); + defer std.testing.allocator.free(out); + try std.testing.expectEqualStrings("hello\n", out); +} + +test "failure without retries" { + const env = try TestEnv.init(); + defer env.deinit(); + const id = try env.create(&.{ "sh", "-c", "exit 7" }, .{ .max_retries = 0 }); + var ctl: Control = .{}; + try std.testing.expectEqual(Outcome.failed, run(std.testing.allocator, std.testing.io, env.repo(), id, &ctl, fast)); + const j = try env.job(id); + try std.testing.expectEqual(State.failed, j.state); + try std.testing.expectEqual(@as(i32, 7), j.exit_code.?.code); + try std.testing.expectEqualStrings("Process exited with code 7", j.err.?); +} + +test "failure with retries is re-queued with a future retry_at" { + const env = try TestEnv.init(); + defer env.deinit(); + const id = try env.create(&.{ "sh", "-c", "exit 2" }, .{ .max_retries = 2, .retry_delay_seconds = 60 }); + var ctl: Control = .{}; + try std.testing.expectEqual(Outcome.retried, run(std.testing.allocator, std.testing.io, env.repo(), id, &ctl, fast)); + const j = try env.job(id); + try std.testing.expectEqual(State.queued, j.state); + try std.testing.expectEqual(@as(u32, 1), j.retry_count); + try std.testing.expect(j.retry_at.? > timestamp.now(std.testing.io) + 30 * std.time.ns_per_s); +} + +test "retries stop once exhausted and exit-code filter applies" { + const env = try TestEnv.init(); + defer env.deinit(); + const id = try env.create(&.{ "sh", "-c", "exit 2" }, .{ .max_retries = 1, .retry_delay_seconds = 0 }); + var ctl: Control = .{}; + try std.testing.expectEqual(Outcome.retried, run(std.testing.allocator, std.testing.io, env.repo(), id, &ctl, fast)); + try std.testing.expectEqual(Outcome.failed, run(std.testing.allocator, std.testing.io, env.repo(), id, &ctl, fast)); + try std.testing.expectEqual(State.failed, (try env.job(id)).state); + + const id2 = try env.create(&.{ "sh", "-c", "exit 2" }, .{ .max_retries = 3 }); + var opts = fast; + opts.retry_codes = &.{137}; + var ctl2: Control = .{}; + try std.testing.expectEqual(Outcome.failed, run(std.testing.allocator, std.testing.io, env.repo(), id2, &ctl2, opts)); +} + +test "spawn failure records start_failed" { + const env = try TestEnv.init(); + defer env.deinit(); + const id = try env.create(&.{"/no/such/binary"}, .{}); + var ctl: Control = .{}; + try std.testing.expectEqual(Outcome.start_failed, run(std.testing.allocator, std.testing.io, env.repo(), id, &ctl, fast)); + const j = try env.job(id); + try std.testing.expectEqual(State.failed, j.state); + try std.testing.expectEqualStrings("start_failed", j.exit_code.?.symbol); + try std.testing.expect(std.mem.startsWith(u8, j.err.?, "Failed to start process")); +} + +test "timeout fails the job with symbolic exit code" { + const env = try TestEnv.init(); + defer env.deinit(); + const id = try env.create(&.{ "sleep", "30" }, .{ .max_retries = 3 }); + var ctl: Control = .{}; + var opts = fast; + opts.timeout_seconds = 1; + try std.testing.expectEqual(Outcome.timed_out, run(std.testing.allocator, std.testing.io, env.repo(), id, &ctl, opts)); + const j = try env.job(id); + try std.testing.expectEqual(State.failed, j.state); + try std.testing.expectEqualStrings("timeout", j.exit_code.?.symbol); + try std.testing.expectEqual(@as(u32, 0), j.retry_count); +} + +fn killLater(io: Io, ctl: *Control, force: bool) void { + io.sleep(.fromMilliseconds(300), .real) catch return; + ctl.requestKill(force); +} + +test "kill cancels a running job (TERM, then KILL for stubborn processes)" { + const env = try TestEnv.init(); + defer env.deinit(); + + const id = try env.create(&.{ "sleep", "30" }, .{}); + var ctl: Control = .{}; + const t = try std.Thread.spawn(.{}, killLater, .{ std.testing.io, &ctl, false }); + try std.testing.expectEqual(Outcome.canceled, run(std.testing.allocator, std.testing.io, env.repo(), id, &ctl, fast)); + t.join(); + try std.testing.expectEqual(State.canceled, (try env.job(id)).state); + + // Ignores SIGTERM, so it needs the grace period to elapse before SIGKILL. + const id2 = try env.create(&.{ "sh", "-c", "trap '' TERM; while true; do sleep 1; done" }, .{}); + var ctl2: Control = .{}; + const t2 = try std.Thread.spawn(.{}, killLater, .{ std.testing.io, &ctl2, false }); + try std.testing.expectEqual(Outcome.canceled, run(std.testing.allocator, std.testing.io, env.repo(), id2, &ctl2, fast)); + t2.join(); + try std.testing.expectEqual(State.canceled, (try env.job(id2)).state); +} + +test "a job canceled before it starts never runs" { + const env = try TestEnv.init(); + defer env.deinit(); + const id = try env.create(&.{ "sh", "-c", "touch ran" }, .{}); + var ctl: Control = .{}; + ctl.requestKill(false); + try std.testing.expectEqual(Outcome.canceled, run(std.testing.allocator, std.testing.io, env.repo(), id, &ctl, fast)); + var jd = try env.dirs.openJob(std.testing.io, id); + defer jd.close(std.testing.io); + try std.testing.expectError(error.FileNotFound, jd.statFile(std.testing.io, "work/ran", .{})); +} + +test "heartbeat is refreshed while running" { + const env = try TestEnv.init(); + defer env.deinit(); + const id = try env.create(&.{ "sleep", "1" }, .{}); + var ctl: Control = .{}; + const T = struct { + fn go(e: *TestEnv, i: []const u8, c: *Control) void { + _ = run(std.testing.allocator, std.testing.io, e.repo(), i, c, fast); + } + }; + const t = try std.Thread.spawn(.{}, T.go, .{ env, id, &ctl }); + try std.testing.io.sleep(.fromMilliseconds(400), .real); + const mid = try env.job(id); + try std.testing.expectEqual(State.running, mid.state); + try std.testing.expect(mid.heartbeat.? > mid.started_at.?); + t.join(); +}