// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! What one pass of the scheduler should do, decided without doing any of it. //! //! Everything the decision needs -- the droplets DigitalOcean listed, the //! daemon's own record of them, each forge's jobs and runners, the clock -- //! goes in, and a list of droplets to destroy, runners to delete and work to //! provision comes out. Nothing here //! touches the network, so every case the reaper has to get right is a unit //! test rather than something found out in production. const std = @import("std"); const Allocator = std.mem.Allocator; const Config = @import("Config.zig"); const DigitalOcean = @import("DigitalOcean.zig"); const Forgejo = @import("Forgejo.zig"); const tags = @import("tags.zig"); const RunStore = @import("RunStore.zig"); /// A job the forge listed, with the tier its label asked for and when this /// daemon first saw it waiting. The forge's API gives no timestamp of its /// own, and the shared queue is ordered by this. pub const Job = struct { job: Forgejo.Job, tier: []const u8, first_seen: i64, /// Waiting out a backoff after its droplet could not be created: still /// a job the forge lists, so a droplet may still be for it, but not one /// to provision this pass. held: bool = false, }; pub const ForgeView = struct { name: []const u8, /// Whether `runners` and `jobs` were fetched on this pass. A forge not /// polled this pass, or whose poll failed, is judged only by the lifetime /// cap: deciding that a runner is gone or a job cancelled on data that /// may be a minute old is how a droplet gets destroyed mid-job. fresh: bool, runners: []const Forgejo.Runner = &.{}, /// Every job for every tier's label, whatever its status. jobs: []const Job = &.{}, }; /// A Radicle run, as much of it as scheduling needs. pub const RadicleRun = struct { id: u64, tier: []const u8, state: RunStore.State, created_at: i64, started_at: ?i64 = null, heartbeat_at: ?i64 = null, droplet_id: ?u64 = null, /// As for `Job.held`. held: bool = false, }; pub const RadicleView = struct { /// Waiting for a droplet, oldest first. queued: []const RadicleRun, /// With a droplet, or about to have one. active: []const RadicleRun, }; pub const Input = struct { /// Seconds since the Unix epoch. now: i64, config: Config, known: tags.Known, droplets: []const DigitalOcean.Droplet, /// The daemon's record of every droplet not yet gone. rows: []const RunStore.Droplet = &.{}, forges: []const ForgeView, radicle: ?RadicleView = null, /// When work last started in each tier, in the order of `config.tiers`, /// or null for never. Empty means none known. What keeps a tier warm. activity: []const ?i64 = &.{}, /// The id of the snapshot a new droplet would boot, if known. A warm /// droplet booted from any other has been superseded. newest_image: ?[]const u8 = null, }; pub const Reason = enum { /// Forgejo deleted the ephemeral runner, which it does when the one job /// is done. job_finished, /// The job was cancelled before this droplet's runner could take it. job_gone_before_it_started, exceeded_lifetime, /// The Radicle run is over: the droplet reported, or the run was failed. run_finished, /// The droplet never fetched its job. never_booted, /// The droplet stopped sending its log and heartbeats. heartbeat_lost, /// The droplet's agent said its work is over. done, /// The droplet carries a row id the database has no record of: the /// database was lost or replaced, and nothing can say what it is for. unrecorded, /// A warm droplet in a tier no longer warm, or beyond its `warm` count. pool_idle, /// A warm droplet booted from a snapshot that has since been replaced. pool_stale, pub fn describe(r: Reason) []const u8 { return switch (r) { .job_finished => "job finished", .job_gone_before_it_started => "job gone before it started", .exceeded_lifetime => "exceeded lifetime", .run_finished => "run finished", .never_booted => "the droplet never fetched its job", .heartbeat_lost => "the droplet stopped sending heartbeats", .done => "its work is done", .unrecorded => "no record of it", .pool_idle => "warm and no longer wanted", .pool_stale => "warm, but booted from an old snapshot", }; } }; pub const Destroy = struct { droplet: u64, name: []const u8, reason: Reason, /// The runner to delete along with it, when Forgejo will not: an /// abandoned or expired droplet's runner is still registered. runner: ?struct { forge: usize, id: u64 } = null, /// The Radicle run to fail along with it, for the same reason. fail_run: ?u64 = null, /// Its row in the droplet database, to be marked gone. row: ?u64 = null, }; /// A droplet the database has but DigitalOcean no longer lists: destroyed by /// hand, or never made because the daemon stopped partway through creating /// it. Its row is marked gone, and its runner deleted if one is left. pub const Forget = struct { row: u64, runner: ?struct { forge: usize, id: u64 } = null, }; pub const Provision = union(enum) { forgejo: struct { forge: usize, job: Job }, radicle: RadicleRun, pub fn tier(p: Provision) []const u8 { return switch (p) { .forgejo => |f| f.job.tier, .radicle => |r| r.tier, }; } fn firstSeen(p: Provision) i64 { return switch (p) { .forgejo => |f| f.job.first_seen, .radicle => |r| r.created_at, }; } }; /// A Radicle run to fail that has no droplet to destroy with it. pub const Fail = struct { run: u64, reason: []const u8, }; /// Work handed to a warm droplet rather than a new one. pub const Assign = struct { row: u64, /// DigitalOcean's id of the droplet. droplet: u64, item: Provision, }; pub const Plan = struct { destroy: []const Destroy, assign: []const Assign = &.{}, /// How many warm droplets to create in each tier, in the order of /// `config.tiers`. warm: []const u32 = &.{}, forget: []const Forget, provision: []const Provision, fail: []const Fail, /// Droplets the listing returned that are not ours. They are never /// touched, but one turning up means the tag filter has gone wrong, which /// is worth shouting about. refused: []const DigitalOcean.Droplet, /// Droplets standing in each tier after the destroys, before provisioning, /// in the order of `config.tiers`. standing: []const u32, /// Jobs left waiting because their tier was full. deferred: usize, }; pub fn decide(arena: Allocator, in: Input) !Plan { var destroy: std.ArrayList(Destroy) = .empty; var provision: std.ArrayList(Provision) = .empty; var refused: std.ArrayList(DigitalOcean.Droplet) = .empty; var fail: std.ArrayList(Fail) = .empty; var forget: std.ArrayList(Forget) = .empty; // Radicle runs whose droplet the listing showed, so that one whose droplet // has gone can be told apart. var seen_runs: std.AutoHashMapUnmanaged(u64, void) = .empty; // Rows whose droplet the listing showed, likewise. var seen_rows: std.AutoHashMapUnmanaged(u64, void) = .empty; // Rows whose droplet is destroyed this pass. var destroyed_rows: std.AutoHashMapUnmanaged(u64, void) = .empty; // Warm droplets with no work, standing and fit to be given some. var idle: std.ArrayList(Idle) = .empty; const standing = try arena.alloc(u32, in.config.tiers.len); @memset(standing, 0); // Job tags on droplets still standing, per forge, so a job that already // has a droplet is not given a second. const claimed = try arena.alloc(std.StringHashMapUnmanaged(void), in.forges.len); for (claimed) |*c| c.* = .empty; for (in.droplets) |droplet| { const owner = tags.owner(in.known, droplet.name, droplet.tags) orelse { try refused.append(arena, droplet); continue; }; const age = in.now - @as(i64, @intCast(@divFloor(droplet.created_at.timestamp, std.time.ns_per_s))); const expired = age > in.config.max_lifetime_seconds; const forge_index = forgeIndex(in.forges, owner.source); var verdict: ?Destroy = null; switch (owner.work) { .droplet => |row_id| { const row = findRow(in.rows, row_id) orelse { // Old enough that its row cannot merely be in flight. if (age > in.config.grace_seconds) verdict = .{ .droplet = droplet.id, .name = droplet.name, .reason = .unrecorded }; if (verdict) |v| { try destroy.append(arena, v); continue; } if (tierIndex(in.config.tiers, owner.tier)) |t| standing[t] += 1; continue; }; try seen_rows.put(arena, row_id, {}); if (row.binding == null) { verdict = judgeIdle(in, droplet, row, age, expired); if (verdict == null) if (tierIndex(in.config.tiers, row.tier)) |t| if (row.state == .booting) { try idle.append(arena, .{ .row = row, .droplet = droplet, .tier = t }); }; } else { verdict = try judgeRow(arena, in, droplet, row, age, expired, &seen_runs); } }, .forgejo_runner => |runner_id| { const view: ?ForgeView = if (forge_index) |i| in.forges[i] else null; const runner = if (view) |v| findRunner(v.runners, runner_id) else null; const fresh = view != null and view.?.fresh; // Forgejo deletes an ephemeral runner once its job finishes, // so a missing runner means the work is done. The runner is // registered before the droplet is created, so it is present // throughout boot and setup; the grace period only covers a // just-created runner not yet showing up in the listing. const finished = fresh and runner == null and age > in.config.grace_seconds; // The job went away before this droplet's runner could take // it -- superseded by a newer push, most often. One-job // runners serve only the handle they were made for, so the // runner sits registered and idle, the check above never // fires, and the droplet would hold a slot in its tier until // the lifetime cap while other jobs queue behind it. Idle is // what makes this safe: a connected runner whose job was still // waiting would have taken it within seconds. A runner still // booting reads offline, not idle, and is left to the cap if // it never comes up. const abandoned = fresh and !finished and runner != null and std.mem.eql(u8, runner.?.status, "idle") and !anyPending(view.?.jobs, droplet.tags) and age > in.config.grace_seconds; const reason: ?Reason = if (finished) .job_finished else if (abandoned) .job_gone_before_it_started else if (expired) .exceeded_lifetime else null; if (reason) |r| { verdict = .{ .droplet = droplet.id, .name = droplet.name, .reason = r }; // Only a runner known to be registered is deleted, and // only when Forgejo will not do it itself. if (r != .job_finished and fresh and runner != null) verdict.?.runner = .{ .forge = forge_index.?, .id = runner_id }; } }, .radicle_run => |run_id| { try seen_runs.put(arena, run_id, {}); const reason: ?Reason = if (in.radicle) |rv| reason: { // A run that is not active is finished, or was never ours: // either way nothing is waiting on this droplet. const run = findRun(rv.active, run_id) orelse break :reason .run_finished; if (expired) break :reason .exceeded_lifetime; const since_start = in.now - (run.started_at orelse run.created_at); if (run.state == .provisioning and since_start > in.config.boot_timeout_seconds) break :reason .never_booted; const since_heard = in.now - (run.heartbeat_at orelse run.started_at orelse run.created_at); if (run.state == .running and since_heard > in.config.heartbeat_timeout_seconds) break :reason .heartbeat_lost; break :reason null; } else if (expired) .exceeded_lifetime else null; if (reason) |r| verdict = .{ .droplet = droplet.id, .name = droplet.name, .reason = r, .fail_run = if (r == .run_finished) null else run_id, }; }, } if (verdict) |v| { try destroy.append(arena, v); if (v.row) |r| try destroyed_rows.put(arena, r, {}); continue; } if (tierIndex(in.config.tiers, owner.tier)) |t| standing[t] += 1; if (forge_index) |i| for (droplet.tags) |tag| { if (tags.isJobTag(tag)) try claimed[i].put(arena, tag, {}); }; } // Rows whose droplet the listing did not show. One just created may not be // listed yet, and still holds its slot and its job; one older than that // is gone. A row still `creating` never got a droplet id: the daemon // stopped between making the row and hearing back from DigitalOcean, and // a droplet made in that window would have been listed by now. for (in.rows) |row| { if (seen_rows.contains(row.id)) continue; const since = in.now - row.created_at; const lost = if (row.do_id == null) since > 600 else since > in.config.grace_seconds; if (lost) { var item: Forget = .{ .row = row.id }; if (row.binding) |binding| switch (binding) { .forgejo => |f| if (forgeIndex(in.forges, f.forge)) |i| { const view = in.forges[i]; if (view.fresh and findRunner(view.runners, f.runner_id) != null) item.runner = .{ .forge = i, .id = f.runner_id }; }, .radicle => {}, }; try forget.append(arena, item); try destroyed_rows.put(arena, row.id, {}); } else if (tierIndex(in.config.tiers, row.tier)) |t| { standing[t] += 1; } } // Jobs with a droplet already, from the database: the listing is not // enough, since a droplet created last pass may not be in it yet. for (in.rows) |row| { if (destroyed_rows.contains(row.id)) continue; if (row.binding) |binding| switch (binding) { .forgejo => |f| if (forgeIndex(in.forges, f.forge)) |i| { const tag = tags.jobTag(f.handle); try claimed[i].put(arena, try arena.dupe(u8, &tag), {}); }, .radicle => {}, }; } // A run that was given a droplet which is no longer there: destroyed by // hand, or by something that is not this daemon. The grace period covers // a droplet so new the listing does not have it yet. if (in.radicle) |rv| for (rv.active) |run| { if (run.droplet_id == null or seen_runs.contains(run.id)) continue; if (in.now - (run.started_at orelse run.created_at) <= in.config.grace_seconds) continue; try fail.append(arena, .{ .run = run.id, .reason = "the droplet disappeared" }); }; // The shared queue: every waiting job from every forge polled this pass, // and every queued Radicle run, oldest first. var queue: std.ArrayList(Provision) = .empty; for (in.forges, 0..) |forge, i| { if (!forge.fresh) continue; for (forge.jobs) |job| { if (!std.mem.eql(u8, job.job.status, "waiting")) continue; if (tierIndex(in.config.tiers, job.tier) == null) continue; const tag = tags.jobTag(job.job.handle); if (claimed[i].contains(&tag)) continue; if (job.held) continue; try queue.append(arena, .{ .forgejo = .{ .forge = i, .job = job } }); } } if (in.radicle) |rv| for (rv.queued) |run| { if (tierIndex(in.config.tiers, run.tier) == null) { try fail.append(arena, .{ .run = run.id, .reason = "its tier no longer exists" }); continue; } if (run.held) continue; try queue.append(arena, .{ .radicle = run }); }; std.mem.sort(Provision, queue.items, {}, older); const room = try arena.alloc(u32, in.config.tiers.len); for (in.config.tiers, standing, room) |tier, s, *r| r.* = tier.max -| s; // A warm droplet already booted is the nearest to ready, then the one // that has been booting longest. std.mem.sort(Idle, idle.items, {}, Idle.readier); var assign: std.ArrayList(Assign) = .empty; const placed = try arena.alloc(bool, in.config.tiers.len); @memset(placed, false); var deferred: usize = 0; for (queue.items) |item| { const t = tierIndex(in.config.tiers, item.tier()).?; placed[t] = true; // Work goes to a warm droplet before a new one, and needs no room: // the warm droplet already has its slot. if (takeIdle(&idle, t)) |w| { try assign.append(arena, .{ .row = w.row.id, .droplet = w.droplet.id, .item = item }); continue; } if (room[t] == 0) { deferred += 1; continue; } room[t] -= 1; try provision.append(arena, item); } // Then the pool: a tier that has had work within the linger keeps `warm` // idle droplets, in what room is left once queued work has been placed. // Warm droplets left over -- the tier has gone quiet, or has more than // it keeps -- are destroyed. const warm = try arena.alloc(u32, in.config.tiers.len); for (in.config.tiers, 0..) |tier, t| { const last: ?i64 = if (t < in.activity.len) in.activity[t] else null; const active = placed[t] or (last != null and in.now - last.? <= in.config.warm_linger_seconds); const keep: u32 = if (active) tier.warm else 0; var have: u32 = 0; for (idle.items) |w| { if (w.tier != t) continue; if (have < keep) { have += 1; continue; } try destroy.append(arena, .{ .droplet = w.droplet.id, .name = w.droplet.name, .reason = .pool_idle, .row = w.row.id }); } warm[t] = @min(keep - have, room[t]); room[t] -= warm[t]; } return .{ .destroy = destroy.items, .assign = assign.items, .warm = warm, .forget = forget.items, .provision = provision.items, .fail = fail.items, .refused = refused.items, .standing = standing, .deferred = deferred, }; } const Idle = struct { row: RunStore.Droplet, droplet: DigitalOcean.Droplet, tier: usize, fn readier(_: void, a: Idle, b: Idle) bool { const a_up = a.row.agent_at != null; const b_up = b.row.agent_at != null; if (a_up != b_up) return a_up; return a.row.created_at < b.row.created_at; } }; /// Takes the readiest warm droplet in tier `t`, if there is one. fn takeIdle(idle: *std.ArrayList(Idle), t: usize) ?Idle { for (idle.items, 0..) |w, i| if (w.tier == t) return idle.orderedRemove(i); return null; } /// What to do with a warm droplet that has no work, before any is handed /// out. Whether its tier still wants it is decided after that. fn judgeIdle(in: Input, droplet: DigitalOcean.Droplet, row: RunStore.Droplet, age: i64, expired: bool) ?Destroy { const reason: Reason = if (expired) .exceeded_lifetime else if (row.agent_at == null and age > in.config.boot_timeout_seconds) .never_booted else if (row.agent_at != null and in.now - (row.heard_at orelse row.agent_at.?) > in.config.heartbeat_timeout_seconds) .heartbeat_lost else if (in.newest_image != null and row.image != null and !std.mem.eql(u8, row.image.?, in.newest_image.?)) .pool_stale else return null; return .{ .droplet = droplet.id, .name = droplet.name, .reason = reason, .row = row.id }; } /// What to do with a droplet the database knows about. fn judgeRow( arena: Allocator, in: Input, droplet: DigitalOcean.Droplet, row: RunStore.Droplet, age: i64, expired: bool, seen_runs: *std.AutoHashMapUnmanaged(u64, void), ) !?Destroy { var verdict: Destroy = .{ .droplet = droplet.id, .name = droplet.name, .reason = undefined, .row = row.id }; const booted = row.agent_at != null; switch (row.binding.?) { .forgejo => |f| { const forge_index = forgeIndex(in.forges, f.forge); const view: ?ForgeView = if (forge_index) |i| in.forges[i] else null; const fresh = view != null and view.?.fresh; const runner = if (view) |v| findRunner(v.runners, f.runner_id) else null; // The runner is registered before the droplet is created, so it // is listed throughout boot and setup. Forgejo deletes it once // its one job is over, which makes a missing runner the sign the // work is done, should the agent's own word never arrive; the // grace period only covers a runner too new to be listed. const finished = fresh and runner == null and age > in.config.grace_seconds; // The job went away -- cancelled, or superseded by a newer push -- // or ended without the runner being deleted yet. Either way // nothing is left for this droplet to do, whether or not it has // booted: a one-job runner serves only the handle it was made for. const gone = fresh and !pendingHandle(view.?.jobs, f.handle) and age > in.config.grace_seconds; verdict.reason = if (row.state == .done) .done else if (finished) .job_finished else if (gone) .job_gone_before_it_started else if (!booted and age > in.config.boot_timeout_seconds) .never_booted else if (expired) .exceeded_lifetime else return null; // Forgejo deletes the runner of a job that ran; one that is still // registered is deleted here, and only one known to be. if (fresh and runner != null) verdict.runner = .{ .forge = forge_index.?, .id = f.runner_id }; }, .radicle => |run_id| { try seen_runs.put(arena, run_id, {}); const rv = in.radicle orelse { if (row.state == .done) verdict.reason = .done else if (expired) verdict.reason = .exceeded_lifetime else return null; return verdict; }; // A run that is not active is finished, or was never ours: either // way nothing is waiting on this droplet. const run = findRun(rv.active, run_id) orelse { verdict.reason = if (row.state == .done) .done else .run_finished; return verdict; }; const since_heard = in.now - (run.heartbeat_at orelse run.started_at orelse run.created_at); verdict.reason = if (row.state == .done) .done else if (expired) .exceeded_lifetime else if (!booted and age > in.config.boot_timeout_seconds) .never_booted else if (run.state == .running and since_heard > in.config.heartbeat_timeout_seconds) .heartbeat_lost else return null; // The run is failed along with its droplet unless the droplet was // done, in which case it reported; if it somehow did not, the // run has no droplet left and is failed as having lost it. if (verdict.reason != .done) verdict.fail_run = run_id; }, } return verdict; } fn findRow(rows: []const RunStore.Droplet, id: u64) ?RunStore.Droplet { for (rows) |r| if (r.id == id) return r; return null; } /// Whether the job with `handle` is still waiting or running. fn pendingHandle(jobs: []const Job, handle: []const u8) bool { for (jobs) |job| { if (!std.mem.eql(u8, job.job.handle, handle)) continue; const status = job.job.status; if (std.mem.eql(u8, status, "waiting") or std.mem.eql(u8, status, "running")) return true; } return false; } fn older(_: void, a: Provision, b: Provision) bool { if (a.firstSeen() != b.firstSeen()) return a.firstSeen() < b.firstSeen(); // Ties: Forgejo before Radicle, then forge by forge, then by id. const rank = struct { fn f(p: Provision) struct { u8, usize, u64 } { return switch (p) { .forgejo => |j| .{ 0, j.forge, j.job.job.id }, .radicle => |r| .{ 1, 0, r.id }, }; } }.f; const x = rank(a); const y = rank(b); if (x[0] != y[0]) return x[0] < y[0]; if (x[1] != y[1]) return x[1] < y[1]; return x[2] < y[2]; } fn findRun(runs: []const RadicleRun, id: u64) ?RadicleRun { for (runs) |r| if (r.id == id) return r; return null; } fn forgeIndex(forges: []const ForgeView, name: []const u8) ?usize { for (forges, 0..) |f, i| if (std.mem.eql(u8, f.name, name)) return i; return null; } fn tierIndex(tiers: []const Config.Tier, name: []const u8) ?usize { for (tiers, 0..) |t, i| if (std.mem.eql(u8, t.name, name)) return i; return null; } fn findRunner(runners: []const Forgejo.Runner, id: u64) ?Forgejo.Runner { for (runners) |r| if (r.id == id) return r; return null; } /// Whether any of the droplet's job tags names a job that is still waiting or /// running. fn anyPending(jobs: []const Job, droplet_tags: []const []const u8) bool { for (droplet_tags) |tag| { if (!tags.isJobTag(tag)) continue; for (jobs) |job| { const status = job.job.status; if (!std.mem.eql(u8, status, "waiting") and !std.mem.eql(u8, status, "running")) continue; const pending = tags.jobTag(job.job.handle); if (std.mem.eql(u8, tag, &pending)) return true; } } return false; } // -- tests ------------------------------------------------------------------- const testing = std.testing; const datetime = @import("datetime"); const test_config: Config = .{ .region = "nyc3", .base_image = "ubuntu-26-04-x64", .snapshot_prefix = "forgejo-runner", .runner_image = "image", .runner_binary_url = "https://example.com/runner", .runner_binary_sha256 = "0" ** 64, .public_url = "https://ci.example.org", .agent = "/bin/ci-agent", .max_lifetime_seconds = 7200, .grace_seconds = 120, .tiers = &.{ .{ .name = "s", .size = "s-2vcpu-4gb", .max = 2 }, .{ .name = "l", .size = "s-8vcpu-16gb", .max = 1 }, }, .forges = &.{ .{ .name = "ocjtech", .url = "https://git.jcollie.dev", .credential = "a" }, .{ .name = "codeberg", .url = "https://codeberg.org", .credential = "b" }, }, }; const test_known: tags.Known = .{ .sources = &.{ "ocjtech", "codeberg", "radicle" }, .tiers = &.{ "s", "l" }, }; const now: i64 = 1_000_000; /// A Forgejo droplet for runner `id`, created `age` seconds ago, for the job /// with handle `handle`. fn fjDroplet(comptime forge: []const u8, comptime tier: []const u8, comptime id: u64, age: i64, comptime handle: []const u8) DigitalOcean.Droplet { const job_tag = comptime blk: { @setEvalBranchQuota(100_000); break :blk tags.jobTag(handle); }; return .{ .id = 1000 + id, .name = std.fmt.comptimePrint("fj-runner-{d}", .{id}), .created_at = .{ .timestamp = @as(i128, now - age) * std.time.ns_per_s }, .tags = &.{ tags.marker, "ci-" ++ forge ++ "-" ++ tier, &job_tag, std.fmt.comptimePrint("fjrunner-{d}", .{id}) }, }; } fn testJob(id: u64, handle: []const u8, status: []const u8, tier: []const u8) Job { return .{ .job = .{ .id = id, .handle = handle, .status = status }, .tier = tier, .first_seen = @intCast(id) }; } fn runForgejo(arena: Allocator, droplets: []const DigitalOcean.Droplet, forges: []const ForgeView) !Plan { return decide(arena, .{ .now = now, .config = test_config, .known = test_known, .droplets = droplets, .forges = forges }); } fn expectOnlyDestroy(plan: Plan, droplet: u64, reason: Reason, delete_runner: bool) !void { try testing.expectEqual(@as(usize, 1), plan.destroy.len); try testing.expectEqual(droplet, plan.destroy[0].droplet); try testing.expectEqual(reason, plan.destroy[0].reason); try testing.expectEqual(delete_runner, plan.destroy[0].runner != null); } // The nine cases the Python reaper was checked against when the "job gone // before it started" reason was added, one test each. test "running: left alone" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const plan = try runForgejo(arena.allocator(), &.{fjDroplet("ocjtech", "s", 7, 600, "h7")}, &.{ .{ .name = "ocjtech", .fresh = true, .runners = &.{.{ .id = 7, .status = "active" }}, .jobs = &.{testJob(1, "h7", "running", "s")} }, }); try testing.expectEqual(@as(usize, 0), plan.destroy.len); try testing.expectEqual(@as(u32, 1), plan.standing[0]); } test "waiting, runner still booting: left alone" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const plan = try runForgejo(arena.allocator(), &.{fjDroplet("ocjtech", "s", 7, 600, "h7")}, &.{ .{ .name = "ocjtech", .fresh = true, .runners = &.{.{ .id = 7, .status = "offline" }}, .jobs = &.{testJob(1, "h7", "waiting", "s")} }, }); try testing.expectEqual(@as(usize, 0), plan.destroy.len); // and the job is not given a second droplet try testing.expectEqual(@as(usize, 0), plan.provision.len); } test "waiting, runner idle: left alone" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const plan = try runForgejo(arena.allocator(), &.{fjDroplet("ocjtech", "s", 7, 600, "h7")}, &.{ .{ .name = "ocjtech", .fresh = true, .runners = &.{.{ .id = 7, .status = "idle" }}, .jobs = &.{testJob(1, "h7", "waiting", "s")} }, }); try testing.expectEqual(@as(usize, 0), plan.destroy.len); } test "cancelled: destroyed, runner deleted" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const plan = try runForgejo(arena.allocator(), &.{fjDroplet("ocjtech", "s", 7, 600, "h7")}, &.{ .{ .name = "ocjtech", .fresh = true, .runners = &.{.{ .id = 7, .status = "idle" }}, .jobs = &.{} }, }); try expectOnlyDestroy(plan, 1007, .job_gone_before_it_started, true); try testing.expectEqual(@as(u64, 7), plan.destroy[0].runner.?.id); } test "cancelled within grace: left alone" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const plan = try runForgejo(arena.allocator(), &.{fjDroplet("ocjtech", "s", 7, 60, "h7")}, &.{ .{ .name = "ocjtech", .fresh = true, .runners = &.{.{ .id = 7, .status = "idle" }}, .jobs = &.{} }, }); try testing.expectEqual(@as(usize, 0), plan.destroy.len); } test "cancelled, runner offline: left to the lifetime cap" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const plan = try runForgejo(arena.allocator(), &.{fjDroplet("ocjtech", "s", 7, 600, "h7")}, &.{ .{ .name = "ocjtech", .fresh = true, .runners = &.{.{ .id = 7, .status = "offline" }}, .jobs = &.{} }, }); try testing.expectEqual(@as(usize, 0), plan.destroy.len); } test "finished: destroyed, runner left to Forgejo" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const plan = try runForgejo(arena.allocator(), &.{fjDroplet("ocjtech", "s", 7, 600, "h7")}, &.{ .{ .name = "ocjtech", .fresh = true, .runners = &.{}, .jobs = &.{} }, }); try expectOnlyDestroy(plan, 1007, .job_finished, false); } test "expired: destroyed, runner deleted" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const plan = try runForgejo(arena.allocator(), &.{fjDroplet("ocjtech", "s", 7, 7201, "h7")}, &.{ .{ .name = "ocjtech", .fresh = true, .runners = &.{.{ .id = 7, .status = "active" }}, .jobs = &.{testJob(1, "h7", "running", "s")} }, }); try expectOnlyDestroy(plan, 1007, .exceeded_lifetime, true); } test "another job waiting while ours is gone: destroyed, and the other provisioned" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const plan = try runForgejo(arena.allocator(), &.{fjDroplet("ocjtech", "s", 7, 600, "h7")}, &.{ .{ .name = "ocjtech", .fresh = true, .runners = &.{.{ .id = 7, .status = "idle" }}, .jobs = &.{testJob(2, "h8", "waiting", "s")} }, }); try expectOnlyDestroy(plan, 1007, .job_gone_before_it_started, true); try testing.expectEqual(@as(usize, 1), plan.provision.len); try testing.expectEqualStrings("h8", plan.provision[0].forgejo.job.job.handle); } // And what is new with one daemon for every source. test "a forge not polled this pass is judged by the lifetime cap alone" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const droplets = [_]DigitalOcean.Droplet{ fjDroplet("codeberg", "s", 7, 600, "h7"), fjDroplet("codeberg", "s", 8, 7300, "h8"), }; const plan = try runForgejo(arena.allocator(), &droplets, &.{ .{ .name = "ocjtech", .fresh = true }, .{ .name = "codeberg", .fresh = false }, }); // expired, but whether its runner is still registered is not known, so // it is not deleted try expectOnlyDestroy(plan, 1008, .exceeded_lifetime, false); } test "the cap is shared across forges, oldest job first" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const plan = try runForgejo(arena.allocator(), &.{fjDroplet("codeberg", "s", 7, 600, "h7")}, &.{ .{ .name = "ocjtech", .fresh = true, .jobs = &.{ testJob(30, "late", "waiting", "s"), testJob(10, "early", "waiting", "s") } }, .{ .name = "codeberg", .fresh = true, .runners = &.{.{ .id = 7, .status = "active" }}, .jobs = &.{ testJob(1, "h7", "running", "s"), testJob(20, "middle", "waiting", "s") } }, }); // s has room for two and one is standing, so one more: the oldest try testing.expectEqual(@as(usize, 1), plan.provision.len); try testing.expectEqualStrings("early", plan.provision[0].forgejo.job.job.handle); try testing.expectEqual(@as(usize, 2), plan.deferred); } test "a full tier does not hold up another" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const plan = try runForgejo(arena.allocator(), &.{fjDroplet("ocjtech", "l", 7, 600, "h7")}, &.{ .{ .name = "ocjtech", .fresh = true, .runners = &.{.{ .id = 7, .status = "active" }}, .jobs = &.{ testJob(1, "h7", "running", "l"), testJob(2, "big", "waiting", "l"), testJob(3, "small", "waiting", "s"), } }, }); try testing.expectEqual(@as(usize, 1), plan.provision.len); try testing.expectEqualStrings("small", plan.provision[0].forgejo.job.job.handle); try testing.expectEqual(@as(usize, 1), plan.deferred); } test "a droplet destroyed this pass frees its slot" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const plan = try runForgejo(arena.allocator(), &.{fjDroplet("ocjtech", "l", 7, 600, "h7")}, &.{ .{ .name = "ocjtech", .fresh = true, .jobs = &.{testJob(2, "next", "waiting", "l")} }, }); try expectOnlyDestroy(plan, 1007, .job_finished, false); try testing.expectEqual(@as(usize, 1), plan.provision.len); } test "a droplet that is not ours is refused and never destroyed" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const host: DigitalOcean.Droplet = .{ .id = 1, .name = "cloud04", .created_at = .{ .timestamp = 0 }, .tags = &.{tags.marker}, }; const plan = try runForgejo(arena.allocator(), &.{host}, &.{.{ .name = "ocjtech", .fresh = true }}); try testing.expectEqual(@as(usize, 0), plan.destroy.len); try testing.expectEqual(@as(usize, 1), plan.refused.len); } test "a Radicle droplet is reaped at the lifetime cap" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const droplet: DigitalOcean.Droplet = .{ .id = 5, .name = "rad-run-3", .created_at = .{ .timestamp = @as(i128, now - 7300) * std.time.ns_per_s }, .tags = &.{ tags.marker, "ci-radicle-l", "radrun-3" }, }; const plan = try runForgejo(arena.allocator(), &.{droplet}, &.{}); try expectOnlyDestroy(plan, 5, .exceeded_lifetime, false); } comptime { _ = datetime; } test { std.testing.refAllDecls(@This()); } // Radicle runs. fn radDroplet(comptime id: u64, age: i64) DigitalOcean.Droplet { return .{ .id = 2000 + id, .name = std.fmt.comptimePrint("rad-run-{d}", .{id}), .created_at = .{ .timestamp = @as(i128, now - age) * std.time.ns_per_s }, .tags = &.{ tags.marker, "ci-radicle-s", std.fmt.comptimePrint("radrun-{d}", .{id}) }, }; } fn radicle(queued: []const RadicleRun, active: []const RadicleRun) RadicleView { return .{ .queued = queued, .active = active }; } fn runRadicle(arena: Allocator, droplets: []const DigitalOcean.Droplet, forges: []const ForgeView, view: RadicleView) !Plan { return decide(arena, .{ .now = now, .config = test_config, .known = test_known, .droplets = droplets, .forges = forges, .radicle = view }); } test "a Radicle run that reported is reaped, and not failed" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const plan = try runRadicle(arena.allocator(), &.{radDroplet(3, 600)}, &.{}, radicle(&.{}, &.{})); try expectOnlyDestroy(plan, 2003, .run_finished, false); try testing.expectEqual(null, plan.destroy[0].fail_run); } test "a Radicle droplet that never boots, or goes quiet, is reaped and its run failed" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); { const plan = try runRadicle(arena.allocator(), &.{radDroplet(3, 1000)}, &.{}, radicle(&.{}, &.{ .{ .id = 3, .tier = "s", .state = .provisioning, .created_at = now - 1100, .started_at = now - 1000, .droplet_id = 2003 }, })); try expectOnlyDestroy(plan, 2003, .never_booted, false); try testing.expectEqual(@as(?u64, 3), plan.destroy[0].fail_run); } { const plan = try runRadicle(arena.allocator(), &.{radDroplet(3, 1000)}, &.{}, radicle(&.{}, &.{ .{ .id = 3, .tier = "s", .state = .running, .created_at = now - 1100, .started_at = now - 1000, .heartbeat_at = now - 301, .droplet_id = 2003 }, })); try expectOnlyDestroy(plan, 2003, .heartbeat_lost, false); } { // quiet for less than the timeout: left alone const plan = try runRadicle(arena.allocator(), &.{radDroplet(3, 1000)}, &.{}, radicle(&.{}, &.{ .{ .id = 3, .tier = "s", .state = .running, .created_at = now - 1100, .started_at = now - 1000, .heartbeat_at = now - 30, .droplet_id = 2003 }, })); try testing.expectEqual(@as(usize, 0), plan.destroy.len); try testing.expectEqual(@as(u32, 1), plan.standing[0]); } } test "a Radicle run whose droplet disappeared is failed" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const plan = try runRadicle(arena.allocator(), &.{}, &.{}, radicle(&.{}, &.{ .{ .id = 3, .tier = "s", .state = .running, .created_at = now - 700, .started_at = now - 600, .heartbeat_at = now - 5, .droplet_id = 2003 }, // too new to be in the listing yet .{ .id = 4, .tier = "s", .state = .provisioning, .created_at = now - 20, .started_at = now - 10, .droplet_id = 2004 }, })); try testing.expectEqual(@as(usize, 1), plan.fail.len); try testing.expectEqual(@as(u64, 3), plan.fail[0].run); } test "Radicle runs and Forgejo jobs share the queue, oldest first" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const plan = try runRadicle(arena.allocator(), &.{}, &.{ .{ .name = "ocjtech", .fresh = true, .jobs = &.{ testJob(50, "forgejo-late", "waiting", "l"), testJob(5, "forgejo-early", "waiting", "l") } }, }, radicle(&.{ .{ .id = 9, .tier = "l", .state = .queued, .created_at = 20 }, }, &.{})); // l has room for one: the Forgejo job first seen at 5 beats the run // created at 20, which beats the job first seen at 50 try testing.expectEqual(@as(usize, 1), plan.provision.len); try testing.expectEqualStrings("forgejo-early", plan.provision[0].forgejo.job.job.handle); try testing.expectEqual(@as(usize, 2), plan.deferred); const second = try runRadicle(arena.allocator(), &.{}, &.{ .{ .name = "ocjtech", .fresh = true, .jobs = &.{testJob(50, "forgejo-late", "waiting", "l")} }, }, radicle(&.{ .{ .id = 9, .tier = "l", .state = .queued, .created_at = 20 }, }, &.{})); try testing.expectEqual(@as(u64, 9), second.provision[0].radicle.id); } test "a queued run on a tier that has gone is failed" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const plan = try runRadicle(arena.allocator(), &.{}, &.{}, radicle(&.{ .{ .id = 9, .tier = "xl", .state = .queued, .created_at = 20 }, }, &.{})); try testing.expectEqual(@as(usize, 0), plan.provision.len); try testing.expectEqual(@as(u64, 9), plan.fail[0].run); } test "a held job is not provisioned, and holds no slot" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var held = testJob(1, "refused", "waiting", "l"); held.held = true; const plan = try runForgejo(arena.allocator(), &.{}, &.{ .{ .name = "ocjtech", .fresh = true, .jobs = &.{ held, testJob(2, "next", "waiting", "l") } }, }); try testing.expectEqual(@as(usize, 1), plan.provision.len); try testing.expectEqualStrings("next", plan.provision[0].forgejo.job.job.handle); } // Droplets with a row in the database. fn rowDroplet(comptime id: u64, comptime source: []const u8, comptime tier: []const u8, age: i64) DigitalOcean.Droplet { return .{ .id = 3000 + id, .name = std.fmt.comptimePrint("ci-droplet-{d}", .{id}), .created_at = .{ .timestamp = @as(i128, now - age) * std.time.ns_per_s }, .tags = &.{ tags.marker, "ci-" ++ source ++ "-" ++ tier, std.fmt.comptimePrint("cidroplet-{d}", .{id}) }, }; } fn fjRow(id: u64, tier: []const u8, age: i64, handle: []const u8, runner_id: u64) RunStore.Droplet { return .{ .id = id, .do_id = 3000 + id, .tier = tier, .size = null, .image = null, .state = .booting, .binding = .{ .forgejo = .{ .forge = "ocjtech", .handle = handle, .runner_id = runner_id } }, .exit_code = null, .queued_at = null, .created_at = now - age, .active_at = null, .booted_at = null, .agent_at = null, .claimed_at = null, .work_started_at = null, .done_at = null, .destroyed_at = null, .heard_at = null, }; } fn runRows(arena: Allocator, droplets: []const DigitalOcean.Droplet, rows: []const RunStore.Droplet, forges: []const ForgeView, view: ?RadicleView) !Plan { return decide(arena, .{ .now = now, .config = test_config, .known = test_known, .droplets = droplets, .rows = rows, .forges = forges, .radicle = view }); } test "a droplet whose agent is done is destroyed at once" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var row = fjRow(1, "s", 30, "h1", 7); row.state = .done; row.agent_at = now - 10; // not polled this pass, and within the grace period: only the agent's // word says it is over, and that is enough const plan = try runRows(arena.allocator(), &.{rowDroplet(1, "ocjtech", "s", 30)}, &.{row}, &.{.{ .name = "ocjtech", .fresh = false }}, null); try expectOnlyDestroy(plan, 3001, .done, false); try testing.expectEqual(@as(?u64, 1), plan.destroy[0].row); } test "a booting Forgejo droplet is left alone, and its job not provisioned again" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const plan = try runRows(arena.allocator(), &.{rowDroplet(1, "ocjtech", "s", 300)}, &.{fjRow(1, "s", 300, "h1", 7)}, &.{ .{ .name = "ocjtech", .fresh = true, .runners = &.{.{ .id = 7, .status = "offline" }}, .jobs = &.{testJob(1, "h1", "waiting", "s")} }, }, null); try testing.expectEqual(@as(usize, 0), plan.destroy.len); try testing.expectEqual(@as(usize, 0), plan.provision.len); try testing.expectEqual(@as(u32, 1), plan.standing[0]); } test "a droplet too new to be listed still holds its job and its slot" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const plan = try runRows(arena.allocator(), &.{}, &.{fjRow(1, "l", 5, "h1", 7)}, &.{ .{ .name = "ocjtech", .fresh = true, .runners = &.{.{ .id = 7, .status = "offline" }}, .jobs = &.{ testJob(1, "h1", "waiting", "l"), testJob(2, "h2", "waiting", "l") } }, }, null); try testing.expectEqual(@as(usize, 0), plan.forget.len); try testing.expectEqual(@as(usize, 0), plan.provision.len); try testing.expectEqual(@as(usize, 1), plan.deferred); } test "a Forgejo droplet whose job was cancelled while it booted is destroyed with its runner" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const plan = try runRows(arena.allocator(), &.{rowDroplet(1, "ocjtech", "s", 300)}, &.{fjRow(1, "s", 300, "h1", 7)}, &.{ .{ .name = "ocjtech", .fresh = true, .runners = &.{.{ .id = 7, .status = "offline" }}, .jobs = &.{} }, }, null); try expectOnlyDestroy(plan, 3001, .job_gone_before_it_started, true); } test "a Forgejo droplet whose runner Forgejo deleted is finished" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var row = fjRow(1, "s", 600, "h1", 7); row.state = .claimed; row.agent_at = now - 500; const plan = try runRows(arena.allocator(), &.{rowDroplet(1, "ocjtech", "s", 600)}, &.{row}, &.{ .{ .name = "ocjtech", .fresh = true, .runners = &.{}, .jobs = &.{testJob(1, "h1", "running", "s")} }, }, null); try expectOnlyDestroy(plan, 3001, .job_finished, false); } test "a droplet whose agent never called is reaped at the boot timeout" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const plan = try runRows(arena.allocator(), &.{rowDroplet(1, "ocjtech", "s", 901)}, &.{fjRow(1, "s", 901, "h1", 7)}, &.{ .{ .name = "ocjtech", .fresh = true, .runners = &.{.{ .id = 7, .status = "offline" }}, .jobs = &.{testJob(1, "h1", "waiting", "s")} }, }, null); try expectOnlyDestroy(plan, 3001, .never_booted, true); // and the job, no longer held by a droplet, is given another try testing.expectEqual(@as(usize, 1), plan.provision.len); } test "a droplet with no row is destroyed once it cannot be in flight" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const plan = try runRows(arena.allocator(), &.{ rowDroplet(1, "ocjtech", "s", 600), rowDroplet(2, "ocjtech", "s", 30) }, &.{}, &.{.{ .name = "ocjtech", .fresh = true }}, null); try expectOnlyDestroy(plan, 3001, .unrecorded, false); try testing.expectEqual(@as(u32, 1), plan.standing[0]); } test "a row whose droplet has gone is forgotten, and its runner deleted" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var creating = fjRow(2, "s", 700, "h2", 8); creating.state = .creating; creating.do_id = null; var recent = fjRow(3, "s", 300, "h3", 9); recent.state = .creating; recent.do_id = null; const plan = try runRows(arena.allocator(), &.{}, &.{ fjRow(1, "s", 300, "h1", 7), creating, recent }, &.{ .{ .name = "ocjtech", .fresh = true, .runners = &.{.{ .id = 7, .status = "idle" }}, .jobs = &.{} }, }, null); try testing.expectEqual(@as(usize, 2), plan.forget.len); try testing.expectEqual(@as(u64, 1), plan.forget[0].row); try testing.expectEqual(@as(u64, 7), plan.forget[0].runner.?.id); try testing.expectEqual(@as(u64, 2), plan.forget[1].row); try testing.expectEqual(null, plan.forget[1].runner); } test "a Radicle droplet with a row follows its run" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var row = fjRow(1, "s", 600, "", 0); row.binding = .{ .radicle = 9 }; row.agent_at = now - 500; const d = rowDroplet(1, "radicle", "s", 600); { // running and heard from: left alone, and the run is not failed as // having lost its droplet const plan = try runRows(arena.allocator(), &.{d}, &.{row}, &.{}, radicle(&.{}, &.{ .{ .id = 9, .tier = "s", .state = .running, .created_at = now - 700, .started_at = now - 600, .heartbeat_at = now - 5, .droplet_id = 3001 }, })); try testing.expectEqual(@as(usize, 0), plan.destroy.len); try testing.expectEqual(@as(usize, 0), plan.fail.len); } { const plan = try runRows(arena.allocator(), &.{d}, &.{row}, &.{}, radicle(&.{}, &.{ .{ .id = 9, .tier = "s", .state = .running, .created_at = now - 700, .started_at = now - 600, .heartbeat_at = now - 400, .droplet_id = 3001 }, })); try expectOnlyDestroy(plan, 3001, .heartbeat_lost, false); try testing.expectEqual(@as(?u64, 9), plan.destroy[0].fail_run); } { // the run reported and finished const plan = try runRows(arena.allocator(), &.{d}, &.{row}, &.{}, radicle(&.{}, &.{})); try expectOnlyDestroy(plan, 3001, .run_finished, false); try testing.expectEqual(null, plan.destroy[0].fail_run); } } // The warm pool. const pool_config: Config = blk: { var c = test_config; c.tiers = &.{ .{ .name = "s", .size = "s-2vcpu-4gb", .max = 2, .warm = 1 }, .{ .name = "l", .size = "s-8vcpu-16gb", .max = 1, .warm = 1 }, }; c.warm_linger_seconds = 900; break :blk c; }; const pool_known: tags.Known = .{ .sources = &.{ "ocjtech", "codeberg", "radicle", "pool" }, .tiers = &.{ "s", "l" }, }; fn poolDroplet(comptime id: u64, comptime tier: []const u8, age: i64) DigitalOcean.Droplet { return .{ .id = 3000 + id, .name = std.fmt.comptimePrint("ci-droplet-{d}", .{id}), .created_at = .{ .timestamp = @as(i128, now - age) * std.time.ns_per_s }, .tags = &.{ tags.marker, "ci-pool-" ++ tier, std.fmt.comptimePrint("cidroplet-{d}", .{id}) }, }; } fn poolRow(id: u64, tier: []const u8, age: i64, up: bool) RunStore.Droplet { var row = fjRow(id, tier, age, "", 0); row.binding = null; row.image = "snap-1"; if (up) { row.agent_at = now - age + 40; row.heard_at = now - 10; } return row; } fn runPool(arena: Allocator, droplets: []const DigitalOcean.Droplet, rows: []const RunStore.Droplet, forges: []const ForgeView, activity: []const ?i64) !Plan { return decide(arena, .{ .now = now, .config = pool_config, .known = pool_known, .droplets = droplets, .rows = rows, .forges = forges, .activity = activity, .newest_image = "snap-1", }); } test "queued work takes a warm droplet before a new one, even with no room" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); // l has one slot, and the warm droplet holds it const plan = try runPool(arena.allocator(), &.{poolDroplet(1, "l", 300)}, &.{poolRow(1, "l", 300, true)}, &.{ .{ .name = "ocjtech", .fresh = true, .jobs = &.{testJob(1, "big", "waiting", "l")} }, }, &.{ null, now - 60 }); try testing.expectEqual(@as(usize, 1), plan.assign.len); try testing.expectEqual(@as(u64, 1), plan.assign[0].row); try testing.expectEqual(@as(u64, 3001), plan.assign[0].droplet); try testing.expectEqualStrings("big", plan.assign[0].item.forgejo.job.job.handle); try testing.expectEqual(@as(usize, 0), plan.provision.len); try testing.expectEqual(@as(usize, 0), plan.deferred); // and no room is left to warm another try testing.expectEqual(@as(u32, 0), plan.warm[1]); } test "a booted warm droplet is taken before a booting one" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const plan = try runPool(arena.allocator(), &.{ poolDroplet(1, "s", 30), poolDroplet(2, "s", 300) }, &.{ poolRow(1, "s", 30, false), poolRow(2, "s", 300, true) }, &.{ .{ .name = "ocjtech", .fresh = true, .jobs = &.{testJob(1, "a", "waiting", "s")} }, }, &.{ now - 60, null }); try testing.expectEqual(@as(u64, 2), plan.assign[0].row); } test "the pool fills only the room queued work leaves, and only while warm" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); { // s: max 2. Two waiting jobs take both slots; nothing left to warm. const plan = try runPool(arena.allocator(), &.{}, &.{}, &.{ .{ .name = "ocjtech", .fresh = true, .jobs = &.{ testJob(1, "a", "waiting", "s"), testJob(2, "b", "waiting", "s") } }, }, &.{ now - 60, null }); try testing.expectEqual(@as(usize, 2), plan.provision.len); try testing.expectEqual(@as(u32, 0), plan.warm[0]); } { // One job: one slot left, and s is warm, so one warm droplet. const plan = try runPool(arena.allocator(), &.{}, &.{}, &.{ .{ .name = "ocjtech", .fresh = true, .jobs = &.{testJob(1, "a", "waiting", "s")} }, }, &.{ null, null }); try testing.expectEqual(@as(usize, 1), plan.provision.len); try testing.expectEqual(@as(u32, 1), plan.warm[0]); // l has had nothing, so it stays cold try testing.expectEqual(@as(u32, 0), plan.warm[1]); } { // Work within the linger keeps a tier warm with nothing queued. const plan = try runPool(arena.allocator(), &.{}, &.{}, &.{.{ .name = "ocjtech", .fresh = true }}, &.{ now - 600, now - 1000 }); try testing.expectEqual(@as(u32, 1), plan.warm[0]); try testing.expectEqual(@as(u32, 0), plan.warm[1]); } } test "a warm droplet is kept while its tier is warm, and destroyed after" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const droplets = [_]DigitalOcean.Droplet{poolDroplet(1, "s", 300)}; const rows = [_]RunStore.Droplet{poolRow(1, "s", 300, true)}; { const plan = try runPool(arena.allocator(), &droplets, &rows, &.{.{ .name = "ocjtech", .fresh = true }}, &.{ now - 600, null }); try testing.expectEqual(@as(usize, 0), plan.destroy.len); // it is the one the tier keeps try testing.expectEqual(@as(u32, 0), plan.warm[0]); } { const plan = try runPool(arena.allocator(), &droplets, &rows, &.{.{ .name = "ocjtech", .fresh = true }}, &.{ now - 901, null }); try expectOnlyDestroy(plan, 3001, .pool_idle, false); try testing.expectEqual(@as(?u64, 1), plan.destroy[0].row); try testing.expectEqual(@as(u32, 0), plan.warm[0]); } } test "warm droplets beyond the tier's count are destroyed" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const plan = try runPool(arena.allocator(), &.{ poolDroplet(1, "s", 300), poolDroplet(2, "s", 200) }, &.{ poolRow(1, "s", 300, true), poolRow(2, "s", 200, true) }, &.{.{ .name = "ocjtech", .fresh = true }}, &.{ now - 60, null }); try expectOnlyDestroy(plan, 3002, .pool_idle, false); } test "a stale, silent or never-booted warm droplet is destroyed" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const warm: []const ?i64 = &.{ now - 60, null }; { var row = poolRow(1, "s", 300, true); row.image = "snap-0"; const plan = try runPool(arena.allocator(), &.{poolDroplet(1, "s", 300)}, &.{row}, &.{.{ .name = "ocjtech", .fresh = true }}, warm); try expectOnlyDestroy(plan, 3001, .pool_stale, false); // and a fresh one takes its place try testing.expectEqual(@as(u32, 1), plan.warm[0]); } { var row = poolRow(1, "s", 1000, true); row.heard_at = now - 301; const plan = try runPool(arena.allocator(), &.{poolDroplet(1, "s", 1000)}, &.{row}, &.{.{ .name = "ocjtech", .fresh = true }}, warm); try expectOnlyDestroy(plan, 3001, .heartbeat_lost, false); } { const plan = try runPool(arena.allocator(), &.{poolDroplet(1, "s", 901)}, &.{poolRow(1, "s", 901, false)}, &.{.{ .name = "ocjtech", .fresh = true }}, warm); try expectOnlyDestroy(plan, 3001, .never_booted, false); } } test "a warm droplet given work is judged by that work" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); // tagged as the pool's, bound since to a job whose runner Forgejo deleted var row = fjRow(1, "s", 600, "h1", 7); row.state = .claimed; row.agent_at = now - 500; const plan = try runPool(arena.allocator(), &.{poolDroplet(1, "s", 600)}, &.{row}, &.{ .{ .name = "ocjtech", .fresh = true, .runners = &.{}, .jobs = &.{testJob(1, "h1", "running", "s")} }, }, &.{ now - 60, null }); try expectOnlyDestroy(plan, 3001, .job_finished, false); }