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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
merge origin/main: the round planner and halt on main's split lane host
Main (46a08c1) moved the lane host's endings to lane_host_end.zig, its
disk asks to lane_host_rows.zig, added Recall readers and Copy proposals,
and made deliver() take a finished job off `admitted` itself. #861's
changes go onto that shape:

- lane_stream.open carries main's stream fields (cacheKey/bornLen, Recall
  reader, images, key, fill_on); freeProposer also releases the Recall reader.
- halt's reason reaches main's ends.closeAll; failAll keeps its warning.
- the round planner's loop answers disk asks, refuses on a stale learner,
  writes on idle turns and flushes on its last stop, as main's loop does.
- the round planner no longer removes a delivered job again: with main's
  deliver it removed the next live job, or panicked at the list's end
  (lane_rounds_test's first test, index out of bounds, before this fix).
- windows.copyProposal: a priced proposer's copy stands as given, its none
  too, ahead of main's Recall fallback; new recall_engine_test case.
- engine_api.zig stays at 600 lines: Opened on one line, Rounds exported
  beside LaneHost, the redundant lane_host_test import dropped (lane_host.zig's
  test block imports it).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • Loading branch information
jayleaton and claude committed Oct 16, 2026
commit e6df8ad5b9fdcac67029e1a67d64ac2bb1c6d45f
21 changes: 4 additions & 17 deletions zig/src/core/engine_api.zig
Original file line number Diff line number Diff line change
Expand Up @@ -345,14 +345,8 @@ pub const Decision = struct {
arena: ?std.mem.Allocator = null, // the request's, for what the engine hands back
};

/// 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,
/// A drain's deadline: rounds end at the next boundary, what is left fails with `reason`; null: `close` alone.
halt: ?*const fn (ctx: *anyopaque, reason: []const u8) void = null,
};
/// An opened engine; ``close`` stops its thread and frees its backend; ``halt`` (null: none) a drain's deadline.
pub const Opened = struct { engine: Engine, close: *const fn (ctx: *anyopaque) void, ctx: *anyopaque, halt: ?*const fn (ctx: *anyopaque, reason: []const u8) void = null };

pub const Memory = struct { active: u64 = 0, cache: u64 = 0, peak: u64 = 0, pinned: u64 = 0, limit: ?u64 = null };

Expand Down Expand Up @@ -565,9 +559,8 @@ pub const LoneHooks = struct {
resumed: bool = false, // the stream comes from the lane core between rounds: no prompt pass, its drafts the core's
};

/// The lane core served to the HTTP threads (lane_host.zig).
/// The lane core served to the HTTP threads (lane_host.zig), and a family's opt-in round planner (lane_rounds.zig).
pub const LaneHost = @import("lane_host.zig").LaneHost;
/// An opt-in family round planner for the lane host, in place of its `prefill_step` chunks (lane_rounds.zig).
pub const Rounds = @import("lane_host.zig").Rounds;

/// Exact prompt reuse between requests, for any family (prompt_cache.zig).
Expand Down Expand Up @@ -598,13 +591,7 @@ pub const keepalive = @import("keepalive.zig");
pub const originals = @import("originals.zig");

test {
_ = @import("lane_host.zig");
_ = @import("lane_host_test.zig");
_ = @import("lane_rounds_test.zig");
_ = @import("lane_halt_test.zig");
_ = @import("lane_host_reuse_test.zig");
_ = @import("lane_host_warm_test.zig");
_ = @import("lane_host_fill_test.zig");
_ = @import("lane_host.zig"); // its test block imports lane_host_test.zig and the other lane host tests
_ = @import("prompt_cache.zig");
_ = @import("prompt_radix.zig");
_ = @import("prompt_imprint.zig");
Expand Down
72 changes: 4 additions & 68 deletions zig/src/core/lane_host.zig
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ pub const LaneHost = struct {
filling: std.ArrayList(*Job) = .empty, // admitted jobs whose prompt is still going in, a chunk a round, oldest first
cancels: std.ArrayList(Id) = .empty,
closing: bool = false,
stale: bool = false, // the learner's last step: a put-back has not reached the device, so replies are refused
/// `halt`'s reason: what is left finishes failed with it (null: a stop cancels what is left)
halt_reason: ?[]const u8 = null,
thread: ?std.Thread = null,
Expand All @@ -65,6 +66,7 @@ pub const LaneHost = struct {
admissions: u64 = 0, // jobs admitted so far: each job's `seq`
memory_lanes: ?usize = null, // lanes the backend had memory for at its last LaneMemory, until a job ends
warm_quiet: u64 = 0, // ns a warm pass waits for other work before its first chunk (0: none), set by its family
disk: rows_host.Disk = .{}, // the Mac app's questions about kept states, and the disk writer's quiet
/// Runs first on the engine thread: a backend whose API state is per thread (a CUDA context) binds it there.
on_thread: ?ThreadInit = null,
/// opt-in: a family round planner (prompt pieces, decode rows in one pass); null: whole or `prefill_step` prompts
Expand All @@ -85,6 +87,7 @@ pub const LaneHost = struct {
proposer: lanes.SuffixLookup = undefined,
/// the family's proposer (LaneHost.proposers), in place of `proposer`
custom: ?lanes.proposer.Proposer = null,
recall: recalls.Slot = .{}, // its reads of Recall's record (lane_host_recall.zig)
delivered: usize = 0,
started: bool = false,
prefill_sent: bool = false, // a lone driver's prefilled event went out
Expand Down Expand Up @@ -290,35 +293,6 @@ pub const LaneHost = struct {
h.gpa.destroy(job);
}

/// Cancels queued and admitted jobs named since the last round.
pub fn takeCancels(h: *LaneHost) void {
h.mutex.lockUncancelable(h.io);
const ids = h.gpa.dupe(Id, h.cancels.items) catch &.{};
h.cancels.clearRetainingCapacity();
var dropped: std.ArrayList(*Job) = .empty;
for (ids) |id| {
for (h.queued.items, 0..) |job, i| if (job.id == id) {
dropped.append(h.gpa, h.queued.orderedRemove(i)) catch {};
break;
};
}
h.mutex.unlock(h.io);
for (dropped.items) |job| h.finish(job, .cancelled, "");
dropped.deinit(h.gpa);
for (ids) |id| {
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, "");
break;
};
}
h.gpa.free(ids);
}

pub fn lock(h: *LaneHost) void {
h.mutex.lockUncancelable(h.io);
}
Expand Down Expand Up @@ -449,14 +423,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);
lane_stream.freeProposer(h, job);
job.started = false;
job.fill_began = false;
job.entry = null; // looked up again at its next admission
h.gpa.free(job.marks);
job.marks = &.{};
h.lock();
for (h.admitted.items, 0..) |j, i| if (j == job) {
_ = h.admitted.orderedRemove(i);
Expand All @@ -476,8 +442,7 @@ pub const LaneHost = struct {
job.reported();
if (job.stream.grammar) |g| g.deinit(h.gpa); // the next admission compiles its own
job.stream.deinit(h.gpa);
job.proposer.deinit();
recalls.release(job);
lane_stream.freeProposer(h, job);
job.started = false;
job.fill_began = false;
job.entry = null; // looked up again at its next admission
Expand Down Expand Up @@ -562,37 +527,8 @@ pub const LaneHost = struct {
lone.reclaim(h);
}
}

/// A failed round ends every stream it held, with the backend's error.
pub fn failAll(h: *LaneHost, message: []const u8) void {
std.log.warn("lane host: a round failed ({s}): every admitted stream fails", .{message});
h.lock();
const jobs = h.gpa.dupe(*Job, h.admitted.items) catch &.{};
h.admitted.clearRetainingCapacity();
h.filling.clearRetainingCapacity();
h.unlock();
for (jobs) |job| {
if (!job.stream.finished) h.core.discard(&job.stream);
h.finish(job, .failed, message);
}
h.gpa.free(jobs);
}

pub fn closeAll(h: *LaneHost) void {
if (h.halt_reason) |reason| return lane_halt.haltAll(h, reason);
h.lock();
for (h.queued.items) |job| h.cancels.append(h.gpa, job.id) catch {};
for (h.admitted.items) |job| h.cancels.append(h.gpa, job.id) catch {};
h.unlock();
h.takeCancels();
}
};

/// The prompt length a request's kept states count as: its own, or for a warm pass the request whose reply it prefills.
pub fn born(r: *const Request) u32 {
return if (r.born > 0) r.born else @intCast(r.prompt.len);
}

test {
_ = @import("lane_host_test.zig");
_ = @import("lane_rounds_test.zig");
Expand Down
3 changes: 3 additions & 0 deletions zig/src/core/lane_host_end.zig
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
const std = @import("std");
const api = @import("engine_api.zig");
const fill = @import("lane_host_fill.zig");
const lane_halt = @import("lane_halt.zig");
const LaneHost = @import("lane_host.zig").LaneHost;
const Job = LaneHost.Job;
const Id = api.Id;
Expand Down Expand Up @@ -40,6 +41,7 @@ pub fn takeCancels(h: *LaneHost) void {

/// A failed round ends every stream it held, with the backend's error.
pub fn failAll(h: *LaneHost, message: []const u8) void {
std.log.warn("lane host: a round failed ({s}): every admitted stream fails", .{message});
h.lock();
const jobs = h.gpa.dupe(*Job, h.admitted.items) catch &.{};
h.admitted.clearRetainingCapacity();
Expand All @@ -53,6 +55,7 @@ pub fn failAll(h: *LaneHost, message: []const u8) void {
}

pub fn closeAll(h: *LaneHost) void {
if (h.halt_reason) |reason| return lane_halt.haltAll(h, reason);
h.lock();
for (h.queued.items) |job| h.cancels.append(h.gpa, job.id) catch {};
for (h.admitted.items) |job| h.cancels.append(h.gpa, job.id) catch {};
Expand Down
24 changes: 13 additions & 11 deletions zig/src/core/lane_rounds.zig
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ const host = @import("lane_host.zig");
const lane_stream = @import("lane_stream.zig");
const learn = @import("lane_host_learn.zig");
const status = @import("lane_host_status.zig");
const ends = @import("lane_host_end.zig");
const rows_host = @import("lane_host_rows.zig");
const LaneHost = host.LaneHost;
const Job = LaneHost.Job;
const Allocator = std.mem.Allocator;
Expand Down Expand Up @@ -84,7 +86,7 @@ fn round(h: *LaneHost, rd: Rounds) bool {
h.unlock();
for (refused.items) |x| h.finish(x.job, .failed, x.why);
rd.vtable.admitted(rd.ctx) catch |e| {
h.failAll(h.words(e));
ends.failAll(h, h.words(e));
return true;
};
for (admits.items) |job| {
Expand All @@ -99,7 +101,7 @@ fn round(h: *LaneHost, rd: Rounds) bool {
}
// this round's pieces, a decode round of the streams decoding, then the prompts whose rows are in
rd.vtable.plan(rd.ctx, &h.pieces, &h.finals) catch |e| {
h.failAll(h.words(e));
ends.failAll(h, h.words(e));
return true;
};
const t0 = std.Io.Clock.awake.now(h.io).toNanoseconds();
Expand Down Expand Up @@ -148,7 +150,7 @@ fn round(h: *LaneHost, rd: Rounds) bool {
if (h.core.activeCount() > 0) {
did = true;
h.core.step() catch |e| {
h.failAll(@errorName(e));
ends.failAll(h, @errorName(e));
return true;
};
}
Expand All @@ -160,11 +162,8 @@ fn round(h: *LaneHost, rd: Rounds) bool {
var i: usize = 0;
while (i < h.admitted.items.len) {
const job = h.admitted.items[i];
if (job.started and h.deliver(job)) {
h.lock();
_ = h.admitted.orderedRemove(i);
h.unlock();
} else i += 1;
if (job.started and h.deliver(job)) continue; // it left the list: the next job slid into slot i
i += 1;
}
rd.vtable.after(rd.ctx, seconds(t1 - t0), seconds(t2 - t1));
return did;
Expand Down Expand Up @@ -247,7 +246,9 @@ fn runFinals(h: *LaneHost) void {
/// The engine thread under a round planner; an idle round waits for an arrival, a cancel or a short timeout.
pub fn run(h: *LaneHost, rd: Rounds) void {
while (true) {
h.takeCancels();
ends.takeCancels(h);
rows_host.answer(h);
learn.refuse(h);
h.lock();
if (h.closing) {
const left = h.queued.items.len + h.admitted.items.len;
Expand All @@ -256,8 +257,8 @@ pub fn run(h: *LaneHost, rd: Rounds) void {
h.learner.?.abort(h.learner.?.ctx);
h.lesson_open = false;
}
if (left == 0) return;
h.closeAll();
if (left == 0) return rows_host.flush(h);
ends.closeAll(h);
continue;
}
const work = h.admitted.items.len > 0 or (h.queued.items.len > 0 and h.admitted.items.len < h.info_.lanes);
Expand All @@ -267,6 +268,7 @@ pub fn run(h: *LaneHost, rd: Rounds) void {
continue;
}
if (!work) {
if (rows_host.idle(h)) continue;
if (h.cancels.items.len == 0) h.wake.waitTimeout(h.io, &h.mutex, .{ .duration = .{ .raw = .fromMilliseconds(100), .clock = .awake } }) catch {};
h.unlock();
continue;
Expand Down
14 changes: 10 additions & 4 deletions zig/src/core/lane_stream.zig
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
//! A request's stream on the lane host: its kept prefix looked up, its drafter made, the stream set up.
const std = @import("std");
const lanes = @import("lanes");
const host = @import("lane_host.zig");
const LaneHost = host.LaneHost;
const recalls = @import("lane_host_recall.zig");
const LaneHost = @import("lane_host.zig").LaneHost;
const Job = LaneHost.Job;

/// A job's drafter freed: the family's (LaneHost.proposers) or the built-in one.
/// A job's drafters freed: the family's (LaneHost.proposers) or the built-in one, and its Recall reader.
pub fn freeProposer(h: *LaneHost, job: *Job) void {
if (job.custom) |c| h.proposers.?.free(h.proposers.?.ctx, c) else job.proposer.deinit();
job.custom = null;
recalls.release(job);
}

/// An admitted job's stream (its kept prefix looked up, its drafter): false when it failed (the job is finished).
pub fn open(h: *LaneHost, job: *Job) bool {
const r = job.request;
var reuse: lanes.stream.Reuse = .{};
// the entry stays alive until the backend restores it: nothing keeps between here and this stream's own pass
if (h.cache) |store| if (r.prompt_logprobs == null and !r.untaught) if (store.lookupRewind(h.gpa, r.prompt, host.born(r), r.history_len, r.rewind_len, r.shared_prefixes, r.chunks, h.spans(r))) |l| {
if (h.cache) |store| if (r.prompt_logprobs == null and !r.untaught) if (store.lookupRewind(h.gpa, r.cacheKey(), r.bornLen(), r.history_len, r.rewind_len, r.shared_prefixes, r.chunks, h.spans(r))) |l| {
job.entry = l.entry;
job.kept0 = store.counts.kept;
job.marks = l.marks;
Expand All @@ -25,6 +26,7 @@ pub fn open(h: *LaneHost, job: *Job) bool {
if (h.proposers) |ps| {
job.custom = ps.make(ps.ctx, h.gpa, r.prompt, r.eos) catch return !h.drop(job, "the drafter could not start");
} else job.proposer = lanes.SuffixLookup.init(h.gpa, .{ .min_match = h.min_match }) catch return !h.drop(job, "the drafter could not start");
const recall = recalls.reader(h, job);
job.stream = lanes.Stream.init(h.gpa, .{
.id = "request",
.prompt = r.prompt,
Expand All @@ -33,6 +35,7 @@ pub fn open(h: *LaneHost, job: *Job) bool {
.sampling = r.sampling,
.drafts = r.drafts,
.proposer = job.custom orelse job.proposer.proposer(),
.recall = recall,
.stop_check = if (r.stop) |s| .{ .ptr = s.ctx, .check = s.check } else null,
.cancel_check = .{ .ptr = job, .check = LaneHost.cancelled },
.yield_check = if (r.background and r.max_tokens == 0) .{ .ptr = job, .check = LaneHost.yieldsTo } else null,
Expand All @@ -53,11 +56,14 @@ pub fn open(h: *LaneHost, job: *Job) bool {
.decode_spans = h.spans(r),
.decide = r.decide,
.untaught = r.untaught,
.images = r.images,
.key = r.cache_key,
}) catch {
freeProposer(h, job);
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
job.began = std.Io.Clock.awake.now(h.io).toNanoseconds();
return true;
}
Loading
Loading
You are viewing a condensed version of this merge commit. You can view the full changes here.