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:
1 parent
4242132b2a
commit
0879b9497b
10 files changed
+481
-10
No files matched your search
@@ -27,6 +27,7 @@ Status values: `open`, `resolved`.
|
||||
| Q-019 | resolved | P3 | Non-terminating programs in test tooling |
|
||||
| Q-020 | resolved | P2 | Size bound for SSA array values |
|
||||
| Q-024 | resolved | P5 | Memory-model clarifications found by the independent oracle |
|
||||
| Q-025 | open | — | No array construction from element values in AIR |
|
||||
|
||||
## Q-001 — Text AIR grammar
|
||||
|
||||
@@ -197,3 +198,7 @@ Points 1–3 and 5 are editorial. Point 4 fixes FIFO, which spec 04 §38 already
|
||||
- capacity-based synchronization would be a separate feature by RFC.
|
||||
5. The C++20 release sequence, stated explicitly.
|
||||
|
||||
## Q-025 — No array construction from element values in AIR
|
||||
|
||||
Found by the independent author of `program_atomic_stats.air` (P5-9b). AIR has `array.splat` but no way to build an array from distinct element values. A six-element constant array costs a mutable borrow, six `borrow.index`/`store`/`borrow.end` triples and six index constants. `.aji` has the same gap: it has `[e; N]` but no array literal. The options are an `array.make T (%a, %b, …)` instruction (a value constructor like `struct.make`) with an `.aji` literal `[a, b, c]`, or no change. This is a convenience question, not a correctness one. It is not urgent, and any RFC for it must report its agent-complexity cost.
|
||||
|
||||
@@ -83,12 +83,12 @@ Phase 4 commit frozen (tag p4-frozen)
|
||||
| P5-3 | done | AIR parse/print, types (linear `atomic<T>`, AtomicScalar, not IslandSafe), ordering tables, `E4202` | P5-1a | `src/air/`, `src/verifier/` | `E4201` accept/reject for every operation and every cmpxchg success/failure pair; `E4202`; `E1001`, `E2111`, `E0006` cases |
|
||||
| P5-4 | done | `atomic` / `atomic.weak` effects (spec 05 §13); weak sites in `aji report` | P5-3 | verifier + report | each non-`seq_cst` ordering without `atomic.weak` is `E3101`; `seq_cst` needs only `atomic`; weak sites listed |
|
||||
| P5-5 | done | Interpreter: atomic cells with message histories, views, weak reads drawn from the schedule stream; atomic operations are scheduling points | P5-3 | `src/interp/` | sound on the corpus and the differential test; no extra draw without weak accesses; existing records unchanged |
|
||||
| P5-6 | todo | Happens-before tracking and dynamic race detector (validates the verifier) | P5-5 | `src/interp/` | any race the verifier missed aborts the test run with a diagnostic |
|
||||
| P5-6 | done | Happens-before tracking and dynamic race detector (validates the verifier) | P5-5 | `src/interp/` | any race the verifier missed aborts the test run with a diagnostic |
|
||||
| P5-7 | done | Exhaustive bounded exploration of schedules and weak-read choices | P5-5 | `src/interp/` | for each litmus test, the outcome set observed equals the oracle's allowed set exactly |
|
||||
| P5-8 | dropped | Record and replay: moved to Phase 8 (P8-10) by RFC 0015 D13 | — | — | — |
|
||||
| P5-9 | done | Litmus runner and differential test (random small programs; interpreter outcomes ⊆ oracle outcomes) | P5-7 | `tests/litmus/`, `zig build litmus` | all corpus tests pass with exact equality; differential test in CI |
|
||||
| P5-9a | done | `.aji` layer 10 (spec 15 §12), Quick Reference subsection after mutexes, source coverage rows, bundle measurement | P5-4 | `src/frontend/`, `docs/agent/` | `.aji` run/reject tests for every row; Quick Reference excerpts checked; growth recorded against RFC 0015's estimate |
|
||||
| P5-9b | todo | Reference program with atomics in AIR (written by an independent author from the spec) and `.aji`, with `equivalent:` | P5-9a | `tests/conformance/` | passes under all stress modes and under `aji explore` with no forbidden outcome |
|
||||
| P5-9b | done | Reference program with atomics in AIR (written by an independent author from the spec) and `.aji`, with `equivalent:` | P5-9a | `tests/conformance/` | passes under all stress modes and under `aji explore` with no forbidden outcome |
|
||||
| P5-10 | todo | Phase exit review | all | plan status | exit criterion passes |
|
||||
|
||||
## Regression gate (P5-0)
|
||||
|
||||
@@ -257,7 +257,7 @@ Allowed only in functions that declare the effect `unsafe` or are `trusted` (`E6
|
||||
|
||||
## Feature `tasks`
|
||||
|
||||
Types `scope` and `task<T>` (linear, function-bound), instructions `task.scope.begin`, `task.spawn %s, @f(…)`, `task.join`, `task.cancel`, `task.cancelled`, `task.scope.end`; loans, `Send`/`Share` and the scheduler: spec 04 §33–§36.
|
||||
Types `scope` and `task<T>` (linear, function-bound), instructions `task.scope.begin`, `task.spawn %s, @f(…)`, `task.join`, `task.cancel`, `task.cancelled`, `task.scope.end`; loans, `Send`/`Share` and the scheduler: spec 04 §33–§36. In a module that declares `cancellation`, `task.join` waits and requires the effect `task.wait` (spec 04 §37.4); `task.spawn` always requires `task.spawn`.
|
||||
|
||||
## Features `cancellation`, `channels`, `sync`
|
||||
|
||||
@@ -281,7 +281,8 @@ Status `reserved` until it is published with its implementation (P5-2a). Its con
|
||||
|
||||
- type: linear `atomic<T>` for AtomicScalar `T`;
|
||||
- instructions: `atomic.new`, `atomic.take`, `atomic.load.<o>`, `atomic.store.<o>`, `atomic.<rmw>.<o>` (`xchg`, `add.wrap`, `sub.wrap`, `and`, `or`, `xor`), `atomic.cmpxchg.<s>.<f>` (two results), `atomic.fence.<o>`;
|
||||
- the contract table: spec 04 §42;
|
||||
- the contract table: spec 04 §42. `atomic.cmpxchg` has two results, in this order: the value read and a `bool` that is `true` when it exchanged;
|
||||
- `atomic<T>` is `Share`, so one `ref<atomic<T>>` may be lent to any number of tasks (spec 04 §35);
|
||||
- the orderings: spec 04 §24;
|
||||
- the memory model: spec 04 §20–§30;
|
||||
- effects: spec 05 §13.
|
||||
|
||||
@@ -28,4 +28,5 @@ pub const memory_test = struct {
|
||||
test {
|
||||
_ = machine;
|
||||
_ = @import("interp/weak.zig");
|
||||
_ = @import("interp/race.zig");
|
||||
}
|
||||
+133
-6
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
//! Dynamic data-race detector for ordinary memory (spec 04 §21; P5-6).
|
||||
//!
|
||||
//! A verified safe program has no data race: the ownership, borrow and loan
|
||||
//! rules exclude it. This detector checks that claim at run time, so a race
|
||||
//! the verifier missed fails the test that runs into it. It is a test tool,
|
||||
//! enabled by `Options.detect_races`; it never changes an outcome otherwise.
|
||||
//!
|
||||
//! Happens-before is carried by the weak-memory views (weak.zig): a task's
|
||||
//! vector clock is the part of its `cur` view whose keys are tasks
|
||||
//! (`clockKey`). Views already travel along every synchronization edge of
|
||||
//! spec 04 §20.3 and every release/acquire pair, so no other plumbing is
|
||||
//! needed. Every memory cell has a shadow: per access path, the last write
|
||||
//! and the reads since, each as (task, clock). Two accesses conflict when
|
||||
//! their paths overlap (one is a prefix of the other) and one writes; they
|
||||
//! race when neither happens-before the other.
|
||||
|
||||
const std = @import("std");
|
||||
const weak = @import("weak.zig");
|
||||
|
||||
/// The view key of task `t`'s clock: above every atomic cell index.
|
||||
pub fn clockKey(t: u32) u32 {
|
||||
return 0x8000_0000 | t;
|
||||
}
|
||||
|
||||
pub const Epoch = struct { task: u32, clock: u64 };
|
||||
|
||||
pub const Shadow = struct {
|
||||
entries: std.ArrayList(Entry) = .empty,
|
||||
|
||||
pub const Entry = struct {
|
||||
path: []const u32,
|
||||
write: ?Epoch = null,
|
||||
reads: std.ArrayList(Epoch) = .empty,
|
||||
};
|
||||
|
||||
pub fn copy(s: *const Shadow, gpa: std.mem.Allocator) !*Shadow {
|
||||
const n = try gpa.create(Shadow);
|
||||
n.* = .{};
|
||||
try n.entries.ensureTotalCapacity(gpa, s.entries.items.len);
|
||||
for (s.entries.items) |e| {
|
||||
var reads: std.ArrayList(Epoch) = .empty;
|
||||
try reads.appendSlice(gpa, e.reads.items);
|
||||
n.entries.appendAssumeCapacity(.{ .path = try gpa.dupe(u32, e.path), .write = e.write, .reads = reads });
|
||||
}
|
||||
return n;
|
||||
}
|
||||
};
|
||||
|
||||
fn overlap(a: []const u32, b: []const u32) bool {
|
||||
const n = @min(a.len, b.len);
|
||||
return std.mem.eql(u32, a[0..n], b[0..n]);
|
||||
}
|
||||
|
||||
fn ordered(e: Epoch, t: u32, cur: weak.View) bool {
|
||||
return e.task == t or e.clock <= cur.get(clockKey(e.task));
|
||||
}
|
||||
|
||||
/// Checks an access by task `t` (view `cur`) and records it. Returns the
|
||||
/// task of a racing access, or null.
|
||||
pub fn access(gpa: std.mem.Allocator, shadow: *Shadow, path: []const u32, write: bool, t: u32, cur: weak.View) !?u32 {
|
||||
for (shadow.entries.items) |e| {
|
||||
if (!overlap(e.path, path)) continue;
|
||||
if (e.write) |w| if (!ordered(w, t, cur)) return w.task;
|
||||
if (write) for (e.reads.items) |r| if (!ordered(r, t, cur)) return r.task;
|
||||
}
|
||||
const now: Epoch = .{ .task = t, .clock = cur.get(clockKey(t)) };
|
||||
const entry = for (shadow.entries.items) |*e| {
|
||||
if (std.mem.eql(u32, e.path, path)) break e;
|
||||
} else blk: {
|
||||
try shadow.entries.append(gpa, .{ .path = try gpa.dupe(u32, path) });
|
||||
break :blk &shadow.entries.items[shadow.entries.items.len - 1];
|
||||
};
|
||||
if (write) {
|
||||
entry.write = now;
|
||||
entry.reads.clearRetainingCapacity();
|
||||
} else {
|
||||
for (entry.reads.items) |*r| if (r.task == t) {
|
||||
r.clock = now.clock;
|
||||
return null;
|
||||
};
|
||||
try entry.reads.append(gpa, now);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
test "unordered writes race; ordered ones do not" {
|
||||
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const a = arena.allocator();
|
||||
var sh: Shadow = .{};
|
||||
const t0: weak.View = try (weak.View{}).with(clockKey(0), 1, a);
|
||||
const t1: weak.View = try (weak.View{}).with(clockKey(1), 1, a);
|
||||
try std.testing.expectEqual(@as(?u32, null), try access(a, &sh, &.{}, true, 0, t0));
|
||||
// Task 1 has not synchronized with task 0: a race.
|
||||
try std.testing.expectEqual(@as(?u32, 0), try access(a, &sh, &.{0}, false, 1, t1));
|
||||
// After acquiring task 0's clock it is ordered.
|
||||
const t1b = try t1.join(t0, a);
|
||||
try std.testing.expectEqual(@as(?u32, null), try access(a, &sh, &.{0}, true, 1, t1b));
|
||||
// Disjoint paths never conflict.
|
||||
var sh2: Shadow = .{};
|
||||
_ = try access(a, &sh2, &.{ 0, 1 }, true, 0, t0);
|
||||
try std.testing.expectEqual(@as(?u32, null), try access(a, &sh2, &.{ 0, 2 }, true, 1, t1));
|
||||
}
|
||||
@@ -311,6 +311,8 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
|
||||
.limit_exceeded => .limit_exceeded,
|
||||
.not_instantiated => .not_instantiated,
|
||||
.blocked => .blocked,
|
||||
// Only with Options.detect_races, which the CLI does not set.
|
||||
.race_detected => .trapped,
|
||||
};
|
||||
}
|
||||
return switch (report.status) {
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
; Phase 5 reference program (hand-written AIR): atomic statistics. Three workers sum
|
||||
; their parts of a lent array into a relaxed counter, raise a shared maximum with a
|
||||
; compare-exchange loop, and count themselves done with an acq_rel add; the last one
|
||||
; publishes the total, which it must see complete (release sequence of RMWs).
|
||||
; expect: run
|
||||
; schedules: 30
|
||||
; quantum: 3
|
||||
; result: 26091
|
||||
; phase: 5
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module test.atomic_stats
|
||||
air 0
|
||||
lang 0.1
|
||||
features [arrays, atomics, cancellation, effects, ownership, tasks]
|
||||
|
||||
fn @work(%part: slice<u64>, %total: ref<atomic<u64>>, %max: ref<atomic<u64>>, %done: ref<atomic<u64>>, %report: ref<atomic<u64>>) -> u8
|
||||
effects [atomic, atomic.weak]
|
||||
entry:
|
||||
%i0 = const.usize 0
|
||||
%z = const.u64 0
|
||||
br @scan(%i0, %z, %z)
|
||||
scan(%i: usize, %sum: u64, %hi: u64):
|
||||
%n = slice.len %part
|
||||
%end = eq.usize %i, %n
|
||||
cbr %end, @publish(%sum, %hi), @elem(%i, %sum, %hi)
|
||||
elem(%j: usize, %s: u64, %h: u64):
|
||||
%e = borrow.index %part, %j
|
||||
%x = load %e
|
||||
borrow.end %e
|
||||
%s2 = add.checked.u64 %s, %x
|
||||
%bigger = gt.u64 %x, %h
|
||||
cbr %bigger, @next(%j, %s2, %x), @next(%j, %s2, %h)
|
||||
next(%k: usize, %s3: u64, %h3: u64):
|
||||
%one = const.usize 1
|
||||
%k2 = add.checked.usize %k, %one
|
||||
br @scan(%k2, %s3, %h3)
|
||||
publish(%psum: u64, %pmax: u64):
|
||||
%old = atomic.add.wrap.relaxed %total, %psum
|
||||
br @raise(%pmax)
|
||||
raise(%m: u64):
|
||||
%cur = atomic.load.relaxed %max
|
||||
%low = le.u64 %m, %cur
|
||||
cbr %low, @count(), @try(%m, %cur)
|
||||
try(%m2: u64, %seen: u64):
|
||||
%prev, %ok = atomic.cmpxchg.relaxed.relaxed %max, %seen, %m2
|
||||
cbr %ok, @count(), @raise(%m2)
|
||||
count:
|
||||
%uno = const.u64 1
|
||||
%f = atomic.add.wrap.acq_rel %done, %uno
|
||||
%two = const.u64 2
|
||||
%last = eq.u64 %f, %two
|
||||
cbr %last, @report(), @finish()
|
||||
report:
|
||||
%t = atomic.load.relaxed %total
|
||||
atomic.store.release %report, %t
|
||||
br @finish()
|
||||
finish:
|
||||
%r = const.u8 0
|
||||
ret %r
|
||||
|
||||
fn @main() -> u64
|
||||
effects [atomic, atomic.weak, task.spawn, task.wait]
|
||||
entry:
|
||||
%arr = local.alloc array<u64, 6>
|
||||
local.zero %arr
|
||||
%w = borrow.mut %arr
|
||||
%a0 = const.u64 3
|
||||
%a1 = const.u64 9
|
||||
%a2 = const.u64 4
|
||||
%a3 = const.u64 1
|
||||
%a4 = const.u64 7
|
||||
%a5 = const.u64 2
|
||||
%i0 = const.usize 0
|
||||
%i1 = const.usize 1
|
||||
%i2 = const.usize 2
|
||||
%i3 = const.usize 3
|
||||
%i4 = const.usize 4
|
||||
%i5 = const.usize 5
|
||||
%e0 = borrow.index %w, %i0
|
||||
store %e0, %a0
|
||||
borrow.end %e0
|
||||
%e1 = borrow.index %w, %i1
|
||||
store %e1, %a1
|
||||
borrow.end %e1
|
||||
%e2 = borrow.index %w, %i2
|
||||
store %e2, %a2
|
||||
borrow.end %e2
|
||||
%e3 = borrow.index %w, %i3
|
||||
store %e3, %a3
|
||||
borrow.end %e3
|
||||
%e4 = borrow.index %w, %i4
|
||||
store %e4, %a4
|
||||
borrow.end %e4
|
||||
%e5 = borrow.index %w, %i5
|
||||
store %e5, %a5
|
||||
borrow.end %e5
|
||||
borrow.end %w
|
||||
%z = const.u64 0
|
||||
%ctotal = atomic.new %z
|
||||
%cmax = atomic.new %z
|
||||
%cdone = atomic.new %z
|
||||
%creport = atomic.new %z
|
||||
%rtotal = borrow.ref %ctotal
|
||||
%rmax = borrow.ref %cmax
|
||||
%rdone = borrow.ref %cdone
|
||||
%rreport = borrow.ref %creport
|
||||
%ra = borrow.ref %arr
|
||||
%s = slice.make %ra
|
||||
%pa, %rest = slice.split %s, %i2
|
||||
%pb, %pc = slice.split %rest, %i2
|
||||
%sc = task.scope.begin
|
||||
%ta = task.spawn %sc, @work(%pa, %rtotal, %rmax, %rdone, %rreport)
|
||||
%tb = task.spawn %sc, @work(%pb, %rtotal, %rmax, %rdone, %rreport)
|
||||
%tc = task.spawn %sc, @work(%pc, %rtotal, %rmax, %rdone, %rreport)
|
||||
%xa = task.join %ta
|
||||
%xb = task.join %tb
|
||||
%xc = task.join %tc
|
||||
task.scope.end %sc
|
||||
borrow.end %pb
|
||||
borrow.end %pc
|
||||
borrow.end %pa
|
||||
borrow.end %rest
|
||||
borrow.end %s
|
||||
borrow.end %ra
|
||||
borrow.end %rtotal
|
||||
borrow.end %rmax
|
||||
borrow.end %rdone
|
||||
borrow.end %rreport
|
||||
%vtotal = atomic.take %ctotal
|
||||
%vmax = atomic.take %cmax
|
||||
%vdone = atomic.take %cdone
|
||||
%vreport = atomic.take %creport
|
||||
%k1000 = const.u64 1000
|
||||
%k10 = const.u64 10
|
||||
%p1 = mul.checked.u64 %vtotal, %k1000
|
||||
%p2 = mul.checked.u64 %vmax, %k10
|
||||
%p3 = add.checked.u64 %p1, %p2
|
||||
%same = eq.u64 %vreport, %vtotal
|
||||
cbr %same, @ok(%p3), @no(%p3)
|
||||
ok(%acc: u64):
|
||||
%one = const.u64 1
|
||||
%res = add.checked.u64 %acc, %one
|
||||
ret %res
|
||||
no(%acc2: u64):
|
||||
ret %acc2
|
||||
@@ -0,0 +1,85 @@
|
||||
// Reference program (Phase 5): atomic statistics. Three workers each sum one third
|
||||
// of a lent array into a relaxed counter and raise a shared maximum with a
|
||||
// compare_exchange loop. Each then counts itself done with an acq_rel add.wrap; the
|
||||
// last one to finish synchronizes with the others through that counter (a release
|
||||
// sequence of read-modify-writes), so its relaxed read of the total sees every add,
|
||||
// and it publishes the total as a report. Result: total * 1000 + max * 10 + (report == total).
|
||||
// expect: run
|
||||
// schedules: 30
|
||||
// quantum: 3
|
||||
// result: 26091
|
||||
// equivalent: phase5/run/program_atomic_stats.air
|
||||
// phase: 6
|
||||
// spec: docs/spec/04-concurrency-and-atomics.md
|
||||
module demo.atomic_stats
|
||||
|
||||
fn work(part: slice<u64>, total: ref<atomic<u64>>, max: ref<atomic<u64>>, done: ref<atomic<u64>>, report: ref<atomic<u64>>) -> u8
|
||||
effects [atomic, atomic.weak]
|
||||
{
|
||||
var sum: u64 = 0;
|
||||
var top: u64 = 0;
|
||||
var i: usize = 0;
|
||||
while i < part.len {
|
||||
sum = sum + part[i];
|
||||
if part[i] > top {
|
||||
top = part[i];
|
||||
}
|
||||
i = i + 1;
|
||||
}
|
||||
let before = atomic.add.wrap(total, sum, relaxed);
|
||||
loop {
|
||||
let current = atomic.load(max, relaxed);
|
||||
if top <= current {
|
||||
break;
|
||||
}
|
||||
let (old, exchanged) = atomic.compare_exchange(max, current, top, relaxed, relaxed);
|
||||
if exchanged {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let finished = atomic.add.wrap(done, 1u64, acq_rel);
|
||||
if finished == 2 {
|
||||
let seen = atomic.load(total, relaxed);
|
||||
atomic.store(report, seen, release);
|
||||
}
|
||||
0u8
|
||||
}
|
||||
|
||||
fn main() -> u64
|
||||
effects [atomic, atomic.weak, task.spawn, task.wait]
|
||||
{
|
||||
var data: [u64; 6] = [0u64; 6];
|
||||
data[0] = 3;
|
||||
data[1] = 9;
|
||||
data[2] = 4;
|
||||
data[3] = 1;
|
||||
data[4] = 7;
|
||||
data[5] = 2;
|
||||
let total = atomic.new(0u64);
|
||||
let max = atomic.new(0u64);
|
||||
let done = atomic.new(0u64);
|
||||
let report = atomic.new(0u64);
|
||||
{
|
||||
ref t = total;
|
||||
ref m = max;
|
||||
ref d = done;
|
||||
ref r = report;
|
||||
ref all = data;
|
||||
let (first, rest) = all.split_at(2);
|
||||
let (second, third) = rest.split_at(2);
|
||||
scope s {
|
||||
let a = task.spawn(s, work, first, t, m, d, r);
|
||||
let b = task.spawn(s, work, second, t, m, d, r);
|
||||
let c = task.spawn(s, work, third, t, m, d, r);
|
||||
let ra = task.join(move a);
|
||||
let rb = task.join(move b);
|
||||
let rc = task.join(move c);
|
||||
}
|
||||
}
|
||||
let sum = atomic.take(move total);
|
||||
let top = atomic.take(move max);
|
||||
let n = atomic.take(move done);
|
||||
let published = atomic.take(move report);
|
||||
let flag: u64 = if published == sum { 1 } else { 0 };
|
||||
sum * 1000 + top * 10 + flag
|
||||
}
|
||||
@@ -330,6 +330,8 @@ fn runSeed(arena: std.mem.Allocator, module: aji.air.Module, want: Expect.Run, h
|
||||
.quantum = header.quantum,
|
||||
.task_limit = header.task_limit,
|
||||
.collect_every_step = collect_every_step and k == 1,
|
||||
// Every run test also checks the verifier's DRF guarantee (spec 04 §21).
|
||||
.detect_races = true,
|
||||
.schedule_seed = schedule_seed,
|
||||
}) catch |err| switch (err) {
|
||||
error.EntryNotFound => return .{ .outcome = .fail, .detail = "module has no @main whose parameters are all capabilities" },
|
||||
|
||||
Reference in new issue
Block a user