scheduler: run only one job at a time, drop per-load-level limits

Replace the per-load-level concurrency caps (2 high / 8 medium / 32
low) with a strict single-job FIFO: the scheduler starts the next
eligible queued job only when nothing is running.

- Scheduler.Options loses 'limits'; Active loses 'level'; counts[3],
  runningAt(), setLimits() and limitFor() are removed; the capacity
  check is now active.count() >= 1.
- Service no longer passes cfg.load_levels to the scheduler and
  reload() no longer calls setLimits().
- Tests: the three load-level limit tests are replaced by a single
  'only one job runs at a time and jobs finish in FIFO order' test.

Part of issue #2. The LoadLevels config type, --load-level flag and
the loadLevel JSON/XML fields remain and are removed in follow-ups.
This commit is contained in:
Daniel Samson committed 2026-11-11 20:16:39 +00:00
1 parent 0567e2ef8d
commit 575c895306
2 files changed
+32 -89

No files matched your search

+31 -86
View File
@@ -1,7 +1,8 @@
//! Job scheduler: polls for queued jobs, enforces per-load-level concurrency limits and runs //! Job scheduler: polls for queued jobs and runs them one at a time, each on its own thread.
//! each job on its own thread. Port of barn's `JobScheduler`. //! Port of barn's `JobScheduler` (with the per-load-level concurrency limits removed).
//! //!
//! Jobs start oldest-first (by `created_at`), skipping ones whose `retry_at` is in the future. //! Only one job runs at a time; queued 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`). //! Only one scheduler may run per base directory (guarded by `locks/scheduler.lock`).
const std = @import("std"); const std = @import("std");
const Io = std.Io; const Io = std.Io;
@@ -11,12 +12,9 @@ const dirs_mod = @import("dirs.zig");
const fsutil = @import("fsutil.zig"); const fsutil = @import("fsutil.zig");
const runner = @import("runner.zig"); const runner = @import("runner.zig");
const timestamp = @import("timestamp.zig"); const timestamp = @import("timestamp.zig");
const LoadLevel = @import("loadlevel.zig").LoadLevel;
const LoadLevels = @import("config.zig").LoadLevels;
const Job = @import("job.zig").Job; const Job = @import("job.zig").Job;
pub const Options = struct { pub const Options = struct {
limits: LoadLevels = .{},
/// Poll interval. /// Poll interval.
tick_ms: u64 = 1_000, tick_ms: u64 = 1_000,
runner: runner.Options = .{}, runner: runner.Options = .{},
@@ -35,7 +33,6 @@ pub const KillResult = enum {
const Active = struct { const Active = struct {
id: []u8, id: []u8,
ctl: runner.Control = .{}, ctl: runner.Control = .{},
level: LoadLevel,
}; };
pub const Scheduler = struct { pub const Scheduler = struct {
@@ -46,7 +43,6 @@ pub const Scheduler = struct {
mutex: Io.Mutex = .init, mutex: Io.Mutex = .init,
active: std.StringHashMapUnmanaged(*Active) = .empty, active: std.StringHashMapUnmanaged(*Active) = .empty,
counts: [3]u32 = .{ 0, 0, 0 },
stopping: std.atomic.Value(bool) = .init(false), stopping: std.atomic.Value(bool) = .init(false),
thread: ?std.Thread = null, thread: ?std.Thread = null,
lock: ?fsutil.FileLock = null, lock: ?fsutil.FileLock = null,
@@ -101,19 +97,6 @@ pub const Scheduler = struct {
return self.active.count(); 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)];
}
/// Applies new concurrency limits; running jobs are unaffected.
pub fn setLimits(self: *Scheduler, limits: LoadLevels) void {
self.mutex.lockUncancelable(self.io);
defer self.mutex.unlock(self.io);
self.opts.limits = limits;
}
/// Applies new runner settings (heartbeat, timeout, retry codes) to jobs started from now on. /// Applies new runner settings (heartbeat, timeout, retry codes) to jobs started from now on.
pub fn setRunnerOptions(self: *Scheduler, ro: runner.Options) void { pub fn setRunnerOptions(self: *Scheduler, ro: runner.Options) void {
self.mutex.lockUncancelable(self.io); self.mutex.lockUncancelable(self.io);
@@ -127,14 +110,6 @@ pub const Scheduler = struct {
return self.opts.runner; return self.opts.runner;
} }
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 { fn loop(self: *Scheduler) void {
while (!self.stopping.load(.acquire)) { while (!self.stopping.load(.acquire)) {
self.tick() catch |err| std.log.warn("scheduler tick failed: {s}", .{@errorName(err)}); self.tick() catch |err| std.log.warn("scheduler tick failed: {s}", .{@errorName(err)});
@@ -146,7 +121,8 @@ pub const Scheduler = struct {
} }
} }
/// One scheduling pass: starts every eligible queued job that fits its level's limit. /// One scheduling pass: if no job is running, starts the next eligible queued job
/// (oldest first). Exactly one job runs at a time.
pub fn tick(self: *Scheduler) !void { pub fn tick(self: *Scheduler) !void {
var arena_state = std.heap.ArenaAllocator.init(self.gpa); var arena_state = std.heap.ArenaAllocator.init(self.gpa);
defer arena_state.deinit(); defer arena_state.deinit();
@@ -160,9 +136,12 @@ pub const Scheduler = struct {
if (job.retry_at) |t| if (t > now) continue; if (job.retry_at) |t| if (t > now) continue;
if (self.stopping.load(.acquire)) return; if (self.stopping.load(.acquire)) return;
self.startJob(job) catch |err| switch (err) { self.startJob(job) catch |err| switch (err) {
error.AtCapacity, error.AlreadyActive => continue, // A job is already running (or this one is already tracked): wait for the
// next tick.
error.AtCapacity, error.AlreadyActive => return,
else => return err, else => return err,
}; };
return; // one job runs at a time
} }
} }
@@ -173,21 +152,17 @@ pub const Scheduler = struct {
const StartJobError = error{ AtCapacity, AlreadyActive } || Allocator.Error || std.Thread.SpawnError; const StartJobError = error{ AtCapacity, AlreadyActive } || Allocator.Error || std.Thread.SpawnError;
fn startJob(self: *Scheduler, job: Job) StartJobError!void { fn startJob(self: *Scheduler, job: Job) StartJobError!void {
const level = job.load_level;
const idx = @intFromEnum(level);
const entry = try self.gpa.create(Active); const entry = try self.gpa.create(Active);
errdefer self.gpa.destroy(entry); errdefer self.gpa.destroy(entry);
entry.* = .{ .id = try self.gpa.dupe(u8, job.id), .level = level }; entry.* = .{ .id = try self.gpa.dupe(u8, job.id) };
errdefer self.gpa.free(entry.id); errdefer self.gpa.free(entry.id);
{ {
self.mutex.lockUncancelable(self.io); self.mutex.lockUncancelable(self.io);
defer self.mutex.unlock(self.io); defer self.mutex.unlock(self.io);
if (self.active.contains(job.id)) return error.AlreadyActive; if (self.active.contains(job.id)) return error.AlreadyActive;
if (self.counts[idx] >= self.limitFor(level)) return error.AtCapacity; if (self.active.count() >= 1) return error.AtCapacity;
try self.active.put(self.gpa, entry.id, entry); try self.active.put(self.gpa, entry.id, entry);
self.counts[idx] += 1;
} }
errdefer self.release(entry); errdefer self.release(entry);
@@ -205,7 +180,6 @@ pub const Scheduler = struct {
self.mutex.lockUncancelable(self.io); self.mutex.lockUncancelable(self.io);
defer self.mutex.unlock(self.io); defer self.mutex.unlock(self.io);
_ = self.active.remove(entry.id); _ = self.active.remove(entry.id);
self.counts[@intFromEnum(entry.level)] -= 1;
} }
self.gpa.free(entry.id); self.gpa.free(entry.id);
self.gpa.destroy(entry); self.gpa.destroy(entry);
@@ -305,25 +279,23 @@ test "runs queued jobs to completion" {
try std.testing.expectEqual(@as(usize, 0), s.stop(2000)); try std.testing.expectEqual(@as(usize, 0), s.stop(2000));
} }
test "load level limits cap concurrency and the rest wait their turn" { test "only one job runs at a time and jobs finish in FIFO order" {
const env = try Env.init(); const env = try Env.init();
defer env.deinit(); defer env.deinit();
const a = env.arena.allocator(); const a = env.arena.allocator();
var ids: [3][]const u8 = undefined; var ids: [3][]const u8 = undefined;
for (&ids) |*id| id.* = (try env.repo().create(a, &.{ "sleep", "0.4" }, .{ .load_level = .high })).id; for (&ids) |*id| id.* = (try env.repo().create(a, &.{ "sleep", "0.3" }, .{})).id;
var opts = test_opts; var s = Scheduler.init(std.testing.allocator, std.testing.io, env.repo(), 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(); defer s.deinit();
try s.start(); try s.start();
// While work remains, never more than one high job runs at a time. // While work remains, never more than one job runs at a time.
var max_seen: u32 = 0; var max_seen: usize = 0;
var done = false; var done = false;
var waited: u64 = 0; var waited: u64 = 0;
while (!done and waited < 8000) : (waited += 10) { while (!done and waited < 10_000) : (waited += 10) {
max_seen = @max(max_seen, s.runningAt(.high)); max_seen = @max(max_seen, s.activeCount());
done = true; done = true;
for (ids) |id| { for (ids) |id| {
if ((try env.state(id)) != .succeeded) done = false; if ((try env.state(id)) != .succeeded) done = false;
@@ -331,27 +303,19 @@ test "load level limits cap concurrency and the rest wait their turn" {
try std.testing.io.sleep(.fromMilliseconds(10), .real); try std.testing.io.sleep(.fromMilliseconds(10), .real);
} }
try std.testing.expect(done); try std.testing.expect(done);
try std.testing.expectEqual(@as(u32, 1), max_seen); try std.testing.expectEqual(@as(usize, 1), max_seen);
_ = s.stop(2000);
}
test "different levels run concurrently" { // FIFO: each job started only after the previous one finished.
const env = try Env.init(); var prev_finished: i128 = 0;
defer env.deinit(); for (ids) |id| {
const a = env.arena.allocator(); const job = (try env.repo().findById(a, id)).?;
const hi = try env.repo().create(a, &.{ "sleep", "0.6" }, .{ .load_level = .high }); try std.testing.expect(job.started_at != null and job.finished_at != null);
const lo = try env.repo().create(a, &.{ "sleep", "0.6" }, .{ .load_level = .low }); const started = job.started_at.?;
const finished = job.finished_at.?;
var opts = test_opts; try std.testing.expect(started >= prev_finished);
opts.limits = .{ .max_high_jobs = 1, .max_medium_jobs = 1, .max_low_jobs = 1 }; try std.testing.expect(finished > started);
var s = Scheduler.init(std.testing.allocator, std.testing.io, env.repo(), opts); prev_finished = finished;
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); _ = s.stop(2000);
} }
@@ -407,22 +371,3 @@ test "only one scheduler per base dir" {
try s2.start(); // lock released by stop try s2.start(); // lock released by stop
_ = s2.stop(1000); _ = s2.stop(1000);
} }
test "limits can be changed while running" {
const env = try Env.init();
defer env.deinit();
const a = env.arena.allocator();
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();
const j1 = try env.repo().create(a, &.{ "sleep", "0.8" }, .{});
const j2 = try env.repo().create(a, &.{ "sleep", "0.8" }, .{});
try env.waitFor(j1.id, .running, 3000);
try std.testing.io.sleep(.fromMilliseconds(150), .real);
try std.testing.expectEqual(State.queued, try env.state(j2.id)); // capped at 1
s.setLimits(.{ .max_high_jobs = 1, .max_medium_jobs = 2, .max_low_jobs = 1 });
try env.waitFor(j2.id, .running, 3000); // now allowed alongside j1
_ = s.stop(5000);
}
+1 -3
View File
@@ -2,7 +2,7 @@
//! IPC server together. Port of barn's `BarnService`. //! IPC server together. Port of barn's `BarnService`.
//! //!
//! Start order: directories, crash recovery, scheduler (takes the scheduler lock), IPC server, //! Start order: directories, crash recovery, scheduler (takes the scheduler lock), IPC server,
//! cleanup timer. Stop order is the reverse. Configuration can be reloaded at runtime: limits, //! cleanup timer. Stop order is the reverse. Configuration can be reloaded at runtime:
//! retry/timeout defaults, heartbeat and cleanup settings apply immediately; paths need a restart. //! retry/timeout defaults, heartbeat and cleanup settings apply immediately; paths need a restart.
const std = @import("std"); const std = @import("std");
const Io = std.Io; const Io = std.Io;
@@ -101,7 +101,6 @@ pub const Service = struct {
fn schedulerOptions(self: *Service, cfg: config.Config) scheduler_mod.Options { fn schedulerOptions(self: *Service, cfg: config.Config) scheduler_mod.Options {
return .{ return .{
.limits = cfg.load_levels,
.tick_ms = self.opts.scheduler_tick_ms, .tick_ms = self.opts.scheduler_tick_ms,
.runner = self.runnerOptions(cfg), .runner = self.runnerOptions(cfg),
}; };
@@ -187,7 +186,6 @@ pub const Service = struct {
self.cfg = new_cfg; self.cfg = new_cfg;
self.cfg_mutex.unlock(self.io); self.cfg_mutex.unlock(self.io);
self.scheduler.setLimits(new_cfg.load_levels);
self.scheduler.setRunnerOptions(self.runnerOptions(new_cfg)); self.scheduler.setRunnerOptions(self.runnerOptions(new_cfg));
} }