diff --git a/AGENTS.md b/AGENTS.md index 080e25a..75cadf6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -36,3 +36,10 @@ Guidance for AI coding agents working in `zag`, the Zig port of the | `src/config.zig` | Config structs, defaults, TOML loading/merging, `ZAG_*` env overrides, validation | | `src/loadclass.zig` | `.load` whitelist parsing and load-level classifier | | `src/defaults.zig`, `src/defaults/` | Default `zag.conf` and `*.load` files embedded in the binary | +| `src/retry.zig` | Retry decision and backoff/jitter delay | +| `src/proc.zig` | Spawn with log redirection, process-group signals, liveness | +| `src/runner.zig` | Runs one job: heartbeat, timeout, kill, completion, retry | +| `src/recovery.zig` | Startup crash recovery of orphaned running jobs | +| `src/scheduler.zig` | Per-load-level concurrency, thread per job, `killJob` | +| `src/usage.zig` | `ps`/`nvidia-smi` sampling, `usage.csv`, summaries | +| `src/cleanup.zig` | Automatic and manual (`zag clean`) cleanup planning | diff --git a/src/cleanup.zig b/src/cleanup.zig new file mode 100644 index 0000000..d5a6e75 --- /dev/null +++ b/src/cleanup.zig @@ -0,0 +1,262 @@ +//! Removing finished jobs: the periodic automatic policy (`[cleanup]` config) and the manual +//! `zag clean` flags. Running and queued jobs are never touched. +//! +//! Manual semantics are identical whether the CLI runs offline or through the service: with +//! none of `all`, `older_than_seconds` or `job_id` set, nothing is selected. +const std = @import("std"); +const Io = std.Io; +const Allocator = std.mem.Allocator; +const Repository = @import("repository.zig").Repository; +const Job = @import("job.zig").Job; +const Instant = @import("job.zig").Instant; +const config = @import("config.zig"); +const usage = @import("usage.zig"); + +pub const Candidate = struct { + job: Job, + size_bytes: u64, +}; + +pub const ManualPolicy = struct { + /// Remove every cleanable job regardless of age. + all: bool = false, + older_than_seconds: ?u64 = null, + include_failed: bool = false, + job_id: ?[]const u8 = null, +}; + +pub const ManualError = error{ JobNotFound, NotCleanable }; + +/// Finished jobs only; failed ones just when `include_failed` is set. +pub fn isCleanable(job: Job, include_failed: bool) bool { + return switch (job.state) { + .running, .queued => false, + .failed => include_failed, + .succeeded, .canceled, .killed => true, + }; +} + +/// When the job last finished, falling back to its creation time. +pub fn ageBase(job: Job) Instant { + return job.finished_at orelse job.created_at; +} + +pub fn jobSize(gpa: Allocator, io: Io, repo: Repository, id: []const u8) u64 { + var dir = repo.dirs.base.openDir(io, "jobs", .{}) catch return 0; + defer dir.close(io); + var job_dir = dir.openDir(io, id, .{ .iterate = true }) catch return 0; + defer job_dir.close(io); + return usage.dirSize(gpa, io, job_dir) catch 0; +} + +fn candidate(gpa: Allocator, io: Io, repo: Repository, job: Job) Candidate { + return .{ .job = job, .size_bytes = jobSize(gpa, io, repo, job.id) }; +} + +/// Selects jobs for `zag clean`. All memory comes from `arena`. +pub fn planManual(arena: Allocator, io: Io, repo: Repository, policy: ManualPolicy, now: Instant) (ManualError || anyerror)![]Candidate { + var out: std.ArrayList(Candidate) = .empty; + + if (policy.job_id) |id| { + const job = (try repo.findById(arena, id)) orelse return error.JobNotFound; + if (!isCleanable(job, policy.include_failed)) return error.NotCleanable; + try out.append(arena, candidate(arena, io, repo, job)); + return out.toOwnedSlice(arena); + } + if (!policy.all and policy.older_than_seconds == null) return &.{}; + + for (try repo.findAll(arena)) |job| { + if (!isCleanable(job, policy.include_failed)) continue; + if (policy.older_than_seconds) |secs| { + if (ageBase(job) >= now - @as(Instant, secs) * std.time.ns_per_s) continue; + } + try out.append(arena, candidate(arena, io, repo, job)); + } + return out.toOwnedSlice(arena); +} + +/// True when the periodic cleanup should remove this job. +pub fn shouldAutoClean(job: Job, cfg: config.Cleanup, now: Instant) bool { + if (!isCleanable(job, true)) return false; + const hours: u64 = if (job.state == .failed and cfg.keep_failed_jobs) cfg.keep_failed_jobs_hours else cfg.max_age_hours; + return ageBase(job) < now - @as(Instant, hours) * 3600 * std.time.ns_per_s; +} + +/// Selects jobs for the automatic policy. +pub fn planAutomatic(arena: Allocator, io: Io, repo: Repository, cfg: config.Cleanup, now: Instant) ![]Candidate { + var out: std.ArrayList(Candidate) = .empty; + for (try repo.findAll(arena)) |job| { + if (shouldAutoClean(job, cfg, now)) try out.append(arena, candidate(arena, io, repo, job)); + } + return out.toOwnedSlice(arena); +} + +/// Deletes the candidates' job directories; returns how many were removed. +pub fn execute(repo: Repository, candidates: []const Candidate) usize { + var removed: usize = 0; + for (candidates) |c| { + repo.delete(c.job.id) catch |err| { + std.log.warn("cleanup: cannot delete {s}: {s}", .{ c.job.id, @errorName(err) }); + continue; + }; + removed += 1; + } + return removed; +} + +/// Runs the automatic policy once and returns how many jobs were removed. +pub fn runAutomatic(gpa: Allocator, io: Io, repo: Repository, cfg: config.Cleanup, now: Instant) !usize { + var arena_state = std.heap.ArenaAllocator.init(gpa); + defer arena_state.deinit(); + return execute(repo, try planAutomatic(arena_state.allocator(), io, repo, cfg, now)); +} + +// -- tests ----------------------------------------------------------------------------- + +const Dirs = @import("dirs.zig").Dirs; +const State = @import("state.zig").State; +const StateFiles = @import("statefiles.zig").StateFiles; +const timestamp = @import("timestamp.zig"); + +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); + } + + /// Creates a job in `state`, finished `age_hours` ago. + fn jobIn(self: *Env, state: State, age_hours: u64) ![]const u8 { + const a = self.arena.allocator(); + const r = self.repo(); + const j = try r.create(a, &.{"true"}, .{}); + switch (state) { + .queued => {}, + .running => try r.markStarted(j.id, 1), + .succeeded => { + try r.markStarted(j.id, 1); + try r.markCompleted(j.id, 0, null); + }, + .failed => { + try r.markStarted(j.id, 1); + try r.markCompleted(j.id, 1, null); + }, + .canceled => try r.markCanceled(j.id), + .killed => { + try r.markStarted(j.id, 1); + try r.markKilled(j.id, null); + }, + } + if (state != .queued and state != .running) { + var dir = try self.dirs.openJob(std.testing.io, j.id); + defer dir.close(std.testing.io); + const t = timestamp.now(std.testing.io) - @as(Instant, age_hours) * 3600 * std.time.ns_per_s; + try StateFiles.init(std.testing.io, dir).writeFinishedAt(t); + } + return j.id; + } + + fn exists(self: *Env, id: []const u8) bool { + return self.dirs.jobExists(std.testing.io, id); + } +}; + +test "auto policy: ages, failed retention and untouchable states" { + const env = try Env.init(); + defer env.deinit(); + const old_ok = try env.jobIn(.succeeded, 100); + const new_ok = try env.jobIn(.succeeded, 1); + const old_canceled = try env.jobIn(.canceled, 100); + const failed_100h = try env.jobIn(.failed, 100); // < 168h: kept + const failed_200h = try env.jobIn(.failed, 200); // > 168h: removed + const running = try env.jobIn(.running, 0); + const queued = try env.jobIn(.queued, 0); + + const n = try runAutomatic(std.testing.allocator, std.testing.io, env.repo(), .{}, timestamp.now(std.testing.io)); + try std.testing.expectEqual(@as(usize, 3), n); + try std.testing.expect(!env.exists(old_ok) and !env.exists(old_canceled) and !env.exists(failed_200h)); + try std.testing.expect(env.exists(new_ok) and env.exists(failed_100h) and env.exists(running) and env.exists(queued)); +} + +test "auto policy without keep_failed treats failed like the rest" { + const env = try Env.init(); + defer env.deinit(); + const f = try env.jobIn(.failed, 100); + const n = try runAutomatic(std.testing.allocator, std.testing.io, env.repo(), .{ .keep_failed_jobs = false }, timestamp.now(std.testing.io)); + try std.testing.expectEqual(@as(usize, 1), n); + try std.testing.expect(!env.exists(f)); +} + +test "manual clean with no selector removes nothing" { + const env = try Env.init(); + defer env.deinit(); + const id = try env.jobIn(.succeeded, 100); + const plan = try planManual(env.arena.allocator(), std.testing.io, env.repo(), .{}, timestamp.now(std.testing.io)); + try std.testing.expectEqual(@as(usize, 0), plan.len); + try std.testing.expect(env.exists(id)); +} + +test "manual --all skips failed unless included, and never running/queued" { + const env = try Env.init(); + defer env.deinit(); + const ok = try env.jobIn(.succeeded, 0); + const failed = try env.jobIn(.failed, 0); + const running = try env.jobIn(.running, 0); + const now = timestamp.now(std.testing.io); + + var plan = try planManual(env.arena.allocator(), std.testing.io, env.repo(), .{ .all = true }, now); + try std.testing.expectEqual(@as(usize, 1), plan.len); + try std.testing.expectEqualStrings(ok, plan[0].job.id); + + plan = try planManual(env.arena.allocator(), std.testing.io, env.repo(), .{ .all = true, .include_failed = true }, now); + try std.testing.expectEqual(@as(usize, 2), plan.len); + try std.testing.expectEqual(@as(usize, 2), execute(env.repo(), plan)); + try std.testing.expect(!env.exists(ok) and !env.exists(failed) and env.exists(running)); +} + +test "manual --older-than filters by age" { + const env = try Env.init(); + defer env.deinit(); + const old = try env.jobIn(.succeeded, 48); + const fresh = try env.jobIn(.succeeded, 1); + const plan = try planManual(env.arena.allocator(), std.testing.io, env.repo(), .{ .older_than_seconds = 24 * 3600 }, timestamp.now(std.testing.io)); + try std.testing.expectEqual(@as(usize, 1), plan.len); + try std.testing.expectEqualStrings(old, plan[0].job.id); + try std.testing.expect(env.exists(fresh)); +} + +test "manual --job-id errors and sizes" { + const env = try Env.init(); + defer env.deinit(); + const a = env.arena.allocator(); + const now = timestamp.now(std.testing.io); + const running = try env.jobIn(.running, 0); + const failed = try env.jobIn(.failed, 0); + const ok = try env.jobIn(.succeeded, 0); + + try std.testing.expectError(error.JobNotFound, planManual(a, std.testing.io, env.repo(), .{ .job_id = "job-deadbeef" }, now)); + try std.testing.expectError(error.NotCleanable, planManual(a, std.testing.io, env.repo(), .{ .job_id = running }, now)); + try std.testing.expectError(error.NotCleanable, planManual(a, std.testing.io, env.repo(), .{ .job_id = failed }, now)); + + const plan = try planManual(a, std.testing.io, env.repo(), .{ .job_id = ok }, now); + try std.testing.expectEqual(@as(usize, 1), plan.len); + try std.testing.expect(plan[0].size_bytes > 0); // manifest + state files +} diff --git a/src/root.zig b/src/root.zig index 2d20784..87571e9 100644 --- a/src/root.zig +++ b/src/root.zig @@ -20,6 +20,7 @@ pub const runner = @import("runner.zig"); pub const recovery = @import("recovery.zig"); pub const scheduler = @import("scheduler.zig"); pub const usage = @import("usage.zig"); +pub const cleanup = @import("cleanup.zig"); test { @import("std").testing.refAllDecls(@This());