From 575c895306001ae55d540049d4022a999435ad21 Mon Sep 17 00:00:00 2001 From: Daniel Samson <12231216+daniel-samson@users.noreply.github.com> Date: Wed, 11 Nov 2026 20:16:39 +0000 Subject: [PATCH 1/7] 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. --- src/scheduler.zig | 117 ++++++++++++---------------------------------- src/service.zig | 4 +- 2 files changed, 32 insertions(+), 89 deletions(-) diff --git a/src/scheduler.zig b/src/scheduler.zig index d60eb62..dce2b1b 100644 --- a/src/scheduler.zig +++ b/src/scheduler.zig @@ -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); -} diff --git a/src/service.zig b/src/service.zig index c937124..9c4fd54 100644 --- a/src/service.zig +++ b/src/service.zig @@ -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)); } -- 2.54.0 From 8f3f61c86aa5038d39fed1aeaa519e0ce5334c68 Mon Sep 17 00:00:00 2001 From: Daniel Samson <12231216+daniel-samson@users.noreply.github.com> Date: Wed, 11 Nov 2026 20:46:16 +0000 Subject: [PATCH 2/7] test: make liveness and search-path tests portable to macOS std.os.linux.getpid() is a raw Linux syscall (number 39), which maps to a different syscall on macOS, so it returned a bogus pid (or killed the test process with SIGSYS) when the suite ran on a Mac. Use the portable proc.currentPid() in the proc and recovery tests, and make the config search-path test expect the macOS user config dir on macOS. This clears the three pre-existing environment failures so 'zig build test' is green on both macOS and Linux. --- src/config.zig | 6 +++++- src/proc.zig | 2 +- src/recovery.zig | 2 +- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/config.zig b/src/config.zig index 998768a..f85091d 100644 --- a/src/config.zig +++ b/src/config.zig @@ -563,7 +563,11 @@ test "search paths point at zag.conf" { try env.put("HOME", "/home/dan"); const paths = try searchPaths(arena.allocator(), &env); try std.testing.expectEqualStrings("/etc/zag/zag.conf", paths[0]); - try std.testing.expectEqualStrings("/home/dan/.config/zag/zag.conf", paths[1]); + const user_path = switch (builtin.os.tag) { + .macos => "/home/dan/Library/Application Support/zag/zag.conf", + else => "/home/dan/.config/zag/zag.conf", + }; + try std.testing.expectEqualStrings(user_path, paths[1]); } test "problems reports unknown names, bad types and ranges" { diff --git a/src/proc.zig b/src/proc.zig index 0630e8f..75ee488 100644 --- a/src/proc.zig +++ b/src/proc.zig @@ -185,7 +185,7 @@ test "signalTree kills the whole process group" { } test "isAlive" { - try std.testing.expect(isAlive(std.os.linux.getpid())); + try std.testing.expect(isAlive(currentPid())); try std.testing.expect(!isAlive(-1)); try std.testing.expect(!isAlive(0)); } diff --git a/src/recovery.zig b/src/recovery.zig index f828bb2..88b6540 100644 --- a/src/recovery.zig +++ b/src/recovery.zig @@ -73,7 +73,7 @@ test "stale and orphaned detection" { j.heartbeat = now - 60 * std.time.ns_per_s; try std.testing.expect(isStale(j, now, 30)); try std.testing.expect(isOrphaned(j, now, 30)); // pid does not exist - j.pid = std.os.linux.getpid(); + j.pid = proc.currentPid(); try std.testing.expect(!isOrphaned(j, now, 30)); // alive: stale but not orphaned j.pid = null; try std.testing.expect(isOrphaned(j, now, 30)); -- 2.54.0 From 4abc94f6816833baacd3dc73ca248bb1108df59a Mon Sep 17 00:00:00 2001 From: Daniel Samson <12231216+daniel-samson@users.noreply.github.com> Date: Thu, 12 Nov 2026 10:07:30 +0000 Subject: [PATCH 3/7] load levels: remove load levels from model, config, CLI, IPC, tests, docs Completes issue #2 on top of the phase-1 strict single-job FIFO scheduler. Removed: - Job.load_level / Manifest.load_level / CreateOptions.load_level and the manifest.json loadLevel field (old manifests still parse: unknown fields are ignored) - loadLevel in job JSON and in XML output (field order shifts; old JSON still parses) - the [load_levels] config section, service.max_concurrent_jobs, ZAG_LOAD_LEVELS_*/ZAG_LOADLEVELS_*/ZAG_SERVICE_MAX_CONCURRENT_JOBS env vars, loadlevel.zig / loadclass.zig and the default .load files Friendly deprecation: old configs and environments still load fine. config validate and config show report the removed settings as non-fatal warnings (validate exit 1 stays reserved for real errors) and the CLI/daemon logs them once at startup. --load-level is gone from zag run; old IPC clients sending loadLevel are simply ignored. e2e: wait_state is now portable to macOS bash 3.2 (it silently skipped three checks before) and a serial-execution check asserts the second job stays QUEUED while the first runs and both finish in FIFO order. README and AGENTS.md document the deviation from barn. --- AGENTS.md | 11 +- README.md | 55 +++------- src/cli.zig | 9 +- src/cli_admin.zig | 96 +++++++++-------- src/cli_jobs.zig | 20 +--- src/config.zig | 170 +++++++++++++++++++++-------- src/defaults.zig | 6 -- src/defaults/high.load | 16 --- src/defaults/low.load | 16 --- src/defaults/medium.load | 4 - src/defaults/zag.conf | 14 +-- src/job.zig | 3 - src/jobjson.zig | 10 +- src/loadclass.zig | 223 --------------------------------------- src/loadlevel.zig | 56 ---------- src/output.zig | 2 - src/repository.zig | 29 +++-- src/root.zig | 2 - src/service.zig | 29 ++--- test/e2e.sh | 22 +++- 20 files changed, 250 insertions(+), 543 deletions(-) delete mode 100644 src/defaults/high.load delete mode 100644 src/defaults/low.load delete mode 100644 src/defaults/medium.load delete mode 100644 src/loadclass.zig delete mode 100644 src/loadlevel.zig diff --git a/AGENTS.md b/AGENTS.md index 6a4dd56..43e99bb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -16,6 +16,9 @@ Guidance for AI coding agents working in `zag`, the Zig port of the - Keep CLI flags, JSON/XML output field order, config defaults and the on-disk job directory layout compatible with barn (`zag` replaces `barn` in names and paths). - Port specs from barn's unit tests alongside each module (`test` blocks). +- **Intentional deviation (issue #2)**: zag runs only one job at a time (strict FIFO); + barn's load levels are gone. Old `[load_levels]` / `max_concurrent_jobs` settings and + `ZAG_LOAD_LEVELS_*` env vars still load, are reported as non-fatal warnings, and ignored. ## Layout @@ -28,19 +31,17 @@ Guidance for AI coding agents working in `zag`, the Zig port of the | `src/fsutil.zig` | Atomic writes, trimmed reads, advisory `FileLock` | | `src/jsonpretty.zig` | Streaming JSON writer matching Jackson `INDENT_OUTPUT` layout | | `src/toml.zig` | Parser for barn's TOML subset (`[section]`, `key = value`, arrays) | -| `src/loadlevel.zig` | `high`/`medium`/`low` load levels | | `src/job.zig` | `Job`, `Manifest`, `ExitCode` types | | `src/dirs.zig` | On-disk layout under the base dir | | `src/statefiles.zig` | One-value-per-file job state (atomic) | | `src/repository.zig` | Job create/find/transition/retry persistence, `manifest.json` I/O | -| `src/config.zig` | Config structs, defaults, TOML loading/merging, `ZAG_*` env overrides, validation | -| `src/loadclass.zig` | `.load` whitelist parsing and load-level classifier | -| `src/defaults.zig`, `src/defaults/` | Default `zag.conf` and `*.load` files embedded in the binary | +| `src/config.zig` | Config structs, defaults, TOML loading/merging, `ZAG_*` env overrides, validation, deprecated-setting warnings | +| `src/defaults.zig`, `src/defaults/` | Default `zag.conf` embedded in the binary | | `src/retry.zig` | Retry decision and backoff/jitter delay | | `src/proc.zig` | Spawn with log redirection, process-group signals, liveness | | `src/runner.zig` | Runs one job: heartbeat, timeout, kill, completion, retry | | `src/recovery.zig` | Startup crash recovery of orphaned running jobs | -| `src/scheduler.zig` | Per-load-level concurrency, thread per job, `killJob` | +| `src/scheduler.zig` | Strict single-job FIFO scheduling, thread per job, `killJob` | | `src/usage.zig` | `ps`/`nvidia-smi` sampling, `usage.csv`, summaries | | `src/cleanup.zig` | Automatic and manual (`zag clean`) cleanup planning | | `src/jobjson.zig` | `Job` JSON (shared by CLI `--output=json` and IPC) | diff --git a/README.md b/README.md index e75059d..7bbcba2 100644 --- a/README.md +++ b/README.md @@ -172,7 +172,6 @@ There needs to be a zag service in order to run jobs (unless you use `--offline` |---------------|--------------------------------------------------------| | `job_id` | the id of the job | | `state` | `queued`, `running`, `succeeded`, `failed`, `canceled` | -| `load_level` | `HIGH`, `MEDIUM`, or `LOW` (auto-detected or manual) | | `tag` | user defined string | | `created_at` | Job creation timestamp | | `started_at` | Execution start timestamp | @@ -186,7 +185,7 @@ There needs to be a zag service in order to run jobs (unless you use `--offline` Users can tag jobs for the purpose of filtering using the `--tag=string` CLI option. -Jobs are automatically assigned a **load level** based on the command being run (see [Load Levels](#load-levels)). You can override this with `--load-level={high|medium|low}`. +Zag runs **one job at a time** (strict FIFO by creation order); there are no load levels. Developers can use the `--offline` command line option to test how the service behaves (e.g., creating tmp files). This runs the same code as the service but without having to run the service. @@ -195,8 +194,8 @@ Developers can use the `--offline` command line option to test how the service b `zag status` gets the status of all jobs found in /tmp. ``` -ID STATE LOAD TAG CREATED EXIT PID RETRIES NEXT RETRY -job-6d368040 succeeded medium - 2026-01-22 01:48:46 0 17486 - - +ID STATE TAG CREATED EXIT PID RETRIES NEXT RETRY +job-6d368040 succeeded - 2026-01-22 01:48:46 0 17486 - - Total: 1 job (1 succeeded) ``` @@ -215,35 +214,11 @@ Total: 1 job (1 succeeded) --- -## Load Levels +## Concurrency -Zag supports **per-level job limits** to allow concurrent execution of different types of jobs. For example, you can run multiple downloads while transcoding without overwhelming the system. - -### Load Level Types - -| Level | Default Max | Use Case | -|-------|-------------|----------| -| HIGH | 2 | CPU/GPU intensive (transcoding, encoding) | -| MEDIUM | 8 | General purpose commands | -| LOW | 32 | Network/IO intensive (downloads, uploads) | - -### Auto-Classification - -Jobs are automatically classified based on whitelist files in `/etc/zag/`: - -- `high.load` - ffmpeg, ffprobe, handbrake, x264, x265, etc. -- `medium.load` - general commands (default if not matched) -- `low.load` - curl, wget, rclone, rsync, aria2c, etc. - -### Manual Override - -```bash -# Run ffmpeg as LOW load (bypass normal HIGH classification) -zag run --load-level=low -- ffmpeg -i input.mp4 output.mp4 - -# Run curl as HIGH load (override normal LOW classification) -zag run --load-level=high -- curl -O https://example.com/file.zip -``` +Zag runs **one job at a time**: jobs execute strictly in FIFO order by creation time. There +are no load levels, per-level limits, or `--load-level` override (barn had these; zag +intentionally does not — see [Migration from barn](#migration-from-barn)). --- @@ -255,12 +230,11 @@ zag run --load-level=high -- curl -O https://example.com/file.zip | Binary | `barn` | `zag` | | Data dir | `/tmp/barn` | `/tmp/zag` | | Config | `/etc/barn/barn.conf`, `~/.config/barn/barn.conf` | `/etc/zag/zag.conf`, `~/.config/zag/zag.conf` | -| Environment overrides | `BARN_
_` | `ZAG_
_` (`ZAG_LOAD_LEVELS_MAX_HIGH_JOBS` works) | +| Environment overrides | `BARN_
_` | `ZAG_
_` (deprecated load-level variables are detected, warned about, and ignored) | | Socket | `/barn.sock` | `/zag.sock` (mode 0600) | -The CLI surface, `--output={json|xml}` formats, job states, load levels and the on-disk job -layout match barn. Where barn's code disagreed with its own documentation, zag follows the -documentation: +The CLI surface, `--output={json|xml}` formats, job states and the on-disk job layout match +barn. Where barn's code disagreed with its own documentation, zag follows the documentation: - `zag clean` behaves the same offline and through the service: with none of `--all`, `--older-than` or `--job-id` it removes nothing. @@ -273,9 +247,12 @@ documentation: used consistently by the daemon *and* the CLI. - Jobs run in their own process group, so `kill` and `service stop --force` take down the whole process tree. Job directories are created and deleted atomically. -- Without `config install`, the built-in `.load` lists still classify `ffmpeg` as HIGH and - `curl` as LOW. -- `config show` calls the load-limit section `load_levels`, matching the config file. +- Zag runs **one job at a time** (strict FIFO); barn's load levels (high/medium/low + classification, per-level limits, `--load-level`, the `loadLevel` JSON/XML field and the + `LOAD` column of `zag status`) do not exist. +- Old configs and environments still load fine: `[load_levels]`, `max_concurrent_jobs`, + `ZAG_LOAD_LEVELS_*` and `ZAG_SERVICE_MAX_CONCURRENT_JOBS` are detected, reported as + non-fatal warnings, and ignored. Not implemented: Windows (dropped on purpose), `max_disk_usage_gb`, `preserve_work_dir`, auto-update. diff --git a/src/cli.zig b/src/cli.zig index 74f3423..aeaf547 100644 --- a/src/cli.zig +++ b/src/cli.zig @@ -36,6 +36,8 @@ pub const Context = struct { config_value: config.Config = .{}, config_error: ?config.Error = null, config_diag: config.Diagnostic = .{}, + /// Deprecation warnings collected while loading the config; printed once per process. + config_deprecations: std.ArrayList([]const u8) = .empty, pub fn flag(self: *const Context, name: []const u8) bool { return self.parsed.flag(name); @@ -71,8 +73,11 @@ pub const Context = struct { fn loadConfigOnce(self: *Context) void { if (self.config_loaded) return; self.config_loaded = true; - if (config.load(self.arena, self.io, self.env, .{ .explicit_path = self.value("config") }, &self.config_diag)) |c| { + if (config.load(self.arena, self.io, self.env, .{ .explicit_path = self.value("config") }, &self.config_diag, &self.config_deprecations)) |c| { self.config_value = c; + for (self.config_deprecations.items) |w| { + self.stderr.print("warning: {s}\n", .{w}) catch {}; + } } else |err| { self.config_error = err; } @@ -423,7 +428,7 @@ test "per-command help" { defer arena.deinit(); const r = try runCaptured(arena.allocator(), &.{ "run", "--help" }, null); try std.testing.expectEqual(exit_ok, r.code); - try std.testing.expect(std.mem.indexOf(u8, r.out, "--load-level") != null); + try std.testing.expect(std.mem.indexOf(u8, r.out, "--tag") != null); const s = try runCaptured(arena.allocator(), &.{ "service", "--help" }, null); try std.testing.expect(std.mem.indexOf(u8, s.out, "restart") != null); } diff --git a/src/cli_admin.zig b/src/cli_admin.zig index 4f48fd0..2c5476d 100644 --- a/src/cli_admin.zig +++ b/src/cli_admin.zig @@ -21,7 +21,6 @@ const proc = @import("proc.zig"); const timestamp = @import("timestamp.zig"); const Repository = @import("repository.zig").Repository; const state_mod = @import("state.zig"); -const Classifier = @import("loadclass.zig").Classifier; const jsonpretty = @import("jsonpretty.zig"); const servicemgr = @import("servicemgr.zig"); @@ -57,7 +56,7 @@ const ReloadState = struct { fn reloadConfig(ctx_ptr: ?*anyopaque, arena: Allocator) anyerror!config.Config { const st: *const ReloadState = @ptrCast(@alignCast(ctx_ptr.?)); - return config.load(arena, st.io, st.env, .{ .explicit_path = st.explicit_path }, null); + return config.load(arena, st.io, st.env, .{ .explicit_path = st.explicit_path }, null, null); } fn startBackground(ctx: *Context) !u8 { @@ -125,14 +124,11 @@ pub fn cmdServiceStart(ctx: *Context) !u8 { } logging.setFromConfig(cfg.service.log_level); - const sys_dir = try config.systemConfigDir(ctx.arena, ctx.env); - const classifier = try Classifier.loadOrDefaults(ctx.arena, ctx.io, sys_dir); const reload_state = try ctx.arena.create(ReloadState); reload_state.* = .{ .io = ctx.io, .env = ctx.env, .explicit_path = ctx.value("config") }; var svc = service_mod.Service.init(ctx.gpa, ctx.io, &dirs, .{ .config = cfg, - .classifier = classifier, .reload_fn = reloadConfig, .reload_ctx = reload_state, }); @@ -554,11 +550,10 @@ pub const config_show_usage = \\ ; -fn configNode(arena: Allocator, cfg: config.Config, socket: []const u8) !Node { +fn configNode(arena: Allocator, cfg: config.Config, socket: []const u8, warnings: []const []const u8) !Node { var root = MapBuilder.init(arena); var s = MapBuilder.init(arena); try s.put("log_level", Node.str(@tagName(cfg.service.log_level))); - try s.put("max_concurrent_jobs", Node.num(cfg.service.max_concurrent_jobs)); try s.put("heartbeat_interval_seconds", Node.num(cfg.service.heartbeat_interval_seconds)); try s.put("ipc_socket", Node.str(socket)); try s.put("stale_heartbeat_threshold_seconds", Node.num(cfg.service.stale_heartbeat_threshold_seconds)); @@ -588,11 +583,11 @@ fn configNode(arena: Allocator, cfg: config.Config, socket: []const u8) !Node { try st.put("preserve_work_dir", .{ .boolean = cfg.storage.preserve_work_dir }); try root.put("storage", try st.done()); - var l = MapBuilder.init(arena); - try l.put("max_high_jobs", Node.num(cfg.load_levels.max_high_jobs)); - try l.put("max_medium_jobs", Node.num(cfg.load_levels.max_medium_jobs)); - try l.put("max_low_jobs", Node.num(cfg.load_levels.max_low_jobs)); - try root.put("load_levels", try l.done()); + if (warnings.len > 0) { + const wn = try arena.alloc(Node, warnings.len); + for (warnings, wn) |msg, *n| n.* = Node.str(msg); + try root.put("warnings", .{ .list = wn }); + } return root.done(); } @@ -602,7 +597,7 @@ pub fn cmdConfigShow(ctx: *Context) !u8 { const socket = if (show_defaults) try (config.Config{}).ipcSocketPath(ctx.arena) else try cfg.ipcSocketPath(ctx.arena); if (ctx.format != .human) { - try ctx.emit(try configNode(ctx.arena, cfg, socket)); + try ctx.emit(try configNode(ctx.arena, cfg, socket, ctx.config_deprecations.items)); return exit_ok; } @@ -621,8 +616,8 @@ pub fn cmdConfigShow(ctx: *Context) !u8 { try w.print("Config file: {s}\n", .{try std.mem.join(ctx.arena, ", ", found.items)}); } } - try w.print("\n[service]\nlog_level = {s}\nmax_concurrent_jobs = {d}\nheartbeat_interval_seconds = {d}\nipc_socket = {s}\nstale_heartbeat_threshold_seconds = {d}\n", .{ - @tagName(cfg.service.log_level), cfg.service.max_concurrent_jobs, cfg.service.heartbeat_interval_seconds, socket, cfg.service.stale_heartbeat_threshold_seconds, + try w.print("\n[service]\nlog_level = {s}\nheartbeat_interval_seconds = {d}\nipc_socket = {s}\nstale_heartbeat_threshold_seconds = {d}\n", .{ + @tagName(cfg.service.log_level), cfg.service.heartbeat_interval_seconds, socket, cfg.service.stale_heartbeat_threshold_seconds, }); try w.print("\n[jobs]\ndefault_timeout_seconds = {d}\nmax_retries = {d}\nretry_delay_seconds = {d}\nretry_backoff_multiplier = {d:.1}\nretry_on_exit_codes = [", .{ cfg.jobs.default_timeout_seconds, cfg.jobs.max_retries, cfg.jobs.retry_delay_seconds, cfg.jobs.retry_backoff_multiplier, @@ -635,9 +630,6 @@ pub fn cmdConfigShow(ctx: *Context) !u8 { try w.print("\n[storage]\nbase_dir = {s}\nmax_disk_usage_gb = {d}\npreserve_work_dir = {any}\n", .{ cfg.storage.base_dir, cfg.storage.max_disk_usage_gb, cfg.storage.preserve_work_dir, }); - try w.print("\n[load_levels]\nmax_high_jobs = {d}\nmax_medium_jobs = {d}\nmax_low_jobs = {d}\n", .{ - cfg.load_levels.max_high_jobs, cfg.load_levels.max_medium_jobs, cfg.load_levels.max_low_jobs, - }); return exit_ok; } @@ -647,6 +639,7 @@ pub const config_validate_usage = \\Usage: zag config validate --file \\ \\Check a configuration file for syntax errors, unknown sections or keys, and bad values. + \\Deprecated settings are reported as warnings and do not affect the exit code. \\Exits 1 if anything is wrong. \\ \\Options: @@ -676,38 +669,53 @@ pub fn cmdConfigValidate(ctx: *Context) !u8 { try list.append(a, .{ .section = "", .key = "", .message = try std.fmt.allocPrint(a, "Parse error at line {d}: {s}", .{ td.line, what }) }); } - if (list.items.len == 0) { - if (ctx.format == .human) { - try ctx.stdout.print("Configuration is valid: {s}\n", .{path}); - } else { - var m = MapBuilder.init(a); - try m.put("valid", .{ .boolean = true }); - try m.put("file", Node.str(path)); - try ctx.emit(try m.done()); - } - return exit_ok; + var error_count: usize = 0; + for (list.items) |p| { + if (!p.is_warning) error_count += 1; } + const warnings = try problemNodes(a, list.items, true); + const errors = try problemNodes(a, list.items, false); if (ctx.format == .human) { - try ctx.stdout.print("Configuration errors in {s}:\n\n", .{path}); - for (list.items) |p| { - if (p.key.len > 0) try ctx.stdout.print(" Key '{s}': {s}\n", .{ p.key, p.message }) else try ctx.stdout.print(" {s}\n", .{p.message}); + for (list.items) |p| if (p.is_warning) try ctx.stdout.print(" Warning: {s}\n", .{p.message}); + if (error_count == 0) { + try ctx.stdout.print("Configuration is valid: {s}\n", .{path}); + } else { + try ctx.stdout.print("\nConfiguration errors in {s}:\n\n", .{path}); + for (list.items) |p| { + if (p.is_warning) continue; + if (p.key.len > 0) try ctx.stdout.print(" Key '{s}': {s}\n", .{ p.key, p.message }) else try ctx.stdout.print(" {s}\n", .{p.message}); + } } } else { - const nodes = try a.alloc(Node, list.items.len); - for (list.items, nodes) |p, *n| { - var em = MapBuilder.init(a); - if (p.key.len > 0) try em.put("key", Node.str(p.key)); - try em.put("message", Node.str(p.message)); - n.* = try em.done(); - } var m = MapBuilder.init(a); - try m.put("valid", .{ .boolean = false }); + try m.put("valid", .{ .boolean = error_count == 0 }); try m.put("file", Node.str(path)); - try m.put("errors", .{ .list = nodes }); + if (warnings.len > 0) try m.put("warnings", .{ .list = warnings }); + if (error_count > 0) try m.put("errors", .{ .list = errors }); try ctx.emit(try m.done()); } - return exit_error; + return if (error_count == 0) exit_ok else exit_error; +} + +/// The JSON node list for the warnings or the errors of a problem list. +fn problemNodes(a: Allocator, list: []const config.Problem, warnings_only: bool) ![]Node { + var count: usize = 0; + for (list) |p| { + if (p.is_warning == warnings_only) count += 1; + } + if (count == 0) return a.alloc(Node, 0); + const nodes = try a.alloc(Node, count); + var i: usize = 0; + for (list) |p| { + if (p.is_warning != warnings_only) continue; + var em = MapBuilder.init(a); + if (p.key.len > 0) try em.put("key", Node.str(p.key)); + try em.put("message", Node.str(p.message)); + nodes[i] = try em.done(); + i += 1; + } + return nodes; } fn writeFileCreatingParents(ctx: *Context, path: []const u8, data: []const u8) !void { @@ -756,8 +764,7 @@ pub const config_install_opts = [_]args_mod.Opt{ pub const config_install_usage = \\Usage: zag config install [options] \\ - \\Install the default configuration files (zag.conf and the high/medium/low .load - \\whitelists) into the system config directory. + \\Install the default configuration file (zag.conf) into the system config directory. \\ \\Options: \\ -d, --directory Target directory (default: /etc/zag) @@ -824,7 +831,6 @@ const bash_completion = \\ case "$prev" in \\ -o|--output) COMPREPLY=( $(compgen -W "human json xml" -- "$cur") ); return ;; \\ -s|--state) COMPREPLY=( $(compgen -W "queued running succeeded failed canceled killed" -- "$cur") ); return ;; - \\ -l|--load-level) COMPREPLY=( $(compgen -W "high medium low" -- "$cur") ); return ;; \\ --config|--barn-dir|-d|--directory|-p|--path|-f|--file) COMPREPLY=( $(compgen -f -- "$cur") ); return ;; \\ esac \\ if [[ -z "$cmd" ]]; then @@ -832,7 +838,7 @@ const bash_completion = \\ fi \\ local opts="$global" \\ case "$cmd" in - \\ run) opts="$opts -t --tag -l --load-level --max-retries --retry-delay --timeout" ;; + \\ run) opts="$opts -t --tag --max-retries --retry-delay --timeout" ;; \\ status) opts="$opts -t --tag -s --state -n --limit" ;; \\ describe) opts="$opts --logs --manifest" ;; \\ usage) opts="$opts -n --limit --csv --summary" ;; diff --git a/src/cli_jobs.zig b/src/cli_jobs.zig index 09d460a..203fe47 100644 --- a/src/cli_jobs.zig +++ b/src/cli_jobs.zig @@ -10,7 +10,6 @@ const Node = output.Node; const MapBuilder = output.MapBuilder; const jsonpretty = @import("jsonpretty.zig"); const jobjson = @import("jobjson.zig"); -const config = @import("config.zig"); const dirs_mod = @import("dirs.zig"); const Dirs = dirs_mod.Dirs; const Repository = @import("repository.zig").Repository; @@ -23,8 +22,6 @@ const duration = @import("duration.zig"); const timestamp = @import("timestamp.zig"); const proc = @import("proc.zig"); const state_mod = @import("state.zig"); -const LoadLevel = @import("loadlevel.zig").LoadLevel; -const Classifier = @import("loadclass.zig").Classifier; const Job = @import("job.zig").Job; const Instant = @import("job.zig").Instant; @@ -113,7 +110,6 @@ fn summaryNode(arena: Allocator, jobs: []const Job) !Node { pub const run_opts = [_]args_mod.Opt{ .{ .long = "tag", .short = 't', .takes_value = true }, - .{ .long = "load-level", .short = 'l', .takes_value = true }, .{ .long = "max-retries", .takes_value = true }, .{ .long = "retry-delay", .takes_value = true }, .{ .long = "timeout", .takes_value = true }, @@ -127,7 +123,6 @@ pub const run_usage = \\ \\Options: \\ -t, --tag Tag for filtering jobs - \\ -l, --load-level high, medium or low (default: auto-detect) \\ --max-retries Override the maximum number of retries \\ --retry-delay Override the initial retry delay \\ --timeout Kill the job after this many seconds @@ -141,9 +136,6 @@ pub fn cmdRun(ctx: *Context) !u8 { const command = ctx.parsed.positionals; if (command.len == 0) return ctx.usageError("No command specified", .{}); - var load_level: ?LoadLevel = null; - if (ctx.value("load-level")) |l| load_level = LoadLevel.parse(l) orelse - return ctx.usageError("Invalid load level '{s}'. Valid values are: high, medium, low", .{l}); var max_retries: ?u32 = null; if (ctx.value("max-retries")) |v| max_retries = parseCount(v) orelse return ctx.usageError("Invalid --max-retries '{s}'", .{v}); var retry_delay: ?u32 = null; @@ -154,7 +146,7 @@ pub fn cmdRun(ctx: *Context) !u8 { var job: Job = undefined; if (ctx.flag("offline")) { - job = (try runOffline(ctx, command, load_level, max_retries, retry_delay, timeout)) orelse return exit_error; + job = (try runOffline(ctx, command, max_retries, retry_delay, timeout)) orelse return exit_error; } else { var p: Payload = undefined; p.init(ctx.arena); @@ -164,7 +156,6 @@ pub fn cmdRun(ctx: *Context) !u8 { for (command) |c| try p.w.string(c); try p.w.endArray(); if (ctx.value("tag")) |t| try p.w.field("tag", .string, t); - if (load_level) |l| try p.w.field("loadLevel", .string, l.upper()); if (max_retries) |n| try p.w.field("maxRetries", .int, n); if (retry_delay) |n| try p.w.field("retryDelaySeconds", .int, n); if (timeout) |n| try p.w.field("timeoutSeconds", .int, n); @@ -186,17 +177,14 @@ pub fn cmdRun(ctx: *Context) !u8 { return exit_ok; } -fn runOffline(ctx: *Context, command: []const []const u8, load_level: ?LoadLevel, max_retries: ?u32, retry_delay: ?u32, timeout: ?u32) !?Job { +fn runOffline(ctx: *Context, command: []const []const u8, max_retries: ?u32, retry_delay: ?u32, timeout: ?u32) !?Job { var dirs = try ctx.openDirs(); defer dirs.close(ctx.io); const repo = Repository.init(ctx.io, &dirs); const cfg = ctx.configOrDefault(); - const sys_dir = try config.systemConfigDir(ctx.arena, ctx.env); - const classifier = try Classifier.loadOrDefaults(ctx.arena, ctx.io, sys_dir); const created = try repo.create(ctx.arena, command, .{ .tag = ctx.value("tag"), - .load_level = load_level orelse classifier.classify(command), .max_retries = max_retries orelse cfg.jobs.max_retries, .retry_delay_seconds = retry_delay orelse cfg.jobs.retry_delay_seconds, .retry_backoff_multiplier = cfg.jobs.retry_backoff_multiplier, @@ -308,8 +296,6 @@ fn printStatusTable(ctx: *Context, jobs: []const Job) !void { try w.writeAll(sep); try pad(w, "STATE", 9); try w.writeAll(sep); - try pad(w, "LOAD", 6); - try w.writeAll(sep); try pad(w, "TAG", tag_w); try w.writeAll(sep); try pad(w, "CREATED", 19); @@ -327,8 +313,6 @@ fn printStatusTable(ctx: *Context, jobs: []const Job) !void { try w.writeAll(sep); try colorCell(ctx, j.state.lower(), 9, stateStyle(j.state)); try w.writeAll(sep); - try pad(w, j.load_level.lower(), 6); - try w.writeAll(sep); try pad(w, j.tag orelse "-", tag_w); try w.writeAll(sep); try pad(w, fmtTime(a, j.created_at), 19); diff --git a/src/config.zig b/src/config.zig index f85091d..13cdefc 100644 --- a/src/config.zig +++ b/src/config.zig @@ -19,20 +19,12 @@ pub const LogLevel = enum { pub const Service = struct { log_level: LogLevel = .info, - /// Deprecated: superseded by `[load_levels]`. - max_concurrent_jobs: u32 = 4, heartbeat_interval_seconds: u32 = 5, /// Defaults to `/zag.sock` when unset. ipc_socket: ?[]const u8 = null, stale_heartbeat_threshold_seconds: u32 = 30, }; -pub const LoadLevels = struct { - max_high_jobs: u32 = 2, - max_medium_jobs: u32 = 8, - max_low_jobs: u32 = 32, -}; - pub const Jobs = struct { default_timeout_seconds: u32 = 3600, max_retries: u32 = 3, @@ -63,7 +55,6 @@ pub const Config = struct { jobs: Jobs = .{}, cleanup: Cleanup = .{}, storage: Storage = .{}, - load_levels: LoadLevels = .{}, /// Socket path: explicit `service.ipc_socket`, else `/zag.sock`. pub fn ipcSocketPath(self: Config, arena: Allocator) ![]const u8 { @@ -75,10 +66,6 @@ pub const Config = struct { const checks = .{ .{ "service", "heartbeat_interval_seconds", self.service.heartbeat_interval_seconds, 1 }, .{ "service", "stale_heartbeat_threshold_seconds", self.service.stale_heartbeat_threshold_seconds, 1 }, - .{ "service", "max_concurrent_jobs", self.service.max_concurrent_jobs, 1 }, - .{ "load_levels", "max_high_jobs", self.load_levels.max_high_jobs, 1 }, - .{ "load_levels", "max_medium_jobs", self.load_levels.max_medium_jobs, 1 }, - .{ "load_levels", "max_low_jobs", self.load_levels.max_low_jobs, 1 }, .{ "jobs", "default_timeout_seconds", self.jobs.default_timeout_seconds, 1 }, .{ "cleanup", "max_age_hours", self.cleanup.max_age_hours, 1 }, .{ "cleanup", "cleanup_interval_minutes", self.cleanup.cleanup_interval_minutes, 1 }, @@ -179,7 +166,6 @@ pub fn fromDoc(arena: Allocator, doc: toml.Doc, diag: ?*Diagnostic) Error!Config try applySection(arena, Jobs, "jobs", doc.get("jobs"), &cfg.jobs, diag); try applySection(arena, Cleanup, "cleanup", doc.get("cleanup"), &cfg.cleanup, diag); try applySection(arena, Storage, "storage", doc.get("storage"), &cfg.storage, diag); - try applySection(arena, LoadLevels, "load_levels", doc.get("load_levels"), &cfg.load_levels, diag); try cfg.validate(diag); return cfg; } @@ -191,9 +177,15 @@ pub const Problem = struct { /// Empty for problems that concern a whole section. key: []const u8, message: []const u8, + /// Non-fatal notice (a deprecated setting); never fails validation. + is_warning: bool = false, }; -const known_sections = [_][]const u8{ "service", "jobs", "cleanup", "storage", "load_levels" }; +/// A setting that pre-flattening configs still carry: it loads fine, is ignored, and is +/// reported as a warning (`Problem.is_warning`). +fn isDeprecatedKey(section: []const u8, key: []const u8) bool { + return std.mem.eql(u8, section, "service") and std.mem.eql(u8, key, "max_concurrent_jobs"); +} fn expectation(comptime T: type) []const u8 { return switch (@typeInfo(T)) { @@ -229,24 +221,50 @@ fn checkSection(arena: Allocator, comptime T: type, name: []const u8, section: t } } if (!known) { - try out.append(arena, .{ - .section = name, - .key = key, - .message = try std.fmt.allocPrint(arena, "Unknown key '{s}' in [{s}] section", .{ key, name }), - }); + if (isDeprecatedKey(name, key)) { + try out.append(arena, .{ + .section = name, + .key = key, + .message = try std.fmt.allocPrint(arena, "'{s}' is deprecated: only one job runs at a time; remove it from your config", .{key}), + .is_warning = true, + }); + } else { + try out.append(arena, .{ + .section = name, + .key = key, + .message = try std.fmt.allocPrint(arena, "Unknown key '{s}' in [{s}] section", .{ key, name }), + }); + } } } } /// Everything wrong with a parsed config document: unknown sections and keys, values of the -/// wrong type, and values outside their allowed range. +/// wrong type, and values outside their allowed range. Deprecated settings are reported as +/// warnings and never fail validation. pub fn problems(arena: Allocator, doc: toml.Doc) Allocator.Error![]const Problem { var out: std.ArrayList(Problem) = .empty; var it = doc.iterator(); while (it.next()) |entry| { const name = entry.key_ptr.*; const section = entry.value_ptr.*; - if (std.mem.eql(u8, name, "service")) try checkSection(arena, Service, name, section, &out) else if (std.mem.eql(u8, name, "jobs")) try checkSection(arena, Jobs, name, section, &out) else if (std.mem.eql(u8, name, "cleanup")) try checkSection(arena, Cleanup, name, section, &out) else if (std.mem.eql(u8, name, "storage")) try checkSection(arena, Storage, name, section, &out) else if (std.mem.eql(u8, name, "load_levels")) try checkSection(arena, LoadLevels, name, section, &out) else { + if (std.mem.eql(u8, name, "service")) { + try checkSection(arena, Service, name, section, &out); + } else if (std.mem.eql(u8, name, "jobs")) { + try checkSection(arena, Jobs, name, section, &out); + } else if (std.mem.eql(u8, name, "cleanup")) { + try checkSection(arena, Cleanup, name, section, &out); + } else if (std.mem.eql(u8, name, "storage")) { + try checkSection(arena, Storage, name, section, &out); + } else if (std.mem.eql(u8, name, "load_levels")) { + // Kept for compatibility with pre-flattening (and barn) configs. + try out.append(arena, .{ + .section = name, + .key = "", + .message = try std.fmt.allocPrint(arena, "[{s}] is deprecated: only one job runs at a time; remove it from your config", .{name}), + .is_warning = true, + }); + } else { try out.append(arena, .{ .section = name, .key = "", @@ -287,20 +305,33 @@ pub fn mergeInto(arena: Allocator, dst: *toml.Doc, src: toml.Doc) Allocator.Erro const env_prefix = "ZAG_"; const env_sections = [_]struct { name: []const u8, canonical: []const u8 }{ - .{ .name = "load_levels", .canonical = "load_levels" }, - .{ .name = "loadlevels", .canonical = "load_levels" }, .{ .name = "service", .canonical = "service" }, .{ .name = "jobs", .canonical = "jobs" }, .{ .name = "cleanup", .canonical = "cleanup" }, .{ .name = "storage", .canonical = "storage" }, }; -/// Applies `ZAG_
_=value` overrides, e.g. `ZAG_JOBS_MAX_RETRIES=5` or -/// `ZAG_LOAD_LEVELS_MAX_HIGH_JOBS=1`. Values are typed as bool, int, float, else string. -pub fn applyEnvironment(arena: Allocator, doc: *toml.Doc, env: *const Environ.Map) Allocator.Error!void { +/// `ZAG_LOAD_LEVELS_*`, `ZAG_LOADLEVELS_*` and `ZAG_SERVICE_MAX_CONCURRENT_JOBS` still +/// survive in old service files and shell profiles; `rest` is the name without `ZAG_`. +fn isDeprecatedEnvName(rest: []const u8) bool { + return (rest.len > "load_levels_".len and std.ascii.startsWithIgnoreCase(rest, "load_levels_")) or + (rest.len > "loadlevels_".len and std.ascii.startsWithIgnoreCase(rest, "loadlevels_")) or + std.ascii.eqlIgnoreCase(rest, "service_max_concurrent_jobs"); +} + +/// Applies `ZAG_
_=value` overrides, e.g. `ZAG_JOBS_MAX_RETRIES=5`. Values are +/// typed as bool, int, float, else string. Deprecated load-level variables are skipped and, +/// when `deprecations` is non-null, reported there. +pub fn applyEnvironment(arena: Allocator, doc: *toml.Doc, env: *const Environ.Map, deprecations: ?*std.ArrayList([]const u8)) Allocator.Error!void { for (env.keys(), env.values()) |name, value| { if (!std.ascii.startsWithIgnoreCase(name, env_prefix)) continue; const rest = name[env_prefix.len..]; + if (isDeprecatedEnvName(rest)) { + if (deprecations) |list| { + try list.append(arena, try std.fmt.allocPrint(arena, "{s} is deprecated: only one job runs at a time; remove it from your environment", .{name})); + } + continue; + } for (env_sections) |sec| { if (rest.len <= sec.name.len + 1) continue; if (!std.ascii.eqlIgnoreCase(rest[0..sec.name.len], sec.name) or rest[sec.name.len] != '_') continue; @@ -389,8 +420,10 @@ pub const LoadOptions = struct { }; /// Loads the effective configuration. Unreadable or malformed *implicit* files (system/user) -/// are skipped like barn does; an explicit file that fails to parse is reported. -pub fn load(arena: Allocator, io: Io, env: *const Environ.Map, opts: LoadOptions, diag: ?*Diagnostic) Error!Config { +/// are skipped like barn does; an explicit file that fails to parse is reported. When +/// `deprecations` is non-null, removed settings found in the files or the environment are +/// appended to it as warnings. +pub fn load(arena: Allocator, io: Io, env: *const Environ.Map, opts: LoadOptions, diag: ?*Diagnostic, deprecations: ?*std.ArrayList([]const u8)) Error!Config { var merged: toml.Doc = .empty; const paths = opts.search_paths orelse try searchPaths(arena, env); for (paths) |p| { @@ -403,7 +436,12 @@ pub fn load(arena: Allocator, io: Io, env: *const Environ.Map, opts: LoadOptions if (opts.explicit_path) |p| { if (try loadFile(arena, io, p, diag)) |d| try mergeInto(arena, &merged, d); } - try applyEnvironment(arena, &merged, env); + try applyEnvironment(arena, &merged, env, deprecations); + if (deprecations) |list| { + for (try problems(arena, merged)) |p| { + if (p.is_warning) try list.append(arena, p.message); + } + } return fromDoc(arena, merged, diag); } @@ -420,9 +458,6 @@ test "defaults match barn" { try std.testing.expectEqual(LogLevel.info, cfg.service.log_level); try std.testing.expectEqual(@as(u32, 5), cfg.service.heartbeat_interval_seconds); try std.testing.expectEqual(@as(u32, 30), cfg.service.stale_heartbeat_threshold_seconds); - try std.testing.expectEqual(@as(u32, 2), cfg.load_levels.max_high_jobs); - try std.testing.expectEqual(@as(u32, 8), cfg.load_levels.max_medium_jobs); - try std.testing.expectEqual(@as(u32, 32), cfg.load_levels.max_low_jobs); try std.testing.expectEqual(@as(u32, 3600), cfg.jobs.default_timeout_seconds); try std.testing.expectEqual(@as(u32, 3), cfg.jobs.max_retries); try std.testing.expectEqual(@as(f64, 2.0), cfg.jobs.retry_backoff_multiplier); @@ -439,7 +474,6 @@ test "embedded default zag.conf parses to the built-in defaults" { const defaults = @import("defaults.zig"); const cfg = try fromDoc(arena.allocator(), try testDoc(arena.allocator(), defaults.zag_conf), null); try std.testing.expectEqual((Config{}).jobs.max_retries, cfg.jobs.max_retries); - try std.testing.expectEqual((Config{}).load_levels, cfg.load_levels); try std.testing.expectEqual((Config{}).cleanup, cfg.cleanup); try std.testing.expectEqual(@as(usize, 0), cfg.jobs.retry_on_exit_codes.len); try std.testing.expectEqualStrings("/tmp/zag", cfg.storage.base_dir); @@ -479,8 +513,6 @@ test "validation rejects bad values and names the key" { const a = arena.allocator(); var diag: Diagnostic = .{}; - try std.testing.expectError(error.OutOfRange, fromDoc(a, try testDoc(a, "[load_levels]\nmax_high_jobs = 0\n"), &diag)); - try std.testing.expectEqualStrings("max_high_jobs", diag.key); try std.testing.expectError(error.OutOfRange, fromDoc(a, try testDoc(a, "[jobs]\nretry_backoff_multiplier = 0.5\n"), &diag)); try std.testing.expectEqualStrings("retry_backoff_multiplier", diag.key); try std.testing.expectError(error.InvalidValue, fromDoc(a, try testDoc(a, "[service]\nlog_level = \"loud\"\n"), &diag)); @@ -489,7 +521,7 @@ test "validation rejects bad values and names the key" { try std.testing.expectError(error.InvalidValue, fromDoc(a, try testDoc(a, "[cleanup]\nenabled = 5\n"), &diag)); } -test "environment overrides, including load_levels" { +test "environment overrides; deprecated load-level vars are warned about and ignored" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); @@ -498,6 +530,7 @@ test "environment overrides, including load_levels" { try env.put("ZAG_JOBS_MAX_RETRIES", "7"); try env.put("ZAG_LOAD_LEVELS_MAX_HIGH_JOBS", "1"); try env.put("ZAG_LOADLEVELS_MAX_LOW_JOBS", "4"); + try env.put("ZAG_SERVICE_MAX_CONCURRENT_JOBS", "2"); try env.put("ZAG_CLEANUP_ENABLED", "false"); try env.put("ZAG_SERVICE_LOG_LEVEL", "warn"); try env.put("ZAG_JOBS_RETRY_BACKOFF_MULTIPLIER", "1.5"); @@ -505,11 +538,14 @@ test "environment overrides, including load_levels" { try env.put("OTHER_JOBS_MAX_RETRIES", "99"); var doc = try testDoc(a, "[jobs]\nmax_retries = 2\n"); - try applyEnvironment(a, &doc, &env); + var deprecations: std.ArrayList([]const u8) = .empty; + try applyEnvironment(a, &doc, &env, &deprecations); + try std.testing.expectEqual(@as(usize, 3), deprecations.items.len); + for (deprecations.items) |msg| try std.testing.expect(std.mem.indexOf(u8, msg, "deprecated") != null); + try std.testing.expect(doc.get("load_levels") == null); + const cfg = try fromDoc(a, doc, null); try std.testing.expectEqual(@as(u32, 7), cfg.jobs.max_retries); - try std.testing.expectEqual(@as(u32, 1), cfg.load_levels.max_high_jobs); - try std.testing.expectEqual(@as(u32, 4), cfg.load_levels.max_low_jobs); try std.testing.expect(!cfg.cleanup.enabled); try std.testing.expectEqual(LogLevel.warn, cfg.service.log_level); try std.testing.expectEqual(@as(f64, 1.5), cfg.jobs.retry_backoff_multiplier); @@ -542,7 +578,7 @@ test "files merge per key with explicit file and env on top" { const cfg = try load(a, io, &env, .{ .search_paths = &paths, .explicit_path = try std.fmt.allocPrint(a, "{s}/explicit.conf", .{base}), - }, null); + }, null, null); try std.testing.expectEqual(@as(u32, 2), cfg.jobs.max_retries); // user beats system try std.testing.expectEqual(@as(u32, 99), cfg.jobs.retry_delay_seconds); // env beats files try std.testing.expectEqual(@as(u32, 20), cfg.cleanup.max_age_hours); // explicit beats system @@ -551,7 +587,7 @@ test "files merge per key with explicit file and env on top" { try std.testing.expectError(error.ParseFailed, load(a, io, &env, .{ .search_paths = &.{}, .explicit_path = try std.fmt.allocPrint(a, "{s}/broken.conf", .{base}), - }, &diag)); + }, &diag, null)); try std.testing.expectEqual(@as(usize, 1), diag.line); } @@ -603,3 +639,53 @@ test "problems reports unknown names, bad types and ranges" { try std.testing.expectEqual(@as(usize, 1), range.len); try std.testing.expectEqualStrings("retry_backoff_multiplier", range[0].key); } + +test "deprecated settings warn instead of failing validation" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + + const ps = try problems(a, try testDoc(a, + \\ [service] + \\ max_concurrent_jobs = 4 + \\ [load_levels] + \\ max_high_jobs = 2 + )); + try std.testing.expectEqual(@as(usize, 2), ps.len); + var saw_section = false; + var saw_key = false; + for (ps) |p| { + try std.testing.expect(p.is_warning); + try std.testing.expect(std.mem.indexOf(u8, p.message, "deprecated") != null); + if (std.mem.eql(u8, p.section, "load_levels")) saw_section = true; + if (std.mem.eql(u8, p.key, "max_concurrent_jobs")) saw_key = true; + } + try std.testing.expect(saw_section and saw_key); + + // The deprecated values never make it into the config, and nothing errors. + const cfg = try fromDoc(a, try testDoc(a, "[service]\nmax_concurrent_jobs = 4\n[load_levels]\nmax_high_jobs = 2\n"), null); + try std.testing.expectEqual((Config{}).jobs.max_retries, cfg.jobs.max_retries); +} + +test "load reports deprecated settings from files and env" { + const io = std.testing.io; + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + + try tmp.dir.writeFile(io, .{ .sub_path = "old.conf", .data = "[service]\nmax_concurrent_jobs = 4\n[load_levels]\nmax_high_jobs = 2\n" }); + + var env = Environ.Map.init(std.testing.allocator); + defer env.deinit(); + try env.put("ZAG_LOAD_LEVELS_MAX_HIGH_JOBS", "1"); + + var deprecations: std.ArrayList([]const u8) = .empty; + const cfg = try load(a, io, &env, .{ + .search_paths = &.{try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}/old.conf", .{tmp.sub_path})}, + }, null, &deprecations); + try std.testing.expectEqual(@as(usize, 3), deprecations.items.len); + for (deprecations.items) |msg| try std.testing.expect(std.mem.indexOf(u8, msg, "deprecated") != null); + try std.testing.expectEqual(LogLevel.info, cfg.service.log_level); +} diff --git a/src/defaults.zig b/src/defaults.zig index e6e4ae0..61c742f 100644 --- a/src/defaults.zig +++ b/src/defaults.zig @@ -1,15 +1,9 @@ //! Default configuration files embedded in the binary (written by `zag config install`). pub const zag_conf = @embedFile("defaults/zag.conf"); -pub const high_load = @embedFile("defaults/high.load"); -pub const medium_load = @embedFile("defaults/medium.load"); -pub const low_load = @embedFile("defaults/low.load"); pub const File = struct { name: []const u8, content: []const u8 }; /// Everything `config install` writes into the system config directory. pub const files = [_]File{ .{ .name = "zag.conf", .content = zag_conf }, - .{ .name = "high.load", .content = high_load }, - .{ .name = "medium.load", .content = medium_load }, - .{ .name = "low.load", .content = low_load }, }; diff --git a/src/defaults/high.load b/src/defaults/high.load deleted file mode 100644 index 462018f..0000000 --- a/src/defaults/high.load +++ /dev/null @@ -1,16 +0,0 @@ -# High load commands - CPU/GPU intensive (transcoding, encoding) -# Maximum concurrent: 2 (default) -# -# Format: -# - Binary name: ffmpeg (matches any path ending with this executable) -# - Full path: /usr/local/bin/ffmpeg -# - Directory: /opt/encoders/ (trailing slash = match any executable in this directory) - -ffmpeg -ffprobe -handbrake -HandBrakeCLI -x264 -x265 -av1an -svt-av1 diff --git a/src/defaults/low.load b/src/defaults/low.load deleted file mode 100644 index e19e570..0000000 --- a/src/defaults/low.load +++ /dev/null @@ -1,16 +0,0 @@ -# Low load commands - Network/IO intensive (downloads, uploads) -# Maximum concurrent: 32 (default) -# -# Format: -# - Binary name: curl (matches any path ending with this executable) -# - Full path: /usr/local/bin/rclone -# - Directory: /opt/downloaders/ (trailing slash = match any executable in this directory) - -curl -wget -rclone -rsync -aria2c -scp -sftp -cadaver diff --git a/src/defaults/medium.load b/src/defaults/medium.load deleted file mode 100644 index b0a7ade..0000000 --- a/src/defaults/medium.load +++ /dev/null @@ -1,4 +0,0 @@ -# Medium load commands -# Maximum concurrent: 8 (default) -# -# Empty by default - unmatched commands are classified as MEDIUM diff --git a/src/defaults/zag.conf b/src/defaults/zag.conf index 711ce0c..8c31403 100644 --- a/src/defaults/zag.conf +++ b/src/defaults/zag.conf @@ -5,8 +5,8 @@ # Logging verbosity: debug, info, warn, error log_level = "info" -# DEPRECATED: Use [load_levels] section instead -# max_concurrent_jobs = 4 +# Zag runs only one job at a time (strict FIFO by creation order); +# concurrency is not configurable. # How often running jobs update their heartbeat (seconds) heartbeat_interval_seconds = 5 @@ -14,16 +14,6 @@ heartbeat_interval_seconds = 5 # Heartbeat age before a job is considered orphaned (seconds) stale_heartbeat_threshold_seconds = 30 -[load_levels] -# Maximum concurrent high load jobs (CPU/GPU intensive) -max_high_jobs = 2 - -# Maximum concurrent medium load jobs (general purpose) -max_medium_jobs = 8 - -# Maximum concurrent low load jobs (network/IO intensive) -max_low_jobs = 32 - [jobs] # Maximum time a job can run before being killed (seconds) default_timeout_seconds = 3600 diff --git a/src/job.zig b/src/job.zig index e169918..d49f570 100644 --- a/src/job.zig +++ b/src/job.zig @@ -1,7 +1,6 @@ //! Job and manifest data types. Timestamps are nanoseconds since the Unix epoch (`Instant`). const std = @import("std"); const State = @import("state.zig").State; -const LoadLevel = @import("loadlevel.zig").LoadLevel; pub const Instant = i128; @@ -30,7 +29,6 @@ pub const Job = struct { heartbeat: ?Instant = null, retry_count: u32 = 0, retry_at: ?Instant = null, - load_level: LoadLevel = .medium, pub fn isTerminal(self: Job) bool { return self.state.isTerminal(); @@ -54,7 +52,6 @@ pub const Manifest = struct { max_retries: u32 = 0, retry_delay_seconds: u32 = 30, retry_backoff_multiplier: f64 = 2.0, - load_level: LoadLevel = .medium, /// Per-job timeout in seconds; null uses the configured default. timeout_seconds: ?u32 = null, diff --git a/src/jobjson.zig b/src/jobjson.zig index a771a3c..836e3dd 100644 --- a/src/jobjson.zig +++ b/src/jobjson.zig @@ -1,12 +1,11 @@ //! JSON representation of a `Job`, shared by `--output=json` and the IPC protocol. -//! Field order matches barn: id, state (UPPERCASE), loadLevel, command, tag, timestamps, +//! Field order matches barn: id, state (UPPERCASE), command, tag, timestamps, //! exitCode, error, pid, heartbeat, retryCount, retryAt, terminal, running, queued. const std = @import("std"); const Allocator = std.mem.Allocator; const jsonpretty = @import("jsonpretty.zig"); const timestamp = @import("timestamp.zig"); const state_mod = @import("state.zig"); -const LoadLevel = @import("loadlevel.zig").LoadLevel; const job_mod = @import("job.zig"); const Job = job_mod.Job; const Instant = job_mod.Instant; @@ -33,7 +32,6 @@ pub fn writeJob(w: *jsonpretty.Writer, job: Job) !void { try w.beginObject(); try w.field("id", .string, job.id); try w.field("state", .string, upperState(job.state)); - try w.field("loadLevel", .string, job.load_level.upper()); try w.key("command"); try w.beginArray(); for (job.command) |arg| try w.string(arg); @@ -75,7 +73,6 @@ pub fn writeJobs(w: *jsonpretty.Writer, jobs: []const Job) !void { const RawJob = struct { id: []const u8, state: []const u8, - loadLevel: ?[]const u8 = null, command: []const []const u8, tag: ?[]const u8 = null, createdAt: []const u8, @@ -121,7 +118,6 @@ pub fn jobFromValue(arena: Allocator, value: std.json.Value) ParseError!Job { .heartbeat = try optInstant(raw.heartbeat), .retry_count = raw.retryCount, .retry_at = try optInstant(raw.retryAt), - .load_level = if (raw.loadLevel) |l| LoadLevel.parse(l) orelse return error.InvalidJob else .medium, }; } @@ -146,7 +142,6 @@ fn sampleJob() Job { .exit_code = .{ .code = 0 }, .pid = 17486, .heartbeat = 1_769_046_527 * std.time.ns_per_s + 161_895_000, - .load_level = .medium, }; } @@ -159,7 +154,6 @@ test "job JSON matches barn's field layout" { \\{ \\ "id" : "job-6d368040", \\ "state" : "SUCCEEDED", - \\ "loadLevel" : "MEDIUM", \\ "command" : [ "echo", "Hello World" ], \\ "tag" : null, \\ "createdAt" : "2026-01-22T01:48:46.739979Z", @@ -189,7 +183,6 @@ test "jobs round-trip through compact JSON" { failed.tag = "t"; failed.retry_count = 2; failed.retry_at = failed.created_at + std.time.ns_per_s; - failed.load_level = .low; const jobs = [_]Job{ sampleJob(), failed }; var aw: std.Io.Writer.Allocating = .init(a); @@ -206,7 +199,6 @@ test "jobs round-trip through compact JSON" { try std.testing.expectEqualStrings("start_failed", back[1].exit_code.?.symbol); try std.testing.expectEqualStrings("boom \"quoted\"", back[1].err.?); try std.testing.expectEqual(@as(u32, 2), back[1].retry_count); - try std.testing.expectEqual(LoadLevel.low, back[1].load_level); try std.testing.expectEqual(failed.retry_at.?, back[1].retry_at.?); } diff --git a/src/loadclass.zig b/src/loadclass.zig deleted file mode 100644 index 87534c5..0000000 --- a/src/loadclass.zig +++ /dev/null @@ -1,223 +0,0 @@ -//! Load-level classification from `high.load`, `medium.load` and `low.load` whitelist files. -//! Each line is a binary name (`ffmpeg`), a full path (`/usr/bin/ffmpeg`) or a directory -//! (`/opt/encoders/`); `#` starts a comment. HIGH is checked first, then MEDIUM, then LOW; -//! unmatched commands are MEDIUM. Port of barn's `LoadLevelClassifier` and `CommandMatcher`. -const std = @import("std"); -const Io = std.Io; -const Allocator = std.mem.Allocator; -const LoadLevel = @import("loadlevel.zig").LoadLevel; - -pub const Matcher = union(enum) { - /// Matches when the basename of the executable equals the name. - executable_name: []const u8, - /// Matches when the executable path equals this path. - full_path: []const u8, - /// Matches when the executable lives directly in this directory. - directory: []const u8, - - pub fn matches(self: Matcher, command: []const []const u8) bool { - if (command.len == 0) return false; - const exe = command[0]; - return switch (self) { - .executable_name => |n| std.mem.eql(u8, n, basename(exe)), - .full_path => |p| std.mem.eql(u8, normalize(p), normalize(exe)), - .directory => |d| if (dirname(exe)) |parent| - std.mem.eql(u8, normalize(parent), normalize(d)) - else - false, - }; - } -}; - -fn basename(path: []const u8) []const u8 { - const t = std.mem.trimEnd(u8, path, "/"); - const i = std.mem.lastIndexOfScalar(u8, t, '/') orelse return t; - return t[i + 1 ..]; -} - -fn dirname(path: []const u8) ?[]const u8 { - const t = std.mem.trimEnd(u8, path, "/"); - const i = std.mem.lastIndexOfScalar(u8, t, '/') orelse return null; - if (i == 0) return "/"; - return t[0..i]; -} - -/// Strips trailing slashes (keeping a lone `/`). -fn normalize(path: []const u8) []const u8 { - if (path.len <= 1) return path; - const t = std.mem.trimEnd(u8, path, "/"); - return if (t.len == 0) "/" else t; -} - -pub fn parseEntry(entry: []const u8) Matcher { - if (std.mem.endsWith(u8, entry, "/")) return .{ .directory = entry }; - if (std.mem.indexOfScalar(u8, entry, '/') != null) return .{ .full_path = entry }; - return .{ .executable_name = entry }; -} - -/// Parses a `.load` file body. Slices point into `text`; the list is allocated from `arena`. -pub fn parseLoadFile(arena: Allocator, text: []const u8) Allocator.Error![]const Matcher { - var list: std.ArrayList(Matcher) = .empty; - var lines = std.mem.splitScalar(u8, text, '\n'); - while (lines.next()) |raw| { - const line = std.mem.trim(u8, raw, &std.ascii.whitespace); - if (line.len == 0 or line[0] == '#') continue; - try list.append(arena, parseEntry(line)); - } - return list.toOwnedSlice(arena); -} - -pub const Classifier = struct { - high: []const Matcher = &.{}, - medium: []const Matcher = &.{}, - low: []const Matcher = &.{}, - - pub fn classify(self: Classifier, command: []const []const u8) LoadLevel { - if (command.len == 0) return .default; - for (self.high) |m| if (m.matches(command)) return .high; - for (self.medium) |m| if (m.matches(command)) return .medium; - for (self.low) |m| if (m.matches(command)) return .low; - return .default; - } - - /// Loads the three files from `config_dir`; missing or unreadable files count as empty. - pub fn load(arena: Allocator, io: Io, config_dir: []const u8) Allocator.Error!Classifier { - return .{ - .high = try loadOne(arena, io, config_dir, "high.load"), - .medium = try loadOne(arena, io, config_dir, "medium.load"), - .low = try loadOne(arena, io, config_dir, "low.load"), - }; - } - - /// True when at least one of the three `.load` files exists in `config_dir`. - pub fn anyFileExists(io: Io, config_dir: []const u8) bool { - var buf: [512]u8 = undefined; - for ([_][]const u8{ "high.load", "medium.load", "low.load" }) |name| { - const path = std.fmt.bufPrint(&buf, "{s}/{s}", .{ config_dir, name }) catch continue; - if (Io.Dir.cwd().statFile(io, path, .{})) |_| return true else |_| {} - } - return false; - } - - /// Loads from `config_dir` when it holds any `.load` file, else uses the embedded defaults - /// (so `ffmpeg` is HIGH and `curl` is LOW even before `zag config install`). - pub fn loadOrDefaults(arena: Allocator, io: Io, config_dir: []const u8) Allocator.Error!Classifier { - if (anyFileExists(io, config_dir)) return load(arena, io, config_dir); - return fromDefaults(arena); - } - - /// Classifier built from the embedded default files. - pub fn fromDefaults(arena: Allocator) Allocator.Error!Classifier { - const defaults = @import("defaults.zig"); - return .{ - .high = try parseLoadFile(arena, defaults.high_load), - .medium = try parseLoadFile(arena, defaults.medium_load), - .low = try parseLoadFile(arena, defaults.low_load), - }; - } -}; - -fn loadOne(arena: Allocator, io: Io, dir: []const u8, name: []const u8) Allocator.Error![]const Matcher { - const path = try std.fmt.allocPrint(arena, "{s}/{s}", .{ dir, name }); - const text = Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(1 << 20)) catch |err| switch (err) { - error.OutOfMemory => return error.OutOfMemory, - else => return &.{}, - }; - return parseLoadFile(arena, text); -} - -fn cmd(comptime args: []const []const u8) []const []const u8 { - return args; -} - -test "entry kinds" { - try std.testing.expectEqualStrings("ffmpeg", parseEntry("ffmpeg").executable_name); - try std.testing.expectEqualStrings("/usr/bin/ffmpeg", parseEntry("/usr/bin/ffmpeg").full_path); - try std.testing.expectEqualStrings("/opt/encoders/", parseEntry("/opt/encoders/").directory); -} - -test "executable name matches any path ending with it" { - const m = parseEntry("ffmpeg"); - try std.testing.expect(m.matches(cmd(&.{ "ffmpeg", "-i", "x" }))); - try std.testing.expect(m.matches(cmd(&.{"/usr/local/bin/ffmpeg"}))); - try std.testing.expect(!m.matches(cmd(&.{"ffmpeg2"}))); - try std.testing.expect(!m.matches(cmd(&.{ "echo", "ffmpeg" }))); - try std.testing.expect(!m.matches(&.{})); -} - -test "full path and directory matching" { - const fp = parseEntry("/usr/local/bin/rclone"); - try std.testing.expect(fp.matches(cmd(&.{ "/usr/local/bin/rclone", "copy" }))); - try std.testing.expect(!fp.matches(cmd(&.{"rclone"}))); - try std.testing.expect(!fp.matches(cmd(&.{"/usr/bin/rclone"}))); - - const d = parseEntry("/opt/encoders/"); - try std.testing.expect(d.matches(cmd(&.{"/opt/encoders/x265"}))); - try std.testing.expect(d.matches(cmd(&.{"/opt/encoders//x265"}))); - try std.testing.expect(!d.matches(cmd(&.{"/opt/encoders/sub/x265"}))); - try std.testing.expect(!d.matches(cmd(&.{"x265"}))); -} - -test "load files skip comments and blanks" { - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - const ms = try parseLoadFile(arena.allocator(), "# c\n\n ffmpeg \n/opt/x/\n # more\ncurl\n"); - try std.testing.expectEqual(@as(usize, 3), ms.len); -} - -test "priority is high, then medium, then low, default medium" { - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - const a = arena.allocator(); - const c: Classifier = .{ - .high = try parseLoadFile(a, "ffmpeg\n"), - .medium = try parseLoadFile(a, "both\n"), - .low = try parseLoadFile(a, "curl\nboth\nffmpeg\n"), - }; - try std.testing.expectEqual(LoadLevel.high, c.classify(cmd(&.{"ffmpeg"}))); - try std.testing.expectEqual(LoadLevel.low, c.classify(cmd(&.{"curl"}))); - try std.testing.expectEqual(LoadLevel.medium, c.classify(cmd(&.{"both"}))); - try std.testing.expectEqual(LoadLevel.medium, c.classify(cmd(&.{"echo"}))); - try std.testing.expectEqual(LoadLevel.medium, c.classify(&.{})); -} - -test "embedded defaults classify ffmpeg high and curl low" { - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - const c = try Classifier.fromDefaults(arena.allocator()); - try std.testing.expectEqual(LoadLevel.high, c.classify(cmd(&.{ "ffprobe", "-i", "x" }))); - try std.testing.expectEqual(LoadLevel.high, c.classify(cmd(&.{"/usr/bin/HandBrakeCLI"}))); - try std.testing.expectEqual(LoadLevel.low, c.classify(cmd(&.{ "curl", "-O", "u" }))); - try std.testing.expectEqual(LoadLevel.medium, c.classify(cmd(&.{ "echo", "hi" }))); -} - -test "load reads files from a directory and tolerates missing ones" { - const io = std.testing.io; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - const a = arena.allocator(); - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.writeFile(io, .{ .sub_path = "high.load", .data = "mytool\n" }); - const dir = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path}); - const c = try Classifier.load(a, io, dir); - try std.testing.expectEqual(LoadLevel.high, c.classify(cmd(&.{"mytool"}))); - try std.testing.expectEqual(@as(usize, 0), c.low.len); -} - -test "loadOrDefaults falls back to the embedded lists when no file exists" { - const io = std.testing.io; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - const a = arena.allocator(); - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - const dir = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path}); - - const defaults = try Classifier.loadOrDefaults(a, io, dir); - try std.testing.expectEqual(LoadLevel.high, defaults.classify(cmd(&.{"ffmpeg"}))); - - try tmp.dir.writeFile(io, .{ .sub_path = "low.load", .data = "ffmpeg\n" }); - const custom = try Classifier.loadOrDefaults(a, io, dir); - try std.testing.expectEqual(LoadLevel.low, custom.classify(cmd(&.{"ffmpeg"}))); -} diff --git a/src/loadlevel.zig b/src/loadlevel.zig deleted file mode 100644 index 6305c68..0000000 --- a/src/loadlevel.zig +++ /dev/null @@ -1,56 +0,0 @@ -//! Load levels cap how many jobs of each weight run at once. -const std = @import("std"); - -pub const LoadLevel = enum { - high, - medium, - low, - - pub const default: LoadLevel = .medium; - - pub fn defaultMaxJobs(self: LoadLevel) u32 { - return switch (self) { - .high => 2, - .medium => 8, - .low => 32, - }; - } - - pub fn lower(self: LoadLevel) []const u8 { - return @tagName(self); - } - - /// Uppercase form used in JSON (`HIGH`, `MEDIUM`, `LOW`) and manifests. - pub fn upper(self: LoadLevel) []const u8 { - return switch (self) { - .high => "HIGH", - .medium => "MEDIUM", - .low => "LOW", - }; - } - - /// Case-insensitive; surrounding whitespace is ignored. - pub fn parse(text: []const u8) ?LoadLevel { - const t = std.mem.trim(u8, text, &std.ascii.whitespace); - inline for (@typeInfo(LoadLevel).@"enum".fields) |f| { - if (std.ascii.eqlIgnoreCase(t, f.name)) return @field(LoadLevel, f.name); - } - return null; - } -}; - -test "defaults and names" { - try std.testing.expectEqual(LoadLevel.medium, LoadLevel.default); - try std.testing.expectEqual(@as(u32, 2), LoadLevel.high.defaultMaxJobs()); - try std.testing.expectEqual(@as(u32, 8), LoadLevel.medium.defaultMaxJobs()); - try std.testing.expectEqual(@as(u32, 32), LoadLevel.low.defaultMaxJobs()); - try std.testing.expectEqualStrings("HIGH", LoadLevel.high.upper()); - try std.testing.expectEqualStrings("low", LoadLevel.low.lower()); -} - -test "parse is case-insensitive and trims" { - try std.testing.expectEqual(LoadLevel.high, LoadLevel.parse(" High ").?); - try std.testing.expectEqual(LoadLevel.low, LoadLevel.parse("LOW").?); - try std.testing.expect(LoadLevel.parse("extreme") == null); - try std.testing.expect(LoadLevel.parse("") == null); -} diff --git a/src/output.zig b/src/output.zig index 4e686b2..3556239 100644 --- a/src/output.zig +++ b/src/output.zig @@ -196,7 +196,6 @@ fn xmlJob(out: *Io.Writer, job: Job, depth: usize) !void { if (job.heartbeat) |t| try xmlJobTime(out, d, "heartbeat", t); if (job.retry_count > 0) try xmlLeaf(out, d, "retry_count", "{d}", .{job.retry_count}); if (job.retry_at) |t| try xmlJobTime(out, d, "retry_at", t); - try xmlLeaf(out, d, "load_level", "{s}", .{job.load_level.lower()}); try indent(out, depth); try out.writeAll("\n"); } @@ -522,7 +521,6 @@ test "XML job follows barn's element shape" { \\ 2026-01-22T01:48:46Z \\ 0 \\ 17486 - \\ medium \\ \\ ); diff --git a/src/repository.zig b/src/repository.zig index e46f4ba..5994420 100644 --- a/src/repository.zig +++ b/src/repository.zig @@ -9,7 +9,6 @@ const Dirs = @import("dirs.zig").Dirs; const dirs_mod = @import("dirs.zig"); const StateFiles = @import("statefiles.zig").StateFiles; const State = @import("state.zig").State; -const LoadLevel = @import("loadlevel.zig").LoadLevel; const job_mod = @import("job.zig"); const Job = job_mod.Job; const Manifest = job_mod.Manifest; @@ -26,7 +25,6 @@ pub const Error = error{ InvalidTransition, JobNotFound, InvalidManifest }; pub const CreateOptions = struct { tag: ?[]const u8 = null, - load_level: LoadLevel = .medium, max_retries: u32 = 3, retry_delay_seconds: u32 = 30, retry_backoff_multiplier: f64 = 2.0, @@ -66,7 +64,6 @@ pub const Repository = struct { .max_retries = opts.max_retries, .retry_delay_seconds = opts.retry_delay_seconds, .retry_backoff_multiplier = opts.retry_backoff_multiplier, - .load_level = opts.load_level, .timeout_seconds = opts.timeout_seconds, }; try manifest.validate(); @@ -93,7 +90,6 @@ pub const Repository = struct { .command = command, .tag = opts.tag, .created_at = manifest.created_at, - .load_level = opts.load_level, }; } @@ -159,7 +155,6 @@ pub const Repository = struct { .heartbeat = try sf.readHeartbeat(), .retry_count = (try sf.readRetryCount()) orelse 0, .retry_at = try sf.readRetryAt(), - .load_level = manifest.load_level, }; } @@ -299,7 +294,6 @@ pub fn writeManifestJson(out: *Io.Writer, m: Manifest) !void { try w.field("maxRetries", .int, m.max_retries); try w.field("retryDelaySeconds", .int, m.retry_delay_seconds); try w.field("retryBackoffMultiplier", .float, m.retry_backoff_multiplier); - try w.field("loadLevel", .string, m.load_level.upper()); if (m.timeout_seconds) |t| try w.field("timeoutSeconds", .int, t); try w.endObject(); } @@ -312,11 +306,11 @@ const RawManifest = struct { maxRetries: u32 = 0, retryDelaySeconds: u32 = 30, retryBackoffMultiplier: f64 = 2.0, - loadLevel: ?[]const u8 = null, timeoutSeconds: ?u32 = null, }; -/// Parses a barn- or zag-written `manifest.json`. A missing `loadLevel` defaults to MEDIUM. +/// Parses a barn- or zag-written `manifest.json`; unknown fields (e.g. barn's `loadLevel`) +/// are ignored. pub fn parseManifestJson(arena: Allocator, text: []const u8) !Manifest { const raw = std.json.parseFromSliceLeaky(RawManifest, arena, text, .{ .ignore_unknown_fields = true }) catch return error.InvalidManifest; @@ -328,7 +322,6 @@ pub fn parseManifestJson(arena: Allocator, text: []const u8) !Manifest { .max_retries = raw.maxRetries, .retry_delay_seconds = raw.retryDelaySeconds, .retry_backoff_multiplier = raw.retryBackoffMultiplier, - .load_level = if (raw.loadLevel) |l| LoadLevel.parse(l) orelse return error.InvalidManifest else .medium, .timeout_seconds = raw.timeoutSeconds, }; m.validate() catch return error.InvalidManifest; @@ -373,7 +366,6 @@ test "manifest JSON matches barn's layout and round-trips" { .max_retries = 3, .retry_delay_seconds = 30, .retry_backoff_multiplier = 2.0, - .load_level = .high, }; var aw: Io.Writer.Allocating = .init(arena.allocator()); try writeManifestJson(&aw.writer, m); @@ -385,25 +377,22 @@ test "manifest JSON matches barn's layout and round-trips" { \\ "createdAt" : "2026-01-22T01:48:46Z", \\ "maxRetries" : 3, \\ "retryDelaySeconds" : 30, - \\ "retryBackoffMultiplier" : 2.0, - \\ "loadLevel" : "HIGH" + \\ "retryBackoffMultiplier" : 2.0 \\} , aw.written()); const back = try parseManifestJson(arena.allocator(), aw.written()); try std.testing.expectEqualStrings("job-6d368040", back.id); try std.testing.expectEqual(m.created_at, back.created_at); - try std.testing.expectEqual(LoadLevel.high, back.load_level); try std.testing.expectEqualStrings("Hello World", back.command[1]); } -test "manifest without loadLevel (older barn jobs) defaults to medium" { +test "manifest without optional fields (older barn jobs) still parses" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const m = try parseManifestJson(arena.allocator(), \\{"id":"job-1","command":["ls"],"tag":"t","createdAt":"2026-01-22T01:48:46.749629Z", \\ "maxRetries":0,"retryDelaySeconds":30,"retryBackoffMultiplier":2.0} ); - try std.testing.expectEqual(LoadLevel.medium, m.load_level); try std.testing.expectEqualStrings("t", m.tag.?); try std.testing.expectError(error.InvalidManifest, parseManifestJson(arena.allocator(), "{}")); try std.testing.expectError(error.InvalidManifest, parseManifestJson(arena.allocator(), @@ -411,18 +400,24 @@ test "manifest without loadLevel (older barn jobs) defaults to medium" { )); } +test "manifest with unknown loadLevel field (upgraded from older zag) still parses" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const m = try parseManifestJson(arena.allocator(), "{\"id\":\"job-2\",\"command\":[\"ls\"],\"createdAt\":\"2026-01-22T01:48:46.749629Z\",\"loadLevel\":\"HIGH\"}"); + try std.testing.expectEqualStrings("job-2", m.id); +} + test "create then find" { const env = try TestEnv.init(); defer env.deinit(); const a = env.arena.allocator(); - const created = try env.repo().create(a, &.{ "echo", "hi" }, .{ .tag = "downloading", .load_level = .low }); + const created = try env.repo().create(a, &.{ "echo", "hi" }, .{ .tag = "downloading" }); try std.testing.expect(jobid.isValid(created.id)); try std.testing.expectEqual(State.queued, created.state); const found = (try env.repo().findById(a, created.id)).?; try std.testing.expectEqualStrings("downloading", found.tag.?); - try std.testing.expectEqual(LoadLevel.low, found.load_level); try std.testing.expectEqual(@as(u32, 0), found.retry_count); try std.testing.expectEqual(created.created_at, found.created_at); try std.testing.expectEqualStrings("hi", found.command[1]); diff --git a/src/root.zig b/src/root.zig index ca7dbca..cd95c6d 100644 --- a/src/root.zig +++ b/src/root.zig @@ -13,14 +13,12 @@ pub const jobid = @import("jobid.zig"); pub const fsutil = @import("fsutil.zig"); pub const jsonpretty = @import("jsonpretty.zig"); pub const toml = @import("toml.zig"); -pub const loadlevel = @import("loadlevel.zig"); pub const job = @import("job.zig"); pub const dirs = @import("dirs.zig"); pub const statefiles = @import("statefiles.zig"); pub const repository = @import("repository.zig"); pub const defaults = @import("defaults.zig"); pub const config = @import("config.zig"); -pub const loadclass = @import("loadclass.zig"); pub const retry = @import("retry.zig"); pub const proc = @import("proc.zig"); pub const runner = @import("runner.zig"); diff --git a/src/service.zig b/src/service.zig index 9c4fd54..fa16b7e 100644 --- a/src/service.zig +++ b/src/service.zig @@ -23,8 +23,6 @@ const duration = @import("duration.zig"); const timestamp = @import("timestamp.zig"); const proc = @import("proc.zig"); const state_mod = @import("state.zig"); -const LoadLevel = @import("loadlevel.zig").LoadLevel; -const Classifier = @import("loadclass.zig").Classifier; const Job = @import("job.zig").Job; const Instant = @import("job.zig").Instant; @@ -32,7 +30,6 @@ pub const ReloadFn = *const fn (ctx: ?*anyopaque, arena: Allocator) anyerror!con pub const Options = struct { config: config.Config = .{}, - classifier: Classifier = .{}, reload_fn: ?ReloadFn = null, reload_ctx: ?*anyopaque = null, scheduler_tick_ms: u64 = 1_000, @@ -308,11 +305,6 @@ pub const Service = struct { if (req.payloadInt("timeoutSeconds")) |n| { create_opts.timeout_seconds = std.math.cast(u32, n) orelse return res.fail(.INVALID_REQUEST, "timeoutSeconds must be non-negative"); } - create_opts.load_level = if (req.payloadString("loadLevel")) |l| - LoadLevel.parse(l) orelse return res.failFmt(.INVALID_REQUEST, "Invalid load level: '{s}'. Valid values are: high, medium, low", .{l}) - else - self.opts.classifier.classify(command); - const job = try self.repo.create(res.arena, command, create_opts); try jobjson.writeJob(&res.json, job); } @@ -453,22 +445,15 @@ test "run a job end to end over IPC" { try std.testing.expect(status.get("pid").?.integer > 0); } -test "load level is auto-classified or overridden" { - var classifier: Classifier = .{}; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - classifier = try Classifier.fromDefaults(arena.allocator()); - const h = try Harness.create(.{ .classifier = classifier, .config = .{ .load_levels = .{ .max_high_jobs = 1, .max_medium_jobs = 1, .max_low_jobs = 1 } } }); +test "unknown loadLevel in a run_job payload is ignored" { + const h = try Harness.create(.{}); defer h.destroy(); - const auto = try h.okObj("run_job", "{\"command\":[\"curl\",\"--version\"]}"); - try std.testing.expectEqualStrings("LOW", auto.get("loadLevel").?.string); - const forced = try h.okObj("run_job", "{\"command\":[\"curl\",\"--version\"],\"loadLevel\":\"high\"}"); - try std.testing.expectEqualStrings("HIGH", forced.get("loadLevel").?.string); - const plain = try h.okObj("run_job", "{\"command\":[\"echo\",\"x\"]}"); - try std.testing.expectEqualStrings("MEDIUM", plain.get("loadLevel").?.string); - const bad = try h.call("run_job", "{\"command\":[\"echo\"],\"loadLevel\":\"extreme\"}"); - try std.testing.expectEqualStrings("INVALID_REQUEST", bad.err.code); + // Old clients (and pre-#2 zag) may still send a loadLevel; it is ignored, not an error. + const job = try h.okObj("run_job", "{\"command\":[\"echo\",\"x\"],\"loadLevel\":\"high\"}"); + try std.testing.expectEqualStrings("QUEUED", job.get("state").?.string); + try std.testing.expect(job.get("loadLevel") == null); + try h.waitState(job.get("id").?.string, "SUCCEEDED"); } test "request validation and not-found errors" { diff --git a/test/e2e.sh b/test/e2e.sh index f4602bd..f938a65 100755 --- a/test/e2e.sh +++ b/test/e2e.sh @@ -17,9 +17,11 @@ contains() { # contains } json_field() { printf '%s\n' "$2" | sed -n "s/.*\"$1\" : \"\{0,1\}\([^\",]*\)\"\{0,1\},\{0,1\}\$/\1/p" | head -1; } wait_state() { # wait_state [seconds] - local i + # ${2,,} would work on bash >= 4, but macOS ships bash 3.2 + local lower i + lower=$(printf '%s' "$2" | tr '[:upper:]' '[:lower:]') for ((i = 0; i < ${3:-100}; i++)); do - [[ $(json_field state "$(Z describe -o json "$1" --offline)") == "${2,,}" ]] && return 0 + [[ $(json_field state "$(Z describe -o json "$1" --offline)") == "$lower" ]] && return 0 sleep 0.1 done return 1 @@ -48,12 +50,15 @@ contains "clean --all removes it" "Cleaned 1 job" "$(Z clean --offline --all)" contains "status empty" "No jobs found." "$(Z status --offline)" # --- config ----------------------------------------------------------------------------- -contains "config show --defaults" "max_high_jobs = 2" "$(Z config show --defaults)" +contains "config show --defaults" "retry_backoff_multiplier = 2.0" "$(Z config show --defaults)" printf '[jobs]\nmax_retries = 0\nbogus = 1\n' >"$DIR/bad.conf" Z config validate --file "$DIR/bad.conf" >/dev/null 2>&1; [[ $? -eq 1 ]] && pass "validate flags bad config" || fail "validate flags bad config" printf '[jobs]\nmax_retries = 0\n' >"$DIR/good.conf" contains "validate accepts good config" "Configuration is valid" "$(Z config validate --file "$DIR/good.conf")" -contains "install --show prints files" "high.load" "$(Z config install --show)" +printf '[service]\nmax_concurrent_jobs = 4\n[load_levels]\nmax_high_jobs = 2\n' >"$DIR/deprecated.conf" +deprecated_out=$(Z config validate --file "$DIR/deprecated.conf" 2>&1); rc=$? +[[ $rc -eq 0 ]] && contains "validate warns on deprecated settings, exit 0" "deprecated" "$deprecated_out" || fail "validate warns on deprecated settings (rc=$rc)" +contains "install --show prints files" "zag.conf" "$(Z config install --show)" # --- daemon ----------------------------------------------------------------------------- Z run echo hi >/dev/null 2>&1; [[ $? -eq 1 ]] && pass "run without service exits 1" || fail "run without service exits 1" @@ -82,6 +87,15 @@ out=$(Z run -o json --timeout 1 sleep 30); tid=$(json_field id "$out") sleep 3 contains "timeout fails the job" '"exitCode" : "timeout"' "$(Z describe -o json "$tid" --offline)" +# Strict single-job FIFO: while the first job runs, the second stays queued, and both +# finish in creation order. +out=$(Z run -o json sleep 3); a1=$(json_field id "$out") +wait_state "$a1" RUNNING && pass "serial: first job is running" || fail "serial: first job is running" +out=$(Z run -o json sleep 1); b1=$(json_field id "$out") +contains "serial: second job stays queued" '"state" : "QUEUED"' "$out" +wait_state "$a1" SUCCEEDED && pass "serial: first job finishes first" || fail "serial: first job finishes first" +wait_state "$b1" SUCCEEDED && pass "serial: second job finishes second" || fail "serial: second job finishes second" + contains "service reload" "Configuration reloaded" "$(Z service reload)" contains "clean via IPC" "Cleaned" "$(Z clean --all --include-failed)" contains "service stop" "Zag service stopped" "$(Z service stop)" -- 2.54.0 From 3a4c4fa3266ae17c801020f20dcec96eb493d453 Mon Sep 17 00:00:00 2001 From: Daniel Samson <12231216+daniel-samson@users.noreply.github.com> Date: Thu, 12 Nov 2026 10:40:41 +0000 Subject: [PATCH 4/7] daemon: flush deprecation warnings into the log at startup The re-exec'd daemon inherits the buffered stderr writer over logs/zag.log from main.zig, so the deprecation warnings printed by Context.loadConfigOnce stayed in the buffer until the process exited and 'zag service logs' showed nothing right after starting with an old config. Flush stderr right after printing the warnings so they reach the log at startup, as the issue requires. e2e now starts the daemon with a config that still carries the deprecated load-level settings and asserts the warnings are in the log while the daemon is running; the settings themselves are ignored, so the effective config is unchanged for the rest of the suite. --- src/cli.zig | 3 +++ test/e2e.sh | 5 ++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/cli.zig b/src/cli.zig index aeaf547..6133515 100644 --- a/src/cli.zig +++ b/src/cli.zig @@ -78,6 +78,9 @@ pub const Context = struct { for (self.config_deprecations.items) |w| { self.stderr.print("warning: {s}\n", .{w}) catch {}; } + // The daemon's stderr is a buffered writer over logs/zag.log; flush so the + // warnings reach the log at startup, not on process exit. + if (self.config_deprecations.items.len > 0) self.stderr.flush() catch {}; } else |err| { self.config_error = err; } diff --git a/test/e2e.sh b/test/e2e.sh index f938a65..0739361 100755 --- a/test/e2e.sh +++ b/test/e2e.sh @@ -62,9 +62,12 @@ contains "install --show prints files" "zag.conf" "$(Z config install --show)" # --- daemon ----------------------------------------------------------------------------- Z run echo hi >/dev/null 2>&1; [[ $? -eq 1 ]] && pass "run without service exits 1" || fail "run without service exits 1" -contains "service start" "Zag service started" "$(Z service start)" +# The daemon starts with the deprecated config: the removed settings must be ignored +# (effective config is the defaults) and its log must warn about them while it is running. +contains "service start" "Zag service started" "$("$ZAG" --barn-dir "$DIR" --config "$DIR/deprecated.conf" service start 2>&1)" contains "second start refused" "already running" "$(Z service start 2>&1)" contains "service status running" "running" "$(Z service status)" +contains "daemon log warns on deprecated settings at startup" "deprecated" "$(cat "$DIR/logs/zag.log" 2>/dev/null)" out=$(Z run -o json -t svc sh -c 'echo from-daemon') sid=$(json_field id "$out") -- 2.54.0 From 5ee6b6021c8e937d102ac71449be6326b99b624e Mon Sep 17 00:00:00 2001 From: Daniel Samson <12231216+daniel-samson@users.noreply.github.com> Date: Thu, 12 Nov 2026 10:53:03 +0000 Subject: [PATCH 5/7] cli: assert --load-level stays out of run --help Last item of issue #2 phase 4 (CLI & output): the per-command help test now checks that the removed flag does not resurface in the help text. --- src/cli.zig | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/cli.zig b/src/cli.zig index 6133515..da6e3db 100644 --- a/src/cli.zig +++ b/src/cli.zig @@ -432,6 +432,8 @@ test "per-command help" { const r = try runCaptured(arena.allocator(), &.{ "run", "--help" }, null); try std.testing.expectEqual(exit_ok, r.code); try std.testing.expect(std.mem.indexOf(u8, r.out, "--tag") != null); + // issue #2 removed the load levels: the flag must not resurface in the help. + try std.testing.expect(std.mem.indexOf(u8, r.out, "load-level") == null); const s = try runCaptured(arena.allocator(), &.{ "service", "--help" }, null); try std.testing.expect(std.mem.indexOf(u8, s.out, "restart") != null); } -- 2.54.0 From 18c77a6e96d20eff2178d83aa844509dba35932d Mon Sep 17 00:00:00 2001 From: Daniel Samson <12231216+daniel-samson@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:47:27 +0000 Subject: [PATCH 6/7] e2e: assert config show --defaults has no load levels Completes the last phase-6 item of issue #2: the defaults check now explicitly asserts max_high_jobs is absent from the output, not just that the old assertion is gone. --- test/e2e.sh | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/e2e.sh b/test/e2e.sh index 0739361..1bde19d 100755 --- a/test/e2e.sh +++ b/test/e2e.sh @@ -50,7 +50,9 @@ contains "clean --all removes it" "Cleaned 1 job" "$(Z clean --offline --all)" contains "status empty" "No jobs found." "$(Z status --offline)" # --- config ----------------------------------------------------------------------------- -contains "config show --defaults" "retry_backoff_multiplier = 2.0" "$(Z config show --defaults)" +defaults_out=$(Z config show --defaults) +contains "config show --defaults" "retry_backoff_multiplier = 2.0" "$defaults_out" +case $defaults_out in *max_high_jobs*) fail "config show --defaults is free of load levels" ;; *) pass "config show --defaults is free of load levels" ;; esac printf '[jobs]\nmax_retries = 0\nbogus = 1\n' >"$DIR/bad.conf" Z config validate --file "$DIR/bad.conf" >/dev/null 2>&1; [[ $? -eq 1 ]] && pass "validate flags bad config" || fail "validate flags bad config" printf '[jobs]\nmax_retries = 0\n' >"$DIR/good.conf" -- 2.54.0 From 6325a876700d508ab290434b97d6f867f3a23312 Mon Sep 17 00:00:00 2001 From: Daniel Samson <12231216+daniel-samson@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:38:30 +0000 Subject: [PATCH 7/7] review fixes: safe reload warnings, idiomatic @field, range-check guard, e2e FIFO assert MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - reloadConfig: use a local ArrayList per reload instead of the shared ctx.config_deprecations — the previous approach could reallocate the backing array into the short-lived reload arena, causing use-after-free on successive reloads when warning counts grew between reloads - fromDoc: replace unsafe @ptrFromInt/@offsetOf arithmetic with &@field, which is idiomatic Zig and carries no extra risk; remove the incorrect comment claiming @field materialises a copy - problems(): fix the out.items.len == 0 range-check guard to count only non-warning (error) items so a deprecated setting no longer suppresses the range check for the rest of the document; add regression test - deprecations now typed as []Problem throughout (env-var warnings carry key/message/is_warning like file-level ones) so callers have full context - e2e: assert b1 never leaves QUEUED while a1 is running (true FIFO check) - sections table shared by fromDoc and checkDoc eliminates drift risk between the two section lists; problemNodes refactored to ArrayList single-pass; isDeprecatedKey inlined; isDeprecatedEnvName comment added Co-Authored-By: Claude Sonnet 4.6 --- src/cli.zig | 4 +- src/cli_admin.zig | 40 ++++++------ src/config.zig | 154 +++++++++++++++++++++++++++++++--------------- test/e2e.sh | 13 ++++ 4 files changed, 140 insertions(+), 71 deletions(-) diff --git a/src/cli.zig b/src/cli.zig index da6e3db..9cfca9c 100644 --- a/src/cli.zig +++ b/src/cli.zig @@ -37,7 +37,7 @@ pub const Context = struct { config_error: ?config.Error = null, config_diag: config.Diagnostic = .{}, /// Deprecation warnings collected while loading the config; printed once per process. - config_deprecations: std.ArrayList([]const u8) = .empty, + config_deprecations: std.ArrayList(config.Problem) = .empty, pub fn flag(self: *const Context, name: []const u8) bool { return self.parsed.flag(name); @@ -76,7 +76,7 @@ pub const Context = struct { if (config.load(self.arena, self.io, self.env, .{ .explicit_path = self.value("config") }, &self.config_diag, &self.config_deprecations)) |c| { self.config_value = c; for (self.config_deprecations.items) |w| { - self.stderr.print("warning: {s}\n", .{w}) catch {}; + self.stderr.print("warning: {s}\n", .{w.message}) catch {}; } // The daemon's stderr is a buffered writer over logs/zag.log; flush so the // warnings reach the log at startup, not on process exit. diff --git a/src/cli_admin.zig b/src/cli_admin.zig index 2c5476d..d123d57 100644 --- a/src/cli_admin.zig +++ b/src/cli_admin.zig @@ -56,7 +56,14 @@ const ReloadState = struct { fn reloadConfig(ctx_ptr: ?*anyopaque, arena: Allocator) anyerror!config.Config { const st: *const ReloadState = @ptrCast(@alignCast(ctx_ptr.?)); - return config.load(arena, st.io, st.env, .{ .explicit_path = st.explicit_path }, null, null); + // Use a local list so its backing array is owned by this reload's arena and + // never outlives the call — avoids use-after-free across successive reloads. + var warnings: std.ArrayList(config.Problem) = .empty; + const cfg = try config.load(arena, st.io, st.env, .{ .explicit_path = st.explicit_path }, null, &warnings); + // The daemon's stderr is its log file (or the journal under a service manager): + // deprecation warnings must reach it on every reload, not only at startup. + for (warnings.items) |p| std.log.warn("{s}", .{p.message}); + return cfg; } fn startBackground(ctx: *Context) !u8 { @@ -550,7 +557,7 @@ pub const config_show_usage = \\ ; -fn configNode(arena: Allocator, cfg: config.Config, socket: []const u8, warnings: []const []const u8) !Node { +fn configNode(arena: Allocator, cfg: config.Config, socket: []const u8, warnings: []const config.Problem) !Node { var root = MapBuilder.init(arena); var s = MapBuilder.init(arena); try s.put("log_level", Node.str(@tagName(cfg.service.log_level))); @@ -584,9 +591,7 @@ fn configNode(arena: Allocator, cfg: config.Config, socket: []const u8, warnings try root.put("storage", try st.done()); if (warnings.len > 0) { - const wn = try arena.alloc(Node, warnings.len); - for (warnings, wn) |msg, *n| n.* = Node.str(msg); - try root.put("warnings", .{ .list = wn }); + try root.put("warnings", .{ .list = try problemNodes(arena, warnings, true) }); } return root.done(); } @@ -673,8 +678,6 @@ pub fn cmdConfigValidate(ctx: *Context) !u8 { for (list.items) |p| { if (!p.is_warning) error_count += 1; } - const warnings = try problemNodes(a, list.items, true); - const errors = try problemNodes(a, list.items, false); if (ctx.format == .human) { for (list.items) |p| if (p.is_warning) try ctx.stdout.print(" Warning: {s}\n", .{p.message}); @@ -688,34 +691,31 @@ pub fn cmdConfigValidate(ctx: *Context) !u8 { } } } else { + const warnings = try problemNodes(a, list.items, true); + const errors = try problemNodes(a, list.items, false); var m = MapBuilder.init(a); - try m.put("valid", .{ .boolean = error_count == 0 }); + try m.put("valid", .{ .boolean = errors.len == 0 }); try m.put("file", Node.str(path)); if (warnings.len > 0) try m.put("warnings", .{ .list = warnings }); - if (error_count > 0) try m.put("errors", .{ .list = errors }); + if (errors.len > 0) try m.put("errors", .{ .list = errors }); try ctx.emit(try m.done()); } return if (error_count == 0) exit_ok else exit_error; } -/// The JSON node list for the warnings or the errors of a problem list. +/// The JSON node list for the warnings or the errors of a problem list: one +/// `{"key": ..., "message": ...}` object per problem (`key` omitted when empty). +/// `config show` and `config validate` render their deprecation warnings through this. fn problemNodes(a: Allocator, list: []const config.Problem, warnings_only: bool) ![]Node { - var count: usize = 0; - for (list) |p| { - if (p.is_warning == warnings_only) count += 1; - } - if (count == 0) return a.alloc(Node, 0); - const nodes = try a.alloc(Node, count); - var i: usize = 0; + var nodes: std.ArrayList(Node) = .empty; for (list) |p| { if (p.is_warning != warnings_only) continue; var em = MapBuilder.init(a); if (p.key.len > 0) try em.put("key", Node.str(p.key)); try em.put("message", Node.str(p.message)); - nodes[i] = try em.done(); - i += 1; + try nodes.append(a, try em.done()); } - return nodes; + return nodes.toOwnedSlice(a); } fn writeFileCreatingParents(ctx: *Context, path: []const u8, data: []const u8) !void { diff --git a/src/config.zig b/src/config.zig index 13cdefc..c1d5edc 100644 --- a/src/config.zig +++ b/src/config.zig @@ -159,13 +159,22 @@ fn applySection(arena: Allocator, comptime T: type, name: []const u8, section: ? } } +/// The sections zag's config understands, in declaration order. `fromDoc` builds the config +/// from these and `checkDoc` validates them, so a section added here is applied and checked +/// in one go. +const sections = [_]struct { name: []const u8, ty: type }{ + .{ .name = "service", .ty = Service }, + .{ .name = "jobs", .ty = Jobs }, + .{ .name = "cleanup", .ty = Cleanup }, + .{ .name = "storage", .ty = Storage }, +}; + /// Builds a `Config` from a merged TOML document (unknown sections/keys are ignored). pub fn fromDoc(arena: Allocator, doc: toml.Doc, diag: ?*Diagnostic) Error!Config { var cfg: Config = .{}; - try applySection(arena, Service, "service", doc.get("service"), &cfg.service, diag); - try applySection(arena, Jobs, "jobs", doc.get("jobs"), &cfg.jobs, diag); - try applySection(arena, Cleanup, "cleanup", doc.get("cleanup"), &cfg.cleanup, diag); - try applySection(arena, Storage, "storage", doc.get("storage"), &cfg.storage, diag); + inline for (sections) |sec| { + try applySection(arena, sec.ty, sec.name, doc.get(sec.name), &@field(cfg, sec.name), diag); + } try cfg.validate(diag); return cfg; } @@ -181,12 +190,6 @@ pub const Problem = struct { is_warning: bool = false, }; -/// A setting that pre-flattening configs still carry: it loads fine, is ignored, and is -/// reported as a warning (`Problem.is_warning`). -fn isDeprecatedKey(section: []const u8, key: []const u8) bool { - return std.mem.eql(u8, section, "service") and std.mem.eql(u8, key, "max_concurrent_jobs"); -} - fn expectation(comptime T: type) []const u8 { return switch (@typeInfo(T)) { .optional => |o| expectation(o.child), @@ -221,7 +224,9 @@ fn checkSection(arena: Allocator, comptime T: type, name: []const u8, section: t } } if (!known) { - if (isDeprecatedKey(name, key)) { + // A key barn (and pre-flattening zag) configs still carry: report it as a + // warning and keep loading; extend this check when the next setting is removed. + if (std.mem.eql(u8, name, "service") and std.mem.eql(u8, key, "max_concurrent_jobs")) { try out.append(arena, .{ .section = name, .key = key, @@ -239,40 +244,53 @@ fn checkSection(arena: Allocator, comptime T: type, name: []const u8, section: t } } +/// Unknown sections and keys, values of the wrong type, and deprecated settings (reported as +/// warnings) in a parsed document. Range violations are not checked here; see `problems`. +fn checkDoc(arena: Allocator, doc: toml.Doc, out: *std.ArrayList(Problem)) Allocator.Error!void { + var it = doc.iterator(); + while (it.next()) |entry| { + const name = entry.key_ptr.*; + const section = entry.value_ptr.*; + var known = false; + inline for (sections) |sec| { + if (std.mem.eql(u8, name, sec.name)) { + known = true; + try checkSection(arena, sec.ty, name, section, out); + } + } + if (!known) { + // Kept for compatibility with pre-flattening (and barn) configs. + if (std.mem.eql(u8, name, "load_levels")) { + try out.append(arena, .{ + .section = name, + .key = "", + .message = try std.fmt.allocPrint(arena, "[{s}] is deprecated: only one job runs at a time; remove it from your config", .{name}), + .is_warning = true, + }); + } else { + try out.append(arena, .{ + .section = name, + .key = "", + .message = try std.fmt.allocPrint(arena, "Unknown section: [{s}]", .{name}), + }); + } + } + } +} + /// Everything wrong with a parsed config document: unknown sections and keys, values of the /// wrong type, and values outside their allowed range. Deprecated settings are reported as /// warnings and never fail validation. pub fn problems(arena: Allocator, doc: toml.Doc) Allocator.Error![]const Problem { var out: std.ArrayList(Problem) = .empty; - var it = doc.iterator(); - while (it.next()) |entry| { - const name = entry.key_ptr.*; - const section = entry.value_ptr.*; - if (std.mem.eql(u8, name, "service")) { - try checkSection(arena, Service, name, section, &out); - } else if (std.mem.eql(u8, name, "jobs")) { - try checkSection(arena, Jobs, name, section, &out); - } else if (std.mem.eql(u8, name, "cleanup")) { - try checkSection(arena, Cleanup, name, section, &out); - } else if (std.mem.eql(u8, name, "storage")) { - try checkSection(arena, Storage, name, section, &out); - } else if (std.mem.eql(u8, name, "load_levels")) { - // Kept for compatibility with pre-flattening (and barn) configs. - try out.append(arena, .{ - .section = name, - .key = "", - .message = try std.fmt.allocPrint(arena, "[{s}] is deprecated: only one job runs at a time; remove it from your config", .{name}), - .is_warning = true, - }); - } else { - try out.append(arena, .{ - .section = name, - .key = "", - .message = try std.fmt.allocPrint(arena, "Unknown section: [{s}]", .{name}), - }); - } + try checkDoc(arena, doc, &out); + // Warnings are not errors: a deprecated setting must not suppress the range check + // (nor the "valid" verdict) for the rest of the document. + var error_count: usize = 0; + for (out.items) |p| { + if (!p.is_warning) error_count += 1; } - if (out.items.len == 0) { + if (error_count == 0) { // Types are fine; now check ranges on the resulting configuration. var diag: Diagnostic = .{}; _ = fromDoc(arena, doc, &diag) catch |err| switch (err) { @@ -314,6 +332,9 @@ const env_sections = [_]struct { name: []const u8, canonical: []const u8 }{ /// `ZAG_LOAD_LEVELS_*`, `ZAG_LOADLEVELS_*` and `ZAG_SERVICE_MAX_CONCURRENT_JOBS` still /// survive in old service files and shell profiles; `rest` is the name without `ZAG_`. fn isDeprecatedEnvName(rest: []const u8) bool { + // The `len >` guards (rather than `>=`) keep the bare prefixes `ZAG_LOAD_LEVELS_` and + // `ZAG_LOADLEVELS_` from matching: they name no setting, mirroring how `env_sections` + // requires at least one character after the section underscore. return (rest.len > "load_levels_".len and std.ascii.startsWithIgnoreCase(rest, "load_levels_")) or (rest.len > "loadlevels_".len and std.ascii.startsWithIgnoreCase(rest, "loadlevels_")) or std.ascii.eqlIgnoreCase(rest, "service_max_concurrent_jobs"); @@ -322,13 +343,18 @@ fn isDeprecatedEnvName(rest: []const u8) bool { /// Applies `ZAG_
_=value` overrides, e.g. `ZAG_JOBS_MAX_RETRIES=5`. Values are /// typed as bool, int, float, else string. Deprecated load-level variables are skipped and, /// when `deprecations` is non-null, reported there. -pub fn applyEnvironment(arena: Allocator, doc: *toml.Doc, env: *const Environ.Map, deprecations: ?*std.ArrayList([]const u8)) Allocator.Error!void { +pub fn applyEnvironment(arena: Allocator, doc: *toml.Doc, env: *const Environ.Map, deprecations: ?*std.ArrayList(Problem)) Allocator.Error!void { for (env.keys(), env.values()) |name, value| { if (!std.ascii.startsWithIgnoreCase(name, env_prefix)) continue; const rest = name[env_prefix.len..]; if (isDeprecatedEnvName(rest)) { if (deprecations) |list| { - try list.append(arena, try std.fmt.allocPrint(arena, "{s} is deprecated: only one job runs at a time; remove it from your environment", .{name})); + try list.append(arena, .{ + .section = "", + .key = name, + .message = try std.fmt.allocPrint(arena, "{s} is deprecated: only one job runs at a time; remove it from your environment", .{name}), + .is_warning = true, + }); } continue; } @@ -423,7 +449,7 @@ pub const LoadOptions = struct { /// are skipped like barn does; an explicit file that fails to parse is reported. When /// `deprecations` is non-null, removed settings found in the files or the environment are /// appended to it as warnings. -pub fn load(arena: Allocator, io: Io, env: *const Environ.Map, opts: LoadOptions, diag: ?*Diagnostic, deprecations: ?*std.ArrayList([]const u8)) Error!Config { +pub fn load(arena: Allocator, io: Io, env: *const Environ.Map, opts: LoadOptions, diag: ?*Diagnostic, deprecations: ?*std.ArrayList(Problem)) Error!Config { var merged: toml.Doc = .empty; const paths = opts.search_paths orelse try searchPaths(arena, env); for (paths) |p| { @@ -438,9 +464,12 @@ pub fn load(arena: Allocator, io: Io, env: *const Environ.Map, opts: LoadOptions } try applyEnvironment(arena, &merged, env, deprecations); if (deprecations) |list| { - for (try problems(arena, merged)) |p| { - if (p.is_warning) try list.append(arena, p.message); - } + // Only the deprecation warnings come from the document scan (unknown names are + // ignored here, like barn), and `fromDoc` below does the range check; skip + // `problems()` and its extra pass over the document. + var found: std.ArrayList(Problem) = .empty; + try checkDoc(arena, merged, &found); + for (found.items) |p| if (p.is_warning) try list.append(arena, p); } return fromDoc(arena, merged, diag); } @@ -538,10 +567,13 @@ test "environment overrides; deprecated load-level vars are warned about and ign try env.put("OTHER_JOBS_MAX_RETRIES", "99"); var doc = try testDoc(a, "[jobs]\nmax_retries = 2\n"); - var deprecations: std.ArrayList([]const u8) = .empty; + var deprecations: std.ArrayList(Problem) = .empty; try applyEnvironment(a, &doc, &env, &deprecations); try std.testing.expectEqual(@as(usize, 3), deprecations.items.len); - for (deprecations.items) |msg| try std.testing.expect(std.mem.indexOf(u8, msg, "deprecated") != null); + for (deprecations.items) |p| { + try std.testing.expect(p.is_warning); + try std.testing.expect(std.mem.indexOf(u8, p.message, "deprecated") != null); + } try std.testing.expect(doc.get("load_levels") == null); const cfg = try fromDoc(a, doc, null); @@ -681,11 +713,35 @@ test "load reports deprecated settings from files and env" { defer env.deinit(); try env.put("ZAG_LOAD_LEVELS_MAX_HIGH_JOBS", "1"); - var deprecations: std.ArrayList([]const u8) = .empty; + var deprecations: std.ArrayList(Problem) = .empty; const cfg = try load(a, io, &env, .{ .search_paths = &.{try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}/old.conf", .{tmp.sub_path})}, }, null, &deprecations); try std.testing.expectEqual(@as(usize, 3), deprecations.items.len); - for (deprecations.items) |msg| try std.testing.expect(std.mem.indexOf(u8, msg, "deprecated") != null); + for (deprecations.items) |p| { + try std.testing.expect(p.is_warning); + try std.testing.expect(std.mem.indexOf(u8, p.message, "deprecated") != null); + } try std.testing.expectEqual(LogLevel.info, cfg.service.log_level); } + +test "deprecation warnings do not suppress the range check" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + + const ps = try problems(a, try testDoc(a, + \\[service] + \\max_concurrent_jobs = 4 + \\[jobs] + \\retry_backoff_multiplier = 0.5 + )); + try std.testing.expectEqual(@as(usize, 2), ps.len); + var saw_warning = false; + var saw_range = false; + for (ps) |p| { + if (p.is_warning) saw_warning = true; + if (!p.is_warning and std.mem.eql(u8, p.key, "retry_backoff_multiplier")) saw_range = true; + } + try std.testing.expect(saw_warning and saw_range); +} diff --git a/test/e2e.sh b/test/e2e.sh index 1bde19d..5775487 100755 --- a/test/e2e.sh +++ b/test/e2e.sh @@ -98,6 +98,19 @@ out=$(Z run -o json sleep 3); a1=$(json_field id "$out") wait_state "$a1" RUNNING && pass "serial: first job is running" || fail "serial: first job is running" out=$(Z run -o json sleep 1); b1=$(json_field id "$out") contains "serial: second job stays queued" '"state" : "QUEUED"' "$out" +# The checks above would still pass if the scheduler ran both jobs concurrently +# (sleep 3 always finishes before sleep 1 started after it could catch up). Assert the +# defining FIFO invariant directly: b1 never leaves QUEUED while a1 is running. +exclusive=1 +last="" +for i in 1 2 3 4 5 6 7 8 9 10 11 12; do + st_a=$(json_field state "$(Z describe -o json "$a1" --offline)") + [[ $st_a == "running" ]] || break + last=$(json_field state "$(Z describe -o json "$b1" --offline)") + [[ $last == "queued" ]] || exclusive=0 + sleep 0.3 +done +[[ $exclusive -eq 1 ]] && pass "serial: second job never runs while the first runs" || fail "serial: second job never runs while the first runs (state: $last)" wait_state "$a1" SUCCEEDED && pass "serial: first job finishes first" || fail "serial: first job finishes first" wait_state "$b1" SUCCEEDED && pass "serial: second job finishes second" || fail "serial: second job finishes second" -- 2.54.0