feat: structured first-wins race over the M:1 fiber scheduler

`s.race((a: ta, b: tb, …))` takes a named tuple of already-spawned
`*Task(..)` handles, suspends the calling fiber until the FIRST task is
ready, and returns a comptime-synthesized tagged-union (`RaceResult`)
mirroring the tuple's labels — variant NAME = the tuple label, payload =
that task's result type. After picking the winner it CANCELS and JOINS
every loser, so no loser fiber outlives the call (structured concurrency).

- `RaceResult($T) -> Type` projects each `*Task(R)` element to `R` via
  `field_type(pointee(field_type(T, i)), 0)` and mints the union with
  `make_enum` (the 0649 composition shape).
- `race` Phase 1 registers the caller as waiter on all pending tasks and
  parks; on wake it DEREGISTERS from every task (a later loser completion
  must never wake it again) and re-scans, lowest-index-first. Phase 2
  builds the winner variant with `make_variant`. Phase 3 cancels + joins
  each loser one at a time — only the joined loser carries a waiter, so no
  other completion can wake the caller mid-join.
- Join correctness rides a new `Task.finished` flag, set at the very end of
  the `go` worker body (after the work ran OR was skipped on an early
  cancel) and checked before parking, so a worker that finishes between the
  cancel and the park can't be lost. Cancellation is cooperative (M:1, no
  preemption): a loser parked mid-`sleep` runs to its natural end, its value
  discarded — `race` returns only once every loser has `finished`.

The tuple must be NAMED; a positional `._0`/`._1` form is future work.

Locked by examples/concurrency/1821 — three tasks (i64/bool/f64) sleeping
10/20/30ms, shortest wins, losers cancelled + joined; byte-identical on
aarch64-macOS and aarch64-linux (deterministic virtual time).
This commit is contained in:
agra
2026-06-26 18:07:14 +03:00
parent 6a97628749
commit 9099735e88
2 changed files with 194 additions and 1 deletions

View File

@@ -0,0 +1,62 @@
// Stream B2/A1 — structured first-wins `race` over the M:1 fiber scheduler.
//
// `s.race((a: ta, b: tb, c: tc))` takes a named tuple of already-spawned
// `*Task(..)` handles, SUSPENDS the calling fiber until the FIRST task is ready,
// and returns a comptime-SYNTHESIZED tagged-union (`RaceResult`) mirroring the
// tuple's labels — variant NAME = the tuple label, payload = that task's result
// type. Here the three tasks return DIFFERENT types (i64 / bool / f64), so the
// minted union is `enum { a: i64; b: bool; c: f64 }` and the winner is matched by
// label. After picking the winner, `race` CANCELS and JOINS every loser, so no
// loser fiber outlives the call (structured concurrency).
//
// Deterministic by virtual time (like 1817 — no real clock): the tasks sleep
// 10/20/30 ms, so `a` (shortest) wins at t=10. Cancellation is COOPERATIVE (M:1,
// no preemption): the losers were already parked mid-`sleep` when cancelled, so
// they cannot be preempted — `race` joins them, letting each run to its natural
// end (its value discarded) before returning. The completion log therefore shows
// all three finishing (a@10 winner, b@20, c@30 joined) and the final virtual
// clock is 30. Each loser's `canceled` flag is set and its worker `finished`.
//
// aarch64-pinned (the scheduler's per-arch asm + per-OS mmap/event constants):
// runs end-to-end on a matching host (macOS + linux), ir-only on a mismatch.
#import "modules/std.sx";
sched :: #import "modules/std/sched.sx";
Log :: struct { id: [8]i64; at: [8]i64; n: i64; }
rec :: (l: *Log, id: i64, at: i64) { l.id[l.n] = id; l.at[l.n] = at; l.n = l.n + 1; }
main :: () -> i64 {
lg : Log = ---; lg.n = 0;
s := sched.Scheduler.init();
ps := @s; pl := @lg;
// The coordinator runs as a fiber so `race` has a `current` to park.
s.spawn(() => {
// Three async tasks with DIFFERENT result types and sleep durations.
a := ps.go(() -> i64 => { ps.sleep(10); rec(pl, 1, ps.now_ms()); 111 });
b := ps.go(() -> bool => { ps.sleep(20); rec(pl, 2, ps.now_ms()); true });
c := ps.go(() -> f64 => { ps.sleep(30); rec(pl, 3, ps.now_ms()); 2.5 });
// Race them. `a` (sleep 10) wins; `b` and `c` are cancelled + joined.
winner := ps.race(.(a = a, b = b, c = c));
if winner == {
case .a: (v) { print("winner: a (i64) = {}\n", v); }
case .b: (v) { print("winner: b (bool) = {}\n", v); }
case .c: (v) { print("winner: c (f64) = {}\n", v); }
}
// The losers were cancelled (flag set) and joined (worker finished).
print("loser b: canceled={} finished={}\n", b.canceled, b.finished);
print("loser c: canceled={} finished={}\n", c.canceled, c.finished);
});
s.run();
print("completion order (id @ virtual-ms):\n");
i := 0;
while i < lg.n {
print(" task {} @ {}ms\n", lg.id[i], lg.at[i]);
i = i + 1;
}
print("final virtual clock: {}ms\n", s.now_ms());
return 0;
}