feat: resource usage sampling and usage.csv logging (M3 part 4)

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:25:15 +01:00
1 parent b2d68bfb32
commit 8b8aa068f9
4 files changed
+343 -3

No files matched your search

+1
View File
@@ -19,6 +19,7 @@ pub const proc = @import("proc.zig");
pub const runner = @import("runner.zig");
pub const recovery = @import("recovery.zig");
pub const scheduler = @import("scheduler.zig");
pub const usage = @import("usage.zig");
test {
@import("std").testing.refAllDecls(@This());
+37 -2
View File
@@ -10,6 +10,7 @@ const proc = @import("proc.zig");
const retry = @import("retry.zig");
const timestamp = @import("timestamp.zig");
const State = @import("state.zig").State;
const usage = @import("usage.zig");
/// Shared between the runner, its monitor thread and whoever may kill the job.
pub const Control = struct {
@@ -35,6 +36,8 @@ pub const Options = struct {
kill_grace_ms: u64 = 5_000,
/// Jitter source for retry delays; null disables jitter.
random: ?std.Random = null,
/// How often resource usage is sampled into `logs/usage.csv`; 0 disables sampling.
usage_interval_ms: u64 = 5_000,
};
pub const Outcome = enum {
@@ -56,6 +59,8 @@ const Monitor = struct {
ctl: *Control,
opts: Options,
pid: proc.Pid,
job_dir: Io.Dir,
gpa: Allocator,
done: std.atomic.Value(bool) = .init(false),
timed_out: std.atomic.Value(bool) = .init(false),
@@ -63,10 +68,16 @@ const Monitor = struct {
return Io.Timestamp.now(self.io, .awake).nanoseconds;
}
fn sampleUsage(self: *Monitor) void {
const sample = usage.collect(self.gpa, self.io, self.pid, self.job_dir);
usage.append(self.gpa, self.io, self.job_dir, sample) catch {};
}
fn loop(self: *Monitor) void {
const ms = std.time.ns_per_ms;
const started = self.monoNow();
var last_heartbeat = started;
var last_usage = started;
var term_sent_at: ?i128 = null;
var kill_sent = false;
@@ -79,6 +90,11 @@ const Monitor = struct {
last_heartbeat = now;
}
if (self.opts.usage_interval_ms > 0 and now - last_usage >= @as(i128, self.opts.usage_interval_ms) * ms) {
self.sampleUsage();
last_usage = 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;
@@ -141,12 +157,14 @@ fn runInner(gpa: Allocator, io: Io, repo: Repository, id: []const u8, ctl: *Cont
return err;
};
var monitor: Monitor = .{ .io = io, .repo = repo, .id = id, .ctl = ctl, .opts = opts, .pid = pid };
var monitor: Monitor = .{ .io = io, .repo = repo, .id = id, .ctl = ctl, .opts = opts, .pid = pid, .job_dir = job_dir, .gpa = gpa };
if (opts.usage_interval_ms > 0) monitor.sampleUsage();
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);
if (opts.usage_interval_ms > 0) monitor.sampleUsage();
const code = proc.exitCodeOf(term catch .{ .unknown = 255 });
@@ -217,7 +235,7 @@ const TestEnv = struct {
}
};
const fast: Options = .{ .tick_ms = 10, .heartbeat_interval_ms = 20, .kill_grace_ms = 300 };
const fast: Options = .{ .tick_ms = 10, .heartbeat_interval_ms = 20, .kill_grace_ms = 300, .usage_interval_ms = 0 };
test "successful job" {
const env = try TestEnv.init();
@@ -356,3 +374,20 @@ test "heartbeat is refreshed while running" {
try std.testing.expect(mid.heartbeat.? > mid.started_at.?);
t.join();
}
test "usage samples are logged while a job runs" {
const env = try TestEnv.init();
defer env.deinit();
const id = try env.create(&.{ "sleep", "1" }, .{});
var ctl: Control = .{};
var opts = fast;
opts.usage_interval_ms = 200;
try std.testing.expectEqual(Outcome.succeeded, run(std.testing.allocator, std.testing.io, env.repo(), id, &ctl, opts));
var jd = try env.dirs.openJob(std.testing.io, id);
defer jd.close(std.testing.io);
const csv = try jd.readFileAlloc(std.testing.io, usage.csv_file, std.testing.allocator, .limited(1 << 16));
defer std.testing.allocator.free(csv);
const rows = try usage.parseCsv(env.arena.allocator(), csv);
try std.testing.expect(rows.len >= 3); // start + periodic + stop
try std.testing.expect(rows[0].memory_bytes > 0);
}
+1 -1
View File
@@ -259,7 +259,7 @@ const Env = struct {
const test_opts: Options = .{
.tick_ms = 20,
.runner = .{ .tick_ms = 10, .heartbeat_interval_ms = 20, .kill_grace_ms = 300 },
.runner = .{ .tick_ms = 10, .heartbeat_interval_ms = 20, .kill_grace_ms = 300, .usage_interval_ms = 0 },
};
test "runs queued jobs to completion" {
+304
View File
@@ -0,0 +1,304 @@
//! Resource usage sampling for a job's process: CPU %, resident memory, work-dir disk size and
//! (when `nvidia-smi` exists) GPU utilisation. Samples are appended to `logs/usage.csv`.
//! CPU and memory come from `ps` (as in barn), so they work on Linux and macOS alike.
const std = @import("std");
const Io = std.Io;
const Dir = Io.Dir;
const Allocator = std.mem.Allocator;
const timestamp = @import("timestamp.zig");
const proc = @import("proc.zig");
const Instant = @import("job.zig").Instant;
pub const csv_file = "logs/usage.csv";
pub const csv_header = "timestamp,cpu_percent,memory_bytes,disk_bytes,gpu_percent,gpu_memory_bytes";
pub const Sample = struct {
at: Instant,
cpu_percent: f64 = 0,
memory_bytes: u64 = 0,
disk_bytes: u64 = 0,
gpu_percent: ?f64 = null,
gpu_memory_bytes: ?u64 = null,
};
// -- parsing ---------------------------------------------------------------------------
pub const PsReading = struct { cpu_percent: f64, rss_bytes: u64 };
/// Parses the output of `ps -p PID -o %cpu= -o rss=` (`" 0.5 5988"`; RSS is in KiB).
pub fn parsePs(text: []const u8) ?PsReading {
var it = std.mem.tokenizeAny(u8, text, " \t\r\n");
const cpu = std.fmt.parseFloat(f64, it.next() orelse return null) catch return null;
const rss = std.fmt.parseInt(u64, it.next() orelse return null, 10) catch return null;
return .{ .cpu_percent = cpu, .rss_bytes = rss * 1024 };
}
pub const GpuReading = struct { percent: f64, memory_bytes: u64 };
/// Parses `nvidia-smi --query-gpu=utilization.gpu,memory.used --format=csv,noheader,nounits`.
/// Multiple GPUs: utilisation is the maximum, memory the sum (MiB -> bytes).
pub fn parseNvidiaSmi(text: []const u8) ?GpuReading {
var best: ?f64 = null;
var mem: u64 = 0;
var lines = std.mem.tokenizeAny(u8, text, "\r\n");
while (lines.next()) |line| {
var cols = std.mem.splitScalar(u8, line, ',');
const util = std.fmt.parseFloat(f64, std.mem.trim(u8, cols.next() orelse continue, " ")) catch continue;
const mib = std.fmt.parseInt(u64, std.mem.trim(u8, cols.next() orelse continue, " "), 10) catch continue;
best = if (best) |b| @max(b, util) else util;
mem += mib * 1024 * 1024;
}
return .{ .percent = best orelse return null, .memory_bytes = mem };
}
// -- collection ------------------------------------------------------------------------
fn runCapture(gpa: Allocator, io: Io, argv: []const []const u8) ?[]u8 {
const res = std.process.run(gpa, io, .{ .argv = argv }) catch return null;
defer gpa.free(res.stderr);
const ok = switch (res.term) {
.exited => |c| c == 0,
else => false,
};
if (!ok) {
gpa.free(res.stdout);
return null;
}
return res.stdout;
}
/// Total size in bytes of all regular files under `dir`.
pub fn dirSize(gpa: Allocator, io: Io, dir: Dir) !u64 {
var walker = try dir.walk(gpa);
defer walker.deinit();
var total: u64 = 0;
while (try walker.next(io)) |entry| {
if (entry.kind != .file) continue;
const st = entry.dir.statFile(io, entry.basename, .{}) catch continue;
total += st.size;
}
return total;
}
/// Samples process `pid` (0 or a dead pid reads as zero CPU/memory) and the job's `work/` size.
pub fn collect(gpa: Allocator, io: Io, pid: i64, job_dir: Dir) Sample {
var s: Sample = .{ .at = timestamp.now(io) };
if (pid > 0 and proc.isAlive(pid)) {
var buf: [24]u8 = undefined;
const pid_str = std.fmt.bufPrint(&buf, "{d}", .{pid}) catch unreachable;
if (runCapture(gpa, io, &.{ "ps", "-p", pid_str, "-o", "%cpu=", "-o", "rss=" })) |out| {
defer gpa.free(out);
if (parsePs(out)) |r| {
s.cpu_percent = r.cpu_percent;
s.memory_bytes = r.rss_bytes;
}
}
if (runCapture(gpa, io, &.{ "nvidia-smi", "--query-gpu=utilization.gpu,memory.used", "--format=csv,noheader,nounits" })) |out| {
defer gpa.free(out);
if (parseNvidiaSmi(out)) |g| {
s.gpu_percent = g.percent;
s.gpu_memory_bytes = g.memory_bytes;
}
}
}
if (job_dir.openDir(io, "work", .{ .iterate = true })) |work_const| {
var work = work_const;
defer work.close(io);
s.disk_bytes = dirSize(gpa, io, work) catch 0;
} else |_| {}
return s;
}
// -- csv -------------------------------------------------------------------------------
pub fn writeCsvRow(w: *Io.Writer, s: Sample) Io.Writer.Error!void {
var tbuf: [timestamp.max_len]u8 = undefined;
try w.print("{s},{d:.2},{d},{d},", .{ timestamp.format(&tbuf, s.at), s.cpu_percent, s.memory_bytes, s.disk_bytes });
if (s.gpu_percent) |g| try w.print("{d:.2}", .{g});
try w.writeByte(',');
if (s.gpu_memory_bytes) |m| try w.print("{d}", .{m});
}
/// Appends a sample to `logs/usage.csv`, writing the header first when the file is new.
pub fn append(gpa: Allocator, io: Io, job_dir: Dir, s: Sample) !void {
var f = try proc.openAppend(io, job_dir, csv_file);
defer f.close(io);
var aw: Io.Writer.Allocating = .init(gpa);
defer aw.deinit();
if ((try f.length(io)) == 0) try aw.writer.print("{s}\n", .{csv_header});
try writeCsvRow(&aw.writer, s);
try aw.writer.writeByte('\n');
try f.writeStreamingAll(io, aw.written());
}
/// Parses the CSV (header optional) into samples; malformed rows are skipped.
pub fn parseCsv(arena: Allocator, text: []const u8) Allocator.Error![]Sample {
var list: std.ArrayList(Sample) = .empty;
var lines = std.mem.tokenizeAny(u8, text, "\r\n");
while (lines.next()) |line| {
if (std.mem.startsWith(u8, line, "timestamp")) continue;
var cols = std.mem.splitScalar(u8, line, ',');
const at = timestamp.parse(cols.next() orelse continue) catch continue;
const cpu = std.fmt.parseFloat(f64, cols.next() orelse continue) catch continue;
const mem = std.fmt.parseInt(u64, cols.next() orelse continue, 10) catch continue;
const disk = std.fmt.parseInt(u64, cols.next() orelse continue, 10) catch continue;
const gpu_s = cols.next() orelse "";
const gpu_m = cols.next() orelse "";
try list.append(arena, .{
.at = at,
.cpu_percent = cpu,
.memory_bytes = mem,
.disk_bytes = disk,
.gpu_percent = std.fmt.parseFloat(f64, gpu_s) catch null,
.gpu_memory_bytes = std.fmt.parseInt(u64, gpu_m, 10) catch null,
});
}
return list.toOwnedSlice(arena);
}
pub const Stat = struct { avg: f64, max: f64, min: f64 };
pub const Summary = struct {
sample_count: usize,
cpu: Stat,
memory: Stat,
disk_max: u64,
gpu: ?Stat = null,
gpu_memory: ?Stat = null,
};
fn stat(values: []const f64) Stat {
var sum: f64 = 0;
var mx = values[0];
var mn = values[0];
for (values) |v| {
sum += v;
mx = @max(mx, v);
mn = @min(mn, v);
}
return .{ .avg = sum / @as(f64, @floatFromInt(values.len)), .max = mx, .min = mn };
}
/// Summary over the samples, or null when there are none.
pub fn summarize(arena: Allocator, samples: []const Sample) Allocator.Error!?Summary {
if (samples.len == 0) return null;
const cpu = try arena.alloc(f64, samples.len);
const mem = try arena.alloc(f64, samples.len);
var gpu: std.ArrayList(f64) = .empty;
var gmem: std.ArrayList(f64) = .empty;
var disk_max: u64 = 0;
for (samples, cpu, mem) |s, *c, *m| {
c.* = s.cpu_percent;
m.* = @floatFromInt(s.memory_bytes);
disk_max = @max(disk_max, s.disk_bytes);
if (s.gpu_percent) |g| try gpu.append(arena, g);
if (s.gpu_memory_bytes) |g| try gmem.append(arena, @floatFromInt(g));
}
return .{
.sample_count = samples.len,
.cpu = stat(cpu),
.memory = stat(mem),
.disk_max = disk_max,
.gpu = if (gpu.items.len > 0) stat(gpu.items) else null,
.gpu_memory = if (gmem.items.len > 0) stat(gmem.items) else null,
};
}
// -- tests -----------------------------------------------------------------------------
test "parsePs" {
const r = parsePs(" 12.5 5988\n").?;
try std.testing.expectEqual(@as(f64, 12.5), r.cpu_percent);
try std.testing.expectEqual(@as(u64, 5988 * 1024), r.rss_bytes);
try std.testing.expect(parsePs("") == null);
try std.testing.expect(parsePs("abc def") == null);
try std.testing.expect(parsePs("1.0") == null);
}
test "parseNvidiaSmi takes max utilisation and summed memory" {
const g = parseNvidiaSmi("35, 1024\n80, 2048\n").?;
try std.testing.expectEqual(@as(f64, 80), g.percent);
try std.testing.expectEqual(@as(u64, 3072 * 1024 * 1024), g.memory_bytes);
try std.testing.expect(parseNvidiaSmi("") == null);
try std.testing.expect(parseNvidiaSmi("No devices were found") == null);
}
test "csv rows round-trip, with and without GPU data" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const t: Instant = 1_769_046_526 * std.time.ns_per_s;
var aw: Io.Writer.Allocating = .init(a);
try aw.writer.print("{s}\n", .{csv_header});
try writeCsvRow(&aw.writer, .{ .at = t, .cpu_percent = 12.345, .memory_bytes = 1000, .disk_bytes = 2000 });
try aw.writer.writeByte('\n');
try writeCsvRow(&aw.writer, .{ .at = t + std.time.ns_per_s, .cpu_percent = 1, .memory_bytes = 5, .disk_bytes = 6, .gpu_percent = 50, .gpu_memory_bytes = 99 });
try aw.writer.writeByte('\n');
try std.testing.expectEqualStrings(
\\timestamp,cpu_percent,memory_bytes,disk_bytes,gpu_percent,gpu_memory_bytes
\\2026-01-22T01:48:46Z,12.35,1000,2000,,
\\2026-01-22T01:48:47Z,1.00,5,6,50.00,99
\\
, aw.written());
const rows = try parseCsv(a, aw.written());
try std.testing.expectEqual(@as(usize, 2), rows.len);
try std.testing.expect(rows[0].gpu_percent == null);
try std.testing.expectEqual(@as(u64, 99), rows[1].gpu_memory_bytes.?);
try std.testing.expectEqual(t, rows[0].at);
}
test "summarize" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
try std.testing.expect((try summarize(arena.allocator(), &.{})) == null);
const s = (try summarize(arena.allocator(), &.{
.{ .at = 0, .cpu_percent = 10, .memory_bytes = 100, .disk_bytes = 5 },
.{ .at = 1, .cpu_percent = 30, .memory_bytes = 300, .disk_bytes = 9, .gpu_percent = 40 },
})).?;
try std.testing.expectEqual(@as(usize, 2), s.sample_count);
try std.testing.expectEqual(@as(f64, 20), s.cpu.avg);
try std.testing.expectEqual(@as(f64, 300), s.memory.max);
try std.testing.expectEqual(@as(f64, 100), s.memory.min);
try std.testing.expectEqual(@as(u64, 9), s.disk_max);
try std.testing.expectEqual(@as(f64, 40), s.gpu.?.avg);
try std.testing.expect(s.gpu_memory == null);
}
test "collect measures a live process and the work dir; append writes one header" {
const io = std.testing.io;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.createDirPath(io, "work/output");
try tmp.dir.createDirPath(io, "logs");
try tmp.dir.writeFile(io, .{ .sub_path = "work/output/a.bin", .data = "0123456789" });
try tmp.dir.writeFile(io, .{ .sub_path = "work/b.bin", .data = "abc" });
var child = try std.process.spawn(io, .{ .argv = &.{ "sleep", "5" }, .stdin = .ignore, .stdout = .ignore, .stderr = .ignore });
defer child.kill(io);
const s = collect(std.testing.allocator, io, child.id.?, tmp.dir);
try std.testing.expectEqual(@as(u64, 13), s.disk_bytes);
try std.testing.expect(s.memory_bytes > 0);
try append(std.testing.allocator, io, tmp.dir, s);
try append(std.testing.allocator, io, tmp.dir, s);
const text = try tmp.dir.readFileAlloc(io, csv_file, std.testing.allocator, .limited(4096));
defer std.testing.allocator.free(text);
var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, text, "\n"), '\n');
try std.testing.expectEqualStrings(csv_header, lines.next().?);
var rows: usize = 0;
while (lines.next()) |_| rows += 1;
try std.testing.expectEqual(@as(usize, 2), rows);
}
test "collect on a dead pid yields zero CPU and memory" {
const io = std.testing.io;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const s = collect(std.testing.allocator, io, 999_999_999, tmp.dir);
try std.testing.expectEqual(@as(f64, 0), s.cpu_percent);
try std.testing.expectEqual(@as(u64, 0), s.memory_bytes);
try std.testing.expectEqual(@as(u64, 0), s.disk_bytes);
}