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:
2 files changed
+32
-89
No files matched your search
+31
-86
@@ -1,7 +1,8 @@
|
||||
//! Job scheduler: polls for queued jobs, enforces per-load-level concurrency limits and runs
|
||||
//! each job on its own thread. Port of barn's `JobScheduler`.
|
||||
//! Job scheduler: polls for queued jobs and runs them one at a time, each on its own thread.
|
||||
//! 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`).
|
||||
const std = @import("std");
|
||||
const Io = std.Io;
|
||||
@@ -11,12 +12,9 @@ const dirs_mod = @import("dirs.zig");
|
||||
const fsutil = @import("fsutil.zig");
|
||||
const runner = @import("runner.zig");
|
||||
const timestamp = @import("timestamp.zig");
|
||||
const LoadLevel = @import("loadlevel.zig").LoadLevel;
|
||||
const LoadLevels = @import("config.zig").LoadLevels;
|
||||
const Job = @import("job.zig").Job;
|
||||
|
||||
pub const Options = struct {
|
||||
limits: LoadLevels = .{},
|
||||
/// Poll interval.
|
||||
tick_ms: u64 = 1_000,
|
||||
runner: runner.Options = .{},
|
||||
@@ -35,7 +33,6 @@ pub const KillResult = enum {
|
||||
const Active = struct {
|
||||
id: []u8,
|
||||
ctl: runner.Control = .{},
|
||||
level: LoadLevel,
|
||||
};
|
||||
|
||||
pub const Scheduler = struct {
|
||||
@@ -46,7 +43,6 @@ pub const Scheduler = struct {
|
||||
|
||||
mutex: Io.Mutex = .init,
|
||||
active: std.StringHashMapUnmanaged(*Active) = .empty,
|
||||
counts: [3]u32 = .{ 0, 0, 0 },
|
||||
stopping: std.atomic.Value(bool) = .init(false),
|
||||
thread: ?std.Thread = null,
|
||||
lock: ?fsutil.FileLock = null,
|
||||
@@ -101,19 +97,6 @@ pub const Scheduler = struct {
|
||||
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.
|
||||
pub fn setRunnerOptions(self: *Scheduler, ro: runner.Options) void {
|
||||
self.mutex.lockUncancelable(self.io);
|
||||
@@ -127,14 +110,6 @@ pub const Scheduler = struct {
|
||||
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 {
|
||||
while (!self.stopping.load(.acquire)) {
|
||||
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 {
|
||||
var arena_state = std.heap.ArenaAllocator.init(self.gpa);
|
||||
defer arena_state.deinit();
|
||||
@@ -160,9 +136,12 @@ pub const Scheduler = struct {
|
||||
if (job.retry_at) |t| if (t > now) continue;
|
||||
if (self.stopping.load(.acquire)) return;
|
||||
self.startJob(job) catch |err| switch (err) {
|
||||
error.AtCapacity, error.AlreadyActive => continue,
|
||||
// A job is already running (or this one is already tracked): wait for the
|
||||
// next tick.
|
||||
error.AtCapacity, error.AlreadyActive => return,
|
||||
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;
|
||||
|
||||
fn startJob(self: *Scheduler, job: Job) StartJobError!void {
|
||||
const level = job.load_level;
|
||||
const idx = @intFromEnum(level);
|
||||
|
||||
const entry = try self.gpa.create(Active);
|
||||
errdefer self.gpa.destroy(entry);
|
||||
entry.* = .{ .id = try self.gpa.dupe(u8, job.id), .level = level };
|
||||
entry.* = .{ .id = try self.gpa.dupe(u8, job.id) };
|
||||
errdefer self.gpa.free(entry.id);
|
||||
|
||||
{
|
||||
self.mutex.lockUncancelable(self.io);
|
||||
defer self.mutex.unlock(self.io);
|
||||
if (self.active.contains(job.id)) return error.AlreadyActive;
|
||||
if (self.counts[idx] >= self.limitFor(level)) return error.AtCapacity;
|
||||
if (self.active.count() >= 1) return error.AtCapacity;
|
||||
try self.active.put(self.gpa, entry.id, entry);
|
||||
self.counts[idx] += 1;
|
||||
}
|
||||
errdefer self.release(entry);
|
||||
|
||||
@@ -205,7 +180,6 @@ pub const Scheduler = struct {
|
||||
self.mutex.lockUncancelable(self.io);
|
||||
defer self.mutex.unlock(self.io);
|
||||
_ = self.active.remove(entry.id);
|
||||
self.counts[@intFromEnum(entry.level)] -= 1;
|
||||
}
|
||||
self.gpa.free(entry.id);
|
||||
self.gpa.destroy(entry);
|
||||
@@ -305,25 +279,23 @@ test "runs queued jobs to completion" {
|
||||
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();
|
||||
defer env.deinit();
|
||||
const a = env.arena.allocator();
|
||||
var ids: [3][]const u8 = undefined;
|
||||
for (&ids) |*id| id.* = (try env.repo().create(a, &.{ "sleep", "0.4" }, .{ .load_level = .high })).id;
|
||||
for (&ids) |*id| id.* = (try env.repo().create(a, &.{ "sleep", "0.3" }, .{})).id;
|
||||
|
||||
var opts = test_opts;
|
||||
opts.limits = .{ .max_high_jobs = 1, .max_medium_jobs = 8, .max_low_jobs = 32 };
|
||||
var s = Scheduler.init(std.testing.allocator, std.testing.io, env.repo(), opts);
|
||||
var s = Scheduler.init(std.testing.allocator, std.testing.io, env.repo(), test_opts);
|
||||
defer s.deinit();
|
||||
try s.start();
|
||||
|
||||
// While work remains, never more than one high job runs at a time.
|
||||
var max_seen: u32 = 0;
|
||||
// While work remains, never more than one job runs at a time.
|
||||
var max_seen: usize = 0;
|
||||
var done = false;
|
||||
var waited: u64 = 0;
|
||||
while (!done and waited < 8000) : (waited += 10) {
|
||||
max_seen = @max(max_seen, s.runningAt(.high));
|
||||
while (!done and waited < 10_000) : (waited += 10) {
|
||||
max_seen = @max(max_seen, s.activeCount());
|
||||
done = true;
|
||||
for (ids) |id| {
|
||||
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.expect(done);
|
||||
try std.testing.expectEqual(@as(u32, 1), max_seen);
|
||||
_ = s.stop(2000);
|
||||
}
|
||||
try std.testing.expectEqual(@as(usize, 1), max_seen);
|
||||
|
||||
test "different levels run concurrently" {
|
||||
const env = try Env.init();
|
||||
defer env.deinit();
|
||||
const a = env.arena.allocator();
|
||||
const hi = try env.repo().create(a, &.{ "sleep", "0.6" }, .{ .load_level = .high });
|
||||
const lo = try env.repo().create(a, &.{ "sleep", "0.6" }, .{ .load_level = .low });
|
||||
|
||||
var opts = test_opts;
|
||||
opts.limits = .{ .max_high_jobs = 1, .max_medium_jobs = 1, .max_low_jobs = 1 };
|
||||
var s = Scheduler.init(std.testing.allocator, std.testing.io, env.repo(), opts);
|
||||
defer s.deinit();
|
||||
try s.start();
|
||||
try env.waitFor(hi.id, .running, 3000);
|
||||
try env.waitFor(lo.id, .running, 3000);
|
||||
try std.testing.expectEqual(@as(usize, 2), s.activeCount());
|
||||
try env.waitFor(hi.id, .succeeded, 5000);
|
||||
try env.waitFor(lo.id, .succeeded, 5000);
|
||||
// FIFO: each job started only after the previous one finished.
|
||||
var prev_finished: i128 = 0;
|
||||
for (ids) |id| {
|
||||
const job = (try env.repo().findById(a, id)).?;
|
||||
try std.testing.expect(job.started_at != null and job.finished_at != null);
|
||||
const started = job.started_at.?;
|
||||
const finished = job.finished_at.?;
|
||||
try std.testing.expect(started >= prev_finished);
|
||||
try std.testing.expect(finished > started);
|
||||
prev_finished = finished;
|
||||
}
|
||||
_ = s.stop(2000);
|
||||
}
|
||||
|
||||
@@ -407,22 +371,3 @@ test "only one scheduler per base dir" {
|
||||
try s2.start(); // lock released by stop
|
||||
_ = 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
@@ -2,7 +2,7 @@
|
||||
//! IPC server together. Port of barn's `BarnService`.
|
||||
//!
|
||||
//! 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.
|
||||
const std = @import("std");
|
||||
const Io = std.Io;
|
||||
@@ -101,7 +101,6 @@ pub const Service = struct {
|
||||
|
||||
fn schedulerOptions(self: *Service, cfg: config.Config) scheduler_mod.Options {
|
||||
return .{
|
||||
.limits = cfg.load_levels,
|
||||
.tick_ms = self.opts.scheduler_tick_ms,
|
||||
.runner = self.runnerOptions(cfg),
|
||||
};
|
||||
@@ -187,7 +186,6 @@ pub const Service = struct {
|
||||
self.cfg = new_cfg;
|
||||
self.cfg_mutex.unlock(self.io);
|
||||
|
||||
self.scheduler.setLimits(new_cfg.load_levels);
|
||||
self.scheduler.setRunnerOptions(self.runnerOptions(new_cfg));
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user