Phase 5: race detector (P5-6) and the atomic_stats reference program (P5-9b)

Dynamic data-race detector for ordinary memory: vector clocks are the
task-keyed part of the weak-memory views, so happens-before follows every
synchronization edge already modelled; per-cell shadows with path
granularity. Enabled for every conformance run test (433, no false
positive); a unit test shows an unverified racy program caught on every
schedule. Reference program atomic_stats in .aji and hand-written AIR by an
independent author (equivalent:, 30 schedule seeds). Author feedback:
07a clarifications; Q-025 (no array construction) logged.
This commit is contained in:
dev committed 2026-10-06 08:11:25 +03:00
1 parent 4242132b2a
commit 0879b9497b
10 files changed
+481 -10

No files matched your search

+133 -6
View File
@@ -28,6 +28,7 @@ const world_mod = @import("world.zig");
const host_mod = @import("host.zig");
const budget = @import("../verifier/budget.zig");
const weak = @import("weak.zig");
const race = @import("race.zig");
pub const WorldOptions = world_mod.Options;
@@ -105,7 +106,12 @@ pub const Value = union(enum) {
};
/// Frame storage. `value` is `.void` while uninitialized.
pub const Cell = struct { value: Value, ty: air.Type };
pub const Cell = struct {
value: Value,
ty: air.Type,
/// Accesses seen by the race detector (`Options.detect_races`).
shadow: ?*race.Shadow = null,
};
/// Path of field or element indices from the cell's value.
pub const Place = struct { cell: *Cell, path: []const u32 };
@@ -131,6 +137,9 @@ pub const Outcome = union(enum) {
/// The deterministic runtime found no future event that could complete
/// a wait (spec 11 §8). Not a trap and not an I/O error.
blocked: Location,
/// The race detector (`Options.detect_races`) found two unordered
/// conflicting accesses to ordinary memory: a verifier defect (spec 04 §21).
race_detected: struct { at: Location, other_task: u32 },
};
pub const Location = struct { function: []const u8, block: []const u8, inst: u32 };
@@ -208,6 +217,8 @@ pub const Options = struct {
/// Exhaustive exploration: choices come from `Explore` instead of the
/// schedule generator (spec 04 §20.5).
explore: ?*Explore = null,
/// Check every ordinary access for data races (spec 04 §21; a test tool).
detect_races: bool = false,
};
/// Observable output of a run in the deterministic profile.
@@ -274,6 +285,7 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti
m.exec_heap.every_step = options.collect_every_step;
m.arc_events = options.arc_events;
m.explore = options.explore;
m.detect_races = options.detect_races;
m.mem.weak_reads = hasWeakReads(module);
if (options.collect_threshold) |t| {
m.exec_heap.floor = t;
@@ -361,7 +373,7 @@ const Copier = struct {
if (c.cells.get(old)) |n| return n;
const n = try c.to.create(Value.Cell);
try c.cells.put(c.tmp, old, n);
n.* = .{ .value = .void, .ty = old.ty };
n.* = .{ .value = .void, .ty = old.ty, .shadow = if (old.shadow) |sh| try sh.copy(c.to) else null };
n.value = try c.value(old.value);
return n;
}
@@ -550,6 +562,7 @@ const Machine = struct {
/// Atomic cells and the `seq_cst` view (spec 04 §42).
mem: weak.Memory = .{},
explore: ?*Explore = null,
detect_races: bool = false,
// ------------------------------------------------------------ tasks and the scheduler (spec 04 §36)
@@ -557,6 +570,7 @@ const Machine = struct {
/// returns, traps, or the environment stops it.
fn runProgram(m: *Machine, fn_index: u32, args: []const Value) std.mem.Allocator.Error!Outcome {
try m.tasks.append(m.arena, .{});
if (m.detect_races) m.tasks.items[0].views.cur = try m.tasks.items[0].views.cur.with(race.clockKey(0), 1, m.heap());
try m.pushFrame(0, fn_index, args);
while (true) {
// Safe point: between instructions no Zig local holds heap values.
@@ -634,6 +648,7 @@ const Machine = struct {
continue;
},
.task_limit => return .{ .limit_exceeded = .{ .kind = "tasks", .limit = m.task_limit, .steps = m.steps } },
.race => |other| return .{ .race_detected = .{ .at = here, .other_task = other } },
}
if (m.quantum_used >= m.quantum) {
if (try m.schedule()) |o| return o;
@@ -795,6 +810,8 @@ const Machine = struct {
task_limit,
/// Continue at a block; the completed instruction is a scheduling point.
jump_yield: u32,
/// The race detector found a racing access by this task.
race: u32,
};
fn exec(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) std.mem.Allocator.Error!Step {
@@ -883,8 +900,10 @@ const Machine = struct {
m.spawned = true;
const id: u32 = @intCast(m.tasks.items.len);
// spawn → the child's first event (spec 04 §20.3).
const parent = m.tasks.items[m.current].views.cur;
var parent = m.tasks.items[m.current].views.cur;
if (m.detect_races) parent = try parent.with(race.clockKey(id), 1, m.heap());
try m.tasks.append(m.arena, .{ .views = .{ .cur = parent, .acq = parent } });
try m.tick();
try m.pushFrame(id, x.callee, try m.gather(vals, x.args));
vals[inst.result.?] = .{ .task = id };
return m.yieldUnlessExploring();
@@ -903,6 +922,7 @@ const Machine = struct {
const target = &m.tasks.items[vals[v].task];
target.cancel = true;
target.cancel_view = try target.cancel_view.join(m.tasks.items[m.current].views.cur, m.heap());
try m.tick();
return .yield;
},
.task_cancelled => {
@@ -1003,6 +1023,7 @@ const Machine = struct {
fn doSend(m: *Machine, id: u32, v: Value) !void {
const c = &m.channels.items[id];
const view = m.tasks.items[m.current].views.cur;
try m.tick();
if (c.capacity > 0) {
try c.views.append(m.heap(), view);
return c.buf.append(m.heap(), try m.deepCopy(v));
@@ -1026,6 +1047,26 @@ const Machine = struct {
return o.value;
}
/// Advances the current task's clock after a releasing operation, so its
/// later accesses are not ordered before what others acquired.
fn tick(m: *Machine) !void {
if (!m.detect_races) return;
const t = &m.tasks.items[m.current];
const key = race.clockKey(m.current);
t.views.cur = try t.views.cur.with(key, t.views.cur.get(key) + 1, m.heap());
}
/// An ordinary access by the current task (spec 04 §21).
fn raceCheck(m: *Machine, cell: *Value.Cell, path: []const u32, write: bool) !?Step {
if (!m.detect_races) return null;
if (cell.shadow == null) {
cell.shadow = try m.heap().create(race.Shadow);
cell.shadow.?.* = .{};
}
const other = try race.access(m.heap(), cell.shadow.?, path, write, m.current, m.tasks.items[m.current].views.cur) orelse return null;
return .{ .race = other };
}
/// The `cancelled` outcome synchronizes with the cancels (spec 04 §20.3).
fn observeCancel(m: *Machine) !void {
const t = &m.tasks.items[m.current];
@@ -1107,6 +1148,7 @@ const Machine = struct {
const id = vals[v].sender;
const ch = &m.channels.items[id];
ch.close_view = try ch.close_view.join(m.tasks.items[self].views.cur, m.heap());
try m.tick();
ch.senders -= 1;
m.maybeRelease(id);
return .yield;
@@ -1283,6 +1325,7 @@ const Machine = struct {
.mutex_unlock => |g| {
vals[g].guard.locked = false;
vals[g].guard.view = m.tasks.items[m.current].views.cur;
try m.tick();
return .yield;
},
else => unreachable,
@@ -1324,6 +1367,11 @@ const Machine = struct {
fn execAtomic(m: *Machine, vals: []Value, inst: air.Inst) !Step {
const gpa = m.heap();
// A write or fence may release: later accesses get a new clock.
defer if (m.detect_races) switch (inst.op) {
.atomic_store, .atomic_rmw, .atomic_cmpxchg, .atomic_fence => m.tick() catch {},
else => {},
};
const views = &m.tasks.items[m.current].views;
switch (inst.op) {
.atomic_new => |v| {
@@ -1462,6 +1510,10 @@ const Machine = struct {
return v;
}
fn pathTo(m: *Machine, p: Value.Place, i: u64) ![]const u32 {
return (try m.extend(p, i)).path;
}
fn extend(m: *Machine, p: Value.Place, i: u64) !Value.Place {
const path = try m.heap().alloc(u32, p.path.len + 1);
@memcpy(path[0..p.path.len], p.path);
@@ -1905,15 +1957,20 @@ const Machine = struct {
return bind(vals, inst.result, .{ .local = cell });
},
.local_store => |x| {
if (try m.raceCheck(vals[x.local].local, &.{}, true)) |r| return r;
vals[x.local].local.value = try m.deepCopy(vals[x.value]);
return .next;
},
.local_zero => |v| {
const cell = vals[v].local;
if (try m.raceCheck(cell, &.{}, true)) |r| return r;
cell.value = try m.zeroValue(cell.ty);
return .next;
},
.local_load => |v| return bind(vals, inst.result, try m.deepCopy(vals[v].local.value)),
.local_load => |v| {
if (try m.raceCheck(vals[v].local, &.{}, false)) |r| return r;
return bind(vals, inst.result, try m.deepCopy(vals[v].local.value));
},
.borrow_ref, .borrow_mut => |v| return bind(vals, inst.result, switch (vals[v]) {
.local => |c| .{ .place = .{ .cell = c, .path = &.{} } },
// A borrowed resource: a place whose cell holds the handle.
@@ -1936,9 +1993,15 @@ const Machine = struct {
}),
.borrow_field => |x| return bind(vals, inst.result, .{ .place = try m.extend(asPlace(vals[x.borrow]), x.field) }),
.borrow_end => return .next,
.load => |v| return bind(vals, inst.result, try m.deepCopy(placePtr(asPlace(vals[v])).*)),
.load => |v| {
const p = asPlace(vals[v]);
if (try m.raceCheck(p.cell, p.path, false)) |r| return r;
return bind(vals, inst.result, try m.deepCopy(placePtr(p).*));
},
.store => |x| {
placePtr(asPlace(vals[x.borrow])).* = try m.deepCopy(vals[x.value]);
const p = asPlace(vals[x.borrow]);
if (try m.raceCheck(p.cell, p.path, true)) |r| return r;
placePtr(p).* = try m.deepCopy(vals[x.value]);
return .next;
},
.array_splat => |x| {
@@ -1986,6 +2049,10 @@ const Machine = struct {
const dst = placePtr(d.place).array;
const src = placePtr(s.place).array;
// Operands never overlap (spec 08 §11.2), so a forward copy is exact.
if (m.detect_races) for (0..s.len) |k| {
if (try m.raceCheck(s.place.cell, try m.pathTo(s.place, s.start + k), false)) |r| return r;
if (try m.raceCheck(d.place.cell, try m.pathTo(d.place, d.start + k), true)) |r| return r;
};
for (0..s.len) |k| dst[d.start + k] = try m.deepCopy(src[s.start + k]);
return .next;
},
@@ -2231,6 +2298,17 @@ pub fn writeOutcome(module: air.Module, outcome: Outcome, out: ?Output, w: *std.
try s.objectField("inst");
try s.write(t.inst);
},
.race_detected => |r| {
try s.write("race_detected");
try s.objectField("function");
try s.write(r.at.function);
try s.objectField("block");
try s.write(r.at.block);
try s.objectField("inst");
try s.write(r.at.inst);
try s.objectField("other_task");
try s.write(r.other_task);
},
.blocked => |l| {
try s.write("blocked");
try s.objectField("kind");
@@ -2696,3 +2774,52 @@ test "moving an island costs the same for any graph size" {
const large = try transferSteps(1000, 10) - try transferSteps(1000, 0);
try std.testing.expectEqual(small, large);
}
test "the race detector catches an unordered write the verifier would reject" {
// Not verified on purpose: main writes the local while a mut borrow of it
// is lent to a running task (E4101 for the verifier, spec 04 §34).
const src =
\\module test.race
\\air 0
\\lang 0.1
\\features [ownership, tasks]
\\
\\fn @poke(%p: mut<u64>) -> u64
\\effects []
\\entry:
\\ %one = const.u64 1
\\ store %p, %one
\\ ret %one
\\
\\fn @main() -> u64
\\effects [task.spawn]
\\entry:
\\ %x = local.alloc u64
\\ %z = const.u64 0
\\ local.store %x, %z
\\ %b = borrow.mut %x
\\ %s = task.scope.begin
\\ %t = task.spawn %s, @poke(%b)
\\ %two = const.u64 2
\\ local.store %x, %two
\\ %r = task.join %t
\\ task.scope.end %s
\\ borrow.end %b
\\ ret %r
\\
;
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
const parsed = try @import("../air/parse.zig").parse(arena, "race.air", src);
try std.testing.expectEqual(@as(usize, 0), parsed.diagnostics.len);
// On every schedule the two writes are unordered: one of them is caught.
var seed: u64 = 0;
while (seed < 20) : (seed += 1) {
const outcome = try run(arena, parsed.module.?, "main", .{ .detect_races = true, .quantum = 1, .schedule_seed = seed });
try std.testing.expect(outcome == .race_detected);
}
// Without the detector the program just runs.
const plain = try run(arena, parsed.module.?, "main", .{ .quantum = 1 });
try std.testing.expect(plain == .returned);
}