Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
2 changes: 1 addition & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ Prefer a restricted file over command-line keys, which can appear in the operati
| Route | Behavior |
| --- | --- |
| `GET /v1/models` | Served model ID and any configured aliases (both servers) |
| `GET /health` | Server health and available status information |
| `GET /health` | Server health and available status information. With no keys configured, the native server also names its `version`, and its `backend` (`metal` or `cuda`) and GPU `device` when it knows them |
| `GET /metrics`, `GET /v1/metrics` | Prometheus text: requests, KV occupancy, drafts and latency (both servers) |
| `GET /dashboard` | Native live dashboard page when `--dashboard` is enabled |
| `GET /stats` | Native JSON dashboard snapshot when `--dashboard` is enabled |
Expand Down
9 changes: 9 additions & 0 deletions zig/src/cuda/driver.zig
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,13 @@ pub const Driver = struct {
try self.check(self.api.cuDeviceGetAttribute(&minor, .compute_capability_minor, dev), "cuDeviceGetAttribute");
return @intCast(10 * major + minor);
}

/// Device `ordinal`'s name ("NVIDIA GB10"), read without making a context.
pub fn deviceName(self: *const Driver, ordinal: c_int, buf: []u8) Error![]const u8 {
if (buf.len < 2) return error.Invalid;
var dev: abi.Device = 0;
try self.check(self.api.cuDeviceGet(&dev, ordinal), "cuDeviceGet");
try self.check(self.api.cuDeviceGetName(buf.ptr, @intCast(buf.len), dev), "cuDeviceGetName");
return std.mem.sliceTo(buf, 0);
}
};
10 changes: 10 additions & 0 deletions zig/src/native/cuda.zig
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,16 @@ pub fn chip(a: Allocator) ?[]const u8 {
return chipClass(a, driver.capability(@intCast(ordinal orelse 0)) catch return null);
}

/// The name of the GPU a serve opens ("NVIDIA GB10"): --device, else TF_CUDA_DEVICE, else 0; null without one.
pub fn deviceName(a: Allocator, flag: ?u32) ?[]const u8 {
const ordinal = flag orelse (envNumber(getenv("TF_CUDA_DEVICE")) catch return null) orelse 0;
var driver = cuda.Driver.open() catch return null;
defer driver.close();
var buf: [256]u8 = undefined;
const text = driver.deviceName(std.math.cast(c_int, ordinal) orelse return null, &buf) catch return null;
return a.dupe(u8, text) catch null;
}

fn chipClass(a: Allocator, capability: u32) ?[]const u8 {
return std.fmt.allocPrint(a, "nvidia-sm{d}", .{capability}) catch null;
}
Expand Down
7 changes: 7 additions & 0 deletions zig/src/native/metal.zig
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,13 @@ pub fn chip(a: Allocator) ?[]const u8 {
return std.fmt.allocPrint(a, "apple-m{d}", .{gen}) catch null;
}

/// The name of the system GPU the Metal engines open ("Apple M5 Max"); null without one.
pub fn deviceName(a: Allocator, _: ?u32) ?[]const u8 {
const device = mtl.Device.init() catch return null;
defer device.deinit();
return a.dupe(u8, std.mem.span(device.name())) catch null;
}

/// The M generation in a Metal device name ("Apple M5 Max": 5).
fn generation(name: []const u8) ?u32 {
var words = std.mem.tokenizeScalar(u8, name, ' ');
Expand Down
6 changes: 6 additions & 0 deletions zig/src/server/engines.zig
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const std = @import("std");
const api = @import("engine_api");
const native = @import("native_engines");
const cli = @import("cli.zig");
const build_identity = @import("identity.zig");
const Allocator = std.mem.Allocator;

pub const Opened = api.Opened;
Expand All @@ -18,6 +19,11 @@ pub fn capabilities(a: Allocator) cli.Engines {
return .{ .version = @import("build_options").version, .chip = if (native.families.len > 0) native.chip(a) else null, .backends = native.backends, .families = native.families };
}

/// What the open /health names: this release, the built-in backend and the GPU a serve with ``args`` opens.
pub fn identity(a: Allocator, args: cli.Args) build_identity.Identity {
return build_identity.of(native, a, @import("build_options").version, args.device);
}

/// The engine for the checkpoint in ``dir``, or null with ``problem`` set.
pub fn open(a: Allocator, gpa: Allocator, io: std.Io, dir: []const u8, model_type: []const u8, args: cli.Args, problem: *[]const u8) !?Opened {
return native.open(a, gpa, io, try cli.request(a, dir, model_type, args), problem);
Expand Down
223 changes: 223 additions & 0 deletions zig/src/server/health_test.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
//! /health: the open body's keys in order with the identity the builder reads, and the keyed body over a socket.
const std = @import("std");
const api = @import("engine_api");
const auth = @import("auth.zig");
const build_identity = @import("identity.zig");
const json = @import("json.zig");
const listener = @import("listener.zig");
const model_text = @import("model_text.zig");
const server = @import("server.zig");
const status_routes = @import("status_routes.zig");
const posix = std.posix;
const Threaded = std.Io.Threaded;
const Allocator = std.mem.Allocator;

/// The keys an open /health sent before it named the release, backend and GPU.
const earlier = [_][]const u8{ "status", "model", "model_ids", "max_batch_size", "warming", "memory", "live" };

/// Four lanes, some memory, nothing running.
const Idle = struct {
fn engine(e: *Idle) api.Engine {
return .{ .ctx = e, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory } };
}

fn info(_: *anyopaque) api.Info {
return .{ .lanes = 4 };
}

fn submit(_: *anyopaque, _: api.Id, _: *const api.Request, _: api.Sink) api.SubmitError!void {
return error.Closed;
}

fn cancel(_: *anyopaque, _: api.Id) void {}

fn status(_: *anyopaque, out: *api.Status, _: []u32) void {
out.* = .{};
}

fn memory(_: *anyopaque, _: bool) ?api.Memory {
return .{ .active = 3, .cache = 2, .peak = 5 };
}
};

/// A template-free vocabulary of bytes.
const Bytes = struct {
fn text(t: *Bytes) 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 } };
}

fn encode(_: *anyopaque, a: Allocator, input: []const u8, _: bool) model_text.Error![]u32 {
const ids = try a.alloc(u32, input.len);
for (input, ids) |byte, *id| id.* = byte;
return ids;
}

fn decode(_: *anyopaque, a: Allocator, _: []const u32) Allocator.Error![]u8 {
return a.dupe(u8, "");
}

fn tokenId(_: *anyopaque, _: []const u8) ?u32 {
return null;
}

fn tokenString(_: *anyopaque, a: Allocator, id: u32) Allocator.Error![]u8 {
return std.fmt.allocPrint(a, "{d}", .{id});
}

fn vocabSize(_: *anyopaque) u32 {
return 256;
}

fn eosIds(_: *anyopaque) []const u32 {
return &.{};
}

fn render(_: *anyopaque, a: Allocator, _: json.Value, _: model_text.RenderOptions, _: *[]const u8) model_text.Error![]u8 {
return a.dupe(u8, "prompt");
}

fn templateSource(_: *anyopaque) []const u8 {
return "";
}
};

/// An engine module with a GPU, as native/metal.zig and native/cuda.zig are; its name says which device was asked for.
const WithGpu = struct {
pub const backends: []const []const u8 = &.{"cuda"};

pub fn deviceName(a: Allocator, device: ?u32) ?[]const u8 {
return std.fmt.allocPrint(a, "Example \"GPU\" {d}", .{device orelse 0}) catch null;
}
};

/// An engine module that finds no GPU.
const NoGpu = struct {
pub const backends: []const []const u8 = &.{"cuda"};

pub fn deviceName(_: Allocator, _: ?u32) ?[]const u8 {
return null;
}
};

/// No engine module, as native/none.zig declares it: no backend and no deviceName.
const NoEngine = struct {
pub const backends: []const []const u8 = &.{};
};

/// The open /health body a server with ``identity`` sends, parsed back as a client reads it.
fn served(a: Allocator, identity: server.Identity) !std.json.ObjectMap {
var engine: Idle = .{};
var text: Bytes = .{};
const srv = try server.Server.init(std.testing.allocator, std.testing.io, engine.engine(), text.text(), .{ .served_name = "m", .model_ids = &.{"m"}, .identity = identity }, null);
defer srv.deinit();
const body = try json.stringify(a, try status_routes.openHealth(srv, a, false), .{});
const doc = try std.json.parseFromSliceLeaky(std.json.Value, a, body, .{});
return doc.object;
}

test "the open health names the release, backend and GPU the builder reads, after its earlier keys" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const o = try served(a, build_identity.of(WithGpu, a, "9.8.7", 1));
try std.testing.expectEqual(earlier.len + 3, o.count());
for (earlier ++ [_][]const u8{ "version", "backend", "device" }, o.keys()) |want, got| try std.testing.expectEqualStrings(want, got);
try std.testing.expectEqualStrings("9.8.7", o.get("version").?.string);
try std.testing.expectEqualStrings("cuda", o.get("backend").?.string);
try std.testing.expectEqualStrings("Example \"GPU\" 1", o.get("device").?.string);
try std.testing.expectEqual(@as(i64, 4), o.get("max_batch_size").?.integer);
try std.testing.expectEqual(@as(i64, 5), o.get("memory").?.object.get("peak").?.integer);
}

test "the open health always names the release, and leaves out a backend or GPU the binary does not know" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const engine_less = try served(a, build_identity.of(NoEngine, a, "9.8.7", null));
try std.testing.expectEqual(earlier.len + 1, engine_less.count());
for (earlier ++ [_][]const u8{"version"}, engine_less.keys()) |want, got| try std.testing.expectEqualStrings(want, got);
try std.testing.expectEqualStrings("9.8.7", engine_less.get("version").?.string);
const no_gpu = try served(a, build_identity.of(NoGpu, a, "9.8.7", null));
try std.testing.expectEqual(earlier.len + 2, no_gpu.count());
try std.testing.expect(no_gpu.get("device") == null);
try std.testing.expectEqualStrings("cuda", no_gpu.get("backend").?.string);
const test_server = try served(a, .{}); // the parity test servers set no identity
try std.testing.expectEqual(earlier.len, test_server.count());
for (earlier, test_server.keys()) |want, got| try std.testing.expectEqualStrings(want, got);
}

const key = "sk-health-test";
const health_open = "GET /health HTTP/1.1\r\nHost: test\r\nConnection: close\r\n\r\n";
const health_keyed = "GET /health HTTP/1.1\r\nHost: test\r\nAuthorization: Bearer " ++ key ++ "\r\nConnection: close\r\n\r\n";
const models_open = "GET /v1/models HTTP/1.1\r\nHost: test\r\nConnection: close\r\n\r\n";
const models_keyed = "GET /v1/models HTTP/1.1\r\nHost: test\r\nAuthorization: Bearer " ++ key ++ "\r\nConnection: close\r\n\r\n";

/// One request on a fresh loopback connection that asks to close, and the whole reply; error.Timeout after 5 s silent.
fn exchange(a: Allocator, port: u16, request: []const u8) ![]const u8 {
const address: std.Io.net.IpAddress = .{ .ip4 = .loopback(port) };
var storage: Threaded.PosixAddress = undefined;
const len = Threaded.addressToPosix(&address, &storage);
const rc = posix.system.socket(posix.AF.INET, posix.SOCK.STREAM, 0);
if (posix.errno(rc) != .SUCCESS) return error.SocketFailed;
const fd: posix.socket_t = @intCast(rc);
defer _ = posix.system.close(fd);
if (posix.errno(posix.system.connect(fd, &storage.any, len)) != .SUCCESS) return error.ConnectFailed;
var sent: usize = 0;
while (sent < request.len) {
const n = posix.system.write(fd, request[sent..].ptr, request.len - sent);
if (posix.errno(n) != .SUCCESS) return error.WriteFailed;
sent += @intCast(n);
}
var reply: std.ArrayList(u8) = .empty;
var buf: [4096]u8 = undefined;
while (true) {
var fds = [_]posix.pollfd{.{ .fd = fd, .events = posix.POLL.IN, .revents = 0 }};
if (try posix.poll(&fds, 5000) == 0) return error.Timeout;
const n = posix.system.read(fd, &buf, buf.len);
if (posix.errno(n) != .SUCCESS) return error.ReadFailed;
if (n == 0) return reply.items;
try reply.appendSlice(a, buf[0..@intCast(n)]);
}
}

fn bodyOf(reply: []const u8) ![]const u8 {
const at = std.mem.indexOf(u8, reply, "\r\n\r\n") orelse return error.NoBody;
return reply[at + 4 ..];
}

/// Stops the accept loop and waits for the connection threads, so the server can be freed.
fn quiesce(srv: *server.Server, stop: *std.atomic.Value(bool), accept: std.Thread) void {
stop.store(true, .release);
accept.join();
var waited: u32 = 0;
while (srv.open_connections.load(.acquire) > 0 and waited < 500) : (waited += 1) std.Io.sleep(std.testing.io, .fromMilliseconds(10), .awake) catch {};
}

test "with keys configured, /health sends only its status, with and without a valid key, whatever the identity" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
var problem: []const u8 = "";
var keys = try auth.Store.init(std.testing.allocator, &.{key}, "", null, false, &problem);
defer keys.deinit();
var engine: Idle = .{};
var text: Bytes = .{};
const identity = build_identity.of(WithGpu, a, "9.8.7", 1);
try std.testing.expect(identity.version.len > 0 and identity.backend.len > 0 and identity.device.len > 0);
const srv = try server.Server.init(std.testing.allocator, std.testing.io, engine.engine(), text.text(), .{ .served_name = "m", .model_ids = &.{"m"}, .identity = identity }, &keys);
defer srv.deinit();
const lis = try listener.Listener.open(.{ .ip4 = .loopback(0) });
defer lis.close();
var stop: std.atomic.Value(bool) = .init(false);
const accept = try std.Thread.spawn(.{}, server.Server.serve, .{ srv, lis, &stop });
defer quiesce(srv, &stop, accept);
const port = lis.port();
for ([_][]const u8{ health_open, health_keyed }) |request| {
const reply = try exchange(a, port, request);
try std.testing.expect(std.mem.startsWith(u8, reply, "HTTP/1.1 200 "));
try std.testing.expectEqualStrings("{\"status\": \"ok\"}", try bodyOf(reply));
}
// the gate is on and the key is valid: a gated route refuses the request without it and serves it with it
try std.testing.expect(std.mem.startsWith(u8, try exchange(a, port, models_open), "HTTP/1.1 401 "));
try std.testing.expect(std.mem.startsWith(u8, try exchange(a, port, models_keyed), "HTTP/1.1 200 "));
}
12 changes: 12 additions & 0 deletions zig/src/server/identity.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
//! What the open /health names besides the model: the release, the GPU backend and the GPU's own name.
const std = @import("std");
const Allocator = std.mem.Allocator;

/// Read once at startup; an empty field is left out of /health, and a test server given none names none.
pub const Identity = struct { version: []const u8 = "", backend: []const u8 = "", device: []const u8 = "" };

/// A binary's identity: its release always, its engine module's first backend, and the GPU `device` picks, if any.
pub fn of(comptime Engines: type, a: Allocator, version: []const u8, device: ?u32) Identity {
const name: ?[]const u8 = if (@hasDecl(Engines, "deviceName")) Engines.deviceName(a, device) else null;
return .{ .version = version, .backend = if (Engines.backends.len > 0) Engines.backends[0] else "", .device = name orelse "" };
}
1 change: 1 addition & 0 deletions zig/src/server/main.zig
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ pub fn main(init: std.process.Init) !u8 {
.sampling = try sampling(a, io, dir, args),
.environ = init.environ_map,
.started = started,
.identity = engines.identity(a, args),
});
}

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 @@ -35,6 +35,7 @@ test {
_ = @import("hub.zig");
_ = @import("chunk_plan.zig");
_ = @import("status_routes.zig");
_ = @import("health_test.zig");
_ = @import("memory_routes.zig");
_ = @import("process_memory.zig");
_ = @import("log.zig");
Expand Down
3 changes: 3 additions & 0 deletions zig/src/server/serve.zig
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ pub const Setup = struct {
sampling: ?json.Value = null,
environ: ?*const std.process.Environ.Map = null,
started: i96 = 0,
/// The release, backend and GPU the open /health names.
identity: server_mod.Identity = .{},
/// Called once the socket listens, with its port (tests read it).
on_listen: ?*const fn (port: u16) void = null,
};
Expand Down Expand Up @@ -125,6 +127,7 @@ pub fn run(gpa: Allocator, io: std.Io, args: cli.Args, s: Setup) u8 {
.slide_graph = args.slide_graph,
.cortheon = args.cortheon,
.cortheon_search_key = env(s, "BRAVE_SEARCH_API_KEY"),
.identity = s.identity,
};
const srv = server_mod.Server.init(gpa, io, s.engine, s.text, config, if (store.enabled()) &store else null) catch {
std.debug.print("tensorfold: the server could not start\n", .{});
Expand Down
4 changes: 4 additions & 0 deletions zig/src/server/server.zig
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ const Allocator = std.mem.Allocator;
/// auto compacts near the window. fraction compacts past that share of it.
pub const CompactAt = union(enum) { auto, fraction: f64 };

pub const Identity = @import("identity.zig").Identity;

pub const Config = struct {
served_name: []const u8,
model_dir: []const u8 = "",
Expand Down Expand Up @@ -62,6 +64,8 @@ pub const Config = struct {
/// BRAVE_SEARCH_API_KEY: Cortheon searches through Brave instead of DuckDuckGo.
cortheon_search_key: ?[]const u8 = null,
timeouts: http_conn.Timeouts = .{},
/// The open /health names these after its other keys; empty fields are left out.
identity: Identity = .{},
};

pub const Server = struct {
Expand Down
12 changes: 10 additions & 2 deletions zig/src/server/status_routes.zig
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ const Allocator = std.mem.Allocator;
/// With keys on, health names nothing about the model.
pub fn health(srv: *Server, conn: *Conn, a: Allocator) !void {
if (srv.keys) |k| if (k.enabled()) return conn.sendJson(200, "{\"status\": \"ok\"}");
routes.sendValue(conn, a, 200, try openHealth(srv, a, std.mem.indexOf(u8, conn.path, "reset_peak=1") != null));
}

/// The open health body: model, lanes, memory and live counts, then whichever of release, backend and GPU it knows.
pub fn openHealth(srv: *Server, a: Allocator, reset_peak: bool) !Value {
const o = try json.newObject(a);
try o.put(a, "status", .{ .string = "ok" });
try o.put(a, "model", .{ .string = srv.config.served_name });
Expand All @@ -24,14 +29,17 @@ pub fn health(srv: *Server, conn: *Conn, a: Allocator) !void {
srv.engine.status(&status, &.{});
try o.put(a, "warming", .{ .bool = status.warming });
const memory = try json.newObject(a);
if (srv.engine.memory(std.mem.indexOf(u8, conn.path, "reset_peak=1") != null)) |mem| {
if (srv.engine.memory(reset_peak)) |mem| {
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));
}
try o.put(a, "memory", .{ .object = memory });
try o.put(a, "live", try live.snapshot(a, srv.engine));
routes.sendValue(conn, a, 200, .{ .object = o });
const ident = srv.config.identity;
for ([_][2][]const u8{ .{ "version", ident.version }, .{ "backend", ident.backend }, .{ "device", ident.device } }) |field|
if (field[1].len > 0) try o.put(a, field[0], .{ .string = field[1] });
return .{ .object = o };
}

pub fn models(srv: *Server, conn: *Conn, a: Allocator) !void {
Expand Down
Loading