feat: crash recovery and per-level job scheduler (M3 part 3)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Daniel SamsonandClaude Sonnet 5.5 committed 2026-10-17 13:23:59 +01:00
1 parent 8cccce1383
commit b2d68bfb32
3 files changed
+496

No files matched your search

+113
View File
@@ -0,0 +1,113 @@
//! Crash recovery: on daemon start, running jobs whose heartbeat is stale and whose process is
//! gone are orphans. They are marked KILLED and, when retries remain, re-queued.
const std = @import("std");
const Allocator = std.mem.Allocator;
const Io = std.Io;
const Repository = @import("repository.zig").Repository;
const Job = @import("job.zig").Job;
const Instant = @import("job.zig").Instant;
const proc = @import("proc.zig");
const retry = @import("retry.zig");
const timestamp = @import("timestamp.zig");
pub const killed_error = "Process killed - daemon restarted";
/// A running job with no heartbeat, or one older than `threshold_seconds`, is stale.
pub fn isStale(job: Job, now: Instant, threshold_seconds: u32) bool {
if (job.state != .running) return false;
const hb = job.heartbeat orelse return true;
return hb < now - @as(Instant, threshold_seconds) * std.time.ns_per_s;
}
/// Stale heartbeat and no live process (or no pid recorded at all).
pub fn isOrphaned(job: Job, now: Instant, threshold_seconds: u32) bool {
if (!isStale(job, now, threshold_seconds)) return false;
const pid = job.pid orelse return true;
return !proc.isAlive(pid);
}
pub const Options = struct {
stale_threshold_seconds: u32 = 30,
random: ?std.Random = null,
};
/// Recovers all orphaned jobs and returns how many were handled.
pub fn recoverOrphanedJobs(gpa: Allocator, io: Io, repo: Repository, opts: Options) !usize {
var arena_state = std.heap.ArenaAllocator.init(gpa);
defer arena_state.deinit();
const arena = arena_state.allocator();
const now = timestamp.now(io);
var recovered: usize = 0;
for (try repo.findByState(arena, .running)) |job| {
if (!isOrphaned(job, now, opts.stale_threshold_seconds)) continue;
repo.markKilled(job.id, killed_error) catch |err| {
std.log.err("recovery: cannot mark {s} killed: {s}", .{ job.id, @errorName(err) });
continue;
};
recovered += 1;
const manifest = repo.loadManifest(arena, job.id) catch continue;
if (manifest.max_retries > 0 and job.retry_count < manifest.max_retries) {
const delay = retry.delaySeconds(job.retry_count, manifest.retry_delay_seconds, manifest.retry_backoff_multiplier, opts.random);
const retry_at = now + @as(Instant, delay) * std.time.ns_per_s;
repo.scheduleRetry(gpa, job.id, retry_at, null, killed_error) catch |err|
std.log.err("recovery: cannot requeue {s}: {s}", .{ job.id, @errorName(err) });
}
}
return recovered;
}
// -- tests -----------------------------------------------------------------------------
const Dirs = @import("dirs.zig").Dirs;
const State = @import("state.zig").State;
test "stale and orphaned detection" {
const now: Instant = 1_000 * std.time.ns_per_s;
var j: Job = .{ .id = "job-1", .state = .running, .command = &.{"x"}, .created_at = 0, .pid = 999_999_999 };
try std.testing.expect(isStale(j, now, 30)); // no heartbeat
j.heartbeat = now - 5 * std.time.ns_per_s;
try std.testing.expect(!isStale(j, now, 30));
try std.testing.expect(!isOrphaned(j, now, 30));
j.heartbeat = now - 60 * std.time.ns_per_s;
try std.testing.expect(isStale(j, now, 30));
try std.testing.expect(isOrphaned(j, now, 30)); // pid does not exist
j.pid = std.os.linux.getpid();
try std.testing.expect(!isOrphaned(j, now, 30)); // alive: stale but not orphaned
j.pid = null;
try std.testing.expect(isOrphaned(j, now, 30));
j.state = .queued;
try std.testing.expect(!isStale(j, now, 30));
}
test "orphans are killed and requeued while retries remain" {
const io = std.testing.io;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const base = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}/zag", .{tmp.sub_path});
var dirs = try Dirs.open(io, base);
defer dirs.close(io);
const repo = Repository.init(io, &dirs);
const orphan = try repo.create(a, &.{"x"}, .{ .max_retries = 2, .retry_delay_seconds = 10 });
const no_retry = try repo.create(a, &.{"x"}, .{ .max_retries = 0 });
const healthy = try repo.create(a, &.{"x"}, .{});
for ([_][]const u8{ orphan.id, no_retry.id }) |id| {
try repo.markStarted(id, 999_999_999);
try repo.updateHeartbeat(id, timestamp.now(io) - 120 * std.time.ns_per_s);
}
try repo.markStarted(healthy.id, 999_999_999); // fresh heartbeat
try std.testing.expectEqual(@as(usize, 2), try recoverOrphanedJobs(std.testing.allocator, io, repo, .{}));
const o = (try repo.findById(a, orphan.id)).?;
try std.testing.expectEqual(State.queued, o.state);
try std.testing.expectEqual(@as(u32, 1), o.retry_count);
try std.testing.expect(o.retry_at.? > timestamp.now(io));
try std.testing.expectEqual(State.killed, (try repo.findById(a, no_retry.id)).?.state);
try std.testing.expectEqual(State.running, (try repo.findById(a, healthy.id)).?.state);
}
+2
View File
@@ -17,6 +17,8 @@ pub const loadclass = @import("loadclass.zig");
pub const retry = @import("retry.zig");
pub const proc = @import("proc.zig");
pub const runner = @import("runner.zig");
pub const recovery = @import("recovery.zig");
pub const scheduler = @import("scheduler.zig");
test {
@import("std").testing.refAllDecls(@This());
+381
View File
@@ -0,0 +1,381 @@
//! Job scheduler: polls for queued jobs, enforces per-load-level concurrency limits and runs
//! each job on its own thread. Port of barn's `JobScheduler`.
//!
//! Jobs start oldest-first (by `created_at`), skipping ones whose `retry_at` is in the future.
//! Only one scheduler may run per base directory (guarded by `locks/scheduler.lock`).
const std = @import("std");
const Io = std.Io;
const Allocator = std.mem.Allocator;
const Repository = @import("repository.zig").Repository;
const dirs_mod = @import("dirs.zig");
const fsutil = @import("fsutil.zig");
const runner = @import("runner.zig");
const timestamp = @import("timestamp.zig");
const LoadLevel = @import("loadlevel.zig").LoadLevel;
const LoadLevels = @import("config.zig").LoadLevels;
const Job = @import("job.zig").Job;
pub const Options = struct {
limits: LoadLevels = .{},
/// Poll interval.
tick_ms: u64 = 1_000,
runner: runner.Options = .{},
};
pub const KillResult = enum {
/// Signalled a running job; it will end up canceled.
signalled,
/// A queued job was canceled directly.
canceled,
/// The job exists but is neither queued nor running here.
not_running,
not_found,
};
const Active = struct {
id: []u8,
ctl: runner.Control = .{},
level: LoadLevel,
};
pub const Scheduler = struct {
gpa: Allocator,
io: Io,
repo: Repository,
opts: Options,
mutex: Io.Mutex = .init,
active: std.StringHashMapUnmanaged(*Active) = .empty,
counts: [3]u32 = .{ 0, 0, 0 },
stopping: std.atomic.Value(bool) = .init(false),
thread: ?std.Thread = null,
lock: ?fsutil.FileLock = null,
pub const StartError = error{AlreadyRunning} || fsutil.FileLock.AcquireError || std.Thread.SpawnError;
pub fn init(gpa: Allocator, io: Io, repo: Repository, opts: Options) Scheduler {
return .{ .gpa = gpa, .io = io, .repo = repo, .opts = opts };
}
/// Takes the scheduler lock and starts the polling thread.
pub fn start(self: *Scheduler) StartError!void {
std.debug.assert(self.thread == null);
self.lock = (try fsutil.FileLock.tryAcquire(self.io, self.repo.dirs.base, dirs_mod.scheduler_lock)) orelse
return error.AlreadyRunning;
errdefer {
self.lock.?.release(self.io);
self.lock = null;
}
self.stopping.store(false, .release);
self.thread = try std.Thread.spawn(.{}, loop, .{self});
}
/// Stops polling and waits up to `wait_ms` for running jobs to finish. Returns how many
/// are still running (they keep running; the caller may kill them).
pub fn stop(self: *Scheduler, wait_ms: u64) usize {
self.stopping.store(true, .release);
if (self.thread) |t| t.join();
self.thread = null;
var waited: u64 = 0;
while (self.activeCount() > 0 and waited < wait_ms) : (waited += 20) {
self.io.sleep(.fromMilliseconds(20), .real) catch break;
}
const remaining = self.activeCount();
if (remaining == 0) {
if (self.lock) |*l| l.release(self.io);
self.lock = null;
}
return remaining;
}
pub fn deinit(self: *Scheduler) void {
std.debug.assert(self.thread == null and self.active.count() == 0);
self.active.deinit(self.gpa);
if (self.lock) |*l| l.release(self.io);
}
pub fn activeCount(self: *Scheduler) usize {
self.mutex.lockUncancelable(self.io);
defer self.mutex.unlock(self.io);
return self.active.count();
}
pub fn runningAt(self: *Scheduler, level: LoadLevel) u32 {
self.mutex.lockUncancelable(self.io);
defer self.mutex.unlock(self.io);
return self.counts[@intFromEnum(level)];
}
pub fn limitFor(self: *const Scheduler, level: LoadLevel) u32 {
return switch (level) {
.high => self.opts.limits.max_high_jobs,
.medium => self.opts.limits.max_medium_jobs,
.low => self.opts.limits.max_low_jobs,
};
}
fn loop(self: *Scheduler) void {
while (!self.stopping.load(.acquire)) {
self.tick() catch |err| std.log.warn("scheduler tick failed: {s}", .{@errorName(err)});
// Sleep in short slices so stop() is responsive.
var slept: u64 = 0;
while (slept < self.opts.tick_ms and !self.stopping.load(.acquire)) : (slept += 20) {
self.io.sleep(.fromMilliseconds(20), .real) catch return;
}
}
}
/// One scheduling pass: starts every eligible queued job that fits its level's limit.
pub fn tick(self: *Scheduler) !void {
var arena_state = std.heap.ArenaAllocator.init(self.gpa);
defer arena_state.deinit();
const arena = arena_state.allocator();
const queued = try self.repo.findByState(arena, .queued);
std.mem.sort(Job, queued, {}, olderFirst);
const now = timestamp.now(self.io);
for (queued) |job| {
if (job.retry_at) |t| if (t > now) continue;
if (self.stopping.load(.acquire)) return;
self.startJob(job) catch |err| switch (err) {
error.AtCapacity, error.AlreadyActive => continue,
else => return err,
};
}
}
fn olderFirst(_: void, a: Job, b: Job) bool {
return a.created_at < b.created_at;
}
const StartJobError = error{ AtCapacity, AlreadyActive } || Allocator.Error || std.Thread.SpawnError;
fn startJob(self: *Scheduler, job: Job) StartJobError!void {
const level = job.load_level;
const idx = @intFromEnum(level);
const entry = try self.gpa.create(Active);
errdefer self.gpa.destroy(entry);
entry.* = .{ .id = try self.gpa.dupe(u8, job.id), .level = level };
errdefer self.gpa.free(entry.id);
{
self.mutex.lockUncancelable(self.io);
defer self.mutex.unlock(self.io);
if (self.active.contains(job.id)) return error.AlreadyActive;
if (self.counts[idx] >= self.limitFor(level)) return error.AtCapacity;
try self.active.put(self.gpa, entry.id, entry);
self.counts[idx] += 1;
}
errdefer self.release(entry);
const t = try std.Thread.spawn(.{}, runJob, .{ self, entry });
t.detach();
}
fn runJob(self: *Scheduler, entry: *Active) void {
_ = runner.run(self.gpa, self.io, self.repo, entry.id, &entry.ctl, self.opts.runner);
self.release(entry);
}
fn release(self: *Scheduler, entry: *Active) void {
{
self.mutex.lockUncancelable(self.io);
defer self.mutex.unlock(self.io);
_ = self.active.remove(entry.id);
self.counts[@intFromEnum(entry.level)] -= 1;
}
self.gpa.free(entry.id);
self.gpa.destroy(entry);
}
/// Kills a job: signals it if it is running here, cancels it if still queued.
pub fn killJob(self: *Scheduler, id: []const u8, force: bool) !KillResult {
{
self.mutex.lockUncancelable(self.io);
defer self.mutex.unlock(self.io);
if (self.active.get(id)) |entry| {
entry.ctl.requestKill(force);
return .signalled;
}
}
var arena_state = std.heap.ArenaAllocator.init(self.gpa);
defer arena_state.deinit();
const job = (try self.repo.findById(arena_state.allocator(), id)) orelse return .not_found;
if (job.state != .queued) return .not_running;
self.repo.markCanceled(id) catch |err| switch (err) {
error.InvalidTransition => return .not_running,
else => |e| return e,
};
return .canceled;
}
};
// -- tests -----------------------------------------------------------------------------
const Dirs = @import("dirs.zig").Dirs;
const State = @import("state.zig").State;
const Env = struct {
tmp: std.testing.TmpDir,
arena: std.heap.ArenaAllocator,
dirs: Dirs,
fn init() !*Env {
const self = try std.testing.allocator.create(Env);
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: *Env) void {
self.dirs.close(std.testing.io);
self.arena.deinit();
self.tmp.cleanup();
std.testing.allocator.destroy(self);
}
fn repo(self: *Env) Repository {
return Repository.init(std.testing.io, &self.dirs);
}
fn state(self: *Env, id: []const u8) !State {
return (try self.repo().findById(self.arena.allocator(), id)).?.state;
}
fn waitFor(self: *Env, id: []const u8, want: State, timeout_ms: u64) !void {
var waited: u64 = 0;
while (waited < timeout_ms) : (waited += 10) {
if ((try self.state(id)) == want) return;
try std.testing.io.sleep(.fromMilliseconds(10), .real);
}
return error.Timeout;
}
};
const test_opts: Options = .{
.tick_ms = 20,
.runner = .{ .tick_ms = 10, .heartbeat_interval_ms = 20, .kill_grace_ms = 300 },
};
test "runs queued jobs to completion" {
const env = try Env.init();
defer env.deinit();
const a = env.arena.allocator();
const j1 = try env.repo().create(a, &.{ "sh", "-c", "echo one" }, .{});
const j2 = try env.repo().create(a, &.{ "sh", "-c", "exit 4" }, .{ .max_retries = 0 });
var s = Scheduler.init(std.testing.allocator, std.testing.io, env.repo(), test_opts);
defer s.deinit();
try s.start();
try env.waitFor(j1.id, .succeeded, 5000);
try env.waitFor(j2.id, .failed, 5000);
try std.testing.expectEqual(@as(usize, 0), s.stop(2000));
}
test "load level limits cap concurrency and the rest wait their turn" {
const env = try Env.init();
defer env.deinit();
const a = env.arena.allocator();
var ids: [3][]const u8 = undefined;
for (&ids) |*id| id.* = (try env.repo().create(a, &.{ "sleep", "0.4" }, .{ .load_level = .high })).id;
var opts = test_opts;
opts.limits = .{ .max_high_jobs = 1, .max_medium_jobs = 8, .max_low_jobs = 32 };
var s = Scheduler.init(std.testing.allocator, std.testing.io, env.repo(), opts);
defer s.deinit();
try s.start();
// While work remains, never more than one high job runs at a time.
var max_seen: u32 = 0;
var done = false;
var waited: u64 = 0;
while (!done and waited < 8000) : (waited += 10) {
max_seen = @max(max_seen, s.runningAt(.high));
done = true;
for (ids) |id| {
if ((try env.state(id)) != .succeeded) done = false;
}
try std.testing.io.sleep(.fromMilliseconds(10), .real);
}
try std.testing.expect(done);
try std.testing.expectEqual(@as(u32, 1), max_seen);
_ = s.stop(2000);
}
test "different levels run concurrently" {
const env = try Env.init();
defer env.deinit();
const a = env.arena.allocator();
const hi = try env.repo().create(a, &.{ "sleep", "0.6" }, .{ .load_level = .high });
const lo = try env.repo().create(a, &.{ "sleep", "0.6" }, .{ .load_level = .low });
var opts = test_opts;
opts.limits = .{ .max_high_jobs = 1, .max_medium_jobs = 1, .max_low_jobs = 1 };
var s = Scheduler.init(std.testing.allocator, std.testing.io, env.repo(), opts);
defer s.deinit();
try s.start();
try env.waitFor(hi.id, .running, 3000);
try env.waitFor(lo.id, .running, 3000);
try std.testing.expectEqual(@as(usize, 2), s.activeCount());
try env.waitFor(hi.id, .succeeded, 5000);
try env.waitFor(lo.id, .succeeded, 5000);
_ = s.stop(2000);
}
test "jobs waiting for a retry are not started early" {
const env = try Env.init();
defer env.deinit();
const a = env.arena.allocator();
const j = try env.repo().create(a, &.{ "sh", "-c", "touch ran" }, .{});
try env.repo().markStarted(j.id, 1);
try env.repo().markCompleted(j.id, 1, null);
try env.repo().scheduleRetry(std.testing.allocator, j.id, timestamp.now(std.testing.io) + 3600 * std.time.ns_per_s, 1, null);
var s = Scheduler.init(std.testing.allocator, std.testing.io, env.repo(), test_opts);
defer s.deinit();
try s.start();
try std.testing.io.sleep(.fromMilliseconds(150), .real);
try std.testing.expectEqual(State.queued, try env.state(j.id));
try std.testing.expectEqual(@as(usize, 0), s.stop(1000));
}
test "killJob cancels queued jobs and signals running ones" {
const env = try Env.init();
defer env.deinit();
const a = env.arena.allocator();
const running = try env.repo().create(a, &.{ "sleep", "30" }, .{});
var s = Scheduler.init(std.testing.allocator, std.testing.io, env.repo(), test_opts);
defer s.deinit();
try s.start();
try env.waitFor(running.id, .running, 3000);
try std.testing.expectEqual(KillResult.signalled, try s.killJob(running.id, false));
try env.waitFor(running.id, .canceled, 5000);
try std.testing.expectEqual(KillResult.not_running, try s.killJob(running.id, false));
try std.testing.expectEqual(KillResult.not_found, try s.killJob("job-deadbeef", false));
_ = s.stop(2000);
const queued = try env.repo().create(a, &.{"true"}, .{});
try std.testing.expectEqual(KillResult.canceled, try s.killJob(queued.id, false));
try std.testing.expectEqual(State.canceled, try env.state(queued.id));
}
test "only one scheduler per base dir" {
const env = try Env.init();
defer env.deinit();
var s1 = Scheduler.init(std.testing.allocator, std.testing.io, env.repo(), test_opts);
defer s1.deinit();
var s2 = Scheduler.init(std.testing.allocator, std.testing.io, env.repo(), test_opts);
defer s2.deinit();
try s1.start();
try std.testing.expectError(error.AlreadyRunning, s2.start());
_ = s1.stop(1000);
try s2.start(); // lock released by stop
_ = s2.stop(1000);
}