Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
the status reader reads only what the engine thread publishes under t…
…he atomics

The reset_peak query restarts the Mac hosts' stored high-water mark at the
footprint now (a fetchMax alone never lowered it), the fill totals read the
engine thread's fill_on flag instead of the plain lifecycle fields it writes
without the host's lock, a requeue takes its job off the lists before the
stream's teardown, and the cancellation walk joins the status reader's
critical section. The remaining Mac family hosts report the process
footprint's memory counts, and their prompt passes store landed fill
progress. The peak's regression test runs on deterministic samples.
  • Loading branch information
heitke committed Oct 14, 2026
commit 105ac26bd79d87fee10c301b9e1803e6396bf815
29 changes: 18 additions & 11 deletions zig/src/core/lane_host.zig
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ pub const LaneHost = struct {
prefill_sent: bool = false, // a lone driver's prefilled event went out
fill_began: bool = false, // its first prompt chunk ran
began: i96 = 0,
/// The engine thread says the prompt pass is going: status readers may count this job's fill atomics.
fill_on: std.atomic.Value(bool) = .init(false),
prefilled: ?i96 = null,
entry: ?*pc.Entry = null, // the kept state the backend restores, until its prompt pass reports
marks: []const u32 = &.{}, // where the pass keeps states (gpa-owned)
Expand Down Expand Up @@ -253,15 +255,17 @@ pub const LaneHost = struct {
for (dropped.items) |job| h.finish(job, .cancelled, "");
dropped.deinit(h.gpa);
for (ids) |id| {
var found: ?*Job = null;
h.lock(); // the status reader walks `admitted` under this lock: the removal joins the walk's critical section
for (h.admitted.items, 0..) |job, i| if (job.id == id) {
fill.unfill(h, job);
if (!job.stream.finished) h.core.discard(&job.stream);
h.lock();
_ = h.admitted.orderedRemove(i);
h.unlock();
h.finish(job, .cancelled, "");
found = job;
break;
};
h.unlock();
if (found) |job| h.finish(job, .cancelled, "");
}
h.gpa.free(ids);
}
Expand Down Expand Up @@ -337,6 +341,7 @@ pub const LaneHost = struct {
return h.drop(job, "out of memory");
};
job.started = true;
job.fill_on.store(true, .release); // status readers count the fill from here until the pass reports
const began = std.Io.Clock.awake.now(h.io).toNanoseconds();
job.began = began;
if (r.max_tokens == 0 and h.info_.warm_turns) return h.warmPass(job, began);
Expand Down Expand Up @@ -387,6 +392,7 @@ pub const LaneHost = struct {

pub fn prefilled(h: *LaneHost, job: *Job, began: i96) void {
const done = std.Io.Clock.awake.now(h.io).toNanoseconds();
job.fill_on.store(false, .release); // the pass reported: status readers stop counting this fill
h.lock();
if (done > began) h.prefill_rate = @as(f64, @floatFromInt(job.request.prompt.len - job.stream.cached)) / (@as(f64, @floatFromInt(done - began)) / 1e9);
h.prefill_at = done;
Expand Down Expand Up @@ -433,14 +439,6 @@ pub const LaneHost = struct {

/// No memory for another lane yet: the job waits at the queue's head, and admission holds until a job ends.
fn requeue(h: *LaneHost, job: *Job) bool {
if (job.stream.grammar) |g| g.deinit(h.gpa); // the next admission compiles its own
job.stream.deinit(h.gpa);
job.proposer.deinit();
job.started = false;
job.fill_began = false;
job.entry = null; // looked up again at its next admission
h.gpa.free(job.marks);
job.marks = &.{};
h.lock();
for (h.admitted.items, 0..) |j, i| if (j == job) {
_ = h.admitted.orderedRemove(i);
Expand All @@ -456,6 +454,15 @@ pub const LaneHost = struct {
h.finish(job, .failed, if (others > 0) "out of memory" else alone_words);
return true;
}
job.fill_on.store(false, .release); // off the lists before the teardown a status reader could have walked into
if (job.stream.grammar) |g| g.deinit(h.gpa); // the next admission compiles its own
job.stream.deinit(h.gpa);
job.proposer.deinit();
job.started = false;
job.fill_began = false;
job.entry = null; // looked up again at its next admission
h.gpa.free(job.marks);
job.marks = &.{};
h.memory_lanes = others;
return false;
}
Expand Down
6 changes: 3 additions & 3 deletions zig/src/core/lane_host_status.zig
Original file line number Diff line number Diff line change
Expand Up @@ -31,19 +31,19 @@ pub fn read(ctx: *anyopaque, out: *api.Status, stream_tokens: []u32) void {
fillTotals(h, out);
}

/// A started job whose prompt pass has not reported yet is filling; `fill_run` hashes the filling jobs' ids.
/// A job whose prompt pass has not reported yet is filling; the engine thread publishes that with `fill_on`.
fn fillTotals(h: *LaneHost, out: *api.Status) void {
var total: u64 = 0;
var left: u64 = 0;
var filling = false;
var run: u64 = 0;
for (h.admitted.items) |job| {
if (!job.started or job.prefilled != null or job.stream.finished) continue;
if (!job.fill_on.load(.acquire)) continue;
filling = true;
const prompt = job.request.prompt.len;
total += prompt;
left += prompt -| job.stream.fill_at.load(.monotonic);
run = run *% 0x9E3779B97F4A7C15 ^ job.id ^ @as(u64, @truncate(@as(u96, @bitCast(job.began))));
run = run *% 0x9E3779B97F4A7C15 ^ job.id ^ job.seq; // `seq` the engine thread published under this lock
}
if (!filling) return;
out.fill_prompt_tokens = @intCast(total);
Expand Down
53 changes: 53 additions & 0 deletions zig/src/core/lane_host_status_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,59 @@ test "status polls through a cancellation, a failed admission and a requeue stay
try std.testing.expect(status.fill_prompt_tokens == null and status.fill_tokens_left == null);
}

// The fill marker pins one fill: stable while a prompt's pass runs, and a later poll races it with no host lock.
test "fill_run is stable within one prompt's fill and changes for the next" {
const gpa = std.testing.allocator;
var cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7);
defer cfg.deinit(gpa);
var target: lanes.fake.Fake = .{ .gpa = gpa, .prefill_chunks = 3 };
defer target.deinit();
var clock: lanes.fake.FixedClock = .{};
var core = lanes.Engine.init(gpa, &cfg, target.stepped(), clock.clock());
defer core.deinit();
var host = LaneHost.init(gpa, std.testing.io, &core, .{ .lanes = 1 });
try host.start();
defer host.stop();
const Seen = struct {
engine: Engine = undefined,
first: ?u64 = null,
runs: std.ArrayList(u64) = .empty,
done: std.atomic.Value(bool) = .init(false),

fn hook(ctx: *anyopaque, _: *lanes.Stream, _: usize) void {
const seen: *@This() = @ptrCast(@alignCast(ctx));
var status: api.Status = .{};
seen.engine.status(&status, &.{}); // the pass holds no host lock here: the poll races it
if (status.fill_prompt_tokens != null) {
if (seen.first == null) seen.first = status.fill_run;
seen.runs.append(gpa, status.fill_run) catch {};
}
}
fn event(ctx: *anyopaque, _: Id, e: *const Event) void {
const seen: *@This() = @ptrCast(@alignCast(ctx));
if (e.* == .finished) seen.done.store(true, .release);
}
};
var seen: Seen = .{};
seen.engine = host.engine();
target.prefill_hook = Seen.hook;
target.prefill_hook_ctx = &seen;
const prompt = [_]u32{ 3, 1, 4, 1, 5, 9, 2, 6 };
const request: Request = .{ .prompt = &prompt, .max_tokens = 4 };
try seen.engine.submit(1, &request, .{ .ctx = &seen, .event = Seen.event });
while (!seen.done.load(.acquire)) std.Io.sleep(std.testing.io, .fromMilliseconds(1), .awake) catch {};
defer seen.runs.deinit(gpa);
try std.testing.expect(seen.runs.items.len >= 2); // the pass sampled the marker at least twice
for (seen.runs.items) |run| try std.testing.expectEqual(seen.first.?, run); // one fill, one marker
const second: Request = .{ .prompt = &prompt, .max_tokens = 4 };
var gone: Box = .{};
try seen.engine.submit(2, &second, .{ .ctx = &gone, .event = Box.event });
try std.testing.expectEqual(Reason.length, gone.wait());
var status: api.Status = .{};
seen.engine.status(&status, &.{}); // idle again
try std.testing.expect(status.fill_run == 0);
}

const Box = struct {
mutex: std.Io.Mutex = .init,
done: ?Reason = null,
Expand Down
1 change: 1 addition & 0 deletions zig/src/families/glm_dsa/backend.zig
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ pub const Backend = struct {
const n = @min(end - at, gpu.prompt_rows);
if (try fl.chunk(e, i, at, n, false)) |t| b.first[i] = t;
at += n;
s.fill_at.store(at, .monotonic); // fl.chunk waits on rank 0: `at` is landed progress
if (std.mem.indexOfScalar(u32, s.reuse.marks, at) != null) if (s.reuse.hook) |k| k.at(k.ptr, s, at);
}
}
Expand Down
1 change: 1 addition & 0 deletions zig/src/families/qwen3_5/backend.zig
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ pub const Metal = struct {
};
try fwd.run(self.model, &self.scratch, &.{.{ .cache = cache, .rows = end - at }}, ids[at..end], false, .last);
at = end;
stream.fill_at.store(@intCast(at), .monotonic); // fwd.run waits: `at` is landed progress
}
try self.caches.put(self.gpa, stream, cache);
}
Expand Down
33 changes: 20 additions & 13 deletions zig/src/native/cache_fit.zig
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,17 @@ pub fn footprint() ?u64 {
/// The Mac hosts' session peak: the footprint's high-water mark since the last `reset_peak`.
var host_peak: std.atomic.Value(u64) = .init(0);

/// A Mac family host's memory counts for `/stats`, `/memory` and `/metrics`, from the process footprint.
/// The mark after a reading: a reset restarts it at the footprint now, else it climbs to the reading's most.
fn peakAfter(mark: *std.atomic.Value(u64), reading: u64, reset_peak: bool) u64 {
if (reset_peak) mark.store(reading, .monotonic) else _ = mark.fetchMax(reading, .monotonic);
return mark.load(.monotonic);
}

/// A Mac host's memory counts from the process footprint; a zero limit means the family has none configured.
pub fn hostMemory(limit_bytes: u64, reset_peak: bool) ?api.Memory {
const active = footprint() orelse return null;
_ = host_peak.fetchMax(active, .monotonic);
const peak = if (reset_peak) active else host_peak.load(.monotonic);
return .{ .active = active, .cache = 0, .peak = peak, .pinned = 0, .limit = limit_bytes };
const peak = peakAfter(&host_peak, active, reset_peak);
return .{ .active = active, .cache = 0, .peak = peak, .pinned = 0, .limit = if (limit_bytes > 0) limit_bytes else null };
}

/// The cache plan: `gib` if it fits (or `over`), else what 70% of RAM leaves up to 16 GiB (no reading: `spare` for it).
Expand Down Expand Up @@ -140,18 +145,20 @@ test "a host's memory counts keep the footprint, its measured peak and the limit
try std.testing.expectEqual(@as(u64, 0), m.cache);
try std.testing.expectEqual(@as(u64, 0), m.pinned);
const after_reset = hostMemory(limit, true).?; // a reset starts a new peak at the footprint now
try std.testing.expectEqual(m.active, after_reset.peak);
try std.testing.expect(after_reset.active <= m.active); // the footprint only shrank since the first read
try std.testing.expectEqual(after_reset.active, after_reset.peak); // the reset's own reading, not an older mark
const again = hostMemory(limit, false).?;
try std.testing.expect(again.peak >= again.active); // the mark climbs again from the reset
try std.testing.expect(again.peak >= again.active); // the mark covers the footprint now
}

test "the high-water mark rises and resets" {
if (builtin.os.tag != .macos) return error.SkipZigTest;
_ = hostMemory(1 << 30, true) orelse return error.SkipZigTest; // start from a fresh mark
const low = hostMemory(1 << 30, false).?; // the footprint now is the mark
const high = hostMemory(1 << 30, false).?; // a second read cannot lower it
try std.testing.expect(high.peak >= low.active);
test "the high-water mark rises, holds, resets and the next read climbs from the reset" {
var mark: std.atomic.Value(u64) = .init(0);
try std.testing.expectEqual(@as(u64, 100), peakAfter(&mark, 100, false)); // the first read is the mark
try std.testing.expectEqual(@as(u64, 100), peakAfter(&mark, 60, false)); // a lower reading leaves the mark
try std.testing.expectEqual(@as(u64, 120), peakAfter(&mark, 120, false)); // a higher one raises it
try std.testing.expectEqual(@as(u64, 40), peakAfter(&mark, 40, true)); // a reset starts the mark at the reading
try std.testing.expectEqual(@as(u64, 50), peakAfter(&mark, 50, false)); // the next read reports 50, not 120
try std.testing.expectEqual(@as(u64, 50), peakAfter(&mark, 45, false)); // and it holds against lower readings
try std.testing.expectEqual(@as(u64, 70), peakAfter(&mark, 70, false)); // then climbs again
}

test "a host without a footprint reading reports no memory rather than zeros" {
Expand Down
4 changes: 2 additions & 2 deletions zig/src/native/flashnext_host.zig
Original file line number Diff line number Diff line change
Expand Up @@ -161,8 +161,8 @@ pub const Host = struct {
};
}

fn memoryFn(_: *anyopaque, _: bool) ?api.Memory {
return null;
fn memoryFn(_: *anyopaque, reset_peak: bool) ?api.Memory {
return cache_fit.hostMemory(0, reset_peak); // the process footprint; no configured load limit
}

fn emit(job: *Job, event: api.Event) void {
Expand Down
10 changes: 10 additions & 0 deletions zig/src/native/glm_dsa_host.zig
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const tf = @import("tensorfold");
const lanes = tf.lanes;
const g = tf.glm_dsa;
const Allocator = std.mem.Allocator;
const cache_fit = @import("cache_fit.zig");

pub const Host = struct {
gpa: Allocator,
Expand All @@ -15,6 +16,7 @@ pub const Host = struct {
wall: lanes.backend.WallClock,
core: lanes.Engine,
host: api.LaneHost,
limit: u64 = 0, // the configured load limit, for the memory counts
cache: ?api.prompt_cache.Store = null, // rank 0's kept prompt states (rank 1 holds the same ids)
warm: mtl.keepalive.Target,
follower: ?std.Thread = null,
Expand All @@ -24,6 +26,12 @@ pub const Host = struct {
}
};

/// The host's memory counts: `cache_fit.hostMemory` under this engine's configured load limit.
fn readMemory(ctx: ?*anyopaque, reset_peak: bool) ?api.Memory {
const h: *Host = @ptrCast(@alignCast(ctx.?));
return cache_fit.hostMemory(h.limit, reset_peak);
}

fn words(_: ?*anyopaque, err: anyerror) ?[]const u8 {
return switch (err) {
error.GreedyOnly => "the native GLM-5.3 engine decodes greedily only: send temperature 0",
Expand All @@ -46,6 +54,7 @@ pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up:
h.gpa = gpa;
h.e = e;
h.follower = null;
h.limit = limit;
h.back = try g.backend.Backend.init(gpa, e);
errdefer h.back.deinit();
if (e.rank() == 0) try h.back.time(io);
Expand All @@ -55,6 +64,7 @@ pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up:
h.core = lanes.Engine.init(gpa, &h.cfg, h.back.backend(), h.wall.clock());
errdefer h.core.deinit();
h.host = api.LaneHost.init(gpa, io, &h.core, .{ .name = "glm-dsa-zig", .lanes = streams, .context_window = window, .prefill_step = g.gpu.prompt_rows, .greedy_only = true });
h.host.memory = .{ .ctx = h, .read = readMemory };
h.host.explain = .{ .text = words };
h.cache = null;
const used = e.device.allocated();
Expand Down
6 changes: 6 additions & 0 deletions zig/src/native/metal.zig
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,11 @@ fn modelContext(a: Allocator, io: std.Io, dir: []const u8) i64 {
return if (limit == .integer and limit.integer > 0) limit.integer else 0;
}

/// The host's memory counts: `cache_fit.hostMemory` from the process footprint (no configured load limit).
fn readMemory(_: ?*anyopaque, reset_peak: bool) ?api.Memory {
return cache_fit.hostMemory(0, reset_peak);
}

/// One loaded model behind the lane host: everything the engine thread reads lives here.
const Host = struct {
gpa: Allocator,
Expand Down Expand Up @@ -162,6 +167,7 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c
h.core = lanes.Engine.init(gpa, &h.cfg, h.metal.backend(), h.clock.clock());
errdefer h.core.deinit();
h.host = api.LaneHost.init(gpa, io, &h.core, .{ .lanes = o.lanes, .context_window = @intCast(@max(window, 0)), .prefill_step = step, .structures = true });
h.host.memory = .{ .ctx = h, .read = readMemory };
h.round = .{ .depth = 8 };
h.cache = null;
var why: []const u8 = "";
Expand Down
6 changes: 6 additions & 0 deletions zig/src/native/qwen27_served.zig
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,11 @@ pub const Host = struct {
}
};

/// The host's memory counts: `cache_fit.hostMemory` from the process footprint (no configured load limit).
fn readMemory(_: ?*anyopaque, reset_peak: bool) ?api.Memory {
return cache_fit.hostMemory(0, reset_peak);
}

/// The words for a request the engine refuses.
fn words(_: ?*anyopaque, err: anyerror) ?[]const u8 {
return switch (err) {
Expand Down Expand Up @@ -253,6 +258,7 @@ pub fn attach(gpa: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q.df
h.core = lanes.Engine.init(gpa, &h.cfg, h.back.backend(), h.clock.clock());
errdefer h.core.deinit();
h.host = api.LaneHost.init(gpa, io, &h.core, .{ .name = "qwen27", .lanes = slots, .context_window = capacity, .prefill_step = 128 });
h.host.memory = .{ .ctx = h, .read = readMemory };
h.host.explain = .{ .text = words };
h.host.decoded_rows = true; // a reply's rows prefill with the bits decoding gave them, with the cache on or off
// a lone greedy request takes the serial loop on tensor units, where it is faster (TF_QWEN27_LANES overrides)
Expand Down
1 change: 1 addition & 0 deletions zig/src/native/qwen27_slots.zig
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ pub fn prefill(b: *Metal, s: *lanes.Stream, slot: u32) !void {
if (b.ringOf(slot)) |g| try ringChunk(b, g, part.len);
}
at = end;
s.fill_at.store(@intCast(at), .monotonic); // a prompt chunk waits: `at` is landed progress
if (std.mem.indexOfScalar(u32, s.reuse.marks, @intCast(at)) != null) if (s.reuse.hook) |k| k.at(k.ptr, s, @intCast(at));
}
}
Expand Down
7 changes: 7 additions & 0 deletions zig/src/native/qwen35.zig
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ const api = @import("engine_api");
const tf = @import("tensorfold");
const q = tf.qwen35;
const lanes = tf.lanes;
const cache_fit = @import("cache_fit.zig");

/// The host's memory counts: `cache_fit.hostMemory` from the process footprint (no configured load limit).
fn readMemory(_: ?*anyopaque, reset_peak: bool) ?api.Memory {
return cache_fit.hostMemory(0, reset_peak);
}

const Host = struct {
gpa: std.mem.Allocator,
Expand Down Expand Up @@ -54,6 +60,7 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope
h.core = lanes.Engine.init(gpa, &h.config, h.metal.backend(), h.clock.clock());
errdefer h.core.deinit();
h.host = api.LaneHost.init(gpa, io, &h.core, .{ .lanes = o.lanes, .context_window = @intCast(window), .prefill_step = chunk, .structures = true });
h.host.memory = .{ .ctx = h, .read = readMemory };
h.warm = .{ .queue = h.metal.model.queue };
h.host.keepalive_target = .{ .ctx = &h.warm, .tick = mtl.keepalive.Target.tick };
try h.host.start();
Expand Down