Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
137 commits
Select commit Hold shift + click to select a range
3688f3c
CUDA keyed graph cache and device arena, both off until a family inst…
jayleaton Oct 10, 2026
b7be793
A failed CUDA kernel launch names its kernel and launch configuration…
jayleaton Oct 10, 2026
faf5901
fix(cuda): correct RDMA VMM capability attribute
jrb-ai Oct 10, 2026
3cc0397
Graph cache: a capture is freed until the map holds it, the keep floo…
jayleaton Oct 11, 2026
c58d83c
CUDA arena: the address maps are rehashed before tombstones fill them
jayleaton Oct 11, 2026
25c02d3
Tensor parallelism across CUDA processes: bootstrap, NCCL, mailbox an…
jayleaton Oct 10, 2026
6b5404d
TP tests: a drain on rank 0 then its clean stop ends rank 1's loop at…
jayleaton Oct 10, 2026
06c4e75
TP RoCE: with no TF_TP_ROCE_HCA, each rank picks the ports on an IPv4…
jayleaton Oct 11, 2026
062af8b
TP README: when -Dtp-nvcc, TF_TP_ROCE_HCA, NCCL_IB_HCA, NCCL_SOCKET_I…
jayleaton Oct 11, 2026
d7510ef
TP test runner: a binary built without the mailbox kernel refuses the…
jayleaton Oct 11, 2026
e16e331
TP RoCE: every RDMA post is bounds-checked before the verb, and peers…
jayleaton Oct 11, 2026
649e788
TP RoCE: no RDMA write past 1 MiB, and boot refuses any setting that …
jayleaton Oct 11, 2026
664a8e2
TP RoCE: TF_TP_ROCE_CHUNKED_KB gathers strides past the slot in slot-…
jayleaton Oct 11, 2026
4ad5029
TP RoCE: a failed transport halts its QPs, drains them and keeps its …
jayleaton Oct 11, 2026
9bbc21a
TP RoCE: tf-tp-test failfast V transport checks the failed-transport …
jayleaton Oct 11, 2026
cf19042
Fix RoCE test smaps lookup for merged mappings
jayleaton Oct 11, 2026
0ba7d30
Sessions: the page map is rehashed before tombstones fill it
jayleaton Oct 11, 2026
0918809
Let a family's round planner drive the lane host with prompt pieces
jayleaton Oct 10, 2026
361f063
Lane host halt: a stop's drain deadline ends the rounds at the next b…
jayleaton Oct 10, 2026
e9f9210
Round planner test: both prompts queue before the host starts, and it…
jayleaton Oct 10, 2026
96ae865
Server hooks for a model family's own chat rules.
jayleaton Oct 10, 2026
df480e0
Server: a stop logs its signal and the open connections when the acce…
jayleaton Oct 10, 2026
2c4d837
Server: SIGTERM / SIGINT drains before stopping.
jayleaton Oct 10, 2026
55bf0a7
Server tests: a stop that lands between a request's count and its dra…
jayleaton Oct 10, 2026
9fbc2b3
Server: a stream that has not sent its first token gets keepalives ev…
jayleaton Oct 10, 2026
bb53ff4
Server tests: the drain test's reply in progress is held until its dr…
jayleaton Oct 10, 2026
9eb765d
DeepSeek-V4.1 host side: release config, EXL3 pack headers, a rank's …
jayleaton Oct 11, 2026
865335e
DeepSeek-V4.1 weight forms built at load, and prepared weight folders…
jayleaton Oct 11, 2026
7ccfc5c
DeepSeek-V4.1 Engram host side: table layout, n-gram hashes of a wind…
jayleaton Oct 11, 2026
b775815
DeepSeek-V4.1 phase timers: where a serving round's time goes, by nam…
jayleaton Oct 11, 2026
def4859
DeepSeek-V4.1 Engram rows from packed per-rank shards on local NVMe, …
jayleaton Oct 11, 2026
c7d29ea
DeepSeek-V4.1 CUDA kernel sources: CSA2 attention and top-k, mHC, rou…
jayleaton Oct 11, 2026
b17df97
DeepSeek-V4.1 kernel tooling: nvcc in a container for any checkout la…
jayleaton Oct 11, 2026
73be75f
DeepSeek-V4.1 kernel launch bindings and their loader: each kernel's …
jayleaton Oct 11, 2026
e687ad5
DeepSeek-V4.1 device kernel tests: tf-dsv41-test, bit-exact against t…
jayleaton Oct 11, 2026
a7674d2
DeepSeek-V4.1 kernel prototypes: attention merge and phase timing, x3…
jayleaton Oct 11, 2026
c0605f0
DeepSeek-V4.1 device-side load: named weights in device buffers, run-…
jayleaton Oct 11, 2026
46bff5e
DeepSeek-V4.1 block emitter: a decode window as calls (attention, the…
jayleaton Oct 11, 2026
6d44dab
CUDA runtime: prioritized streams, external event records, 2D async c…
jayleaton Oct 11, 2026
63e708f
CUDA AOT sets: aot.json specs parsed and matched without cubins, and …
jayleaton Oct 11, 2026
2eeabf7
CUDA memory: a driver allocation count, the arena's first failed chun…
jayleaton Oct 11, 2026
a89bd4f
Graph cache: named caches publish their counts, the floor's state is …
jayleaton Oct 11, 2026
05977fa
Session store: historyOf returns an entry's ids from RAM or from the …
jayleaton Oct 11, 2026
063e855
Graph cache registry: slots claimed, published, released and read und…
jayleaton Oct 11, 2026
d800c62
DeepSeek-V4.1 KV memory: the family's pages, split KV's exchange, the…
jayleaton Oct 11, 2026
bf5a8e8
DeepSeek-V4.1 forward: decode windows over the block emitter, split K…
jayleaton Oct 11, 2026
989ca7e
TP RoCE: run_hosts.sh gives NCCL the RoCE picker's ports when neither…
jayleaton Oct 11, 2026
05c5213
Session memory for paged-KV families: page pool, prefix trie, RAM res…
jayleaton Oct 10, 2026
a3303c7
CUDA keyed graph cache and device arena, both off until a family inst…
jayleaton Oct 10, 2026
69e8a65
A failed CUDA kernel launch names its kernel and launch configuration…
jayleaton Oct 10, 2026
d7e89df
fix(cuda): correct RDMA VMM capability attribute
jrb-ai Oct 10, 2026
5826f89
Graph cache: a capture is freed until the map holds it, the keep floo…
jayleaton Oct 11, 2026
5806e55
CUDA arena: the address maps are rehashed before tombstones fill them
jayleaton Oct 11, 2026
d335520
Graph cache: TF_GRAPH_CACHE=0 or off runs every step eagerly in any f…
jayleaton Oct 14, 2026
7ff83d8
Tensor parallelism across CUDA processes: bootstrap, NCCL, mailbox an…
jayleaton Oct 10, 2026
9af2ea2
TP tests: a drain on rank 0 then its clean stop ends rank 1's loop at…
jayleaton Oct 10, 2026
7c9a26e
TP RoCE: with no TF_TP_ROCE_HCA, each rank picks the ports on an IPv4…
jayleaton Oct 11, 2026
8ebb0be
TP README: when -Dtp-nvcc, TF_TP_ROCE_HCA, NCCL_IB_HCA, NCCL_SOCKET_I…
jayleaton Oct 11, 2026
e9e0056
TP test runner: a binary built without the mailbox kernel refuses the…
jayleaton Oct 11, 2026
0472cbf
TP RoCE: every RDMA post is bounds-checked before the verb, and peers…
jayleaton Oct 11, 2026
9688398
TP RoCE: no RDMA write past 1 MiB, and boot refuses any setting that …
jayleaton Oct 11, 2026
72132f0
TP RoCE: TF_TP_ROCE_CHUNKED_KB gathers strides past the slot in slot-…
jayleaton Oct 11, 2026
e65583c
Server hooks for a model family's own chat rules.
jayleaton Oct 10, 2026
bf19238
TP RoCE: a failed transport halts its QPs, drains them and keeps its …
jayleaton Oct 11, 2026
9a486bb
Server: a stop logs its signal and the open connections when the acce…
jayleaton Oct 10, 2026
beae7e8
TP RoCE: tf-tp-test failfast V transport checks the failed-transport …
jayleaton Oct 11, 2026
467504a
Server: SIGTERM / SIGINT drains before stopping.
jayleaton Oct 10, 2026
602aad5
Fix RoCE test smaps lookup for merged mappings
jayleaton Oct 11, 2026
23bf7d8
Server tests: a stop that lands between a request's count and its dra…
jayleaton Oct 10, 2026
890dfc6
TP RoCE: run_hosts.sh gives NCCL the RoCE picker's ports when neither…
jayleaton Oct 11, 2026
5410eac
Session memory for paged-KV families: page pool, prefix trie, RAM res…
jayleaton Oct 10, 2026
a5b8b35
Server: a stream that has not sent its first token gets keepalives ev…
jayleaton Oct 10, 2026
a3e2fb1
TP NCCL: all_reduce's doc says NCCL adds in its ring's order, so its …
jayleaton Oct 14, 2026
0d0bdb2
Sessions: the page map is rehashed before tombstones fill it
jayleaton Oct 11, 2026
2b3cccf
Server tests: the drain test's reply in progress is held until its dr…
jayleaton Oct 10, 2026
62a75ae
TP: keep Linux-only transport host tests off macOS builds
jayleaton Oct 15, 2026
2cf61d3
Sessions: honor zero residency budgets and reserve uncapped requests
jayleaton Oct 15, 2026
9367784
server: keep shared halt and drain on the existing template path
jayleaton Oct 15, 2026
864fe25
Graph cache: effective settings have one digest for ranks to compare …
jayleaton Oct 16, 2026
e2504f6
TP: bootstrap compares the graph cache's effective settings, so a ran…
jayleaton Oct 16, 2026
dcdc30c
Keep the Linux NVMe lane test out of portable host tests
cwschroeder Oct 16, 2026
368a0d3
Keep the Linux NVMe lane test out of portable host tests
cwschroeder Oct 16, 2026
7a6b32f
server: main's drain stop closes the engine without the closed lane-h…
jayleaton Oct 16, 2026
abcad7d
Merge ashhart/main into stack/02-graph-cache-arena
jayleaton Oct 16, 2026
02d455e
Merge stack/02-graph-cache-arena (with ashhart/main) into stack/03-tp…
jayleaton Oct 16, 2026
9266f3f
Merge stack/03-tp-fabric (with ashhart/main) into stack/04-sessions
jayleaton Oct 16, 2026
001ac2e
Merge stack/04-sessions (with ashhart/main) into stack/07-server
jayleaton Oct 16, 2026
33c0ef6
Merge stack/07-server (sessions, TP, graph cache, current main) into …
jayleaton Oct 16, 2026
af0bc53
Server tests: the drain test imports the named json module
jayleaton Oct 16, 2026
7051a3c
Merge stack/07-server's drain-test json import fix into stack/08a-config
jayleaton Oct 16, 2026
e6df8ad
merge origin/main: the round planner and halt on main's split lane host
jayleaton Oct 16, 2026
4da2618
Merge shared/lane-host-core (#861, on current main) into stack/08a-co…
jayleaton Oct 16, 2026
6b9bede
Merge stack/08a-config (current main, shared layers, #861) into stack…
jayleaton Oct 16, 2026
f17db02
Merge stack/08b-engram (current main, shared layers, #861) into stack…
jayleaton Oct 16, 2026
0137ac2
Merge stack/08c-kernels (current main, shared layers, #861) into stac…
jayleaton Oct 16, 2026
cf649ff
Merge stack/08e-block (current main, shared layers, #861) into stack/…
jayleaton Oct 16, 2026
4a02606
Merge stack/08r-runtime (current main, shared layers, #861) into stac…
jayleaton Oct 16, 2026
968a4f2
Merge stack/09a-kv (current main, shared layers, #861) into stack/09b…
jayleaton Oct 16, 2026
8900c7c
Sessions: a failed prefix insert leaves the index as it was
jayleaton Oct 17, 2026
3aeebb9
CUDA arena: a reuse whose address-map insertion fails keeps its range…
jayleaton Oct 17, 2026
46161ac
Merge stack/02-graph-cache-arena (the #635 arena fix) into stack/03-t…
jayleaton Oct 17, 2026
78ce706
Merge stack/03-tp-fabric (the #635 arena and #637 prefix fixes) into …
jayleaton Oct 17, 2026
9c5bd60
Merge stack/04-sessions (the #635 arena and #637 prefix fixes) into s…
jayleaton Oct 17, 2026
eaa7953
Merge stack/07-server (the #635 arena and #637 prefix fixes) into sta…
jayleaton Oct 17, 2026
4370f91
Merge stack/08a-config (the #635 arena and #637 prefix fixes) into st…
jayleaton Oct 17, 2026
a0f9598
Merge stack/08b-engram (the #635 arena and #637 prefix fixes) into st…
jayleaton Oct 17, 2026
98a1695
Merge stack/08c-kernels (the #635 arena and #637 prefix fixes) into s…
jayleaton Oct 17, 2026
28e33cc
Merge stack/08e-block (the #635 arena and #637 prefix fixes) into sta…
jayleaton Oct 17, 2026
f5a0b8b
Merge the layer below (the #635 arena and #637 prefix fixes) into sta…
jayleaton Oct 17, 2026
3b7681f
Merge the layer below (the #635 arena and #637 prefix fixes) into sta…
jayleaton Oct 17, 2026
88418d8
test(tp): reject malformed runner commands before configuration
cwschroeder Oct 17, 2026
4c69b0d
fix(tp): parse runner commands before opening sessions
cwschroeder Oct 17, 2026
4df28ce
test(tp): retain verbs load failures in HCA diagnostics
cwschroeder Oct 17, 2026
0a80da0
fix(tp): distinguish verbs load errors from absent HCA ports
cwschroeder Oct 17, 2026
999cb03
Merge stack/03-tp-fabric (adopted #636 runner CLI validation and HCA …
jayleaton Oct 18, 2026
5f14a64
Merge the layer below (adopted #636 runner CLI validation and HCA ver…
jayleaton Oct 18, 2026
749240a
Merge the layer below (adopted #636 runner CLI validation and HCA ver…
jayleaton Oct 18, 2026
7122563
Merge the layer below (adopted #636 runner CLI validation and HCA ver…
jayleaton Oct 18, 2026
6390cf1
Merge the layer below (adopted #636 runner CLI validation and HCA ver…
jayleaton Oct 18, 2026
829c4c9
Merge the layer below (adopted #636 runner CLI validation and HCA ver…
jayleaton Oct 18, 2026
b81382d
Merge the layer below (adopted #636 runner CLI validation and HCA ver…
jayleaton Oct 18, 2026
2be028e
Merge the layer below (adopted #636 runner CLI validation and HCA ver…
jayleaton Oct 18, 2026
e47ed0e
Merge the layer below (adopted #636 runner CLI validation and HCA ver…
jayleaton Oct 18, 2026
cdde1a4
Merge ashhart/main (1.1.0, 76aafcf2) into stack/02-graph-cache-arena
jayleaton Oct 18, 2026
adbdb8a
CUDA launches: a not-ready launch returns NotReady unlogged, as Drive…
jayleaton Oct 18, 2026
3bd6a6a
Merge stack/02-graph-cache-arena (adbdb8ab, main 76aafcf2) into stack…
jayleaton Oct 18, 2026
54141a1
Merge stack/03-tp-fabric (3bd6a6ab, main 76aafcf2) into stack/04-sess…
jayleaton Oct 18, 2026
80d4ed5
Merge stack/04-sessions (54141a1e, main 76aafcf2) into stack/07-server
jayleaton Oct 18, 2026
aebceae
Merge stack/07-server (80d4ed5c, main 76aafcf2) into stack/08a-config
jayleaton Oct 18, 2026
1003f08
Build: DeepSeek-V4.1's host tests on hosts other than Windows, whose …
jayleaton Oct 18, 2026
aa96782
Merge stack/08a-config (1003f08f, main 76aafcf2) into stack/08b-engram
jayleaton Oct 18, 2026
3f758dc
Merge stack/08b-engram (aa967828, main 76aafcf2) into stack/08c-kernels
jayleaton Oct 18, 2026
ea54d42
Merge stack/08c-kernels (3f758dcf, main 76aafcf2) into stack/08e-block
jayleaton Oct 18, 2026
d6190dc
Merge stack/08e-block (ea54d42d, main 76aafcf2) into stack/08r-runtime
jayleaton Oct 18, 2026
6742872
Merge stack/08r-runtime (d6190dcf, main 76aafcf2) into stack/09a-kv
jayleaton Oct 18, 2026
a88da5d
Build: DeepSeek-V4.1's KV host tests also skip Windows, like the fami…
jayleaton Oct 18, 2026
696e58a
Merge stack/09a-kv (a88da5de, main 76aafcf2) into stack/09b-forward
jayleaton Oct 18, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Server: a stream that has not sent its first token gets keepalives ev…
…ery TF_SSE_KEEPALIVE_S seconds (default 15).

Queueing and a long prefill send nothing after the head, and clients or proxies
that time out a silent body leave and retry from zero. Chat, completions and
responses streams get an SSE comment (": keepalive"); Anthropic streams get its
ping event. A keepalive that cannot be written cancels the request as a client
that left.
  • Loading branch information
jayleaton committed Oct 11, 2026
commit 9fbc2b3edc2e772d28124dfea2da0a0be554de86
8 changes: 7 additions & 1 deletion zig/src/server/anthropic.zig
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ const Wire = struct {
payload: Value = .null,

fn out(w: *Wire) openai.Out {
return .{ .ctx = w, .vt = &.{ .open = open, .event = event, .reply = whole } };
return .{ .ctx = w, .vt = &.{ .open = open, .event = event, .reply = whole, .keepalive = ping } };
}

fn open(ctx: *anyopaque) error{Closed}!void {
Expand All @@ -125,6 +125,12 @@ const Wire = struct {
w.status = status;
w.payload = payload;
}

/// Anthropic's own keepalive event.
fn ping(ctx: *anyopaque) error{Closed}!void {
const w: *Wire = @ptrCast(@alignCast(ctx));
return w.reply.send("ping", try w.reply.obj("ping"));
}
};

const Call = struct { id: []const u8 = "", name: []const u8 = "", arguments: []const u8 = "", sent: usize = 0, done: bool = false };
Expand Down
13 changes: 13 additions & 0 deletions zig/src/server/chat_generation.zig
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@ pub const Generation = struct {
streaming_done: bool = false,
first_ns: ?i96 = null,
last_ns: ?i96 = null,
/// when the stream last carried bytes (a keepalive goes out after a silence)
wrote_ns: ?i96 = null,
reason: ?[]const u8 = null, // the server ended the reply (a stop string, the length) before the engine said so
engine_done: bool = false,
consumed: usize = 0,
Expand Down Expand Up @@ -166,6 +168,7 @@ pub const Generation = struct {
g.cancel();
return error.Cancelled;
};
g.wrote_ns = nowNs(g.srv.io);
}

pub const cancel = chat.cancel; // in chat.zig with its doc
Expand Down Expand Up @@ -205,6 +208,16 @@ pub const Generation = struct {
g.cancel();
return error.Cancelled;
}
if (chunk == null and @hasDecl(@TypeOf(gone), "beat")) {
// queueing and a long prefill send nothing: a client that times out a silent stream would leave
const now = nowNs(g.srv.io);
const since = g.wrote_ns orelse now;
if (g.wrote_ns == null) g.wrote_ns = now;
if (gone.beat(now - since) catch {
g.cancel();
return error.Cancelled;
}) g.wrote_ns = now;
}
const tokens = chunk orelse continue;
if (g.reason == null) try g.commit(tokens);
}
Expand Down
29 changes: 19 additions & 10 deletions zig/src/server/drain_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const Allocator = std.mem.Allocator;
const testing = std.testing;

/// Slow enough to stop mid-reply: "@short" ends after a dozen tokens, "@long" only when halted or cancelled.
const Slow = struct {
pub const Slow = struct {
gpa: Allocator,
io: std.Io,
halted: std.atomic.Value(bool) = .init(false),
Expand Down Expand Up @@ -65,6 +65,15 @@ const Slow = struct {
for (r.prompt, prompt) |t, *b| b.* = @truncate(t);
const long = std.mem.indexOf(u8, prompt, "@long") != null;
const word: []const u32 = if (long) &.{ ' ', 'l', 'a' } else &.{ ' ', 'o', 'k' };
const hang = std.mem.indexOf(u8, prompt, "@hang") != null;
const wait = std.mem.indexOf(u8, prompt, "@wait") != null;
// a long prefill: nothing for 800 ms ("@wait"), or nothing until stopped ("@hang")
var quiet: u32 = 0;
while (hang or (wait and quiet < 80)) : (quiet += 1) {
if (s.halted.load(.acquire)) return sink.event(sink.ctx, id, &.{ .finished = .{ .reason = .failed, .message = s.reason } });
if (s.cancelled.load(.acquire) == id) return sink.event(sink.ctx, id, &.{ .finished = .{ .reason = .cancelled } });
std.Io.sleep(s.io, .fromMilliseconds(10), .awake) catch {};
}
sink.event(sink.ctx, id, &.{ .prefilled = 0 });
var n: usize = 0;
while (true) : (n += 1) {
Expand Down Expand Up @@ -93,7 +102,7 @@ const Slow = struct {
};

/// Bytes as tokens; a prompt renders as its messages' JSON, so the engine sees the client's marker.
const TestText = struct {
pub const TestText = struct {
fn text(t: *@This()) model_text.Text {
return .{ .ctx = t, .vtable = &.{ .encode = encode, .decode = decode, .token_id = tokenId, .token_string = tokenString, .vocab_size = vocabSize, .eos_ids = eosIds, .render = render, .template_source = templateSource } };
}
Expand Down Expand Up @@ -135,16 +144,16 @@ const TestText = struct {
}
};

var listen_port: std.atomic.Value(u16) = .init(0);
pub var listen_port: std.atomic.Value(u16) = .init(0);

fn onListen(port: u16) void {
listen_port.store(port, .release);
}

const Reply = struct { status: u16, head: []const u8, body: []const u8 };
pub const Reply = struct { status: u16, head: []const u8, body: []const u8 };

/// One request on its own connection (closed by us after it), the whole response read.
fn request(a: Allocator, io: std.Io, port: u16, method: []const u8, path: []const u8, body: []const u8) !Reply {
pub fn request(a: Allocator, io: std.Io, port: u16, method: []const u8, path: []const u8, body: []const u8) !Reply {
const addr: std.Io.net.IpAddress = .{ .ip4 = .loopback(port) };
const stream = try addr.connect(io, .{ .mode = .stream });
defer stream.close(io);
Expand Down Expand Up @@ -175,7 +184,7 @@ fn unchunk(a: Allocator, s: []const u8) ![]const u8 {
return out.items;
}

const Background = struct {
pub const Background = struct {
a: Allocator,
io: std.Io,
port: u16,
Expand All @@ -191,19 +200,19 @@ const Background = struct {
}
};

fn chatBody(a: Allocator, marker: []const u8, stream: bool) ![]const u8 {
pub fn chatBody(a: Allocator, marker: []const u8, stream: bool) ![]const u8 {
return std.fmt.allocPrint(a, "{{\"messages\":[{{\"role\":\"user\",\"content\":\"go {s}\"}}],\"stream\":{},\"max_tokens\":4000}}", .{ marker, stream });
}

const Served = struct {
pub const Served = struct {
code: u8 = 255,
fn run(x: *Served, gpa: Allocator, io: std.Io, setup: serve.Setup) void {
x.code = serve.run(gpa, io, .{ .host = "127.0.0.1", .port = 0 }, setup);
}
};

/// serve.run on its own thread with `drain_s`, the engine `slow`; the port once it listens.
fn start(gpa: Allocator, io: std.Io, env: *std.process.Environ.Map, slow: *Slow, tt: *TestText, x: *Served) !std.Thread {
pub fn start(gpa: Allocator, io: std.Io, env: *std.process.Environ.Map, slow: *Slow, tt: *TestText, x: *Served) !std.Thread {
listen_port.store(0, .release);
const t = try std.Thread.spawn(.{}, Served.run, .{ x, gpa, io, serve.Setup{
.engine = slow.engine(),
Expand All @@ -217,7 +226,7 @@ fn start(gpa: Allocator, io: std.Io, env: *std.process.Environ.Map, slow: *Slow,
return t;
}

fn waitActive(io: std.Io, slow: *Slow, n: u32) void {
pub fn waitActive(io: std.Io, slow: *Slow, n: u32) void {
while (slow.active.load(.acquire) < n) std.Io.sleep(io, .fromMilliseconds(2), .awake) catch {};
}

Expand Down
75 changes: 75 additions & 0 deletions zig/src/server/keepalive_test.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
//! A silent stream keeps its client: keepalives on both routes before the first token; a failed one ends the request.
const std = @import("std");
const server = @import("server.zig");
const d = @import("drain_test.zig");
const testing = std.testing;

/// A raw request whose response is read until the connection ends.
fn messagesBody(a: std.mem.Allocator, marker: []const u8) ![]const u8 {
return std.fmt.allocPrint(a, "{{\"model\":\"x\",\"max_tokens\":50,\"stream\":true,\"messages\":[{{\"role\":\"user\",\"content\":\"go {s}\"}}]}}", .{marker});
}

/// Sends `body` streamed and hangs up once the response head arrived and the request reached `slow`.
fn leave(a: std.mem.Allocator, io: std.Io, port: u16, body: []const u8, slow: *d.Slow) !void {
const addr: std.Io.net.IpAddress = .{ .ip4 = .loopback(port) };
const stream = try addr.connect(io, .{ .mode = .stream });
defer stream.close(io);
const head = try std.fmt.allocPrint(a, "POST /v1/chat/completions HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\nContent-Length: {d}\r\n\r\n{s}", .{ body.len, body });
var wbuf: [4096]u8 = undefined;
var w = std.Io.net.Stream.Writer.init(stream, io, &wbuf);
try w.interface.writeAll(head);
try w.interface.flush();
var rbuf: [64]u8 = undefined;
var r = std.Io.net.Stream.Reader.init(stream, io, &rbuf);
_ = try r.interface.peek(1);
// the head goes out before the engine has the request: a hang-up before that leaves nothing to cancel
d.waitActive(io, slow, 1);
}

test "a silent engine's stream gets keepalives before its first token (chat: SSE comments, messages: ping events)" {
const period = comptime std.meta.fieldInfo(server.Config, .sse_keepalive_s).attrs.defaultValue(f64).?;
try testing.expect(period > 0 and period <= 15);
const gpa = testing.allocator;
const io = testing.io;
var tt: d.TestText = .{};
var arena = std.heap.ArenaAllocator.init(gpa);
defer arena.deinit();
const a = arena.allocator();
var env = std.process.Environ.Map.init(gpa);
defer env.deinit();
try env.put("TENSORFOLD_NO_LIVE", "1");
try env.put("TF_DRAIN_S", "5");
try env.put("TF_SSE_KEEPALIVE_S", "0.1");
var slow: d.Slow = .{ .gpa = gpa, .io = io };
var x: d.Served = .{};
const t = try d.start(gpa, io, &env, &slow, &tt, &x);
const port = d.listen_port.load(.acquire);

const chat = try d.request(a, io, port, "POST", "/v1/chat/completions", try d.chatBody(a, "@wait", true));
try testing.expectEqual(@as(u16, 200), chat.status);
const first_token = std.mem.indexOf(u8, chat.body, "\" ok\"") orelse {
std.debug.print("{s}\n", .{chat.body[0..@min(chat.body.len, 1500)]});
return error.NoToken;
};
try testing.expect(std.mem.count(u8, chat.body[0..first_token], ": keepalive\n\n") >= 3);
try testing.expect(std.mem.indexOf(u8, chat.body, "data: [DONE]") != null);

const msg = try d.request(a, io, port, "POST", "/v1/messages", try messagesBody(a, "@wait"));
try testing.expectEqual(@as(u16, 200), msg.status);
const start = std.mem.indexOf(u8, msg.body, "event: message_start") orelse return error.NoStart;
const ping = std.mem.indexOf(u8, msg.body, "event: ping\ndata: {\"type\": \"ping\"}") orelse return error.NoPing;
const delta = std.mem.indexOf(u8, msg.body, "event: content_block_delta") orelse return error.NoDelta;
try testing.expect(start < ping and ping < delta);

// a client that leaves a silent stream: the request is cancelled (the disconnect poll or a failed keepalive)
var idle: u32 = 0;
while (slow.active.load(.acquire) > 0 and idle < 300) : (idle += 1) std.Io.sleep(io, .fromMilliseconds(10), .awake) catch {};
try leave(a, io, port, try d.chatBody(a, "@hang", true), &slow);
var waited: u32 = 0;
while (slow.cancelled.load(.acquire) == 0 and waited < 300) : (waited += 1) std.Io.sleep(io, .fromMilliseconds(10), .awake) catch {};
try testing.expect(slow.cancelled.load(.acquire) != 0);

try std.posix.raise(.TERM);
t.join();
try testing.expectEqual(@as(u8, 0), x.code);
}
21 changes: 20 additions & 1 deletion zig/src/server/openai.zig
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ pub const Out = struct {
event: *const fn (ctx: *anyopaque, payload: ?Value) error{Closed}!void,
/// A whole JSON reply.
reply: *const fn (ctx: *anyopaque, status: u16, payload: Value) void,
/// Bytes that keep a silent stream alive (an SSE comment, or the API's ping); null: none.
keepalive: ?*const fn (ctx: *anyopaque) error{Closed}!void = null,
};
};

Expand All @@ -57,7 +59,7 @@ const ClientOut = struct {
a: Allocator,

fn out(c: *ClientOut) Out {
return .{ .ctx = c, .vt = &.{ .open = open, .event = event, .reply = reply } };
return .{ .ctx = c, .vt = &.{ .open = open, .event = event, .reply = reply, .keepalive = keepalive } };
}

fn open(ctx: *anyopaque) error{Closed}!void {
Expand All @@ -74,14 +76,31 @@ const ClientOut = struct {
const c: *ClientOut = @ptrCast(@alignCast(ctx));
routes.sendValue(c.conn, c.a, status, payload);
}

fn keepalive(ctx: *anyopaque) error{Closed}!void {
const c: *ClientOut = @ptrCast(@alignCast(ctx));
return sse.comment(c.conn);
}
};

/// Whether the client has gone, read between rounds (Python's socket_cancellation).
pub const Gone = struct {
conn: *Conn,
/// The stream a keepalive goes to once it has been silent `every_ns` (0: never)
out: ?Out = null,
every_ns: i96 = 0,
pub fn check(g: Gone) bool {
return g.conn.peerGone();
}

/// A keepalive if the stream has been silent long enough; a failed write means the client left.
pub fn beat(g: Gone, silent_ns: i96) error{Closed}!bool {
const o = g.out orelse return false;
const send = o.vt.keepalive orelse return false;
if (g.every_ns <= 0 or silent_ns < g.every_ns) return false;
try send(o.ctx);
return true;
}
};

/// ``error_body``: OpenAI's error object, with param and code where clients key on them.
Expand Down
5 changes: 4 additions & 1 deletion zig/src/server/openai_run.zig
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,10 @@ pub const Run = struct {
if (!tools and r.is_chat) r.emit(r.chunk(roleDelta(a) catch return, null) catch return) catch return;
var sink_state: StreamSink = .{ .run = r, .tools = tools };
handed = true;
var reply = chat.generate(r.srv, &cx, prepared, .{ .ctx = &sink_state, .call = StreamSink.call }, gone) catch |e| {
var live = gone;
live.out = r.out;
live.every_ns = @intFromFloat(r.srv.config.sse_keepalive_s * std.time.ns_per_s);
var reply = chat.generate(r.srv, &cx, prepared, .{ .ctx = &sink_state, .call = StreamSink.call }, live) catch |e| {
switch (e) {
error.Cancelled => return,
error.Refused => if (cx.kind != .other and cx.kind != .server) {
Expand Down
7 changes: 6 additions & 1 deletion zig/src/server/responses.zig
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ const Wire = struct {
payload: Value = .null,

fn out(w: *Wire) openai.Out {
return .{ .ctx = w, .vt = &.{ .open = open, .event = event, .reply = whole } };
return .{ .ctx = w, .vt = &.{ .open = open, .event = event, .reply = whole, .keepalive = keepalive } };
}

fn open(ctx: *anyopaque) error{Closed}!void {
Expand All @@ -223,6 +223,11 @@ const Wire = struct {
w.status = status;
w.payload = payload;
}

fn keepalive(ctx: *anyopaque) error{Closed}!void {
const w: *Wire = @ptrCast(@alignCast(ctx));
return sse.comment(w.reply.conn);
}
};

/// A Response built from chat-completion deltas, in order: reasoning, text, calls; streamed as typed events.
Expand Down
1 change: 1 addition & 0 deletions zig/src/server/root.zig
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ test {
_ = @import("stream_preflight_test.zig");
_ = @import("logprobs_test.zig");
_ = @import("drain_test.zig");
_ = @import("keepalive_test.zig");
_ = @import("late_system_test.zig");
_ = @import("compact_test.zig");
_ = @import("completion_prompt_test.zig");
Expand Down
7 changes: 6 additions & 1 deletion zig/src/server/serve.zig
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,10 @@ pub fn run(gpa: Allocator, io: std.Io, args: cli.Args, s: Setup) u8 {
std.debug.print("tensorfold: TF_DRAIN_S: seconds, a number >= 0\n", .{});
return 1;
};
const keepalive_s = seconds(env(s, "TF_SSE_KEEPALIVE_S"), 15) orelse {
std.debug.print("tensorfold: TF_SSE_KEEPALIVE_S: seconds, a number >= 0\n", .{});
return 1;
};
const config: server_mod.Config = .{
.served_name = s.served,
.model_dir = s.model_dir,
Expand All @@ -148,6 +152,7 @@ pub fn run(gpa: Allocator, io: std.Io, args: cli.Args, s: Setup) u8 {
.default_sampling = s.sampling,
.use_drafts = !args.no_drafts,
.seed_salt = salt,
.sse_keepalive_s = keepalive_s,
.request_log = env(s, "TENSORFOLD_REQUEST_LOG"),
.dashboard = args.dashboard,
.family = s.family,
Expand Down Expand Up @@ -236,7 +241,7 @@ fn drain(srv: *server_mod.Server, io: std.Io, stop: ?EngineStop, drain_s: f64) v
while (srv.generating.load(.seq_cst) > 0 and waited < 100) : (waited += 1) std.Io.sleep(io, .fromMilliseconds(20), .awake) catch {};
}

/// A seconds setting (TF_DRAIN_S): unset or blank keeps the default; null: not a number >= 0.
/// A seconds setting (TF_DRAIN_S, TF_SSE_KEEPALIVE_S): unset or blank keeps the default; null: not a number >= 0.
fn seconds(raw: ?[]const u8, default: f64) ?f64 {
const t = std.mem.trim(u8, raw orelse "", " \t");
if (t.len == 0) return default;
Expand Down
2 changes: 2 additions & 0 deletions zig/src/server/server.zig
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ pub const Config = struct {
/// --slide-graph: the file holding the Sliding Weights fact graph; null keeps the graph in memory.
slide_graph: ?[]const u8 = null,
timeouts: http_conn.Timeouts = .{},
/// TF_SSE_KEEPALIVE_S: a silent stream's keepalive period before its first token (serve.zig; 0: none)
sse_keepalive_s: f64 = 15,
/// The checkpoint family's own chat rules (family.zig); null: the chat template path.
family: ?family_mod.Family = null,
};
Expand Down
5 changes: 5 additions & 0 deletions zig/src/server/sse.zig
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ pub fn data(conn: *Conn, a: Allocator, payload: json.Value) error{Closed}!void {
return conn.writeAll(std.mem.concat(a, u8, &.{ "data: ", text, "\n\n" }) catch return error.Closed);
}

/// An SSE comment line, which clients skip: it keeps a stream alive while nothing else is sent.
pub fn comment(conn: *Conn) error{Closed}!void {
return conn.writeAll(": keepalive\n\n");
}

pub fn done(conn: *Conn) error{Closed}!void {
return conn.writeAll("data: [DONE]\n\n");
}
Expand Down