From 2c1d36004737578f50c5af439ba71f1f8864d58f Mon Sep 17 00:00:00 2001 From: Andy Heitke <45763735+heitke@users.noreply.github.com> Date: Mon, 12 Oct 2026 10:15:21 -0400 Subject: [PATCH 1/9] dashboard: the prefill queue's tokens left and ETA on the stats snapshot Status gains optional fill_prompt_tokens and fill_tokens_left; a stream's atomic fill_at counts the prompt tokens its pass has prefilled; the lane host's status read sums them over the admitted jobs still prefilling, and /stats carries the pair only while a fill runs. The dashboard's dialside tile counts the tokens left and estimates the wait to the first token from the poll-to-poll drain, and the dial enters prefill mode as soon as a prompt starts. --- zig/src/core/engine_api.zig | 4 +++ zig/src/core/lane_host_fill_test.zig | 46 +++++++++++++++++++++++++++ zig/src/core/lane_host_status.zig | 18 +++++++++++ zig/src/core/lanes/fake.zig | 2 ++ zig/src/core/lanes/stream.zig | 1 + zig/src/families/glm/backend.zig | 1 + zig/src/families/nemotron/backend.zig | 1 + zig/src/server/dashboard.html | 27 +++++++++++++++- zig/src/server/dashboard_test.zig | 2 ++ zig/src/server/status_routes.zig | 15 +++++++++ 10 files changed, 116 insertions(+), 1 deletion(-) diff --git a/zig/src/core/engine_api.zig b/zig/src/core/engine_api.zig index 99ad4ff84f6..a1ef8a127fc 100644 --- a/zig/src/core/engine_api.zig +++ b/zig/src/core/engine_api.zig @@ -255,6 +255,9 @@ pub const Status = struct { streams: usize = 0, /// Generated tokens held by live streams, excluding their prompts. generation_tokens: u64 = 0, + /// Filling prompts' total tokens and those still to prefill (null: no prompt is going in). + fill_prompt_tokens: ?u32 = null, + fill_tokens_left: ?u32 = null, }; pub const SubmitError = error{ Closed, Busy, InvalidSpans }; @@ -411,6 +414,7 @@ pub const keepalive = @import("keepalive.zig"); test { _ = @import("lane_host.zig"); _ = @import("lane_host_test.zig"); + _ = @import("lane_host_fill_test.zig"); _ = @import("lane_host_reuse_test.zig"); _ = @import("lane_host_warm_test.zig"); _ = @import("lane_host_fill_test.zig"); diff --git a/zig/src/core/lane_host_fill_test.zig b/zig/src/core/lane_host_fill_test.zig index 76c8446be25..d9515068c7e 100644 --- a/zig/src/core/lane_host_fill_test.zig +++ b/zig/src/core/lane_host_fill_test.zig @@ -7,6 +7,7 @@ const Reason = api.Reason; const Id = api.Id; const Event = api.Event; const Request = api.Request; +const Engine = api.Engine; test "a lane host fills the shortest waiting prompt first, so a short request waits on no long one" { const gpa = std.testing.allocator; @@ -121,3 +122,48 @@ test "a foreground prompt arriving while a background one fills takes the next c } try std.testing.expectEqualSlices(Id, &.{ 2, 1 }, &order.prefilled); } + +test "status reads a filling prompt's tokens while its pass runs, and none once it ends" { + 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 = 4 }; + 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, + lefts: std.ArrayList(u32) = .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 runs without the host's lock: this can read + if (status.fill_tokens_left) |left| seen.lefts.append(gpa, left) 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.lefts.deinit(gpa); + try std.testing.expect(seen.lefts.items.len >= 2); // each chunk of the pass sampled the status + for (seen.lefts.items) |left| try std.testing.expect(left > 0 and left <= prompt.len); + try std.testing.expect(seen.lefts.items[0] > seen.lefts.items[seen.lefts.items.len - 1]); // it counted down + var status: api.Status = .{}; + seen.engine.status(&status, &.{}); + try std.testing.expect(status.fill_prompt_tokens == null and status.fill_tokens_left == null); // the pass is over +} diff --git a/zig/src/core/lane_host_status.zig b/zig/src/core/lane_host_status.zig index a92bf19a0c2..7c98126de39 100644 --- a/zig/src/core/lane_host_status.zig +++ b/zig/src/core/lane_host_status.zig @@ -28,6 +28,24 @@ pub fn read(ctx: *anyopaque, out: *api.Status, stream_tokens: []u32) void { .streams = n, .generation_tokens = h.live_generated, }; + fillTotals(h, out); +} + +/// A started job whose prompt pass has not reported yet is filling: sum its prompt and what is left of it. +fn fillTotals(h: *LaneHost, out: *api.Status) void { + var total: u64 = 0; + var left: u64 = 0; + var filling = false; + for (h.admitted.items) |job| { + if (!job.started or job.prefilled != null or job.stream.finished) continue; + filling = true; + const prompt = job.request.prompt.len; + total += prompt; + left += prompt -| job.stream.fill_at.load(.monotonic); + } + if (!filling) return; + out.fill_prompt_tokens = @intCast(total); + out.fill_tokens_left = @intCast(left); } /// `n` tokens delivered now; marks older than the window drop. diff --git a/zig/src/core/lanes/fake.zig b/zig/src/core/lanes/fake.zig index 9434736c46e..7e95ff559b7 100644 --- a/zig/src/core/lanes/fake.zig +++ b/zig/src/core/lanes/fake.zig @@ -133,6 +133,7 @@ pub const Fake = struct { const chunks = if (x.prefill_chunks == 0) 1 else x.prefill_chunks; for (0..chunks) |chunk| { x.prefill_count += 1; + s.fill_at.store(@intCast(s.prompt_len * (chunk + 1) / chunks), .monotonic); if (x.prefill_hook) |hook| hook(x.prefill_hook_ctx.?, s, chunk); if (s.isCancelled()) return error.Cancelled; if (s.yields()) return error.Yielded; @@ -152,6 +153,7 @@ pub const Fake = struct { if (x.prefill_hook) |hook| hook(x.prefill_hook_ctx.?, s, l.filled); if (s.isCancelled()) return error.Cancelled; l.filled += 1; + s.fill_at.store(@intCast(s.prompt_len * l.filled / @max(1, x.prefill_chunks)), .monotonic); if (l.filled < @max(1, x.prefill_chunks)) return false; l.filling = false; try x.fillPrompt(l, s); diff --git a/zig/src/core/lanes/stream.zig b/zig/src/core/lanes/stream.zig index 0d99d32b938..e25984de6c1 100644 --- a/zig/src/core/lanes/stream.zig +++ b/zig/src/core/lanes/stream.zig @@ -156,6 +156,7 @@ pub const Stream = struct { decide: ?u32 = null, untaught: bool = false, cached: u32 = 0, // prompt tokens the backend restored from `reuse` (its prompt pass started there) + fill_at: std.atomic.Value(u32) = .init(0), // prompt tokens the pass has prefilled; the engine thread writes reuse_failed: bool = false, // the backend's restore of `reuse` failed: it prefilled from 0 context: std.ArrayList(u32) = .empty, pending: ?u32 = null, diff --git a/zig/src/families/glm/backend.zig b/zig/src/families/glm/backend.zig index 85b6f8c78e7..6ae3cd5c197 100644 --- a/zig/src/families/glm/backend.zig +++ b/zig/src/families/glm/backend.zig @@ -122,6 +122,7 @@ pub const Backend = struct { try mirror.send(e, .chunk, &.{ i, at, n }); try b.sl.chunk(i, at, n); at += n; + s.fill_at.store(at, .monotonic); // the dashboard's prefill progress reads this between chunks if (std.mem.indexOfScalar(u32, s.reuse.marks, at) != null) if (s.reuse.hook) |k| k.at(k.ptr, s, at); } } diff --git a/zig/src/families/nemotron/backend.zig b/zig/src/families/nemotron/backend.zig index f52e5a4a6cd..62c999ebc4c 100644 --- a/zig/src/families/nemotron/backend.zig +++ b/zig/src/families/nemotron/backend.zig @@ -324,6 +324,7 @@ pub const Metal = struct { try self.submit(.prefill, self.next, Chunks{ .n = ids.len, .c = c, .at = at, .rows = rows }); while (self.flights.items.len > 1) try self.land(); at += rows; + s.fill_at.store(@intCast(at), .monotonic); // the dashboard's prefill progress reads this between chunks if (s.reuse.hook) |hk| if (std.mem.indexOfScalar(u32, s.reuse.marks, @intCast(at)) != null) hk.at(hk.ptr, s, @intCast(at)); } if (self.trace and c.decide != lesson_route.none) try self.traceLessons(c); diff --git a/zig/src/server/dashboard.html b/zig/src/server/dashboard.html index e56e25b0a0c..31f54a01876 100644 --- a/zig/src/server/dashboard.html +++ b/zig/src/server/dashboard.html @@ -58,6 +58,8 @@
+
Prefill queue
idle
+
tokens left to prefill
Memory
—
Tokens in flight
—
@@ -87,6 +89,7 @@

Decode rate · last 5 minutes

const el = id => document.getElementById(id); const fmt = v => v == null ? "—" : nf.format(Math.round(v)); const GiB = v => v == null ? null : (v / 2**30).toFixed(1); +const etaText = s => s < 100 ? `${Math.round(s)} s` : `${Math.round(s / 60)} min`; // the wait to the first token // the page is served at /dashboard; a proxy that adds a prefix still reaches ../stats or /stats const STATS_URL = location.pathname.replace(/\/(dashboard)?\/?$/, "") + "/stats?poll=1"; // the poll URL keeps the cache-busting query @@ -95,6 +98,7 @@

Decode rate · last 5 minutes

let lastGood = 0; let histPoints = []; // the polled decode rates: [{t, tok_s}], newest last, sparse over 5 minutes let prefillRates = []; // the polled prefill rates while a prefill ran, for the average tile +let fillSamples = []; // the polled tokens left: [{t, left}], the drain the ETA reads let histTop = 0; // the chart's current y scale, decayed like the dial's function band(v) { return v >= 60 ? css("--accent") : v >= 40 ? css("--cool") : v >= 20 ? css("--warm") : css("--hot"); } @@ -116,7 +120,8 @@

Decode rate · last 5 minutes

const cx = S / 2, cy = S / 2; arc(x, cx, cy, 232, 22, 1, css("--line"), 1); // one track // prefill and decode share the dial: whichever mode is live colors the arc (they never run together) - const mode = shown.prefill > 0.5 ? "prefill" : "decode"; + const filling = fillSamples.length > 0; // a prompt is going in right now + const mode = filling || shown.prefill > 0.5 ? "prefill" : "decode"; if (mode === "prefill") { arc(x, cx, cy, 232, 22, Math.min(1, Math.log10(1 + shown.prefill) / 4), css("--cool"), 1); } else { @@ -213,6 +218,26 @@

Decode rate · last 5 minutes

el("membar").style.width = "0%"; } + // The prefill queue: a prompt is going in while the snapshot carries fill_tokens_left; its drain + // between polls gives the live rate, and left over that rate the time to the first token. + if (s.fill_tokens_left != null) { + fillSamples.push({ t: now, left: s.fill_tokens_left }); + if (fillSamples.length > 64) fillSamples.shift(); + el("fill").innerHTML = `${fmt(s.fill_tokens_left)} tok`; + let rate = null; // tokens a second, from the poll-to-poll drain + if (fillSamples.length > 1) { + const a = fillSamples[0], b = fillSamples[fillSamples.length - 1]; + if (b.t > a.t && b.left < a.left) rate = (a.left - b.left) / (b.t - a.t); + } + if (rate == null && target.prefill > 0) rate = target.prefill; // one sample: the server's 2 s rate + const eta = rate ? s.fill_tokens_left / rate : null; + el("fillcap").textContent = `of ${fmt(s.fill_prompt_tokens)} · ~${eta == null ? "—" : etaText(eta)} to the first token`; + } else { + fillSamples = []; + el("fill").textContent = "idle"; + el("fillcap").textContent = "tokens left to prefill"; + } + el("gen").textContent = fmt(s.generation_tokens_running); el("gencap").textContent = (s.generation_tokens_running || 0) > 0 ? `across ${s.running || 0} live stream${s.running == 1 ? "" : "s"}` : "held by the live streams"; diff --git a/zig/src/server/dashboard_test.zig b/zig/src/server/dashboard_test.zig index 08e6dc0115b..43fb106b2cb 100644 --- a/zig/src/server/dashboard_test.zig +++ b/zig/src/server/dashboard_test.zig @@ -7,4 +7,6 @@ test "dashboard page polls the public stats snapshot without private details" { try std.testing.expect(std.mem.indexOf(u8, page, "generation_tokens_running") != null); try std.testing.expect(std.mem.indexOf(u8, page, "decode_rounds_total") != null); try std.testing.expect(std.mem.indexOf(u8, page, "memory.peak!=null") != null); + try std.testing.expect(std.mem.indexOf(u8, page, "fill_tokens_left") != null); + try std.testing.expect(std.mem.indexOf(u8, page, "fill_prompt_tokens") != null); } diff --git a/zig/src/server/status_routes.zig b/zig/src/server/status_routes.zig index 89ee5c84889..f3d31fb380d 100644 --- a/zig/src/server/status_routes.zig +++ b/zig/src/server/status_routes.zig @@ -105,6 +105,10 @@ pub fn statsSnapshot(a: Allocator, status: api.Status, memory: ?api.Memory, prom try o.put(a, "decode_tokens_per_second", .{ .float = status.decode_tokens_per_second }); try o.put(a, "prefill_tokens_per_second", .{ .float = status.prefill_tokens_per_second }); try o.put(a, "generation_tokens_running", try json.intValue(a, status.generation_tokens)); + if (status.fill_prompt_tokens != null) { + try o.put(a, "fill_prompt_tokens", try json.intValue(a, status.fill_prompt_tokens.?)); + try o.put(a, "fill_tokens_left", try json.intValue(a, status.fill_tokens_left orelse 0)); + } try o.put(a, "prompt_tokens_total", try json.intValue(a, prompt)); try o.put(a, "generation_tokens_total", try json.intValue(a, generation)); try o.put(a, "mtp_drafted_total", try json.intValue(a, drafted)); @@ -153,4 +157,15 @@ test "stats snapshot exposes counters and omits unknown memory" { for ([_][]const u8{ "running", "waiting", "generation_tokens_running", "prompt_tokens_total", "generation_tokens_total", "mtp_drafted_total", "mtp_accepted_total", "decode_rounds_total", "memory" }) |key| try std.testing.expect(object.contains(key)); try std.testing.expectEqual(@as(usize, 0), object.get("memory").?.object.count()); + try std.testing.expect(object.get("fill_prompt_tokens") == null); // no fill in progress: the keys stay out +} + +test "stats snapshot carries the filling prompt's tokens while a prefill runs" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const status: api.Status = .{ .fill_prompt_tokens = 900, .fill_tokens_left = 300 }; + const value = try statsSnapshot(arena.allocator(), status, null, 0, 0, 0, 0, 0); + const object = value.object; + try std.testing.expectEqual(@as(i64, 900), object.get("fill_prompt_tokens").?.int64().?); + try std.testing.expectEqual(@as(i64, 300), object.get("fill_tokens_left").?.int64().?); } From 97ae179d71ef6d643032f28071341879317e3555 Mon Sep 17 00:00:00 2001 From: Andy Heitke <45763735+heitke@users.noreply.github.com> Date: Mon, 12 Oct 2026 12:59:03 -0400 Subject: [PATCH 2/9] glm host: the dashboard's memory tile gets its bytes from the process footprint The lane host's memoryFn returns null unless the family host wires a MemorySource, and only the CUDA host did, so /stats carried an empty memory object on a Mac and the dashboard's Memory tile fell back to a dash. The GLM host now wires one: the process's physical footprint (rusage_info_v4, Metal buffers included) as active, and the load limit read at load as peak, so the tile and the /metrics gauges show real numbers. --- zig/src/native/glm_host.zig | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/zig/src/native/glm_host.zig b/zig/src/native/glm_host.zig index dab379dbf33..943ecfc06b8 100644 --- a/zig/src/native/glm_host.zig +++ b/zig/src/native/glm_host.zig @@ -6,6 +6,7 @@ const tf = @import("tensorfold"); const lanes = tf.lanes; const glm = tf.glm; const ge = glm.engine; +const cache_fit = @import("cache_fit.zig"); const Allocator = std.mem.Allocator; /// The warm-up reply's draft depth: every rank of a pair pays a process's first-round costs at the same step. @@ -65,6 +66,14 @@ fn cacheBudget(eng: *const ge.Engine, gib: ?f64) u64 { return if (limit > used) @min(want, limit - used) else 0; } +/// The host's memory counts for /stats, /memory and /metrics: the footprint holds the Metal buffers, so it is `active`. +fn readMemory(ctx: ?*anyopaque, reset_peak: bool) ?api.Memory { + const h: *Host = @ptrCast(@alignCast(ctx.?)); + _ = reset_peak; // nothing to reset: `peak` is the load limit read at load, not a high-water mark + const active = cache_fit.footprint() orelse return null; + return .{ .active = active, .cache = 0, .peak = h.eng.limit.bytes, .pinned = 0 }; +} + /// Learned states under `root` by checkpoint, split, chip, OS build, kernel sources and a probe's prompt-pass bits. fn learnedStates(gpa: Allocator, eng: *const ge.Engine, sl: *glm.slots.Slots, root: []const u8, cap: u64) !api.prompt_imprint.Imprint { var h = std.hash.Wyhash.init(0x62); @@ -105,6 +114,7 @@ pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up: errdefer h.core.deinit(); const serves = @min(window, glm.pool.capacity(&h.slots) -| (glm.state.max_rows + 1)); // prompt + reply a stream's caches hold beside its last window (a pool keeps whole blocks) h.host = api.LaneHost.init(gpa, io, &h.core, .{ .name = "glm-zig", .lanes = n, .context_window = serves, .prefill_step = eng.chunk_rows, .greedy_only = true, .admit = if (h.slots.pool != null) .{ .ctx = &h.back, .fits = glm.backend.Backend.fits } else null }); + h.host.memory = .{ .ctx = h, .read = readMemory }; h.cache = null; const budget = cacheBudget(eng, cache_gib); if (!eng.followsPeer() and budget > 0) { From ed8cdc92cadb66df55ab242099cb20fbd4ef6993 Mon Sep 17 00:00:00 2001 From: Andy Heitke <45763735+heitke@users.noreply.github.com> Date: Wed, 14 Oct 2026 13:25:06 -0400 Subject: [PATCH 3/9] the dashboard's fill and memory numbers say what they mean A /stats poll raced the engine thread's completion path: deliver() freed a job that was still in the host's admitted list, and the fill-total reader walked that list, so a poll at the wrong moment read freed memory. A job now leaves the lists inside deliver, before finish runs it down; the status tests poll at the finished event, where the old order still counted the dying job. The GLM host's memory tile put the configured load limit in the peak field. The limit is a plan, not a measurement: it moves to a limit field of its own, the peak is the kernel's lifetime footprint peak, and the tile labels each number for what it is. Mac family hosts share the reading through cache_fit.hostMemory. The page's ETA mixed the drains of different prompts whenever one fill followed another without an idle poll between. The snapshot now carries fill_run, a marker that changes when the filling set does, and the page resets its samples on it; the label says the queue drains, which is what the aggregate of several lanes' remaining work estimates. Nemotron's prompt pass advanced fill_at past what the GPU had landed, so the countdown reached zero while the last chunk still ran. It stores landed tokens now, and a restored prefix counts as done the moment it lands. --- zig/src/core/engine_api.zig | 6 +- zig/src/core/lane_host.zig | 14 +- zig/src/core/lane_host_lone.zig | 2 +- zig/src/core/lane_host_status.zig | 5 +- zig/src/core/lane_host_status_test.zig | 216 +++++++++++++++++++++++++ zig/src/families/glm/backend.zig | 3 +- zig/src/families/nemotron/backend.zig | 3 +- zig/src/native/cache_fit.zig | 38 ++++- zig/src/native/glm_host.zig | 6 +- zig/src/server/dashboard.html | 29 +++- zig/src/server/dashboard_test.zig | 3 + zig/src/server/memory_routes.zig | 12 ++ zig/src/server/status_routes.zig | 14 ++ 13 files changed, 323 insertions(+), 28 deletions(-) create mode 100644 zig/src/core/lane_host_status_test.zig diff --git a/zig/src/core/engine_api.zig b/zig/src/core/engine_api.zig index a1ef8a127fc..90d717e4cb4 100644 --- a/zig/src/core/engine_api.zig +++ b/zig/src/core/engine_api.zig @@ -228,7 +228,7 @@ pub const Open = struct { /// An opened engine; ``close`` stops its thread and frees its backend. pub const Opened = struct { engine: Engine, close: *const fn (ctx: *anyopaque) void, ctx: *anyopaque }; -pub const Memory = struct { active: u64 = 0, cache: u64 = 0, peak: u64 = 0, pinned: u64 = 0 }; +pub const Memory = struct { active: u64 = 0, cache: u64 = 0, peak: u64 = 0, pinned: u64 = 0, limit: ?u64 = null }; /// A backend's words for its own refusals (a request it cannot serve); null: the error's name. pub const Explain = struct { @@ -258,6 +258,8 @@ pub const Status = struct { /// Filling prompts' total tokens and those still to prefill (null: no prompt is going in). fill_prompt_tokens: ?u32 = null, fill_tokens_left: ?u32 = null, + /// Changes whenever the filling set does: a reader pairs its drain samples with one fill. + fill_run: u64 = 0, }; pub const SubmitError = error{ Closed, Busy, InvalidSpans }; @@ -415,9 +417,9 @@ test { _ = @import("lane_host.zig"); _ = @import("lane_host_test.zig"); _ = @import("lane_host_fill_test.zig"); + _ = @import("lane_host_status_test.zig"); _ = @import("lane_host_reuse_test.zig"); _ = @import("lane_host_warm_test.zig"); - _ = @import("lane_host_fill_test.zig"); _ = @import("prompt_cache.zig"); _ = @import("prompt_radix.zig"); _ = @import("prompt_imprint.zig"); diff --git a/zig/src/core/lane_host.zig b/zig/src/core/lane_host.zig index 223de165f30..843a3028967 100644 --- a/zig/src/core/lane_host.zig +++ b/zig/src/core/lane_host.zig @@ -207,10 +207,11 @@ pub const LaneHost = struct { } } - /// Sends a stream's new tokens; true once it has finished (its job freed). + /// Sends a stream's new tokens; true once it has finished and left the lists a status read walks. pub fn deliver(h: *LaneHost, job: *Job) bool { h.send(job); if (!job.stream.finished) return false; + h.remove(job); const reason: Reason = switch (job.stream.reason) { .length => .length, .cancelled => .cancelled, @@ -350,7 +351,7 @@ pub const LaneHost = struct { else => h.drop(job, h.words(e)), }; h.prefilled(job, began); - if (h.deliver(job)) h.remove(job); + _ = h.deliver(job); return true; } @@ -375,7 +376,7 @@ pub const LaneHost = struct { if (!done) return; _ = h.filling.orderedRemove(at); h.prefilled(job, job.began); - if (h.deliver(job)) h.remove(job); + _ = h.deliver(job); } /// A reply's grammar from the server's compiler (Info.structures engines get requests that carry one). @@ -519,11 +520,8 @@ pub const LaneHost = struct { var i: usize = 0; while (i < h.admitted.items.len) { const job = h.admitted.items[i]; - if (h.deliver(job)) { - h.lock(); - _ = h.admitted.orderedRemove(i); - h.unlock(); - } else i += 1; + if (h.deliver(job)) continue; // it left the list: the next job slid into slot i + i += 1; } } } diff --git a/zig/src/core/lane_host_lone.zig b/zig/src/core/lane_host_lone.zig index f661c8a030e..6de60e5b57e 100644 --- a/zig/src/core/lane_host_lone.zig +++ b/zig/src/core/lane_host_lone.zig @@ -50,6 +50,6 @@ pub fn run(h: *LaneHost, job: *Job, began: i96) bool { h.send(job); return true; } - if (h.deliver(job)) h.remove(job); + _ = h.deliver(job); // a finished job leaves the lists inside deliver, before finish frees it return true; } diff --git a/zig/src/core/lane_host_status.zig b/zig/src/core/lane_host_status.zig index 7c98126de39..b70a320d9a1 100644 --- a/zig/src/core/lane_host_status.zig +++ b/zig/src/core/lane_host_status.zig @@ -31,21 +31,24 @@ 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: sum its prompt and what is left of it. +/// A started job whose prompt pass has not reported yet is filling; `fill_run` hashes the filling jobs' ids. 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; 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)))); } if (!filling) return; out.fill_prompt_tokens = @intCast(total); out.fill_tokens_left = @intCast(left); + out.fill_run = run ^ total; } /// `n` tokens delivered now; marks older than the window drop. diff --git a/zig/src/core/lane_host_status_test.zig b/zig/src/core/lane_host_status_test.zig new file mode 100644 index 00000000000..49b97cf31d2 --- /dev/null +++ b/zig/src/core/lane_host_status_test.zig @@ -0,0 +1,216 @@ +//! Status reads stay lifetime-safe: a finishing job has left the host's lists before its event fires. +const std = @import("std"); +const lanes = @import("lanes"); +const api = @import("engine_api.zig"); +const LaneHost = @import("lane_host.zig").LaneHost; +const Reason = api.Reason; +const Id = api.Id; +const Event = api.Event; +const Request = api.Request; +const Engine = api.Engine; + +const short_prompt = [_]u32{ 3, 1, 4, 1, 5, 9, 2, 6 }; + +// The finished event fires inside `finish`, before the host frees the job: this is the racing poll. +test "status at a request's finished event no longer counts the job that just ended" { + 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 = 2 }; + 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 = 2 }); + try host.start(); + defer host.stop(); + const Watch = struct { + engine: Engine = undefined, + mutex: std.Io.Mutex = .init, + done: ?Reason = null, + running_at_finish: usize = 0, + fill_at_finish: bool = false, + + fn event(ctx: *anyopaque, _: Id, e: *const Event) void { + const w: *@This() = @ptrCast(@alignCast(ctx)); + w.mutex.lockUncancelable(std.testing.io); + defer w.mutex.unlock(std.testing.io); + switch (e.*) { + .finished => |f| { + var status: api.Status = .{}; + w.engine.status(&status, &.{}); // the poll that raced with this completion + w.running_at_finish = status.running; + w.fill_at_finish = status.fill_tokens_left != null; + w.done = f.reason; + }, + else => {}, + } + } + fn wait(w: *@This()) Reason { + while (true) { + w.mutex.lockUncancelable(std.testing.io); + const d = w.done; + w.mutex.unlock(std.testing.io); + if (d) |r| return r; + std.Io.sleep(std.testing.io, .fromMilliseconds(1), .awake) catch {}; + } + } + }; + var watch: Watch = .{}; + watch.engine = host.engine(); + const request: Request = .{ .prompt = &short_prompt, .max_tokens = 4 }; + try watch.engine.submit(1, &request, .{ .ctx = &watch, .event = Watch.event }); + try std.testing.expectEqual(Reason.length, watch.wait()); + try std.testing.expectEqual(@as(usize, 0), watch.running_at_finish); // it left `admitted` before the event + try std.testing.expect(!watch.fill_at_finish); // and its fill progress with it + var status: api.Status = .{}; + watch.engine.status(&status, &.{}); + try std.testing.expectEqual(@as(u32, 0), status.running); // the host is idle: nothing is listed +} + +// A second request runs while the first completes: the poll at its finished event counts the survivor. +test "status at one request's finished event still counts the other request running" { + 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 = 2 }; + 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 = 2 }); + try host.start(); + defer host.stop(); + const Watch = struct { + engine: Engine = undefined, + mutex: std.Io.Mutex = .init, + done: ?Reason = null, + running_at_finish: usize = 0, + fill_at_finish: bool = false, + + fn event(ctx: *anyopaque, _: Id, e: *const Event) void { + const w: *@This() = @ptrCast(@alignCast(ctx)); + w.mutex.lockUncancelable(std.testing.io); + defer w.mutex.unlock(std.testing.io); + switch (e.*) { + .finished => |f| { + var status: api.Status = .{}; + w.engine.status(&status, &.{}); + w.running_at_finish = status.running; + w.fill_at_finish = status.fill_tokens_left != null; + w.done = f.reason; + }, + else => {}, + } + } + fn wait(w: *@This()) Reason { + while (true) { + w.mutex.lockUncancelable(std.testing.io); + const d = w.done; + w.mutex.unlock(std.testing.io); + if (d) |r| return r; + std.Io.sleep(std.testing.io, .fromMilliseconds(1), .awake) catch {}; + } + } + }; + var first: Watch = .{}; + first.engine = host.engine(); + var second: Watch = .{}; + second.engine = host.engine(); + const quick: Request = .{ .prompt = &short_prompt, .max_tokens = 1 }; + const long: Request = .{ .prompt = &short_prompt, .max_tokens = 100000 }; + try second.engine.submit(1, &long, .{ .ctx = &second, .event = Watch.event }); + try first.engine.submit(2, &quick, .{ .ctx = &first, .event = Watch.event }); + try std.testing.expectEqual(Reason.length, first.wait()); + try std.testing.expectEqual(@as(usize, 1), first.running_at_finish); // only the long one + try std.testing.expect(!first.fill_at_finish); // the long one decodes: it fills nothing + var status: api.Status = .{}; + second.engine.status(&status, &.{}); + try std.testing.expectEqual(@as(u32, 1), status.running); + second.engine.cancel(1); + try std.testing.expectEqual(Reason.cancelled, second.wait()); +} + +test "status polls through a cancellation, a failed admission and a requeue stay sane" { + 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, .memory_lanes = 1 }; + defer target.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var core = lanes.Engine.init(gpa, &cfg, target.backend(), clock.clock()); + defer core.deinit(); + var host = LaneHost.init(gpa, std.testing.io, &core, .{ .lanes = 2 }); + try host.start(); + defer host.stop(); + const e = host.engine(); + const Poller = struct { + engine: Engine, + stop: std.atomic.Value(bool) = .init(false), + failed: std.atomic.Value(bool) = .init(false), + + fn poll(ctx: *anyopaque) void { + const p: *@This() = @ptrCast(@alignCast(ctx)); + while (!p.stop.load(.acquire)) { + var status: api.Status = .{}; + p.engine.status(&status, &.{}); + if (status.running > 2) p.failed.store(true, .release); // only two lanes exist + std.Io.sleep(std.testing.io, .fromMilliseconds(1), .awake) catch {}; + } + } + }; + var poller: Poller = .{ .engine = e }; + const thread = try std.Thread.spawn(.{}, Poller.poll, .{&poller}); + defer { + poller.stop.store(true, .release); + thread.join(); + } + const running: Request = .{ .prompt = &short_prompt, .max_tokens = 100000 }; + const small: Request = .{ .prompt = &short_prompt, .max_tokens = 4 }; + var a = try gpa.create(Box); + defer gpa.destroy(a); + a.* = .{}; + try e.submit(1, &running, .{ .ctx = a, .event = Box.event }); + var b = try gpa.create(Box); + defer gpa.destroy(b); + b.* = .{}; + try e.submit(2, &small, .{ .ctx = b, .event = Box.event }); // no memory for a second lane: it waits + std.Io.sleep(std.testing.io, .fromMilliseconds(20), .awake) catch {}; + e.cancel(1); + try std.testing.expectEqual(Reason.cancelled, a.wait()); + try std.testing.expectEqual(Reason.length, b.wait()); // admitted once the lane freed, then ran to its end + try std.testing.expect(!poller.failed.load(.acquire)); + var status: api.Status = .{}; + e.status(&status, &.{}); + try std.testing.expectEqual(@as(u32, 0), status.running); + try std.testing.expect(status.fill_prompt_tokens == null and status.fill_tokens_left == null); +} + +const Box = struct { + mutex: std.Io.Mutex = .init, + done: ?Reason = null, + message: []const u8 = "", + tokens: usize = 0, + fn event(ctx: *anyopaque, _: Id, e: *const Event) void { + const b: *@This() = @ptrCast(@alignCast(ctx)); + b.mutex.lockUncancelable(std.testing.io); + defer b.mutex.unlock(std.testing.io); + switch (e.*) { + .tokens => |t| b.tokens += t.len, + .finished => |f| { + b.done = f.reason; + b.message = f.message; + }, + else => {}, + } + } + fn wait(b: *@This()) Reason { + while (true) { + b.mutex.lockUncancelable(std.testing.io); + const d = b.done; + b.mutex.unlock(std.testing.io); + if (d) |r| return r; + std.Io.sleep(std.testing.io, .fromMilliseconds(1), .awake) catch {}; + } + } +}; diff --git a/zig/src/families/glm/backend.zig b/zig/src/families/glm/backend.zig index 6ae3cd5c197..45561c90c1f 100644 --- a/zig/src/families/glm/backend.zig +++ b/zig/src/families/glm/backend.zig @@ -113,6 +113,7 @@ pub const Backend = struct { } else s.reuse_failed = true; } var next: usize = 0; // the planned chunk starts: a resumed pass cuts where a fresh one does + s.fill_at.store(at, .monotonic); // a restored prefix is done the moment it is restored while (at < prompt.len) { if (s.isCancelled()) return error.Cancelled; // the core releases the slot while (next < s.chunks.len and s.chunks[next] <= at) next += 1; @@ -120,7 +121,7 @@ pub const Backend = struct { const n = b.sl.chunkRows(at, end); try b.copyOut(i, at); try mirror.send(e, .chunk, &.{ i, at, n }); - try b.sl.chunk(i, at, n); + try b.sl.chunk(i, at, n); // the chunk's compute completes here: `at` is landed progress at += n; s.fill_at.store(at, .monotonic); // the dashboard's prefill progress reads this between chunks if (std.mem.indexOfScalar(u32, s.reuse.marks, at) != null) if (s.reuse.hook) |k| k.at(k.ptr, s, at); diff --git a/zig/src/families/nemotron/backend.zig b/zig/src/families/nemotron/backend.zig index 62c999ebc4c..5e578fcb9f8 100644 --- a/zig/src/families/nemotron/backend.zig +++ b/zig/src/families/nemotron/backend.zig @@ -312,6 +312,7 @@ pub const Metal = struct { s.cached = @intCast(at); s.reuse_failed = at == 0; } + s.fill_at.store(@intCast(at), .monotonic); // a restored prefix is done the moment it is restored // a command buffer a chunk, each committed before the one ahead of it is waited on, so the GPU keeps a chunk queued var k: usize = 0; while (at < ids.len) { @@ -324,7 +325,7 @@ pub const Metal = struct { try self.submit(.prefill, self.next, Chunks{ .n = ids.len, .c = c, .at = at, .rows = rows }); while (self.flights.items.len > 1) try self.land(); at += rows; - s.fill_at.store(@intCast(at), .monotonic); // the dashboard's prefill progress reads this between chunks + s.fill_at.store(@intCast(at - rows), .monotonic); // landed tokens only: the newest chunk is still queued on the GPU if (s.reuse.hook) |hk| if (std.mem.indexOfScalar(u32, s.reuse.marks, @intCast(at)) != null) hk.at(hk.ptr, s, @intCast(at)); } if (self.trace and c.decide != lesson_route.none) try self.traceLessons(c); diff --git a/zig/src/native/cache_fit.zig b/zig/src/native/cache_fit.zig index 0ea4b64a6d9..d64ad2985e3 100644 --- a/zig/src/native/cache_fit.zig +++ b/zig/src/native/cache_fit.zig @@ -39,6 +39,22 @@ pub fn footprint() ?u64 { return info[9]; } +/// This process's peak physical footprint over its lifetime (rusage_info_v4 slot 30; null elsewhere). +pub fn peakFootprint() ?u64 { + if (builtin.os.tag != .macos) return null; + var info: [43]u64 = undefined; + if (proc_pid_rusage(getpid(), 4, &info) != 0) return null; + return info[30]; +} + +/// A Mac family host's memory counts for `/stats`, `/memory` and `/metrics`, from the process footprint. +pub fn hostMemory(limit_bytes: u64, reset_peak: bool) ?api.Memory { + _ = reset_peak; + const active = footprint() orelse return null; + const peak = peakFootprint() orelse active; + return .{ .active = active, .cache = 0, .peak = peak, .pinned = 0, .limit = limit_bytes }; +} + /// The cache plan: `gib` if it fits (or `over`), else what 70% of RAM leaves up to 16 GiB (no reading: `spare` for it). pub fn budget(gib: ?f64, over: bool, spare: u64, a: std.mem.Allocator, why: *[]const u8, rank: []const u8) !api.PromptCachePlan { return budgetBeside(gib, over, spare, 0, a, why, rank); @@ -114,7 +130,25 @@ test "a given budget that fits is kept, a larger one is refused unless the overr test "the OS readings: RAM and this process's footprint" { if (builtin.os.tag != .macos) return error.SkipZigTest; - const r = ram() orelse return error.NoRam; - const p = footprint() orelse return error.NoFootprint; + const r = ram() orelse return error.SkipZigTest; + const p = footprint() orelse return error.SkipZigTest; try std.testing.expect(r >= 8 * GiB and p > 0 and p < r); } + +test "a host's memory counts keep the footprint, its measured peak and the limit apart" { + if (builtin.os.tag != .macos) return error.SkipZigTest; + const limit = 235 * GiB; + const m = hostMemory(limit, false) orelse return error.SkipZigTest; + try std.testing.expect(m.active > 0); // this test process's own footprint + try std.testing.expect(m.peak >= m.active); // the kernel's lifetime peak covers now + try std.testing.expectEqual(limit, m.limit.?); + try std.testing.expectEqual(@as(u64, 0), m.cache); + try std.testing.expectEqual(@as(u64, 0), m.pinned); + try std.testing.expectEqual(m.active, hostMemory(limit, true).?.active); // reset_peak changes nothing here + try std.testing.expectEqual(m.peak, hostMemory(limit, true).?.peak); +} + +test "a host without a footprint reading reports no memory rather than zeros" { + if (builtin.os.tag == .macos) return error.SkipZigTest; // on macOS the reading always works + try std.testing.expect(hostMemory(1 << 30, false) == null); +} diff --git a/zig/src/native/glm_host.zig b/zig/src/native/glm_host.zig index 943ecfc06b8..a3392fbd4fc 100644 --- a/zig/src/native/glm_host.zig +++ b/zig/src/native/glm_host.zig @@ -66,12 +66,10 @@ fn cacheBudget(eng: *const ge.Engine, gib: ?f64) u64 { return if (limit > used) @min(want, limit - used) else 0; } -/// The host's memory counts for /stats, /memory and /metrics: the footprint holds the Metal buffers, so it is `active`. +/// The host's memory counts: `cache_fit.hostMemory` with this engine's configured load limit. fn readMemory(ctx: ?*anyopaque, reset_peak: bool) ?api.Memory { const h: *Host = @ptrCast(@alignCast(ctx.?)); - _ = reset_peak; // nothing to reset: `peak` is the load limit read at load, not a high-water mark - const active = cache_fit.footprint() orelse return null; - return .{ .active = active, .cache = 0, .peak = h.eng.limit.bytes, .pinned = 0 }; + return cache_fit.hostMemory(h.eng.limit.bytes, reset_peak); } /// Learned states under `root` by checkpoint, split, chip, OS build, kernel sources and a probe's prompt-pass bits. diff --git a/zig/src/server/dashboard.html b/zig/src/server/dashboard.html index 31f54a01876..803fd45ba77 100644 --- a/zig/src/server/dashboard.html +++ b/zig/src/server/dashboard.html @@ -89,7 +89,7 @@

Decode rate · last 5 minutes

const el = id => document.getElementById(id); const fmt = v => v == null ? "—" : nf.format(Math.round(v)); const GiB = v => v == null ? null : (v / 2**30).toFixed(1); -const etaText = s => s < 100 ? `${Math.round(s)} s` : `${Math.round(s / 60)} min`; // the wait to the first token +const etaText = s => s < 100 ? `${Math.round(s)} s` : `${Math.round(s / 60)} min`; // a wait, shown as s or min // the page is served at /dashboard; a proxy that adds a prefix still reaches ../stats or /stats const STATS_URL = location.pathname.replace(/\/(dashboard)?\/?$/, "") + "/stats?poll=1"; // the poll URL keeps the cache-busting query @@ -99,6 +99,7 @@

Decode rate · last 5 minutes

let histPoints = []; // the polled decode rates: [{t, tok_s}], newest last, sparse over 5 minutes let prefillRates = []; // the polled prefill rates while a prefill ran, for the average tile let fillSamples = []; // the polled tokens left: [{t, left}], the drain the ETA reads +let fillRun = 0; // the fill the samples belong to: the server's own transition marker let histTop = 0; // the chart's current y scale, decayed like the dial's function band(v) { return v >= 60 ? css("--accent") : v >= 40 ? css("--cool") : v >= 20 ? css("--warm") : css("--hot"); } @@ -204,12 +205,18 @@

Decode rate · last 5 minutes

el("conns").className = "state" + (((s.running || 0) + (s.waiting || 0)) ? " on" : ""); const memory = s.memory || {}; - if (memory.peak!=null) { + if (memory.peak!=null || memory.limit!=null) { const used = GiB((memory.active || 0) + (memory.cache || 0)); el("mem").innerHTML = `${used} GiB resident`; - el("memcap").textContent = `peak ${GiB(memory.peak)} GiB · cache ${GiB(memory.cache)} GiB`; - // no budget in the snapshot: the bar fills against the session's own peak instead - const frac = memory.peak ? Math.min(100, 100 * ((memory.active || 0) + (memory.cache || 0)) / memory.peak) : 0; + // the labels name each number for what it is: resident now, the measured peak, the configured limit + const caps = []; + if (memory.limit!=null) caps.push(`limit ${GiB(memory.limit)} GiB`); + if (memory.peak!=null) caps.push(`peak ${GiB(memory.peak)} GiB`); + if (memory.cache) caps.push(`cache ${GiB(memory.cache)} GiB`); + el("memcap").textContent = caps.join(" · "); + // the bar fills against the configured limit when there is one, else the measured peak + const against = memory.limit!=null && memory.limit > 0 ? memory.limit : memory.peak; + const frac = against ? Math.min(100, 100 * ((memory.active || 0) + (memory.cache || 0)) / against) : 0; const mb = el("membar"); mb.style.width = frac + "%"; mb.className = frac >= 95 ? "hot" : frac >= 75 ? "warm" : ""; } else { @@ -218,9 +225,15 @@

Decode rate · last 5 minutes

el("membar").style.width = "0%"; } - // The prefill queue: a prompt is going in while the snapshot carries fill_tokens_left; its drain - // between polls gives the live rate, and left over that rate the time to the first token. + // The prefill queue: a prompt is going in while the snapshot carries fill_tokens_left. Its drain + // between polls gives the live rate, and left over that rate the wait — for the whole filling set + // (several lanes fill at once), so the label says when the queue drains, not when a first token lands. + // The server's fill_run marker changes whenever the filling set does (a new prompt, a cancel, a + // requeue): the samples reset then, so one prompt's drain is never mixed with another's. + const run = s.fill_run || 0; + if (run !== fillRun) { fillRun = run; fillSamples = []; } if (s.fill_tokens_left != null) { + if (fillSamples.length && s.fill_tokens_left > fillSamples[fillSamples.length - 1].left) fillSamples = []; // more left than before: the fill restarted fillSamples.push({ t: now, left: s.fill_tokens_left }); if (fillSamples.length > 64) fillSamples.shift(); el("fill").innerHTML = `${fmt(s.fill_tokens_left)} tok`; @@ -231,7 +244,7 @@

Decode rate · last 5 minutes

} if (rate == null && target.prefill > 0) rate = target.prefill; // one sample: the server's 2 s rate const eta = rate ? s.fill_tokens_left / rate : null; - el("fillcap").textContent = `of ${fmt(s.fill_prompt_tokens)} · ~${eta == null ? "—" : etaText(eta)} to the first token`; + el("fillcap").textContent = `of ${fmt(s.fill_prompt_tokens)} · queue drains in ~${eta == null ? "—" : etaText(eta)}`; } else { fillSamples = []; el("fill").textContent = "idle"; diff --git a/zig/src/server/dashboard_test.zig b/zig/src/server/dashboard_test.zig index 43fb106b2cb..8f1c64a3f77 100644 --- a/zig/src/server/dashboard_test.zig +++ b/zig/src/server/dashboard_test.zig @@ -9,4 +9,7 @@ test "dashboard page polls the public stats snapshot without private details" { try std.testing.expect(std.mem.indexOf(u8, page, "memory.peak!=null") != null); try std.testing.expect(std.mem.indexOf(u8, page, "fill_tokens_left") != null); try std.testing.expect(std.mem.indexOf(u8, page, "fill_prompt_tokens") != null); + try std.testing.expect(std.mem.indexOf(u8, page, "fill_run") != null); + try std.testing.expect(std.mem.indexOf(u8, page, "queue drains in") != null); // the label names the queue's wait, not a first token + try std.testing.expect(std.mem.indexOf(u8, page, "memory.limit!=null") != null); // the limit is labelled as one } diff --git a/zig/src/server/memory_routes.zig b/zig/src/server/memory_routes.zig index 5a168451b5d..2ed726b3260 100644 --- a/zig/src/server/memory_routes.zig +++ b/zig/src/server/memory_routes.zig @@ -31,6 +31,7 @@ fn snapshot(a: Allocator, info: api.Info, proc: ?process.Snapshot, device: ?api. try m.put(a, "cache_bytes", try json.intValue(a, d.cache)); try m.put(a, "peak_bytes", try json.intValue(a, d.peak)); try m.put(a, "peak_scope", .{ .string = "since_start_or_health_reset" }); + if (d.limit) |limit| try m.put(a, "load_limit_bytes", try json.intValue(a, limit)); // a configured bound, not a measurement try o.put(a, "device", .{ .object = m }); } if (info.prompt_cache_plan) |plan| { @@ -69,6 +70,17 @@ test "process lifetime peak and resettable device peak retain independent scopes try std.testing.expectEqual(@as(i64, 12), value.get("process").?.get("lifetime_peak_physical_footprint_bytes").?.int64().?); try std.testing.expectEqual(@as(i64, 3), value.get("device").?.get("peak_bytes").?.int64().?); try std.testing.expectEqualStrings("since_start_or_health_reset", value.get("device").?.get("peak_scope").?.string); + try std.testing.expect(value.get("device").?.get("load_limit_bytes") == null); // no limit configured: the key stays out +} + +test "a configured load limit is named as a bound, not folded into the device's measured peak" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const value = try snapshot(arena.allocator(), .{}, null, .{ .active = 2, .peak = 3, .limit = 40 }); + const device = value.get("device").?.object; + try std.testing.expectEqual(@as(i64, 40), device.get("load_limit_bytes").?.int64().?); + try std.testing.expectEqual(@as(i64, 3), device.get("peak_bytes").?.int64().?); // the peak stays measured + try std.testing.expectEqual(@as(usize, 5), device.count()); } test "physical cache plan preserves the applied sizing inputs without runtime or identity fields" { diff --git a/zig/src/server/status_routes.zig b/zig/src/server/status_routes.zig index f3d31fb380d..fcaa0dbed5c 100644 --- a/zig/src/server/status_routes.zig +++ b/zig/src/server/status_routes.zig @@ -108,6 +108,7 @@ pub fn statsSnapshot(a: Allocator, status: api.Status, memory: ?api.Memory, prom if (status.fill_prompt_tokens != null) { try o.put(a, "fill_prompt_tokens", try json.intValue(a, status.fill_prompt_tokens.?)); try o.put(a, "fill_tokens_left", try json.intValue(a, status.fill_tokens_left orelse 0)); + try o.put(a, "fill_run", try json.intValue(a, status.fill_run)); } try o.put(a, "prompt_tokens_total", try json.intValue(a, prompt)); try o.put(a, "generation_tokens_total", try json.intValue(a, generation)); @@ -119,6 +120,7 @@ pub fn statsSnapshot(a: Allocator, status: api.Status, memory: ?api.Memory, prom try mem.put(a, "active", try json.intValue(a, m.active)); try mem.put(a, "cache", try json.intValue(a, m.cache)); try mem.put(a, "peak", try json.intValue(a, m.peak)); + if (m.limit) |limit| try mem.put(a, "limit", try json.intValue(a, limit)); } try o.put(a, "memory", .{ .object = mem }); return .{ .object = o }; @@ -169,3 +171,15 @@ test "stats snapshot carries the filling prompt's tokens while a prefill runs" { try std.testing.expectEqual(@as(i64, 900), object.get("fill_prompt_tokens").?.int64().?); try std.testing.expectEqual(@as(i64, 300), object.get("fill_tokens_left").?.int64().?); } + +test "stats snapshot's memory carries a configured limit and omits none" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const with = try statsSnapshot(arena.allocator(), .{}, .{ .active = 5, .cache = 1, .peak = 9, .pinned = 2, .limit = 100 }, 0, 0, 0, 0, 0); + const memory = with.object.get("memory").?.object; + try std.testing.expectEqual(@as(i64, 5), memory.get("active").?.int64().?); + try std.testing.expectEqual(@as(i64, 9), memory.get("peak").?.int64().?); + try std.testing.expectEqual(@as(i64, 100), memory.get("limit").?.int64().?); + const without = try statsSnapshot(arena.allocator(), .{}, .{ .active = 5, .peak = 9 }, 0, 0, 0, 0, 0); + try std.testing.expect(without.object.get("memory").?.object.get("limit") == null); // no limit configured: the key stays out +} From 6e8b3b5bfb052d0547f98e28d76df770807aa145 Mon Sep 17 00:00:00 2001 From: Andy Heitke <45763735+heitke@users.noreply.github.com> Date: Wed, 14 Oct 2026 13:41:13 -0400 Subject: [PATCH 4/9] the Mac hosts' memory peak is a high-water mark reset by the health query MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A review of the GLM host's memory counts pointed out that the peak field carried the load limit, and the repair put the kernel's lifetime peak there — which never resets, while /health?reset_peak=1 and the metrics' help text say the peak is the most device memory held since start or the last reset. The Mac hosts now keep that mark themselves: the session high-water mark of the process footprint, cleared to the current footprint when the reset is asked for, climbing again from there. /health's memory object carries the limit. --- zig/src/native/cache_fit.zig | 30 ++++++++++++++++++------------ zig/src/server/status_routes.zig | 1 + 2 files changed, 19 insertions(+), 12 deletions(-) diff --git a/zig/src/native/cache_fit.zig b/zig/src/native/cache_fit.zig index d64ad2985e3..498bf135535 100644 --- a/zig/src/native/cache_fit.zig +++ b/zig/src/native/cache_fit.zig @@ -39,19 +39,14 @@ pub fn footprint() ?u64 { return info[9]; } -/// This process's peak physical footprint over its lifetime (rusage_info_v4 slot 30; null elsewhere). -pub fn peakFootprint() ?u64 { - if (builtin.os.tag != .macos) return null; - var info: [43]u64 = undefined; - if (proc_pid_rusage(getpid(), 4, &info) != 0) return null; - return info[30]; -} +/// 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. pub fn hostMemory(limit_bytes: u64, reset_peak: bool) ?api.Memory { - _ = reset_peak; const active = footprint() orelse return null; - const peak = peakFootprint() orelse active; + _ = 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 }; } @@ -140,12 +135,23 @@ test "a host's memory counts keep the footprint, its measured peak and the limit const limit = 235 * GiB; const m = hostMemory(limit, false) orelse return error.SkipZigTest; try std.testing.expect(m.active > 0); // this test process's own footprint - try std.testing.expect(m.peak >= m.active); // the kernel's lifetime peak covers now + try std.testing.expect(m.peak >= m.active); // the high-water mark covers now try std.testing.expectEqual(limit, m.limit.?); try std.testing.expectEqual(@as(u64, 0), m.cache); try std.testing.expectEqual(@as(u64, 0), m.pinned); - try std.testing.expectEqual(m.active, hostMemory(limit, true).?.active); // reset_peak changes nothing here - try std.testing.expectEqual(m.peak, hostMemory(limit, true).?.peak); + 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 + const again = hostMemory(limit, false).?; + try std.testing.expect(again.peak >= again.active); // the mark climbs again from the reset +} + +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 "a host without a footprint reading reports no memory rather than zeros" { diff --git a/zig/src/server/status_routes.zig b/zig/src/server/status_routes.zig index fcaa0dbed5c..152fab8033e 100644 --- a/zig/src/server/status_routes.zig +++ b/zig/src/server/status_routes.zig @@ -28,6 +28,7 @@ pub fn health(srv: *Server, conn: *Conn, a: Allocator) !void { try memory.put(a, "active", try json.intValue(a, mem.active)); try memory.put(a, "cache", try json.intValue(a, mem.cache)); try memory.put(a, "peak", try json.intValue(a, mem.peak)); + if (mem.limit) |limit| try memory.put(a, "limit", try json.intValue(a, limit)); } try o.put(a, "memory", .{ .object = memory }); try o.put(a, "live", try live.snapshot(a, srv.engine)); From 105ac26bd79d87fee10c301b9e1803e6396bf815 Mon Sep 17 00:00:00 2001 From: Andy Heitke <45763735+heitke@users.noreply.github.com> Date: Wed, 14 Oct 2026 17:21:34 -0400 Subject: [PATCH 5/9] the status reader reads only what the engine thread publishes under the 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. --- zig/src/core/lane_host.zig | 29 ++++++++------ zig/src/core/lane_host_status.zig | 6 +-- zig/src/core/lane_host_status_test.zig | 53 ++++++++++++++++++++++++++ zig/src/families/glm_dsa/backend.zig | 1 + zig/src/families/qwen3_5/backend.zig | 1 + zig/src/native/cache_fit.zig | 33 +++++++++------- zig/src/native/flashnext_host.zig | 4 +- zig/src/native/glm_dsa_host.zig | 10 +++++ zig/src/native/metal.zig | 6 +++ zig/src/native/qwen27_served.zig | 6 +++ zig/src/native/qwen27_slots.zig | 1 + zig/src/native/qwen35.zig | 7 ++++ 12 files changed, 128 insertions(+), 29 deletions(-) diff --git a/zig/src/core/lane_host.zig b/zig/src/core/lane_host.zig index 843a3028967..0fd4405847f 100644 --- a/zig/src/core/lane_host.zig +++ b/zig/src/core/lane_host.zig @@ -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) @@ -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); } @@ -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); @@ -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; @@ -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); @@ -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; } diff --git a/zig/src/core/lane_host_status.zig b/zig/src/core/lane_host_status.zig index b70a320d9a1..c587ab0f59f 100644 --- a/zig/src/core/lane_host_status.zig +++ b/zig/src/core/lane_host_status.zig @@ -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); diff --git a/zig/src/core/lane_host_status_test.zig b/zig/src/core/lane_host_status_test.zig index 49b97cf31d2..8f526172323 100644 --- a/zig/src/core/lane_host_status_test.zig +++ b/zig/src/core/lane_host_status_test.zig @@ -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, diff --git a/zig/src/families/glm_dsa/backend.zig b/zig/src/families/glm_dsa/backend.zig index cdfe4969ff3..0cb81fb309e 100644 --- a/zig/src/families/glm_dsa/backend.zig +++ b/zig/src/families/glm_dsa/backend.zig @@ -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); } } diff --git a/zig/src/families/qwen3_5/backend.zig b/zig/src/families/qwen3_5/backend.zig index 55fc09eecb8..a729090838f 100644 --- a/zig/src/families/qwen3_5/backend.zig +++ b/zig/src/families/qwen3_5/backend.zig @@ -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); } diff --git a/zig/src/native/cache_fit.zig b/zig/src/native/cache_fit.zig index 498bf135535..01933313846 100644 --- a/zig/src/native/cache_fit.zig +++ b/zig/src/native/cache_fit.zig @@ -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). @@ -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" { diff --git a/zig/src/native/flashnext_host.zig b/zig/src/native/flashnext_host.zig index 100215a5a6b..af6019296c3 100644 --- a/zig/src/native/flashnext_host.zig +++ b/zig/src/native/flashnext_host.zig @@ -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 { diff --git a/zig/src/native/glm_dsa_host.zig b/zig/src/native/glm_dsa_host.zig index 2a6d28d3317..26091a12659 100644 --- a/zig/src/native/glm_dsa_host.zig +++ b/zig/src/native/glm_dsa_host.zig @@ -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, @@ -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, @@ -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", @@ -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); @@ -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(); diff --git a/zig/src/native/metal.zig b/zig/src/native/metal.zig index a34044bd07c..b349506bad9 100644 --- a/zig/src/native/metal.zig +++ b/zig/src/native/metal.zig @@ -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, @@ -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 = ""; diff --git a/zig/src/native/qwen27_served.zig b/zig/src/native/qwen27_served.zig index 0ca837e9cfa..9e8f6411a2f 100644 --- a/zig/src/native/qwen27_served.zig +++ b/zig/src/native/qwen27_served.zig @@ -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) { @@ -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) diff --git a/zig/src/native/qwen27_slots.zig b/zig/src/native/qwen27_slots.zig index 7cdd191d8cc..d3f882624ec 100644 --- a/zig/src/native/qwen27_slots.zig +++ b/zig/src/native/qwen27_slots.zig @@ -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)); } } diff --git a/zig/src/native/qwen35.zig b/zig/src/native/qwen35.zig index c1dab90e198..49e3060deb8 100644 --- a/zig/src/native/qwen35.zig +++ b/zig/src/native/qwen35.zig @@ -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, @@ -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(); From 8b72f943e2c298a37bf4029099aa9dec01f7c8b0 Mon Sep 17 00:00:00 2001 From: Andy Heitke <45763735+heitke@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:22:28 -0400 Subject: [PATCH 6/9] re-run the checks: the head's push left the pull_request workflows unfired From fd9088de2af9d8aee8dbd5366d8f0edf85815fb3 Mon Sep 17 00:00:00 2001 From: Andy Heitke <45763735+heitke@users.noreply.github.com> Date: Wed, 14 Oct 2026 20:12:34 -0400 Subject: [PATCH 7/9] the fill marker hashes ids and sequences apart, and a backend without fill counters says so --- zig/src/core/engine_api.zig | 2 + zig/src/core/lane_host_status.zig | 16 ++- zig/src/core/lane_host_status_test.zig | 130 ++++++++++++++++++++++++- zig/src/core/lanes/backend.zig | 2 + zig/src/core/lanes/fake.zig | 4 +- zig/src/families/glm/backend.zig | 2 +- zig/src/families/glm_dsa/backend.zig | 2 +- zig/src/families/nemotron/backend.zig | 3 +- zig/src/families/qwen3_5/backend.zig | 2 +- zig/src/native/cuda.zig | 2 +- zig/src/native/flashnext_host.zig | 5 + zig/src/server/dashboard.html | 4 + zig/src/server/dashboard_test.zig | 1 + zig/src/server/status_routes.zig | 13 +++ 14 files changed, 175 insertions(+), 13 deletions(-) diff --git a/zig/src/core/engine_api.zig b/zig/src/core/engine_api.zig index 90d717e4cb4..97dd3ec323b 100644 --- a/zig/src/core/engine_api.zig +++ b/zig/src/core/engine_api.zig @@ -258,6 +258,8 @@ pub const Status = struct { /// Filling prompts' total tokens and those still to prefill (null: no prompt is going in). fill_prompt_tokens: ?u32 = null, fill_tokens_left: ?u32 = null, + /// A prompt pass is running whose backend reports no `fill_at`: the totals stay null rather than guessed. + fill_unknown: bool = false, /// Changes whenever the filling set does: a reader pairs its drain samples with one fill. fill_run: u64 = 0, }; diff --git a/zig/src/core/lane_host_status.zig b/zig/src/core/lane_host_status.zig index c587ab0f59f..d36b5c6f66e 100644 --- a/zig/src/core/lane_host_status.zig +++ b/zig/src/core/lane_host_status.zig @@ -37,18 +37,26 @@ fn fillTotals(h: *LaneHost, out: *api.Status) void { var left: u64 = 0; var filling = false; var run: u64 = 0; + const reported = h.core.backend.vtable.reports_fill; // a backend that never stores `fill_at` has no honest totals for (h.admitted.items) |job| { if (!job.fill_on.load(.acquire)) continue; filling = true; + var fields: [16]u8 = undefined; // id and seq hashed apart: XOR of the raw values collides (2^0 == 3^1) + std.mem.writeInt(u64, fields[0..8], job.id, .little); + std.mem.writeInt(u64, fields[8..16], job.seq, .little); + run = (run *% 0x9E3779B97F4A7C15) ^ std.hash.Wyhash.hash(0, &fields); + if (!reported) continue; // no counter for it: its prompt stays out of the totals rather than guessed const prompt = job.request.prompt.len; total += prompt; left += prompt -| job.stream.fill_at.load(.monotonic); - run = run *% 0x9E3779B97F4A7C15 ^ job.id ^ job.seq; // `seq` the engine thread published under this lock } if (!filling) return; - out.fill_prompt_tokens = @intCast(total); - out.fill_tokens_left = @intCast(left); - out.fill_run = run ^ total; + if (reported) { + out.fill_prompt_tokens = @intCast(total); + out.fill_tokens_left = @intCast(left); + } else out.fill_unknown = true; + run &= (1 << 53) - 1; // JSON numbers stay exact to 2^53: a wider marker loses bits in the page's JavaScript + out.fill_run = if (run == 0) 1 else run; } /// `n` tokens delivered now; marks older than the window drop. diff --git a/zig/src/core/lane_host_status_test.zig b/zig/src/core/lane_host_status_test.zig index 8f526172323..8981b7878bc 100644 --- a/zig/src/core/lane_host_status_test.zig +++ b/zig/src/core/lane_host_status_test.zig @@ -203,13 +203,18 @@ test "fill_run is stable within one prompt's fill and changes for the next" { engine: Engine = undefined, first: ?u64 = null, runs: std.ArrayList(u64) = .empty, + later: std.atomic.Value(bool) = .init(false), + later_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 (status.fill_prompt_tokens == null) return; + if (seen.later.load(.acquire)) { + seen.later_runs.append(gpa, status.fill_run) catch {}; + } else { if (seen.first == null) seen.first = status.fill_run; seen.runs.append(gpa, status.fill_run) catch {}; } @@ -232,8 +237,13 @@ test "fill_run is stable within one prompt's fill and changes for the next" { 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 = .{}; + seen.later.store(true, .release); // the hook's next samples belong to the second fill try seen.engine.submit(2, &second, .{ .ctx = &gone, .event = Box.event }); try std.testing.expectEqual(Reason.length, gone.wait()); + defer seen.later_runs.deinit(gpa); + try std.testing.expect(seen.later_runs.items.len >= 1); // the next fill was sampled as well + try std.testing.expect(seen.later_runs.items[0] != seen.first.?); // its marker really does differ + for (seen.later_runs.items) |run| try std.testing.expectEqual(seen.later_runs.items[0], run); var status: api.Status = .{}; seen.engine.status(&status, &.{}); // idle again try std.testing.expect(status.fill_run == 0); @@ -267,3 +277,121 @@ const Box = struct { } } }; + +// The reviewer's colliding pair: ids 2 and 3 at admissions 0 and 1 XOR alike, so the old marker read alike. +test "fill_run separates two equal-length fills whose id and sequence XOR alike" { + 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, + second: std.atomic.Value(bool) = .init(false), + first_runs: std.ArrayList(u64) = .empty, + second_runs: std.ArrayList(u64) = .empty, + + 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) return; + if (seen.second.load(.acquire)) { + seen.second_runs.append(gpa, status.fill_run) catch {}; + } else seen.first_runs.append(gpa, status.fill_run) catch {}; + } + }; + 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 }; // both prompts the same length: only id and sequence differ + const first: Request = .{ .prompt = &prompt, .max_tokens = 4 }; + var gone_a: Box = .{}; + try seen.engine.submit(2, &first, .{ .ctx = &gone_a, .event = Box.event }); // id 2, admission 0 + try std.testing.expectEqual(Reason.length, gone_a.wait()); + seen.second.store(true, .release); + const second: Request = .{ .prompt = &prompt, .max_tokens = 4 }; + var gone_b: Box = .{}; + try seen.engine.submit(3, &second, .{ .ctx = &gone_b, .event = Box.event }); // id 3, admission 1 + try std.testing.expectEqual(Reason.length, gone_b.wait()); + defer { + seen.first_runs.deinit(gpa); + seen.second_runs.deinit(gpa); + } + try std.testing.expect(seen.first_runs.items.len >= 1); + try std.testing.expect(seen.second_runs.items.len >= 1); // the second fill was sampled too + for (seen.second_runs.items) |run| try std.testing.expect(run != seen.first_runs.items[0]); // not the old collision + var status: api.Status = .{}; + seen.engine.status(&status, &.{}); // idle again + try std.testing.expect(status.fill_run == 0); +} + +// A cancelled filling request replaced by a queued one: the new fill carries its own marker, then idle. +test "fill_run changes when a cancelled fill is replaced by the queued request" { + 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 = 4, .memory_lanes = 1 }; + 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 = 2 }); + try host.start(); + defer host.stop(); + const Seen = struct { + engine: Engine = undefined, + a_runs: std.ArrayList(u64) = .empty, + b_runs: std.ArrayList(u64) = .empty, + + // B's prompt alone is 12 tokens: a sample with that total belongs to the replacement, not to A. + fn hook(ctx: *anyopaque, _: *lanes.Stream, _: usize) void { + const seen: *@This() = @ptrCast(@alignCast(ctx)); + var status: api.Status = .{}; + seen.engine.status(&status, &.{}); + const total = status.fill_prompt_tokens orelse return; + if (total == 12) seen.b_runs.append(gpa, status.fill_run) catch {} else seen.a_runs.append(gpa, status.fill_run) catch {}; + } + }; + var seen: Seen = .{}; + seen.engine = host.engine(); + target.prefill_hook = Seen.hook; + target.prefill_hook_ctx = &seen; + const long_prompt = [_]u32{ 3, 1, 4, 1, 5, 9, 2, 6 }; + const longer_prompt = [_]u32{ 3, 1, 4, 1, 5, 9, 2, 6, 2, 5, 3, 8 }; + const first: Request = .{ .prompt = &long_prompt, .max_tokens = 100000 }; + var a: Box = .{}; + try seen.engine.submit(1, &first, .{ .ctx = &a, .event = Box.event }); + while (seen.a_runs.items.len == 0) std.Io.sleep(std.testing.io, .fromMilliseconds(1), .awake) catch {}; // A is filling + seen.engine.cancel(1); // a poll may never see idle: B takes the lane straight after + try std.testing.expectEqual(Reason.cancelled, a.wait()); + const queued: Request = .{ .prompt = &longer_prompt, .max_tokens = 100000 }; + var b = try gpa.create(Box); + defer gpa.destroy(b); + b.* = .{}; + try seen.engine.submit(2, &queued, .{ .ctx = b, .event = Box.event }); // admitted once the lane freed + var waited: usize = 0; + while (seen.b_runs.items.len == 0 and waited < 2000) { // B is filling: the hook samples its totals + std.Io.sleep(std.testing.io, .fromMilliseconds(1), .awake) catch {}; + waited += 1; + } + seen.engine.cancel(2); + try std.testing.expectEqual(Reason.cancelled, b.wait()); + defer { + seen.a_runs.deinit(gpa); + seen.b_runs.deinit(gpa); + } + try std.testing.expect(seen.b_runs.items.len >= 1); // the replacement fill was sampled + for (seen.b_runs.items) |run| try std.testing.expect(run != seen.a_runs.items[0]); // a new marker without an idle poll + var status: api.Status = .{}; + seen.engine.status(&status, &.{}); // both gone: idle, no fill counters at all + try std.testing.expect(status.fill_prompt_tokens == null and status.fill_tokens_left == null); + try std.testing.expect(status.fill_run == 0); +} diff --git a/zig/src/core/lanes/backend.zig b/zig/src/core/lanes/backend.zig index fe26d3f0039..8378c449003 100644 --- a/zig/src/core/lanes/backend.zig +++ b/zig/src/core/lanes/backend.zig @@ -100,6 +100,8 @@ pub const Backend = struct { held: ?*const fn (ptr: *anyopaque, s: *Stream, out: []u32) anyerror!void = null, /// `prefill` fills `Stream.prompt_rows` for a stream with `prompt_logprobs` (it then starts from 0). prompt_rows: bool = false, + /// The backend stores `Stream.fill_at` as its pass runs: the status reader may count its fill totals. + reports_fill: bool = false, /// The stream left the rounds: free its caches and held drafts. release: *const fn (ptr: *anyopaque, s: *Stream) void, }; diff --git a/zig/src/core/lanes/fake.zig b/zig/src/core/lanes/fake.zig index 7e95ff559b7..7827f286aca 100644 --- a/zig/src/core/lanes/fake.zig +++ b/zig/src/core/lanes/fake.zig @@ -76,12 +76,12 @@ pub const Fake = struct { } pub fn backend(x: *Fake) be.Backend { - return .{ .ptr = x, .vtable = &.{ .prefill = prefill, .first = first, .first_masked = firstMasked, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .features = features, .release = release, .first_row = firstRow, .alternatives = alternatives, .held = heldDrafts } }; + return .{ .ptr = x, .vtable = &.{ .prefill = prefill, .first = first, .first_masked = firstMasked, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .features = features, .release = release, .first_row = firstRow, .alternatives = alternatives, .held = heldDrafts, .reports_fill = true } }; } /// The same target filling its prompt a chunk a call (`prefill_chunks`), as a backend with `prefill_step`. pub fn stepped(x: *Fake) be.Backend { - return .{ .ptr = x, .vtable = &.{ .prefill = prefill, .prefill_step = prefillStep, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .features = features, .release = release, .first_row = firstRow } }; + return .{ .ptr = x, .vtable = &.{ .prefill = prefill, .prefill_step = prefillStep, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .features = features, .release = release, .first_row = firstRow, .reports_fill = true } }; } fn self(ptr: *anyopaque) *Fake { diff --git a/zig/src/families/glm/backend.zig b/zig/src/families/glm/backend.zig index 45561c90c1f..ec31cccfdb7 100644 --- a/zig/src/families/glm/backend.zig +++ b/zig/src/families/glm/backend.zig @@ -38,7 +38,7 @@ pub const Backend = struct { } pub fn backend(b: *Backend) be.Backend { - return .{ .ptr = b, .vtable = &.{ .prefill = prefill, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .release = release } }; + return .{ .ptr = b, .vtable = &.{ .prefill = prefill, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .release = release, .reports_fill = true } }; } /// Windows of up to 16 rows (drafted == plain at every width), the MTP head's chains, every stream in one forward. diff --git a/zig/src/families/glm_dsa/backend.zig b/zig/src/families/glm_dsa/backend.zig index 0cb81fb309e..1bda04b6f6c 100644 --- a/zig/src/families/glm_dsa/backend.zig +++ b/zig/src/families/glm_dsa/backend.zig @@ -41,7 +41,7 @@ pub const Backend = struct { } pub fn backend(b: *Backend) be.Backend { - return .{ .ptr = b, .vtable = &.{ .prefill = prefill, .first = firstFn, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .release = release } }; + return .{ .ptr = b, .vtable = &.{ .prefill = prefill, .first = firstFn, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .release = release, .reports_fill = true } }; } /// Windows of up to 16 rows (each row's bits whatever shares its forward), MTP chains, streams in one forward. diff --git a/zig/src/families/nemotron/backend.zig b/zig/src/families/nemotron/backend.zig index 5e578fcb9f8..a615b0eda74 100644 --- a/zig/src/families/nemotron/backend.zig +++ b/zig/src/families/nemotron/backend.zig @@ -131,8 +131,7 @@ pub const Metal = struct { .keep = keepFn, .draft = draftFn, .release = releaseFn, - .alternatives = alternativesFn, - .held = grammar.held, + .alternatives = alternativesFn, .held = grammar.held, .reports_fill = true, } }; } diff --git a/zig/src/families/qwen3_5/backend.zig b/zig/src/families/qwen3_5/backend.zig index a729090838f..8fd6c179e00 100644 --- a/zig/src/families/qwen3_5/backend.zig +++ b/zig/src/families/qwen3_5/backend.zig @@ -50,7 +50,7 @@ pub const Metal = struct { } pub fn backend(self: *Metal) be.Backend { - return .{ .ptr = self, .vtable = &.{ .prefill = prefillFn, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .release = releaseFn } }; + return .{ .ptr = self, .vtable = &.{ .prefill = prefillFn, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .release = releaseFn, .reports_fill = true } }; } fn cast(ptr: *anyopaque) *Metal { diff --git a/zig/src/native/cuda.zig b/zig/src/native/cuda.zig index d5ae7ed3eb9..39fc7b20a7d 100644 --- a/zig/src/native/cuda.zig +++ b/zig/src/native/cuda.zig @@ -318,7 +318,7 @@ const Host = struct { return x.inner.vtable.held.?(x.inner.ptr, s, out); } }.f else null, - .prompt_rows = v.prompt_rows, + .prompt_rows = v.prompt_rows, .reports_fill = v.reports_fill, .release = struct { fn f(p: *anyopaque, s: *lanes.Stream) void { const x = bind(p); diff --git a/zig/src/native/flashnext_host.zig b/zig/src/native/flashnext_host.zig index af6019296c3..c234eac4451 100644 --- a/zig/src/native/flashnext_host.zig +++ b/zig/src/native/flashnext_host.zig @@ -44,6 +44,7 @@ pub const Host = struct { prefill_at: i96 = 0, live_prompt: u64 = 0, // the running reply's prompt tokens, for status (which never reads the job: finish frees it) live_generated: u64 = 0, + prefilling: bool = false, // the engine thread's prompt pass is running (status reads it under this lock) cache: ?pc.Store = null, // kept prompt states (engine thread only); null: no reuse (rank 1, a zero budget) prompt: []const u32 = &.{}, // the request in the engine (speed-up mode names kept states by its tokens) saved: std.ArrayList(u32) = .empty, // this request's marks the cache kept (speed-up: rank 1 drops the others) @@ -158,6 +159,7 @@ pub const Host = struct { .preemptions = 0, .streams = n, .generation_tokens = generation_tokens, + .fill_unknown = h.prefilling, // this backend reports no fill counters: the page says so, not idle }; } @@ -210,11 +212,13 @@ pub const Host = struct { h.running = job; h.live_prompt = job.request.prompt.len; h.live_generated = 0; + h.prefilling = true; // its prompt pass starts: status shows an unknown-progress fill until it reports h.cancels.clearRetainingCapacity(); // a cancel for an id no longer queued or running h.unlock(); h.serve(job); h.lock(); h.running = null; + h.prefilling = false; h.live_generated = 0; const idle = h.queued.items.len == 0; h.unlock(); @@ -245,6 +249,7 @@ pub const Host = struct { h.lock(); if (done > c.job.began) h.prefill_rate = @as(f64, @floatFromInt(c.job.request.prompt.len - c.job.cached)) / (@as(f64, @floatFromInt(done - c.job.began)) / 1e9); h.prefill_at = done; + h.prefilling = false; // the pass reported: status stops showing an unknown-progress fill c.job.prefilled = done; h.unlock(); c.job.prefill_sent = true; diff --git a/zig/src/server/dashboard.html b/zig/src/server/dashboard.html index 803fd45ba77..f6ca9264ced 100644 --- a/zig/src/server/dashboard.html +++ b/zig/src/server/dashboard.html @@ -245,6 +245,10 @@

Decode rate · last 5 minutes

if (rate == null && target.prefill > 0) rate = target.prefill; // one sample: the server's 2 s rate const eta = rate ? s.fill_tokens_left / rate : null; el("fillcap").textContent = `of ${fmt(s.fill_prompt_tokens)} · queue drains in ~${eta == null ? "—" : etaText(eta)}`; + } else if (s.fill_unknown) { + fillSamples = []; + el("fill").textContent = "prefilling"; + el("fillcap").textContent = "this backend reports no fill progress"; // honest unknown: not idle, no guessed numbers } else { fillSamples = []; el("fill").textContent = "idle"; diff --git a/zig/src/server/dashboard_test.zig b/zig/src/server/dashboard_test.zig index 8f1c64a3f77..50ade480d5c 100644 --- a/zig/src/server/dashboard_test.zig +++ b/zig/src/server/dashboard_test.zig @@ -10,6 +10,7 @@ test "dashboard page polls the public stats snapshot without private details" { try std.testing.expect(std.mem.indexOf(u8, page, "fill_tokens_left") != null); try std.testing.expect(std.mem.indexOf(u8, page, "fill_prompt_tokens") != null); try std.testing.expect(std.mem.indexOf(u8, page, "fill_run") != null); + try std.testing.expect(std.mem.indexOf(u8, page, "fill_unknown") != null); // an unknown-progress fill never reads as idle try std.testing.expect(std.mem.indexOf(u8, page, "queue drains in") != null); // the label names the queue's wait, not a first token try std.testing.expect(std.mem.indexOf(u8, page, "memory.limit!=null") != null); // the limit is labelled as one } diff --git a/zig/src/server/status_routes.zig b/zig/src/server/status_routes.zig index 152fab8033e..624a746f7b4 100644 --- a/zig/src/server/status_routes.zig +++ b/zig/src/server/status_routes.zig @@ -110,6 +110,9 @@ pub fn statsSnapshot(a: Allocator, status: api.Status, memory: ?api.Memory, prom try o.put(a, "fill_prompt_tokens", try json.intValue(a, status.fill_prompt_tokens.?)); try o.put(a, "fill_tokens_left", try json.intValue(a, status.fill_tokens_left orelse 0)); try o.put(a, "fill_run", try json.intValue(a, status.fill_run)); + } else if (status.fill_unknown) { + try o.put(a, "fill_unknown", .{ .bool = true }); // prefilling, but this backend reports no progress + try o.put(a, "fill_run", try json.intValue(a, status.fill_run)); } try o.put(a, "prompt_tokens_total", try json.intValue(a, prompt)); try o.put(a, "generation_tokens_total", try json.intValue(a, generation)); @@ -172,6 +175,16 @@ test "stats snapshot carries the filling prompt's tokens while a prefill runs" { try std.testing.expectEqual(@as(i64, 900), object.get("fill_prompt_tokens").?.int64().?); try std.testing.expectEqual(@as(i64, 300), object.get("fill_tokens_left").?.int64().?); } +test "stats snapshot marks an unknown-progress fill without counters" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const status: api.Status = .{ .fill_unknown = true, .fill_run = 7 }; + const value = try statsSnapshot(arena.allocator(), status, null, 0, 0, 0, 0, 0); + const object = value.object; + try std.testing.expect(object.get("fill_unknown").?.bool); + try std.testing.expectEqual(@as(i64, 7), object.get("fill_run").?.int64().?); + try std.testing.expect(object.get("fill_prompt_tokens") == null); // no counters: the keys stay out +} test "stats snapshot's memory carries a configured limit and omits none" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); From e447c55f10ee93924477cde2da836b151ad41b43 Mon Sep 17 00:00:00 2001 From: Andy Heitke <45763735+heitke@users.noreply.github.com> Date: Wed, 14 Oct 2026 20:27:11 -0400 Subject: [PATCH 8/9] the nemotron vtable fits its file again after the merge --- zig/src/families/nemotron/backend.zig | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/zig/src/families/nemotron/backend.zig b/zig/src/families/nemotron/backend.zig index a615b0eda74..476b8439b24 100644 --- a/zig/src/families/nemotron/backend.zig +++ b/zig/src/families/nemotron/backend.zig @@ -121,18 +121,7 @@ pub const Metal = struct { } pub fn backend(self: *Metal) be.Backend { - return .{ .ptr = self, .vtable = &.{ - .prefill = prefillFn, - .first = firstFn, - .first_masked = grammar.firstMasked, - .queue = queueFn, - .read = readFn, - .verify = verifyFn, - .keep = keepFn, - .draft = draftFn, - .release = releaseFn, - .alternatives = alternativesFn, .held = grammar.held, .reports_fill = true, - } }; + return .{ .ptr = self, .vtable = &.{ .prefill = prefillFn, .first = firstFn, .first_masked = grammar.firstMasked, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .release = releaseFn, .alternatives = alternativesFn, .held = grammar.held, .reports_fill = true } }; } /// The facts the round loop reads at setup (Python's NemotronH attributes), with this engine's own timings. From d91c16f97dde0b89fe5dff9e92ed5da9aa7dec3a Mon Sep 17 00:00:00 2001 From: Andy Heitke <45763735+heitke@users.noreply.github.com> Date: Wed, 14 Oct 2026 20:31:04 -0400 Subject: [PATCH 9/9] the 27B lane backend reports its landed fill progress --- zig/src/native/qwen27_lanes.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zig/src/native/qwen27_lanes.zig b/zig/src/native/qwen27_lanes.zig index e09a508a8cc..7f4d0cb8887 100644 --- a/zig/src/native/qwen27_lanes.zig +++ b/zig/src/native/qwen27_lanes.zig @@ -117,7 +117,7 @@ pub const Metal = struct { const refill = slots.refill; pub fn backend(b: *Metal) be.Backend { - return .{ .ptr = b, .vtable = &.{ .prefill = prefillFn, .first = firstFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .probabilities = probabilitiesFn, .tree = treeFn, .release = releaseFn } }; + return .{ .ptr = b, .vtable = &.{ .prefill = prefillFn, .first = firstFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .probabilities = probabilitiesFn, .tree = treeFn, .release = releaseFn, .reports_fill = true } }; } /// What the round loop reads at setup: slot 0's stream drafts trees; every stream verifies copies.