review fixes: safe reload warnings, idiomatic @field, range-check guard, e2e FIFO assert
CI / test (pull_request) Successful in 3m20s

- 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 <noreply@anthropic.com>
This commit is contained in:
Daniel SamsonandClaude Sonnet 4.6 committed 2026-11-12 14:38:30 +00:00
1 parent 18c77a6e96
commit 6325a87670
4 files changed
+140 -71

No files matched your search

+2 -2
View File
@@ -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.
+20 -20
View File
@@ -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 {
+105 -49
View File
@@ -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_<SECTION>_<KEY>=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);
}
+13
View File
@@ -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"