From cab179063f75f1ab5c841717e36e2a0946e91167 Mon Sep 17 00:00:00 2001 From: Ash <71890694+ashhart@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:27:50 +0000 Subject: [PATCH 1/3] server: tensorfold serve --router answers for several models at one address, each a serve child loaded on demand A request's model field picks the child, which the router starts if need be and relays byte for byte, with --max-loaded, --idle-unload and each model's memory floor bounding what stays loaded, and --router-config FILE.toml listing the models in [[models]] tables. Single-model serve is unchanged. --- docs/api.md | 32 ++ docs/router.md | 128 ++++++++ docs/serve-config.md | 2 + docs/supported-models.md | 1 + zig/build/cuda_server_host.zig | 3 + zig/build/golden.zig | 12 + zig/src/cli/cli.zig | 5 + zig/src/cli/hub.zig | 42 +++ zig/src/cli/info.zig | 55 +++- zig/src/server/auth_gate.zig | 50 ++++ zig/src/server/benchmark_server.zig | 54 +++- zig/src/server/benchmark_server_test.zig | 38 +++ zig/src/server/cli_config.zig | 41 ++- zig/src/server/main.zig | 22 +- zig/src/server/root.zig | 1 + zig/src/server/router/args.zig | 92 ++++++ zig/src/server/router/catalog.zig | 177 +++++++++++ zig/src/server/router/config.zig | 116 ++++++++ zig/src/server/router/config_test.zig | 164 +++++++++++ zig/src/server/router/front.zig | 159 ++++++++++ zig/src/server/router/front_test.zig | 288 ++++++++++++++++++ zig/src/server/router/listing.zig | 138 +++++++++ zig/src/server/router/model_route.zig | 82 ++++++ zig/src/server/router/pool.zig | 357 +++++++++++++++++++++++ zig/src/server/router/pool_test.zig | 195 +++++++++++++ zig/src/server/router/relay.zig | 302 +++++++++++++++++++ zig/src/server/router/replies.zig | 95 ++++++ zig/src/server/router/room.zig | 85 ++++++ zig/src/server/router/router.zig | 108 +++++++ zig/src/server/router/router_test.zig | 13 + zig/src/server/router/test_child.zig | 156 ++++++++++ zig/src/server/router_serve_test.zig | 79 +++++ zig/src/server/serve.zig | 14 +- zig/src/server/server.zig | 42 +-- zig/src/server/toml_flat.zig | 51 +++- 35 files changed, 3116 insertions(+), 83 deletions(-) create mode 100644 docs/router.md create mode 100644 zig/src/server/auth_gate.zig create mode 100644 zig/src/server/router/args.zig create mode 100644 zig/src/server/router/catalog.zig create mode 100644 zig/src/server/router/config.zig create mode 100644 zig/src/server/router/config_test.zig create mode 100644 zig/src/server/router/front.zig create mode 100644 zig/src/server/router/front_test.zig create mode 100644 zig/src/server/router/listing.zig create mode 100644 zig/src/server/router/model_route.zig create mode 100644 zig/src/server/router/pool.zig create mode 100644 zig/src/server/router/pool_test.zig create mode 100644 zig/src/server/router/relay.zig create mode 100644 zig/src/server/router/replies.zig create mode 100644 zig/src/server/router/room.zig create mode 100644 zig/src/server/router/router.zig create mode 100644 zig/src/server/router/router_test.zig create mode 100644 zig/src/server/router/test_child.zig create mode 100644 zig/src/server/router_serve_test.zig diff --git a/docs/api.md b/docs/api.md index 3bf87a646b0..e27ddb1e75a 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1659,6 +1659,38 @@ value. `binding` hashes the field `tensorfold execution binding v1`, then `witne no route does that today, since each path that binds nothing runs only under a flag the witness excludes, so `unbound` would mean a reply path that skipped the binding by mistake. No response cache reads the binding yet. +## Router + +[`tensorfold serve --router`](router.md) forwards each model request to the child its `model` field names and +relays the child's reply unchanged, head and body, as it arrives. It answers these routes itself: + +- `GET /health` (and `GET /`), without a key. With keys configured the body is only `{"status": "ok"}`. Without keys + it has `status` (`"ok"`), `router` (`true`), `models` (how many it serves), `max_loaded`, `loaded` (an object for + each child that is `loading`, `ready` or `stopping`: its `id`, `state` and `requests_in_progress`) and `version`. While the + router stops it answers 503 `{"status": "draining", "requests_in_progress": N}` with `Retry-After`, as a server does. +- `GET /v1/models` (and `/models`) lists every id and alias, loaded or not, each with a boolean `loaded` last. A ready + child's entries are its own `/v1/models` entries, with every field a server gives them; the others have `id`, + `object`, `created` and `owned_by` only, since the rest is known once the model loads. +- `GET /api/tags` lists every id and alias, and `GET /api/ps` the ready children, each as `{"name": ID, "model": ID}`, + as a server lists its own names. `GET /api/version` gives the router's release. + +Its own refusals come in the route's error shape (OpenAI's error object, Anthropic's typed error, or Ollama's +`{"error": "..."}`), with these codes: + +| Status | Code | When | +| --- | --- | --- | +| 400 | `model_required` | The body names no `model` | +| 404 | `model_not_found` | No id or alias is that name | +| 404 | `unsupported_route` | A route the router does not serve in this version, named in the message | +| 502 | `model_server_failed` | The child exited, or closed the connection, before its reply | +| 503 | `models_busy` | Every loaded child is busy and `--max-loaded` leaves no room, after 5 minutes; `Retry-After: 10` | +| 503 | `model_too_large` | The model's memory floor is larger than the machine's memory | +| 503 | `model_load_failed` | Its child exited while loading; the message has the child's last log line | +| 503 | `model_load_timeout` | Its child was not ready in time | +| 503 | `server_restarting` | The router is stopping; `Retry-After: 30` | + +A child's own replies, errors included, pass through as the child sent them. + ## Cancel a request `POST /v1/requests/{id}/cancel` (or `/requests/{id}/cancel`) cancels a running or queued request by the id its diff --git a/docs/router.md b/docs/router.md new file mode 100644 index 00000000000..96a92a35158 --- /dev/null +++ b/docs/router.md @@ -0,0 +1,128 @@ +# Several models at one address + +`tensorfold serve --router` answers for several models at one address and loads each one when a request names it. +Point any OpenAI, Anthropic or Ollama client at it and pick a model by name, as with one server. + +```sh +tensorfold serve --router # every cached checkpoint, by its repo id +tensorfold serve --router --router-config models.toml # the models the file lists +tensorfold serve --router --max-loaded 2 --idle-unload 900 --api-key-file /etc/tensorfold/keys +``` + +Each model runs as its own `tensorfold serve` child: the same binary, serving that one model on 127.0.0.1 at a port +the system picks. A child gets a random key of its own in its environment (`TENSORFOLD_API_KEY`), and the router sends +that key with every request it forwards, so other users of the machine cannot use the child's port. A request's +`model` field picks the child. When it is not running, the router starts it, and the request and any others for that +model wait until it is ready. The child's reply comes back byte for byte as it arrives, streams included. + +The children lead process groups of their own, so a Ctrl-C or a closed terminal reaches only the router, which then +stops every child: SIGTERM, up to 30 seconds to finish the requests in progress, then SIGKILL. Without API keys, a +hangup (SIGHUP) stops the router as SIGTERM does; with keys it rereads the key file, as `serve` does. + +## Flags + +| Flag | Meaning | +| --- | --- | +| `--router` | Route by model instead of serving one; it takes no `MODEL`. | +| `--router-config FILE.toml` | The models to serve, each in a `[[models]]` table (below). Without it, every cached checkpoint. | +| `--max-loaded N` | Children loaded at once, 1 (the default) to 64. | +| `--idle-unload SECONDS` | Stop a child after this long with no request; 0, the default, keeps it. The same seconds as `serve --idle-unload`. | +| `--host HOST`, `--port PORT` | The router's address, default `127.0.0.1:8080`. | +| `--api-key KEY`, `--api-key-file FILE` | The router's keys, with `TENSORFOLD_API_KEY`, as [serve takes them](api.md#api-keys); scoped keys keep their scopes. | +| `--allowed-host NAME`, `--allowed-origin ORIGIN` | The router's [browser request checks](api.md#browser-request-headers). | + +Any other serve flag on the router's command line is refused by name: set it on the model in `--router-config`. + +## Models without a config + +Without `--router-config`, the router serves every checkpoint `tensorfold models` lists, each under its repo id +(`org/name`) with serve's default flags. `GET /v1/models` lists those ids. The list is read once, at startup; a +checkpoint that `serve` would refuse, such as one whose cached revision is missing, is left out and the log says why. + +## The config file + +```toml +# models.toml +[[models]] +id = "glm" +model = "zai-org/GLM-5.3-Flash" +aliases = ["glm-flash"] +context = 131072 +thinking = false +prompt-cache-gib = 8 + +[[models]] +id = "small" +model = "./weights/small" # a folder beside models.toml +parallel = 2 +``` + +Each `[[models]]` table is one model: + +- `id`: the name it answers to. Required. +- `model`: a folder or a Hugging Face repo id in the cache, as `serve MODEL` takes it. Required. +- `aliases`: more names it answers to, a string or a list of strings. +- Any other key is a serve flag, read as [serve config files](serve-config.md) read their keys: the same key rules, + value checks and messages, and a relative path starts at the file's folder. + +An id or alias is 1 to 256 bytes with no spaces or control characters and does not start with `-`. No name may belong +to two models. The router sets these flags on every child itself, so a table that sets one is refused with the reason: +`name`, `alias`, `host`, `port`, `unix-socket`, `api-key`, `api-key-file`, `idle-unload`, `allowed-host` and +`allowed-origin`. A top-level key is refused too: the file holds `[[models]]` tables only, and the router's own flags +go on its command line. The file is opened as `serve --config` opens its file (no link, nothing other users can write, +at most 1 MiB), and every problem names the file and the line. + +At startup the router checks each model's command line as `serve` would and finds its checkpoint (and drafter) in +the cache; a model that fails either stops the start with the model's id and the reason. + +## Loading and stopping + +- At most `--max-loaded` children are loaded at once. Loading another first stops the least recently used child that + has no request in flight. If every loaded child is busy, the request waits up to 5 minutes for one to finish, then + gets 503 `models_busy` with `Retry-After`. +- Memory: each model has a memory floor, the estimate `tensorfold info` prints (weights plus a 2 GiB runtime margin, + or Flash Next's startup budget on Metal), plus its `--drafter`'s weights. Before a child starts, the floors of the + loaded children plus its own must fit in the machine's memory; idle children stop, least recently used first, to + make room. A model whose floor is larger than the machine's memory gets 503 `model_too_large`. A model with no + estimate is bounded by `--max-loaded` alone, and the log says so. +- A child gets as long to load as `tensorfold benchmark` gives its server: 600 seconds, plus 6 seconds for each GB of + weights past 20 GB, at most 3600. Past it the request gets 503 `model_load_timeout`; a child that exits while + loading gives 503 `model_load_failed` with the child's last log line. +- A child that exits while it is loaded is marked unloaded. Requests still waiting for its reply get 502 + `model_server_failed`; a reply already streaming ends where the child stopped, as a lone server's would. The next + request starts it again. +- Each child's log goes to a private file under `~/.tensorfold/router`, removed from the folder as soon as the child + starts. The router prints the child's last lines when it fails to load or exits. + +## Routes + +These routes are forwarded by their JSON body's `model` field (POST; rerank also by PUT): + +| API | Routes | +| --- | --- | +| OpenAI | `/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/v1/embeddings`, `/v1/rerank`, `/tokenize`, `/detokenize` | +| Anthropic | `/v1/messages`, `/v1/messages/count_tokens` | +| Ollama | `/api/chat`, `/api/generate`, `/api/embed`, `/api/show` | + +They also answer at the other spellings a server takes, such as `/chat/completions` and `/messages`. A body with no +`model` gets 400 `model_required`, and a name the router does not serve gets 404 `model_not_found`. The router answers +in the route's own error shape: OpenAI's error object, Anthropic's `not_found_error`, or Ollama's +`{"error": "..."}`. A restricted key's Responses requests must be stateless, as on a server. + +The router answers these itself, with [API keys](api.md#api-keys) and scopes applied as a server applies them: +`GET /health`, `GET /v1/models`, `GET /api/tags`, `GET /api/ps` and `GET /api/version`. See +[the API notes](api.md#router). + +Everything else is refused by name with 404 `unsupported_route` in this version, among them `GET /v1/responses/{id}` +(stored responses stay in the child that made them), the Responses WebSocket mode, `GET /metrics` (each child keeps +its own metrics, which the router does not expose), `POST /v1/requests/{id}/cancel`, speech, images, OCR and the +server's own pages. + +## Limits + +- The router is not available on Windows: run one `tensorfold serve` a model. +- Each child plans its memory as a lone server does. With `--max-loaded` above 1, set `prompt-cache-gib` for each model + so that the first one loaded does not take the room the next needs. +- The memory check counts the machine's system memory. On a discrete GPU, `--max-loaded` is the bound that matters. +- A router killed with SIGKILL leaves its children running; they stop only when the router stops itself. +- `capabilities --json` does not list the router's flags. diff --git a/docs/serve-config.md b/docs/serve-config.md index c07ef3f0084..de2d26b326f 100644 --- a/docs/serve-config.md +++ b/docs/serve-config.md @@ -125,3 +125,5 @@ The startup log names the file and how many options it gave, never a value. - `tensorfold benchmark` and `tensorfold service install` do not read the file. TensorFold Web refuses `--config` as an extra flag, because a file could set the flags that Settings manages. - Prefer `api-key-file` to `api-key` in a file that is checked in, so that no key is stored with it. +- A [router config](router.md#the-config-file) is a different file: one `[[models]]` table a model, whose serve keys + follow these rules. diff --git a/docs/supported-models.md b/docs/supported-models.md index 3e16288ce65..af937a647c2 100644 --- a/docs/supported-models.md +++ b/docs/supported-models.md @@ -93,6 +93,7 @@ It sends the token only to the hub's own host (`huggingface.co`, or the host of When the hub refuses a repo, `pull` names it and says whether a token is missing or the token lacks access; without a token, Hugging Face refuses a mistyped repo name the same way. `models --json` prints one document for programs: `schema` 1 and `models`, each cached checkpoint's `repo`, `family` and `model_type` (`family` is a display title and `model_type` is the key to match on), plus `machine` and `catalog`, each entry's `need_bytes`, `fit`, `tok_s` (null when unmeasured), `quality` (passed, items, share, suite digest and receipt; null when unrated), `on_disk` and `install`. `tensorfold serve REPO` serves a cached checkpoint by its repository name. +`tensorfold serve --router` serves every cached checkpoint, or the models a `--router-config` file lists, at one address, each loaded when a request's `model` field names it; see [several models at one address](router.md). `rm REPO` removes a cached checkpoint with all its snapshots, blobs and refs, and then the repo's folder. `rm REPO@REVISION` removes one snapshot, named by a ref such as `main` or by its commit, and the refs that name it. Blobs another snapshot still links to stay. Before deleting, it lists each snapshot and the bytes freed, counting a blob two snapshots share once, and asks. diff --git a/zig/build/cuda_server_host.zig b/zig/build/cuda_server_host.zig index a104670fa35..a9559a9b0b3 100644 --- a/zig/build/cuda_server_host.zig +++ b/zig/build/cuda_server_host.zig @@ -40,6 +40,9 @@ pub fn steps(b: *std.Build, host: std.Build.ResolvedTarget, cuda: *std.Build.Mod eos_policy.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = kolibri1Module(b, host, .debug, cuda, mods.core, mods.lanes), .filters = &.{"EOS policy:"} })).step); b.step("test-serve-flags-host", "Serve flag parsing, the flat TOML reader and --config expansion, without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{ "--compact-at:", "flat TOML:", "serve --config:" } })).step); b.step("test-request-deadline-host", "deadline_s: the server ends a reply at its deadline with usage and ids").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"request deadline:"} })).step); + const router = b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"serve --router:"} })); + router.has_side_effects = true; // its children are /bin/sh processes and its fakes loopback sockets + b.step("test-router-host", "serve --router: config, routing, child lifecycle and byte-for-byte relay with fake children").dependOn(&router.step); b.step("test-dory-cli-host", "Dory CUDA loop option forwarding and invalid-value refusals").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"--device and --segments:"} })).step); b.step("test-dory-chat-host", "Dory chat template, EOS, reasoning split and qwen3_coder call on the CPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"Dory chat:"} })).step); b.step("test-embeddings-protocol-host", "Embedding request and response contracts without an admitted model or GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"embeddings protocol:"} })).step); diff --git a/zig/build/golden.zig b/zig/build/golden.zig index 20be0ac71b6..fa2f241463e 100644 --- a/zig/build/golden.zig +++ b/zig/build/golden.zig @@ -31,6 +31,18 @@ pub fn step(b: *std.Build, target: std.Build.ResolvedTarget, server: *std.Build. all.dependOn(&run.step); if (std.mem.eql(u8, file, "security-cases.json")) b.step("test-security-golden-host", "Native HTTP key, host and origin security with the local fake server").dependOn(&run.step); } + // serve --router over real serve children: fake_serve under the router's keys, loads, stops and restarts + if (target.result.os.tag != .windows) { + const children = b.addOptions(); + children.addOptionPath("path", fake_serve.getEmittedBin()); + const router = b.createModule(.{ .root_source_file = b.path("zig/src/server/router_serve_test.zig"), .target = target, .optimize = .Debug, .link_libc = true }); + for (server.import_table.keys(), server.import_table.values()) |name, module| router.addImport(name, module); + router.addOptions("fake_serve_exe", children); + const run = b.addRunArtifact(b.addTest(.{ .root_module = router, .filters = &.{"serve --router: real serve children"} })); + run.setCwd(b.path(".")); + run.has_side_effects = true; // it starts processes and reads zig/tests/server/fixtures + b.step("test-router-serve-host", "serve --router over fake_serve children: their own keys, replies, --max-loaded and restarts").dependOn(&run.step); + } const security = b.step("test-server-security", "API authentication and hostile HTTP framing on the CPU"); const wire = b.addSystemCommand(&.{"python3"}); wire.addFileArg(b.path("zig/tests/server/security_check.py")); diff --git a/zig/src/cli/cli.zig b/zig/src/cli/cli.zig index 3afcf3e3cf8..caaa1507a1b 100644 --- a/zig/src/cli/cli.zig +++ b/zig/src/cli/cli.zig @@ -25,6 +25,11 @@ const usage = \\ ; +/// The cached checkpoints `models` lists, by repo id: a router's models when it has no config. +pub const cachedRepos = @import("hub.zig").cachedRepos; +/// One checkpoint's memory floor and weights as `info` computes them: a router's memory check. +pub const memory = info.memory; + /// True when argv starts with a checkpoint subcommand. pub fn wants(args: []const []const u8) bool { if (args.len == 0) return false; diff --git a/zig/src/cli/hub.zig b/zig/src/cli/hub.zig index b775d72fd9a..11c0d719bae 100644 --- a/zig/src/cli/hub.zig +++ b/zig/src/cli/hub.zig @@ -255,6 +255,26 @@ pub fn isDir(io: std.Io, path: []const u8) bool { return true; } +/// The cache's repos whose snapshot a Zig family serves, by id, as `tensorfold models` lists them; none without one. +pub fn cachedRepos(a: Allocator, io: std.Io, env: ?*const std.process.Environ.Map) ![]const []const u8 { + const root = try cacheDir(a, env, null); + var dir = std.Io.Dir.cwd().openDir(io, root, .{ .iterate = true }) catch return &.{}; + defer dir.close(io); + var out: std.ArrayList([]const u8) = .empty; + var it = dir.iterate(); + while (try it.next(io)) |entry| { + // models--Org--Name: the first double dash after the prefix separates the owner from the name + if (entry.kind != .directory or !std.mem.startsWith(u8, entry.name, "models--")) continue; + const rest = entry.name["models--".len..]; + const sep = std.mem.indexOf(u8, rest, "--") orelse continue; + if (sep == 0 or sep + 2 >= rest.len) continue; + const repo = try std.fmt.allocPrint(a, "{s}/{s}", .{ rest[0..sep], rest[sep + 2 ..] }); + const snapshot = (try cachedSnapshot(a, io, root, repo)) orelse continue; + if (family(modelType(a, io, snapshot)) != null) try out.append(a, repo); + } + return out.items; +} + fn readSmall(a: Allocator, io: std.Io, path: []const u8) ?[]u8 { return std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(16 << 20)) catch null; } @@ -339,3 +359,25 @@ test "a checkpoint's size counts shards in a folder inside it" { const dir = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}", .{tmp.sub_path}); try std.testing.expectEqual(@as(u64, 9), try sizeOf(gpa, io, dir)); } + +test "hub: the cache's repos are the ones a Zig family serves, as models lists them, and none without a cache" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = std.testing.io; + const root = try std.fmt.allocPrint(a, ".tf-hub-repos-test-{d}", .{std.Io.Clock.awake.now(io).toNanoseconds()}); + defer std.Io.Dir.cwd().deleteTree(io, root) catch {}; + const w = std.Io.Dir.cwd(); + for ([_][2][]const u8{ .{ "models--Org--Flash", "qwen4_exp" }, .{ "models--Org--Draft", "gemma3n" } }) |repo| { + try w.createDirPath(io, try std.fs.path.join(a, &.{ root, repo[0], "snapshots/rev1" })); + try w.writeFile(io, .{ .sub_path = try std.fs.path.join(a, &.{ root, repo[0], "snapshots/rev1/config.json" }), .data = try std.fmt.allocPrint(a, "{{\"model_type\": \"{s}\"}}", .{repo[1]}) }); + } + try w.createDirPath(io, try std.fs.path.join(a, &.{ root, "datasets--Org--Data/snapshots/rev1" })); + var env: std.process.Environ.Map = .init(a); + try env.put("HF_HUB_CACHE", root); + const got = try cachedRepos(a, io, &env); + try std.testing.expectEqual(@as(usize, 1), got.len); + try std.testing.expectEqualStrings("Org/Flash", got[0]); + try env.put("HF_HUB_CACHE", try std.fs.path.join(a, &.{ root, "missing" })); + try std.testing.expectEqual(@as(usize, 0), (try cachedRepos(a, io, &env)).len); +} diff --git a/zig/src/cli/info.zig b/zig/src/cli/info.zig index 35de28f6559..1a4857709d0 100644 --- a/zig/src/cli/info.zig +++ b/zig/src/cli/info.zig @@ -66,8 +66,8 @@ pub fn runStart(a: Allocator, io: std.Io, out: *std.Io.Writer, env: ?*const std. try out.print("{s}: no registered Zig family serves model_type {s}; the 0.6 line may: tensorfold@0.6\n", .{ model, model_type }); return 1; }; - const flash_metal = @import("builtin").os.tag == .macos and std.mem.eql(u8, model_type, "qwen4_exp"); - const weights = if (flash_metal) try @import("flashnext_memory").weightBytes(checkpoint, a, io, dir) else try hub.sizeOf(a, io, dir); + const flash_metal = flashMetal(model_type); + const weights = try weightBytes(a, io, dir, model_type); const details = hub.configDetails(a, io, dir); defer if (details.modelopt_formats) |formats| { for (formats) |format| a.free(format); @@ -96,9 +96,7 @@ pub fn runStart(a: Allocator, io: std.Io, out: *std.Io.Writer, env: ?*const std. } try out.print("weights: {d:.2} GiB ({d} bytes)\n", .{ @as(f64, @floatFromInt(weights)) / GiB, weights }); if (flash_metal) { - const memory = @import("flashnext_memory"); - const inventory = try memory.weights_plan.read(core.Checkpoint, core.quant.mlx, a, io, dir); - const plan = try memory.budget(weights, memory.trained, inventory, 0); + const plan = try flashBudget(a, io, dir, weights); try out.print("startup budget: {d:.2} GiB (conservative raw/packed text weights, both prompt planes/selectors, KV/state, keepalive and {d} GiB runtime reserve; trained window)\n", .{ @as(f64, @floatFromInt(plan.steady)) / GiB, runtime_margin >> 30 }); try out.print("cold pack budget: {d:.2} GiB (source pages, one output phase and conversion scratch; skipped with a validated pack; vision and requested storage are additional at load)\n", .{@as(f64, @floatFromInt(plan.building)) / GiB}); } else if (try qwen27(a, io, out, model_type, dir, weights, start)) |code| return code else try out.print("memory floor: {d:.2} GiB (weights plus a {d:.2} GiB runtime margin)\n", .{ @@ -145,6 +143,32 @@ fn gib(bytes: u64) f64 { return @as(f64, @floatFromInt(bytes)) / GiB; } +/// Flash Next on Metal reports a startup budget in place of the floor. +fn flashMetal(model_type: []const u8) bool { + return @import("builtin").os.tag == .macos and std.mem.eql(u8, model_type, "qwen4_exp"); +} + +/// The weights `run` prints for a checkpoint of `model_type`. +fn weightBytes(a: Allocator, io: std.Io, dir: []const u8, model_type: []const u8) !u64 { + return if (flashMetal(model_type)) try @import("flashnext_memory").weightBytes(checkpoint, a, io, dir) else try hub.sizeOf(a, io, dir); +} + +fn flashBudget(a: Allocator, io: std.Io, dir: []const u8, weights: u64) !@import("flashnext_memory").Budget { + const flash = @import("flashnext_memory"); + const inventory = try flash.weights_plan.read(core.Checkpoint, core.quant.mlx, a, io, dir); + return flash.budget(weights, flash.trained, inventory, 0); +} + +/// What `run` prints as the floor (the startup budget for Flash Next on Metal) and the weights; null when unreadable. +pub fn memory(a: Allocator, io: std.Io, dir: []const u8) ?struct { floor: u64, weights: u64 } { + const model_type = hub.modelType(a, io, dir); + const weights = weightBytes(a, io, dir, model_type) catch return null; + if (weights == 0) return null; + if (!flashMetal(model_type)) return .{ .floor = weights + runtime_margin, .weights = weights }; + const plan = flashBudget(a, io, dir, weights) catch return null; + return .{ .floor = plan.steady, .weights = weights }; +} + test "info prints family, format, context, weights and floor for a cached checkpoint" { var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena_state.deinit(); @@ -204,6 +228,27 @@ fn runConfig(a: Allocator, io: std.Io, config: []const u8) ![]const u8 { return out.toOwnedSlice(); } +test "info prints family: the floor a router reads is the one info prints, and an empty folder has none" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try tmp.dir.realPathFileAlloc(io, ".", a); + try std.testing.expect(memory(a, io, dir) == null); + try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = "{\"model_type\": \"llama\"}" }); + const weights: [4096]u8 = @splat('x'); + try tmp.dir.writeFile(io, .{ .sub_path = "model.safetensors", .data = &weights }); + const got = memory(a, io, dir).?; + try std.testing.expectEqual(try hub.sizeOf(a, io, dir), got.weights); + try std.testing.expectEqual(got.weights + runtime_margin, got.floor); + var out: std.Io.Writer.Allocating = .init(a); + if (hub.family("llama") == null) return; // a build without the family prints a refusal, not a floor + try std.testing.expectEqual(@as(u8, 0), try run(a, io, &out.writer, null, null, dir)); + try std.testing.expect(has(out.written(), try std.fmt.allocPrint(a, "memory floor: {d:.2} GiB", .{@as(f64, @floatFromInt(got.floor)) / GiB}))); +} + test "info names Bolt and its sorted modelopt formats" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); diff --git a/zig/src/server/auth_gate.zig b/zig/src/server/auth_gate.zig new file mode 100644 index 00000000000..0b5bee771e2 --- /dev/null +++ b/zig/src/server/auth_gate.zig @@ -0,0 +1,50 @@ +//! The key gate before any route: a server's and a router's, with 401 for a gated path without a valid key. +const std = @import("std"); +const auth = @import("auth.zig"); +const scope = @import("auth_scope.zig"); +const http_conn = @import("http_conn.zig"); +const Allocator = std.mem.Allocator; + +/// Whether ``conn`` may go on to its route; a refusal is sent here (``Authenticated._authenticate``). +pub fn admit(store: ?*auth.Store, conn: *http_conn.Conn, a: Allocator) bool { + const keys = store orelse return true; + if (std.mem.eql(u8, conn.method, "OPTIONS") or !keys.enabled()) return true; + const matched = keys.matchIdentity(a, single(conn, "Authorization"), single(conn, "x-api-key")); + if (matched) |m| { + conn.key_label = m.label; + conn.key_digest = m.digest; + conn.key_scopes = m.scopes; + } + if (!auth.gatedRequest(conn.method, conn.path, keys.metrics_open)) return true; + const path = auth.routePath(conn.path); + // a Responses WebSocket upgrade opens with an inference key; the socket checks each response.create again + const upgrade = @import("ws_upgrade.zig").requested(conn) and std.mem.eql(u8, @import("responses.zig").route(path) orelse "-", ""); + if (matched != null and (scope.allows(conn.key_scopes, conn.method, conn.path) or (upgrade and scope.allowsUpgrade(conn.key_scopes)))) return true; + const messages = for ([_][]const u8{ "/v1/messages", "/v1/messages/count_tokens", "/messages", "/messages/count_tokens" }) |p| { + if (std.mem.eql(u8, path, p)) break true; + } else false; + if (matched != null) { + // a key without this route's scope is refused before its body is read or a parked model wakes + @import("auth_scope_reply.zig").deny(conn, messages, .route); + return false; + } + const body = if (messages) + "{\"type\": \"error\", \"error\": {\"type\": \"authentication_error\", \"message\": \"A valid API key is required\"}}" + else + "{\"error\": {\"message\": \"A valid API key is required\", \"type\": \"invalid_request_error\", \"param\": null, \"code\": \"invalid_api_key\"}}"; + conn.close = true; + conn.startResponse(401, null) catch return false; + conn.addHeader("WWW-Authenticate", "Bearer") catch return false; + conn.addHeader("Content-Type", "application/json") catch return false; + var len: [24]u8 = undefined; + conn.addHeader("Content-Length", std.fmt.bufPrint(&len, "{d}", .{body.len}) catch unreachable) catch return false; + conn.addHeader("Connection", "close") catch return false; + conn.finish(if (std.mem.eql(u8, conn.method, "HEAD")) "" else body) catch {}; + return false; +} + +/// A header that appears exactly once; none or several read as absent (as the key match reads them). +fn single(conn: *const http_conn.Conn, name: []const u8) ?[]const u8 { + if (conn.headerCount(name) != 1) return null; + return conn.header(name); +} diff --git a/zig/src/server/benchmark_server.zig b/zig/src/server/benchmark_server.zig index 95593bdc462..0e5a6a5d25b 100644 --- a/zig/src/server/benchmark_server.zig +++ b/zig/src/server/benchmark_server.zig @@ -40,8 +40,19 @@ pub const Options = struct { /// The child's only API key: TENSORFOLD_API_KEY in its environment and the probes' bearer (none for a benchmark). key: ?[]const u8 = null, words: Words = .{}, + /// The child's environment before ``key`` is added, in place of ``environ``'s copy of the parent's. + environ: ?*const std.process.Environ.Map = null, + /// A second Ctrl-C kills the child, a command's one; false: one of a router's several. + guard: bool = true, + /// Ends the startup wait early, as a benchmark's stop signal does. + stop: ?*const std.atomic.Value(bool) = null, + /// Why ``spawn`` gave no child. + failure: ?*Failure = null, }; +/// What ended a ``spawn`` that gave no child: its lock or log, the spawn, an early exit, the timeout or a stop. +pub const Failure = enum { none, setup, spawn, exited, timeout, stopped }; + /// The startup timeout without --startup-timeout: 600 s, plus 6 s per GB of weights past 20 GB, at most 3600 s. pub fn startupTimeout(weight_bytes: u64) f64 { const gb = @as(f64, @floatFromInt(weight_bytes)) / 1e9; @@ -71,8 +82,13 @@ pub fn argv(a: Allocator, plan: Plan) ![]const []const u8 { /// Parent variables minus the API key, request log, journal, seed salt and upload token; no live line or update check. pub fn environ(a: Allocator, parent: *const std.process.Environ.Map) !std.process.Environ.Map { + return environWithout(a, parent, &.{ "TENSORFOLD_API_KEY", "TENSORFOLD_REQUEST_LOG", "TENSORFOLD_REQUEST_JOURNAL", "TENSORFOLD_SEED_SALT", "TENSORFOLD_BENCHMARK_TOKEN" }); +} + +/// The parent's variables without ``drop``, with no live line, update check or Hugging Face download. +pub fn environWithout(a: Allocator, parent: *const std.process.Environ.Map, drop: []const []const u8) !std.process.Environ.Map { var env = try parent.clone(a); - for ([_][]const u8{ "TENSORFOLD_API_KEY", "TENSORFOLD_REQUEST_LOG", "TENSORFOLD_REQUEST_JOURNAL", "TENSORFOLD_SEED_SALT", "TENSORFOLD_BENCHMARK_TOKEN" }) |k| _ = env.orderedRemove(k); + for (drop) |k| _ = env.orderedRemove(k); try env.put("TENSORFOLD_NO_LIVE", "1"); try env.put("TENSORFOLD_NO_UPDATE_CHECK", "1"); try env.put("HF_HUB_OFFLINE", "1"); @@ -143,6 +159,8 @@ pub const Managed = struct { base_url: []const u8 = "", reaped: bool = false, closed: bool = false, + /// The wait status ``exited`` reaped, once it has. + status: c_int = 0, /// Spawns the benchmark's child and waits until it serves its name; null with ``problem`` set, or "" when stopped. pub fn start(a: Allocator, io: std.Io, env: *const std.process.Environ.Map, plan: Plan, o: Options, problem: *[]const u8) !?Managed { @@ -151,17 +169,18 @@ pub const Managed = struct { /// Spawns ``child_argv`` and waits until it serves ``o.served``; null with ``problem`` set, or "" when stopped. pub fn spawn(a: Allocator, io: std.Io, env: *const std.process.Environ.Map, child_argv: []const []const u8, o: Options, problem: *[]const u8) !?Managed { + if (o.failure) |f| f.* = .none; var rand: [8]u8 = undefined; io.random(&rand); const log_path = try std.fmt.allocPrint(a, "{s}/.serve-{s}.log", .{ o.bench_dir, std.fmt.bytesToHex(rand, .lower) }); - var child_env = try environ(a, env); + var child_env = if (o.environ) |base_env| try base_env.clone(a) else try environ(a, env); if (o.key) |k| try child_env.put("TENSORFOLD_API_KEY", k); - const lock = if (o.lock) lockRun(io, o.bench_dir, problem) orelse return null else null; + const lock = if (o.lock) lockRun(io, o.bench_dir, problem) orelse return failed(o, .setup) else null; const cwd = std.Io.Dir.cwd(); const log = cwd.createFile(io, log_path, .{ .exclusive = true, .read = true, .permissions = .fromMode(0o600) }) catch { if (lock) |l| l.close(io); problem.* = o.words.log; - return null; + return failed(o, .setup); }; const group: ?posix.pid_t = if (o.own_group) 0 else null; const child = std.process.spawn(io, .{ .argv = child_argv, .environ_map = &child_env, .stdin = .ignore, .stdout = .{ .file = log }, .stderr = .{ .file = log }, .pgid = group }) catch { @@ -169,12 +188,12 @@ pub const Managed = struct { log.close(io); if (lock) |l| l.close(io); problem.* = o.words.spawn; - return null; + return failed(o, .spawn); }; - stop_flag.guardChild(child.id.?); + if (o.guard) stop_flag.guardChild(child.id.?); cwd.deleteFile(io, log_path) catch {}; var m: Managed = .{ .io = io, .pid = child.id.?, .log = log, .lock = lock, .grace_ms = o.grace_ms, .served = o.served, .stuck = o.words.stuck, .key = o.key }; - const ok = m.ready(a, o.startup_timeout_s, o.tail, o.words, problem) catch |e| { + const ok = m.ready(a, o, problem) catch |e| { _ = m.stop(); return e; }; @@ -183,21 +202,28 @@ pub const Managed = struct { return null; } - fn ready(m: *Managed, a: Allocator, timeout_s: f64, tail: ?*[]const []const u8, words: Words, problem: *[]const u8) !bool { + fn failed(o: Options, why: Failure) ?Managed { + if (o.failure) |f| f.* = why; + return null; + } + + fn ready(m: *Managed, a: Allocator, o: Options, problem: *[]const u8) !bool { var client: std.http.Client = .{ .allocator = std.heap.smp_allocator, .io = m.io }; client.connection_pool.free_size = 0; defer client.deinit(); - const deadline = stream.deadlineAfter(m.io, timeout_s); + const deadline = stream.deadlineAfter(m.io, o.startup_timeout_s); var port: ?u16 = null; var buf: [64 << 10]u8 = undefined; while (stream.now(m.io) < deadline) { - if (stop_flag.requested() != null) { + if (stop_flag.requested() != null or (if (o.stop) |s| s.load(.acquire) else false)) { problem.* = ""; + _ = failed(o, .stopped); return false; } if (m.exited()) { - problem.* = words.exited; - if (tail) |t| t.* = try lastLines(a, m.logEnd(&buf)); + problem.* = o.words.exited; + if (o.tail) |t| t.* = try lastLines(a, m.logEnd(&buf)); + _ = failed(o, .exited); return false; } if (port == null) { @@ -207,7 +233,8 @@ pub const Managed = struct { if (port != null and try probe(a, m.io, &client, m.base_url, m.served, m.key)) return true; m.io.sleep(.fromMilliseconds(200), .awake) catch {}; } - problem.* = try std.fmt.allocPrint(a, "{s} {d} s (--startup-timeout, at most 3600); check the checkpoint, GPU memory and backend toolchain", .{ words.timed_out, timeout_s }); + problem.* = try std.fmt.allocPrint(a, "{s} {d} s (--startup-timeout, at most 3600); check the checkpoint, GPU memory and backend toolchain", .{ o.words.timed_out, o.startup_timeout_s }); + _ = failed(o, .timeout); return false; } @@ -264,6 +291,7 @@ pub const Managed = struct { const rc = platform.c.waitpid(m.pid, &status, 0); if (rc >= 0 or posix.errno(rc) != .INTR) break; } + m.status = status; m.reaped = true; return true; } diff --git a/zig/src/server/benchmark_server_test.zig b/zig/src/server/benchmark_server_test.zig index 7d5aad161c5..2437b14d402 100644 --- a/zig/src/server/benchmark_server_test.zig +++ b/zig/src/server/benchmark_server_test.zig @@ -232,6 +232,44 @@ test "only a child given a key gets TENSORFOLD_API_KEY and probes with it; the b for (probes..f.count()) |i| try std.testing.expectEqualStrings("Bearer child-key", f.header(i, "authorization").?); } +test "a router's child: its own environment and key, no Ctrl-C guard, a stop that ends the wait, each failure named" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var s = try Setup.init(a, &tmp); + try s.env.put("TENSORFOLD_SEED_SALT", "parent-salt"); + var own: std.process.Environ.Map = .init(a); + try own.put("PATH", "/usr/bin:/bin"); + try own.put("TENSORFOLD_SEED_SALT", "router-salt"); + const routes = try healthy(a, "{\"status\": \"ok\"}", "alpha"); + const f = try fake.Fake.start(std.testing.allocator, &routes); + defer f.stop(); + const seen = try std.fs.path.join(a, &.{ s.dir, "env" }); + const ready = try std.fmt.allocPrint(a, "printf '%s %s' \"$TENSORFOLD_SEED_SALT\" \"$TENSORFOLD_API_KEY\" > {s}; printf '[tensorfold] serving alpha at http://127.0.0.1:%s/v1 (x)\\n' {d}; exec sleep 30", .{ seen, f.port }); + var failure: server.Failure = .timeout; + var problem: []const u8 = ""; + const guarded = stop.guardedChild(); + const o: server.Options = .{ .startup_timeout_s = 10, .grace_ms = 2_000, .bench_dir = s.dir, .served = "alpha", .lock = false, .own_group = true, .key = "child-key", .environ = &own, .guard = false, .failure = &failure }; + var m = (try server.Managed.spawn(a, std.testing.io, &s.env, try a.dupe([]const u8, &.{ "/bin/sh", "-c", ready }), o, &problem)) orelse return error.TestUnexpectedResult; + try std.testing.expect(failure == .none and stop.guardedChild() == guarded); + try std.testing.expect(m.stop() == null and gone(m.pid)); + try std.testing.expectEqualStrings("router-salt child-key", try std.Io.Dir.cwd().readFileAlloc(std.testing.io, seen, a, .limited(256))); + var halt: std.atomic.Value(bool) = .init(true); + var early = o; + early.stop = &halt; + early.startup_timeout_s = 30; + try none(try server.Managed.spawn(a, std.testing.io, &s.env, try a.dupe([]const u8, &.{ "/bin/sh", "-c", "exec sleep 30" }), early, &problem)); + try std.testing.expect(failure == .stopped and problem.len == 0); + try none(try server.Managed.spawn(a, std.testing.io, &s.env, try a.dupe([]const u8, &.{ "/bin/sh", "-c", "exit 3" }), o, &problem)); + try std.testing.expect(failure == .exited); + var late = o; + late.startup_timeout_s = 0.3; + try none(try server.Managed.spawn(a, std.testing.io, &s.env, try a.dupe([]const u8, &.{ "/bin/sh", "-c", "exec sleep 30" }), late, &problem)); + try std.testing.expect(failure == .timeout); +} + test "the startup timeout grows with the weights past 20 GB, 6 s per GB from 600 s, to 3600 s" { try std.testing.expectEqual(@as(f64, 600), server.startupTimeout(0)); try std.testing.expectEqual(@as(f64, 600), server.startupTimeout(20_000_000_000)); diff --git a/zig/src/server/cli_config.zig b/zig/src/server/cli_config.zig index fc3316ab9cd..84f49bfcb1f 100644 --- a/zig/src/server/cli_config.zig +++ b/zig/src/server/cli_config.zig @@ -24,32 +24,37 @@ pub const Expanded = struct { }; /// ``--config`` on the command line: its file, its place (`width` tokens from `at`) and whether a model is named. -pub const Found = struct { path: []const u8, at: usize, width: usize, model: bool }; +pub const Found = struct { path: []const u8, at: usize, width: usize, model: bool, flag: []const u8 = "--config" }; /// ``serve``'s arguments with ``--config FILE.toml`` replaced by the file's flags, ahead of the command line's. pub fn expand(a: Allocator, argv: []const []const u8, u: *cli.Usage) Error!Expanded { const found = try locate(a, argv, u) orelse return .{ .argv = argv }; - const path = found.path; + const file = try read(a, found.path, found.flag, u); + const out = try merge(a, argv, found, file.text, u); + if (out.secret != 0 and file.mode & 0o044 != 0) + return cli.fail(u, a, "argument --config: {s} line {d}: api-key is set in a file other users can read (mode 0{o}); use chmod 600, or api-key-file", .{ found.path, out.secret, file.mode & 0o7777 }); + return out; +} + +/// A settings file's text and mode: opened once without following a link, a regular file others cannot write. +pub fn read(a: Allocator, path: []const u8, flag: []const u8, u: *cli.Usage) Error!struct { text: []const u8, mode: u32 } { // opened once: the handle that is checked is the one that is read, and a link is not followed const fd = auth.openKeys(try a.dupeSentinel(u8, path, 0)) catch |e| - return cli.fail(u, a, "argument --config: cannot open {s} ({s}); name an existing file, not a link", .{ path, @errorName(e) }); + return cli.fail(u, a, "argument {s}: cannot open {s} ({s}); name an existing file, not a link", .{ flag, path, @errorName(e) }); defer _ = platform.c.close(fd); - const st = file_meta(fd, null) orelse return cli.fail(u, a, "argument --config: cannot read the mode of {s}", .{path}); - if (st.mode & platform.c.S.IFMT != platform.c.S.IFREG) return cli.fail(u, a, "argument --config: {s} is not a regular file", .{path}); + const st = file_meta(fd, null) orelse return cli.fail(u, a, "argument {s}: cannot read the mode of {s}", .{ flag, path }); + if (st.mode & platform.c.S.IFMT != platform.c.S.IFREG) return cli.fail(u, a, "argument {s}: {s} is not a regular file", .{ flag, path }); if (st.mode & 0o022 != 0) - return cli.fail(u, a, "argument --config: {s} can be written by other users (mode 0{o}): it chooses what is served; use chmod go-w", .{ path, st.mode & 0o7777 }); + return cli.fail(u, a, "argument {s}: {s} can be written by other users (mode 0{o}): it chooses what is served; use chmod go-w", .{ flag, path, st.mode & 0o7777 }); const text = try a.alloc(u8, limit + 1); var got: usize = 0; while (got < text.len) { - const n = auth.readKeys(fd, text[got..]) catch |e| return cli.fail(u, a, "argument --config: cannot read {s} ({s})", .{ path, @errorName(e) }); + const n = auth.readKeys(fd, text[got..]) catch |e| return cli.fail(u, a, "argument {s}: cannot read {s} ({s})", .{ flag, path, @errorName(e) }); if (n == 0) break; got += n; } - if (got > limit) return cli.fail(u, a, "argument --config: {s} is over 1 MiB", .{path}); - const out = try merge(a, argv, found, text[0..got], u); - if (out.secret != 0 and st.mode & 0o044 != 0) - return cli.fail(u, a, "argument --config: {s} line {d}: api-key is set in a file other users can read (mode 0{o}); use chmod 600, or api-key-file", .{ path, out.secret, st.mode & 0o7777 }); - return out; + if (got > limit) return cli.fail(u, a, "argument {s}: {s} is over 1 MiB", .{ flag, path }); + return .{ .text = text[0..got], .mode = st.mode }; } /// One argument of ``serve`` as ``cli.parse`` consumes it: a positional (no name), or a flag with its value. @@ -115,8 +120,13 @@ pub fn merge(a: Allocator, argv: []const []const u8, found: Found, text: []const var problem: toml.Problem = .{}; const entries = toml.parse(a, text, &problem) catch |e| switch (e) { error.OutOfMemory => |x| return x, - error.Invalid => return cli.fail(u, a, "argument --config: {s} line {d}: {s}", .{ found.path, problem.line, problem.message }), + error.Invalid => return cli.fail(u, a, "argument {s}: {s} line {d}: {s}", .{ found.flag, found.path, problem.line, problem.message }), }; + return mergeEntries(a, argv, found, entries, u); +} + +/// ``merge`` of entries already read: each key's flag, checked as it is on the command line, ahead of ``argv``. +pub fn mergeEntries(a: Allocator, argv: []const []const u8, found: Found, entries: []const toml.Entry, u: *cli.Usage) Error!Expanded { var out: std.ArrayList([]const u8) = .empty; var seen: std.ArrayList([]const u8) = .empty; var model: ?[]const u8 = null; @@ -125,7 +135,7 @@ pub fn merge(a: Allocator, argv: []const []const u8, found: Found, text: []const for (entries) |entry| { var scratch: cli.Args = .{}; // one entry's values, read as parse reads them, so its checks see the whole list var repeated: cli.Repeated = .{}; - const at: Where = .{ .a = a, .u = u, .path = found.path, .line = entry.line, .scratch = &scratch, .repeated = &repeated }; + const at: Where = .{ .a = a, .u = u, .flag = found.flag, .path = found.path, .line = entry.line, .scratch = &scratch, .repeated = &repeated }; const key = try a.dupe(u8, entry.key); std.mem.replaceScalar(u8, key, '_', '-'); if (std.mem.eql(u8, key, "model")) { @@ -179,13 +189,14 @@ pub fn note(a: Allocator, e: Expanded) error{OutOfMemory}!?[]const u8 { const Where = struct { a: Allocator, u: *cli.Usage, + flag: []const u8, path: []const u8, line: u32, scratch: *cli.Args, repeated: *cli.Repeated, fn fail(w: Where, comptime fmt: []const u8, args: anytype) Error { - return cli.fail(w.u, w.a, "argument --config: {s} line {d}: " ++ fmt, .{ w.path, w.line } ++ args); + return cli.fail(w.u, w.a, "argument {s}: {s} line {d}: " ++ fmt, .{ w.flag, w.path, w.line } ++ args); } /// The flag's own check of this value, as on the command line, so its refusal names the file's line. diff --git a/zig/src/server/main.zig b/zig/src/server/main.zig index e1e0d5e0a9f..28a216ce0d3 100644 --- a/zig/src/server/main.zig +++ b/zig/src/server/main.zig @@ -73,7 +73,7 @@ pub fn main(init: std.process.Init) !u8 { // help and a bare run lead with what this machine runs: the saved profile, or a quick scan with no driver if (argv.len == 2 and (std.mem.eql(u8, argv[1], "--help") or std.mem.eql(u8, argv[1], "-h") or std.mem.eql(u8, argv[1], "help"))) { try std.Io.File.stdout().writeStreamingAll(io, device_cli.summary(init)); - try std.Io.File.stdout().writeStreamingAll(io, "usage: tensorfold-native --version | capabilities --json | device [--json] [--rescan] | models [--json] | info MODEL | pull REPO[@REVISION] | rm REPO[@REVISION] | log [list|show ID|follow] [PATH] | slide rollback FOLDER | web [ARGS...] | launch [args...] | slide audit [flags] | serve MODEL [flags] | benchmark MODEL [flags] | chat [MODEL] [flags]\n" ++ usage_line); + try std.Io.File.stdout().writeStreamingAll(io, "usage: tensorfold-native --version | capabilities --json | device [--json] [--rescan] | models [--json] | info MODEL | pull REPO[@REVISION] | rm REPO[@REVISION] | log [list|show ID|follow] [PATH] | slide rollback FOLDER | web [ARGS...] | launch [args...] | slide audit [flags] | serve MODEL [flags] | serve --router [flags] | benchmark MODEL [flags] | chat [MODEL] [flags]\n" ++ usage_line); return 0; } if (argv.len >= 2 and std.mem.eql(u8, argv[1], "device")) return device_cli.main(init, argv[2..]); @@ -87,6 +87,13 @@ pub fn main(init: std.process.Init) !u8 { defer launch_writer.interface.flush() catch {}; return launch_cli.command(&.{ .a = a, .io = io, .environ = init.environ_map, .out = &launch_writer.interface }, argv[2..]); } + if (argv.len >= 3 and std.mem.eql(u8, argv[1], "serve") and @import("router/args.zig").wanted(@ptrCast(argv[2..]))) { + // the router runs its children under POSIX signals and process groups; Windows refuses it by name + if (comptime @import("builtin").os.tag == .windows) { + std.debug.print("tensorfold serve --router is not supported on Windows yet: run tensorfold serve MODEL for each model\n", .{}); + return 2; + } else return @import("router/router.zig").main(init, @ptrCast(argv[2..]), .{ .repos = RouterCheckpoints.repos, .memory = RouterCheckpoints.memory }, @import("build_options").version); + } if (argv.len >= 3 and std.mem.eql(u8, argv[1], "serve")) { for (argv[2..]) |arg| if (std.mem.eql(u8, arg, "--help") or std.mem.eql(u8, arg, "-h")) { try std.Io.File.stdout().writeStreamingAll(io, usage_line); @@ -117,7 +124,7 @@ pub fn main(init: std.process.Init) !u8 { // a chat with a running server works on every platform; chat_cli.zig refuses its own serve child on Windows if (argv.len >= 2 and std.mem.eql(u8, argv[1], "chat")) return chat_cli.main(init, argv[2..]); if (argv.len < 2 or !std.mem.eql(u8, argv[1], "serve")) { - std.debug.print("{s}usage: tensorfold-native capabilities --json | device [--json] [--rescan] | models [--json] | info MODEL | pull REPO[@REVISION] | rm REPO[@REVISION] | log [list|show ID|follow] [PATH] | slide rollback FOLDER | launch [args...] | slide audit [flags] | serve MODEL [flags] | benchmark MODEL [flags] | chat [MODEL] [flags]\n", .{if (argv.len < 2) device_cli.summary(init) else ""}); + std.debug.print("{s}usage: tensorfold-native capabilities --json | device [--json] [--rescan] | models [--json] | info MODEL | pull REPO[@REVISION] | rm REPO[@REVISION] | log [list|show ID|follow] [PATH] | slide rollback FOLDER | launch [args...] | slide audit [flags] | serve MODEL [flags] | serve --router [flags] | benchmark MODEL [flags] | chat [MODEL] [flags]\n", .{if (argv.len < 2) device_cli.summary(init) else ""}); return 2; } const started = std.Io.Clock.awake.now(io).toNanoseconds(); @@ -311,3 +318,14 @@ fn samplingFlags(args: cli.Args) @import("family_sampling.zig").Flags { } const Closer = @import("idle_unload_closer.zig").Closer; + +/// What the router reads through ``tensorfold models`` and ``tensorfold info``, from the checkpoint commands. +const RouterCheckpoints = struct { + fn repos(a: std.mem.Allocator, io: std.Io, env: ?*const std.process.Environ.Map) anyerror![]const []const u8 { + return checkpoint_cli.cachedRepos(a, io, env); + } + fn memory(a: std.mem.Allocator, io: std.Io, dir: []const u8) ?@import("router/catalog.zig").Memory { + const m = checkpoint_cli.memory(a, io, dir) orelse return null; + return .{ .floor = m.floor, .weights = m.weights }; + } +}; diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index fcebf9e0b01..af9899aec8c 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -94,6 +94,7 @@ test { _ = @import("compact_at_cli_test.zig"); _ = @import("toml_flat_test.zig"); _ = @import("cli_config_test.zig"); + if (comptime @import("builtin").os.tag != .windows) _ = @import("router/router_test.zig"); // spawns /bin/sh children _ = @import("unix_socket_cli_test.zig"); _ = @import("effort_cli_audit_test.zig"); _ = @import("live.zig"); diff --git a/zig/src/server/router/args.zig b/zig/src/server/router/args.zig new file mode 100644 index 00000000000..c20396244fd --- /dev/null +++ b/zig/src/server/router/args.zig @@ -0,0 +1,92 @@ +//! ``tensorfold serve --router`` flags: the router's own, the serve flags it shares, and the rest refused by name. +const std = @import("std"); +const cli = @import("../cli.zig"); +const Allocator = std.mem.Allocator; + +pub const usage_line = "usage: tensorfold serve --router [-h] [--router-config FILE.toml] [--max-loaded N] [--idle-unload SECONDS]" ++ + " [--host HOST] [--port PORT] [--api-key API_KEY] [--api-key-file API_KEY_FILE] [--allowed-host NAME] [--allowed-origin ORIGIN]\n"; + +/// The most children ``--max-loaded`` allows at once. +pub const max_loaded_limit = 64; + +pub const Settings = struct { + config: ?[]const u8 = null, + max_loaded: u32 = 1, + /// Seconds a child may sit idle before the router stops it (0: never), as ``--idle-unload`` reads them. + idle_s: i64 = 0, + host: []const u8 = "127.0.0.1", + port: u16 = 8080, + api_keys: []const []const u8 = &.{}, + api_key_file: ?[]const u8 = null, + allowed_hosts: []const []const u8 = &.{}, + allowed_origins: []const []const u8 = &.{}, +}; + +/// The serve flags the router reads as ``tensorfold serve`` does, with serve's own checks and messages. +const shared = [_][]const u8{ "--host", "--port", "--api-key", "--api-key-file", "--idle-unload", "--allowed-host", "--allowed-origin" }; + +/// Whether a serve command line asks for the router. +pub fn wanted(argv: []const []const u8) bool { + for (argv) |arg| if (std.mem.eql(u8, arg, "--router")) return true; + return false; +} + +/// Whether the command line asks for help, which needs no models. +pub fn help(argv: []const []const u8) bool { + for (argv) |arg| if (std.mem.eql(u8, arg, "--help") or std.mem.eql(u8, arg, "-h")) return true; + return false; +} + +/// The router's settings from its command line; a usage error names the flag, as ``cli.parse`` does. +pub fn parse(a: Allocator, argv: []const []const u8, u: *cli.Usage) error{ Usage, OutOfMemory }!Settings { + var out: Settings = .{}; + var scratch: cli.Args = .{}; + var repeated: cli.Repeated = .{}; + var i: usize = 0; + while (i < argv.len) : (i += 1) { + const token = argv[i]; + if (!std.mem.startsWith(u8, token, "--")) + return cli.fail(u, a, "unrecognized arguments: {s}: --router serves the models of --router-config or the cache and takes no MODEL", .{token}); + const eq = std.mem.indexOfScalar(u8, token, '='); + const name = token[0 .. eq orelse token.len]; + if (std.mem.eql(u8, name, "--router")) { + if (eq != null) return cli.fail(u, a, "argument --router: ignored explicit argument '{s}'", .{token[eq.? + 1 ..]}); + continue; + } + const own = std.mem.eql(u8, name, "--router-config") or std.mem.eql(u8, name, "--max-loaded"); + const flag = cli.find(name); + const is_shared = for (shared) |s| { + if (std.mem.eql(u8, s, name)) break true; + } else false; + if (!own and !is_shared) { + if (std.mem.eql(u8, name, "--config")) return cli.fail(u, a, "argument --config: with --router, models and their serve flags are listed in --router-config FILE.toml", .{}); + if (std.mem.eql(u8, name, "--name") or std.mem.eql(u8, name, "--alias")) return cli.fail(u, a, "argument {s}: with --router, each model answers to its id and aliases in --router-config FILE.toml", .{name}); + if (std.mem.eql(u8, name, "--unix-socket")) return cli.fail(u, a, "argument --unix-socket: the router listens on --host and --port only", .{}); + if (flag != null) return cli.fail(u, a, "argument {s}: a model's serve flag; with --router, set it on the model in --router-config FILE.toml", .{name}); + return cli.fail(u, a, "unrecognized arguments: {s}", .{token}); + } + const value = if (eq) |e| token[e + 1 ..] else blk: { + i += 1; + if (i >= argv.len) return cli.fail(u, a, "argument {s}: expected one argument", .{name}); + break :blk argv[i]; + }; + if (std.mem.eql(u8, name, "--router-config")) { + if (!std.ascii.endsWithIgnoreCase(value, ".toml")) return cli.fail(u, a, "argument --router-config: expected a .toml file: '{s}'", .{value}); + if (out.config != null) return cli.fail(u, a, "argument --router-config: given twice; the router reads one config file", .{}); + out.config = value; + } else if (std.mem.eql(u8, name, "--max-loaded")) { + const n = try cli.int(u, a, name, value); + if (n < 1 or n > max_loaded_limit) return cli.fail(u, a, "argument --max-loaded: expected 1 to {d} models: '{s}'", .{ max_loaded_limit, value }); + out.max_loaded = @intCast(n); + } else try cli.one(a, &scratch, &repeated, flag.?, value, u); + } + try @import("../cli_late.zig").check(a, scratch, &repeated, u); + out.idle_s = scratch.idle_unload; + out.host = scratch.host; + out.port = scratch.port; + out.api_keys = repeated.keys.items; + out.api_key_file = scratch.api_key_file; + out.allowed_hosts = repeated.hosts.items; + out.allowed_origins = repeated.origins.items; + return out; +} diff --git a/zig/src/server/router/catalog.zig b/zig/src/server/router/catalog.zig new file mode 100644 index 00000000000..1b68b65d3f0 --- /dev/null +++ b/zig/src/server/router/catalog.zig @@ -0,0 +1,177 @@ +//! The router's models: the names each answers to, the serve child that loads it and what loading it needs. +const std = @import("std"); +const cli = @import("../cli.zig"); +const hub = @import("../hub.zig"); +const benchmark_server = @import("../benchmark_server.zig"); +const log = @import("../log.zig"); +const Allocator = std.mem.Allocator; + +/// One model as a config table or the cache names it: its id, aliases, model folder or repo id and serve flags. +pub const Model = struct { + id: []const u8, + aliases: []const []const u8 = &.{}, + model: []const u8, + flags: []const []const u8 = &.{}, + /// The config line of its table's first key, for messages (0: from the cache). + line: u32 = 0, +}; + +/// One loadable model: its names, its child's whole command line and its memory floor. +pub const Entry = struct { + id: []const u8, + aliases: []const []const u8 = &.{}, + argv: []const []const u8, + /// Bytes it needs loaded (weights, drafter and runtime margin); null when there is no estimate. + floor: ?u64 = null, + /// Seconds its child gets to become ready, as the benchmark's child gets them for the same weights. + startup_s: f64 = 600, +}; + +/// One checkpoint's memory floor and weights, as ``tensorfold info`` computes them. +pub const Memory = struct { floor: u64, weights: u64 }; + +/// The checkpoint facts the router reads through ``tensorfold models`` and ``tensorfold info``. +pub const Checkpoints = struct { + repos: *const fn (Allocator, std.Io, ?*const std.process.Environ.Map) anyerror![]const []const u8, + memory: *const fn (Allocator, std.Io, []const u8) ?Memory, +}; + +/// The entry whose id or alias is ``name``. +pub fn find(entries: []const Entry, name: []const u8) ?usize { + for (entries, 0..) |e, i| { + if (std.mem.eql(u8, e.id, name)) return i; + for (e.aliases) |alias| if (std.mem.eql(u8, alias, name)) return i; + } + return null; +} + +/// Every cached checkpoint ``tensorfold models`` lists, each answering to its repo id. +pub fn cached(a: Allocator, io: std.Io, env: *const std.process.Environ.Map, checkpoints: Checkpoints) ![]const Model { + const repos = try checkpoints.repos(a, io, env); + const out = try a.alloc(Model, repos.len); + for (repos, out) |repo, *m| m.* = .{ .id = repo, .model = repo }; + return out; +} + +/// The child's command line: this binary serving ``m`` on 127.0.0.1 at a free port, named by its id and aliases. +pub fn childArgv(a: Allocator, exe: []const u8, m: Model) ![]const []const u8 { + var out: std.ArrayList([]const u8) = .empty; + try out.appendSlice(a, &.{ exe, "serve", m.model, "--host", "127.0.0.1", "--port", "0", "--name", m.id }); + for (m.aliases) |alias| try out.appendSlice(a, &.{ "--alias", alias }); + try out.appendSlice(a, m.flags); + return out.items; +} + +/// The entries for ``models``: each one resolved, its command line checked as serve checks it, its floor read. +pub fn build(a: Allocator, io: std.Io, env: *const std.process.Environ.Map, exe: []const u8, models: []const Model, checkpoints: Checkpoints, problem: *[]const u8) !?[]const Entry { + const out = try a.alloc(Entry, models.len); + for (models, out) |m, *e| e.* = try entry(a, io, env, exe, m, checkpoints, problem) orelse return null; + return out; +} + +/// ``build`` for the cache's models: one that ``serve`` would refuse is left out and logged, so the rest still serve. +pub fn buildCached(a: Allocator, io: std.Io, env: *const std.process.Environ.Map, exe: []const u8, models: []const Model, checkpoints: Checkpoints) ![]const Entry { + var out: std.ArrayList(Entry) = .empty; + for (models) |m| { + var problem: []const u8 = ""; + if (try entry(a, io, env, exe, m, checkpoints, &problem)) |e| try out.append(a, e) else log.line("not routing {s}", .{problem}); + } + return out.items; +} + +fn entry(a: Allocator, io: std.Io, env: *const std.process.Environ.Map, exe: []const u8, m: Model, checkpoints: Checkpoints, problem: *[]const u8) !?Entry { + const argv = try childArgv(a, exe, m); + var u: cli.Usage = .{}; + const parsed = cli.parse(a, argv[2..], &u) catch |err| switch (err) { + error.Usage => { + problem.* = try std.fmt.allocPrint(a, "model '{s}'{s}: {s}", .{ m.id, try where(a, m), u.message }); + return null; + }, + else => |x| return x, + }; + var why: []const u8 = ""; + const dir = try hub.resolve(a, io, env, m.model, &why) orelse { + problem.* = try std.fmt.allocPrint(a, "model '{s}'{s}: {s}", .{ m.id, try where(a, m), why }); + return null; + }; + var drafter: u64 = 0; + var known = true; + if (parsed.drafter) |d| { + const ddir = try hub.resolve(a, io, env, d, &why) orelse { + problem.* = try std.fmt.allocPrint(a, "model '{s}'{s}: drafter: {s}", .{ m.id, try where(a, m), why }); + return null; + }; + if (checkpoints.memory(a, io, ddir)) |dm| drafter = dm.weights else known = false; + } + var e: Entry = .{ .id = m.id, .aliases = m.aliases, .argv = argv }; + if (checkpoints.memory(a, io, dir)) |mem| { + if (known) e.floor = mem.floor + drafter; + e.startup_s = benchmark_server.startupTimeout(mem.weights + drafter); + } + return e; +} + +fn where(a: Allocator, m: Model) ![]const u8 { + return if (m.line > 0) std.fmt.allocPrint(a, " (line {d})", .{m.line}) else ""; +} + +test "serve --router: a name finds its model by id or alias, and the child serves it on loopback under those names" { + const entries = [_]Entry{ + .{ .id = "glm", .aliases = &.{ "glm-flash", "g" }, .argv = &.{} }, + .{ .id = "org/qwen", .argv = &.{} }, + }; + try std.testing.expectEqual(@as(?usize, 0), find(&entries, "glm")); + try std.testing.expectEqual(@as(?usize, 0), find(&entries, "g")); + try std.testing.expectEqual(@as(?usize, 1), find(&entries, "org/qwen")); + try std.testing.expectEqual(@as(?usize, null), find(&entries, "qwen")); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const argv = try childArgv(a, "/opt/example/tensorfold", .{ .id = "glm", .aliases = &.{"g"}, .model = "org/glm", .flags = &.{"--context=8192"} }); + const want = [_][]const u8{ "/opt/example/tensorfold", "serve", "org/glm", "--host", "127.0.0.1", "--port", "0", "--name", "glm", "--alias", "g", "--context=8192" }; + try std.testing.expectEqual(want.len, argv.len); + for (want, argv) |w, g| try std.testing.expectEqualStrings(w, g); + var u: cli.Usage = .{}; + const parsed = try cli.parse(a, argv[2..], &u); + try std.testing.expect(parsed.port == 0 and std.mem.eql(u8, parsed.host, "127.0.0.1") and parsed.context.? == 8192); + try std.testing.expectEqualStrings("glm", parsed.name); + try std.testing.expectEqualStrings("g", parsed.alias[0]); +} + +test "serve --router: an entry's floor adds its drafter, a cached model serve refuses is left out, a config's stops the start" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.createDirPath(io, "model"); + try tmp.dir.createDirPath(io, "drafter"); + const root = try tmp.dir.realPathFileAlloc(io, ".", a); + const gib: u64 = 1 << 30; + const Disk = struct { + fn repos(_: Allocator, _: std.Io, _: ?*const std.process.Environ.Map) anyerror![]const []const u8 { + return &.{}; + } + fn memory(_: Allocator, _: std.Io, dir: []const u8) ?Memory { + if (std.mem.endsWith(u8, dir, "/model")) return .{ .floor = 30 * gib, .weights = 28 * gib }; + if (std.mem.endsWith(u8, dir, "/drafter")) return .{ .floor = 3 * gib, .weights = gib }; + return null; + } + }; + const checkpoints: Checkpoints = .{ .repos = Disk.repos, .memory = Disk.memory }; + var env: std.process.Environ.Map = .init(a); + const drafter = try std.fmt.allocPrint(a, "--drafter={s}", .{try std.fs.path.join(a, &.{ root, "drafter" })}); + const models = [_]Model{ + .{ .id = "big", .model = try std.fs.path.join(a, &.{ root, "model" }), .flags = &.{drafter}, .line = 3 }, + .{ .id = "gone", .model = try std.fs.path.join(a, &.{ root, "missing" }), .line = 9 }, + }; + var problem: []const u8 = ""; + try std.testing.expect(try build(a, io, &env, "/opt/example/tensorfold", &models, checkpoints, &problem) == null); + try std.testing.expect(std.mem.startsWith(u8, problem, "model 'gone' (line 9): ")); + const kept = try buildCached(a, io, &env, "/opt/example/tensorfold", &models, checkpoints); + try std.testing.expectEqual(@as(usize, 1), kept.len); + try std.testing.expectEqualStrings("big", kept[0].id); + try std.testing.expectEqual(31 * gib, kept[0].floor.?); + try std.testing.expectEqual(benchmark_server.startupTimeout(29 * gib), kept[0].startup_s); +} diff --git a/zig/src/server/router/config.zig b/zig/src/server/router/config.zig new file mode 100644 index 00000000000..337f2cb9eb8 --- /dev/null +++ b/zig/src/server/router/config.zig @@ -0,0 +1,116 @@ +//! ``--router-config FILE.toml``: one ``[[models]]`` table a model, its id, aliases, model and serve flags. +const std = @import("std"); +const cli = @import("../cli.zig"); +const cli_config = @import("../cli_config.zig"); +const toml = @import("../toml_flat.zig"); +const catalog = @import("catalog.zig"); +const Allocator = std.mem.Allocator; + +const Error = error{ Usage, OutOfMemory }; +const flag = "--router-config"; + +/// The longest id or alias, in bytes. +pub const name_limit = 256; + +/// The serve flags the router sets on every child itself, and why a model's table cannot. +const owned = [_][2][]const u8{ + .{ "name", "a model answers to its id and aliases" }, + .{ "alias", "a model answers to its id and aliases: list them in aliases" }, + .{ "host", "each model's server listens on 127.0.0.1 at a port the router picks" }, + .{ "port", "each model's server listens on 127.0.0.1 at a port the router picks" }, + .{ "unix-socket", "each model's server listens on 127.0.0.1 at a port the router picks" }, + .{ "api-key", "each model's server takes a key of its own; give the router --api-key or --api-key-file" }, + .{ "api-key-file", "each model's server takes a key of its own; give the router --api-key or --api-key-file" }, + .{ "idle-unload", "the router stops idle models: give it --idle-unload SECONDS" }, + .{ "allowed-host", "the router checks the Host header: give it --allowed-host" }, + .{ "allowed-origin", "the router checks the Origin header: give it --allowed-origin" }, +}; + +/// The models a router config file lists, read and checked as ``serve --config`` reads its file. +pub fn load(a: Allocator, path: []const u8, u: *cli.Usage) Error![]const catalog.Model { + const file = try cli_config.read(a, path, flag, u); + return parse(a, path, file.text, u); +} + +/// The models in ``text``, the file at ``path``: each table's keys checked, its serve flags as a command line's. +pub fn parse(a: Allocator, path: []const u8, text: []const u8, u: *cli.Usage) Error![]const catalog.Model { + var problem: toml.Problem = .{}; + const shaped = toml.parseShaped(a, text, .{ .table = "models" }, &problem) catch |e| switch (e) { + error.OutOfMemory => |x| return x, + error.Invalid => return cli.fail(u, a, "argument {s}: {s} line {d}: {s}", .{ flag, path, problem.line, problem.message }), + }; + for (shaped.entries) |e| if (e.table == 0) + return at(u, a, path, e.line, "top-level keys are not read: each model is a [[models]] table, and the router's flags go on its command line", .{}); + if (shaped.tables.len == 0) return cli.fail(u, a, "argument {s}: {s} lists no models: add a [[models]] table with an id and a model", .{ flag, path }); + var out: std.ArrayList(catalog.Model) = .empty; + for (shaped.tables, 1..) |header, n| { + const m = try table(a, path, header, @intCast(n), shaped.entries, u); + for (out.items) |other| for ([_][]const []const u8{ &.{m.id}, m.aliases }) |names| for (names) |name| { + if (named(other, name)) return at(u, a, path, header, "'{s}' already names model '{s}'", .{ name, other.id }); + }; + try out.append(a, m); + } + return out.items; +} + +/// One ``[[models]]`` table whose header is on ``header``: the router's keys, then serve's for the rest. +fn table(a: Allocator, path: []const u8, header: u32, n: u32, entries: []const toml.Entry, u: *cli.Usage) Error!catalog.Model { + var id: ?[]const u8 = null; + var aliases: std.ArrayList([]const u8) = .empty; + var rest: std.ArrayList(toml.Entry) = .empty; + var model = false; + var first: u32 = 0; + for (entries) |e| { + if (e.table != n) continue; + if (first == 0) first = e.line; + const key = try a.dupe(u8, e.key); + std.mem.replaceScalar(u8, key, '_', '-'); + if (std.mem.eql(u8, key, "id")) { + if (e.value != .scalar or e.value.scalar != .string) return at(u, a, path, e.line, "id takes a string", .{}); + id = try checkName(a, path, e.line, "id", e.value.scalar.string, u); + continue; + } + if (std.mem.eql(u8, key, "aliases")) { + const list: []const []const u8 = switch (e.value) { + .array => |items| items, + .scalar => |s| if (s == .string) &.{s.string} else return at(u, a, path, e.line, "aliases takes strings", .{}), + }; + for (list) |alias| try aliases.append(a, try checkName(a, path, e.line, "alias", alias, u)); + continue; + } + for (owned) |o| if (std.mem.eql(u8, key, o[0])) return at(u, a, path, e.line, "{s} is the router's: {s}", .{ o[0], o[1] }); + model = model or std.mem.eql(u8, key, "model"); + try rest.append(a, e); + } + const name = id orelse return at(u, a, path, header, "a [[models]] table needs an id", .{}); + if (!model) return at(u, a, path, header, "'{s}' has no model: add model = a folder or a Hugging Face repo id", .{name}); + for (aliases.items, 0..) |alias, i| { + const twice = std.mem.eql(u8, alias, name) or for (aliases.items[0..i]) |earlier| { + if (std.mem.eql(u8, earlier, alias)) break true; + } else false; + if (twice) return at(u, a, path, header, "'{s}' is named twice in model '{s}'", .{ alias, name }); + } + const found: cli_config.Found = .{ .path = path, .at = 0, .width = 0, .model = false, .flag = flag }; + const merged = try cli_config.mergeEntries(a, &.{}, found, rest.items, u); + return .{ .id = name, .aliases = aliases.items, .model = merged.argv[0], .flags = merged.argv[1..], .line = first }; +} + +fn named(m: catalog.Model, name: []const u8) bool { + if (std.mem.eql(u8, m.id, name)) return true; + for (m.aliases) |alias| if (std.mem.eql(u8, alias, name)) return true; + return false; +} + +/// A name a request's ``model`` field can carry: 1 to 256 bytes, no spaces or control characters, no leading dash. +fn checkName(a: Allocator, path: []const u8, line: u32, what: []const u8, text: []const u8, u: *cli.Usage) Error![]const u8 { + const plain = for (text) |c| { + if (c <= ' ' or c == 0x7f) break false; + } else true; + if (text.len == 0 or text.len > name_limit or !plain or text[0] == '-') + return at(u, a, path, line, "{s} '{s}': expected 1 to {d} bytes without spaces or control characters, not starting with -", .{ what, text, name_limit }); + return text; +} + +fn at(u: *cli.Usage, a: Allocator, path: []const u8, line: u32, comptime fmt: []const u8, args: anytype) Error { + return cli.fail(u, a, "argument {s}: {s} line {d}: " ++ fmt, .{ flag, path, line } ++ args); +} diff --git a/zig/src/server/router/config_test.zig b/zig/src/server/router/config_test.zig new file mode 100644 index 00000000000..c45e9e1f8f7 --- /dev/null +++ b/zig/src/server/router/config_test.zig @@ -0,0 +1,164 @@ +//! config.zig and args.zig: what a router config and command line give, and each refusal with its line. +const std = @import("std"); +const cli = @import("../cli.zig"); +const config = @import("config.zig"); +const args = @import("args.zig"); +const toml = @import("../toml_flat.zig"); +const t = std.testing; + +const Fixture = struct { + arena: std.heap.ArenaAllocator = .init(t.allocator), + u: cli.Usage = .{}, + + fn deinit(f: *Fixture) void { + f.arena.deinit(); + } + + fn models(f: *Fixture, text: []const u8) ![]const @import("catalog.zig").Model { + return config.parse(f.arena.allocator(), "conf/router.toml", text, &f.u) catch |e| { + if (e == error.Usage) std.debug.print("refused: {s}\n", .{f.u.message}); + return e; + }; + } + + /// ``text`` is refused with exactly ``message`` after the ``argument --router-config: FILE line N: `` prefix. + fn refused(f: *Fixture, text: []const u8, line: u32, message: []const u8) !void { + try t.expectError(error.Usage, config.parse(f.arena.allocator(), "conf/router.toml", text, &f.u)); + try t.expectEqualStrings(try std.fmt.allocPrint(f.arena.allocator(), "argument --router-config: conf/router.toml line {d}: {s}", .{ line, message }), f.u.message); + } + + fn settings(f: *Fixture, argv: []const []const u8) !args.Settings { + return args.parse(f.arena.allocator(), argv, &f.u); + } + + fn badArgs(f: *Fixture, argv: []const []const u8, message: []const u8) !void { + try t.expectError(error.Usage, args.parse(f.arena.allocator(), argv, &f.u)); + try t.expectEqualStrings(message, f.u.message); + } +}; + +test "serve --router: each [[models]] table gives an id, aliases, a model beside the file and serve flags as typed" { + var f: Fixture = .{}; + defer f.deinit(); + const got = try f.models( + \\# two models behind one address + \\[[models]] + \\id = "glm" + \\model = "org/GLM-Example" + \\aliases = ["glm-flash", "g"] + \\context = 131072 + \\thinking = false + \\chat_template = "templates/glm.jinja" + \\ + \\[[ models ]] # a folder beside the file + \\id = "small" + \\model = "./weights/small" + \\aliases = "s" + \\parallel = "auto" + ); + try t.expectEqual(@as(usize, 2), got.len); + try t.expectEqualStrings("glm", got[0].id); + try t.expectEqualStrings("org/GLM-Example", got[0].model); + try t.expectEqual(@as(usize, 2), got[0].aliases.len); + try t.expectEqualStrings("g", got[0].aliases[1]); + const want = [_][]const u8{ "--context=131072", "--no-thinking", "--chat-template=conf/templates/glm.jinja" }; + try t.expectEqual(want.len, got[0].flags.len); + for (want, got[0].flags) |w, g| try t.expectEqualStrings(w, g); + try t.expectEqual(@as(u32, 3), got[0].line); + try t.expectEqualStrings("conf/weights/small", got[1].model); + try t.expectEqualStrings("s", got[1].aliases[0]); + try t.expectEqualStrings("--parallel=auto", got[1].flags[0]); + var u: cli.Usage = .{}; + const parsed = try cli.parse(f.arena.allocator(), try std.mem.concat(f.arena.allocator(), []const u8, &.{ &.{got[0].model}, got[0].flags }), &u); + try t.expect(parsed.context.? == 131072 and !parsed.thinking); +} + +test "serve --router: a router config refuses top-level keys, missing ids and models, owned flags and repeated names" { + var f: Fixture = .{}; + defer f.deinit(); + try f.refused("max-loaded = 2\n[[models]]\nid = \"a\"\nmodel = \"o/a\"\n", 1, "top-level keys are not read: each model is a [[models]] table, and the router's flags go on its command line"); + try f.refused("[[models]]\nmodel = \"o/a\"\n", 1, "a [[models]] table needs an id"); + try f.refused("[[models]]\nid = \"a\"\n", 1, "'a' has no model: add model = a folder or a Hugging Face repo id"); + try f.refused("[[models]]\nid = \"a\"\nmodel = \"o/a\"\nport = 9000\n", 4, "port is the router's: each model's server listens on 127.0.0.1 at a port the router picks"); + try f.refused("[[models]]\nid = \"a\"\nmodel = \"o/a\"\nalias = [\"b\"]\n", 4, "alias is the router's: a model answers to its id and aliases: list them in aliases"); + try f.refused("[[models]]\nid = \"a\"\nmodel = \"o/a\"\napi_key_file = \"/etc/k\"\n", 4, "api-key-file is the router's: each model's server takes a key of its own; give the router --api-key or --api-key-file"); + try f.refused("[[models]]\nid = \"a\"\nmodel = \"o/a\"\nidle-unload = 60\n", 4, "idle-unload is the router's: the router stops idle models: give it --idle-unload SECONDS"); + try f.refused("[[models]]\nid = \"a\"\nmodel = \"o/a\"\n[[models]]\nid = \"b\"\nmodel = \"o/b\"\naliases = [\"a\"]\n", 4, "'a' already names model 'a'"); + try f.refused("[[models]]\nid = \"a\"\nmodel = \"o/a\"\naliases = [\"x\", \"x\"]\n", 1, "'x' is named twice in model 'a'"); + try f.refused("[[models]]\nid = \"has space\"\nmodel = \"o/a\"\n", 2, "id 'has space': expected 1 to 256 bytes without spaces or control characters, not starting with -"); + try f.refused("[[models]]\nid = 7\nmodel = \"o/a\"\n", 2, "id takes a string"); + // a serve key keeps serve's own refusal, and the table and file rules are the flat reader's + try f.refused("[[models]]\nid = \"a\"\nmodel = \"o/a\"\nprot = 1\n", 4, "unknown key 'prot'"); + try f.refused("[[models]]\nid = \"a\"\nmodel = \"o/a\"\ncontext = \"x\"\n", 4, "argument --context: invalid int value: 'x'"); + try f.refused("[models]\nid = \"a\"\n", 1, "a [table] is not read: each item is a [[models]] table"); + try f.refused("[[servers]]\nid = \"a\"\n", 1, "unknown table [[servers]]: this file reads [[models]] tables"); + try f.refused("[[models]]\nid = \"a\"\nid = \"b\"\n", 3, "key defined twice"); + try t.expectError(error.Usage, config.parse(f.arena.allocator(), "conf/router.toml", "# nothing\n", &f.u)); + try t.expectEqualStrings("argument --router-config: conf/router.toml lists no models: add a [[models]] table with an id and a model", f.u.message); +} + +test "serve --router: the flat reader still refuses every table, and a shaped one keys duplicates by table" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var problem: toml.Problem = .{}; + try t.expectError(error.Invalid, toml.parse(a, "[[models]]\nid = \"a\"\n", &problem)); + try t.expectEqualStrings("tables are not read: every key is a top-level setting", problem.message); + const shaped = try toml.parseShaped(a, "top = 1\n[[models]]\nid = \"a\"\n\n[[models]]\nid = \"b\"\n", .{ .table = "models" }, &problem); + try t.expectEqual(@as(usize, 3), shaped.entries.len); + try t.expectEqualSlices(u32, &.{ 2, 5 }, shaped.tables); + try t.expectEqual(@as(u32, 2), shaped.entries[2].table); + try t.expectError(error.Invalid, toml.parseShaped(a, "models = \"x\"\n[[models]]\n", .{ .table = "models" }, &problem)); + try t.expectEqualStrings("key defined twice", problem.message); + try t.expectError(error.Invalid, toml.parseShaped(a, "[[models]] x\n", .{ .table = "models" }, &problem)); + try t.expectEqualStrings("unexpected text after the table header", problem.message); +} + +test "serve --router: the command line takes the router's flags and serve's shared ones, and refuses a model's" { + var f: Fixture = .{}; + defer f.deinit(); + const s = try f.settings(&.{ "--router", "--router-config", "r.toml", "--max-loaded=2", "--idle-unload", "600", "--host", "::1", "--port", "9000", "--api-key-file", "/etc/keys", "--api-key", "sk-example" }); + try t.expectEqualStrings("r.toml", s.config.?); + try t.expect(s.max_loaded == 2 and s.idle_s == 600 and s.port == 9000); + try t.expectEqualStrings("::1", s.host); + try t.expectEqualStrings("/etc/keys", s.api_key_file.?); + try t.expectEqualStrings("sk-example", s.api_keys[0]); + const plain = try f.settings(&.{"--router"}); + try t.expect(plain.config == null and plain.max_loaded == 1 and plain.idle_s == 0 and plain.port == 8080); + try t.expect(args.wanted(&.{ "--port", "1", "--router" }) and !args.wanted(&.{"org/model"})); + try f.badArgs(&.{ "--router", "--context", "8192" }, "argument --context: a model's serve flag; with --router, set it on the model in --router-config FILE.toml"); + try f.badArgs(&.{ "--router", "org/model" }, "unrecognized arguments: org/model: --router serves the models of --router-config or the cache and takes no MODEL"); + try f.badArgs(&.{ "--router", "--config", "a.toml" }, "argument --config: with --router, models and their serve flags are listed in --router-config FILE.toml"); + try f.badArgs(&.{ "--router", "--alias", "x" }, "argument --alias: with --router, each model answers to its id and aliases in --router-config FILE.toml"); + try f.badArgs(&.{ "--router", "--unix-socket", "/run/x.sock" }, "argument --unix-socket: the router listens on --host and --port only"); + try f.badArgs(&.{ "--router", "--max-loaded", "0" }, "argument --max-loaded: expected 1 to 64 models: '0'"); + try f.badArgs(&.{ "--router", "--router-config", "r.json" }, "argument --router-config: expected a .toml file: 'r.json'"); + try f.badArgs(&.{ "--router", "--port", "99999" }, "argument --port: invalid port: '99999'"); + try f.badArgs(&.{ "--router", "--idle-unload", "-1" }, "argument --idle-unload: expected a seconds count from 0 (off) under 9223372036: '-1'"); + try f.badArgs(&.{ "--router", "--bogus" }, "unrecognized arguments: --bogus"); + try f.badArgs(&.{ "--router", "--port" }, "argument --port: expected one argument"); +} + +test "serve --router: the config file is opened as serve opens its own: no link, nothing others can write" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const c = @import("sys").c; + const dir = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + const path = try std.fs.path.join(a, &.{ dir, "router.toml" }); + try tmp.dir.writeFile(t.io, .{ .sub_path = "router.toml", .data = "[[models]]\nid = \"a\"\nmodel = \"./w\"\n" }); + const pathz = try a.dupeSentinel(u8, path, 0); + try t.expectEqual(@as(c_int, 0), c.fchmodat(std.posix.AT.FDCWD, pathz, 0o644, 0)); + var u: cli.Usage = .{}; + const got = try config.load(a, path, &u); + try t.expectEqualStrings(try std.fs.path.join(a, &.{ dir, "w" }), got[0].model); + try t.expectEqual(@as(c_int, 0), c.fchmodat(std.posix.AT.FDCWD, pathz, 0o664, 0)); + try t.expectError(error.Usage, config.load(a, path, &u)); + try t.expectEqualStrings(try std.fmt.allocPrint(a, "argument --router-config: {s} can be written by other users (mode 0664): it chooses what is served; use chmod go-w", .{path}), u.message); + try tmp.dir.symLink(t.io, "router.toml", "link.toml", .{}); + const link = try std.fs.path.join(a, &.{ dir, "link.toml" }); + try t.expectError(error.Usage, config.load(a, link, &u)); + try t.expectEqualStrings(try std.fmt.allocPrint(a, "argument --router-config: cannot open {s} (SymLinkLoop); name an existing file, not a link", .{link}), u.message); +} diff --git a/zig/src/server/router/front.zig b/zig/src/server/router/front.zig new file mode 100644 index 00000000000..c66a4bb7d34 --- /dev/null +++ b/zig/src/server/router/front.zig @@ -0,0 +1,159 @@ +//! The router's HTTP side: a thread a connection behind the server's guards, then a model route or the router's own. +const std = @import("std"); +const auth = @import("../auth.zig"); +const auth_scope = @import("../auth_scope.zig"); +const http_conn = @import("../http_conn.zig"); +const http_body = @import("../http_body.zig"); +const admission = @import("../http_admission.zig"); +const listener_mod = @import("../listener.zig"); +const request_guard = @import("../request_guard.zig"); +const catalog = @import("catalog.zig"); +const pool_mod = @import("pool.zig"); +const relay = @import("relay.zig"); +const replies = @import("replies.zig"); +const listing = @import("listing.zig"); +const model_route = @import("model_route.zig"); +const Conn = http_conn.Conn; +const Allocator = std.mem.Allocator; + +/// The most a kept-alive connection's arena keeps between requests, as the server keeps it. +const arena_limit: usize = 1 << 20; + +/// A POST route that names its model: its error shape, and whether it is Responses (whose storage keys are checked). +pub const ModelRoute = struct { shape: replies.Shape, responses: bool = false }; + +pub const Front = struct { + gpa: Allocator, + io: std.Io, + pool: *pool_mod.Pool, + entries: []const catalog.Entry, + keys: ?*auth.Store = null, + browser: request_guard.Policy = .{}, + version: []const u8 = "", + timeouts: http_conn.Timeouts = .{}, + limits: relay.Limits = .{}, + max_connections: u32 = admission.default_limit, + open: std.atomic.Value(u32) = .init(0), + peers: admission.Peers = .{}, + /// Set once the router is stopping: model requests get 503 and /health says draining. + draining: std.atomic.Value(bool) = .init(false), + + /// Accepts connections until ``stop`` is set, each on its own thread. + pub fn serve(f: *Front, lis: listener_mod.Listener, stop: *const std.atomic.Value(bool)) void { + const loopback_bind = if (lis.boundAddress()) |addr| auth.loopbackAddress(addr) else true; + relay.closeOnExec(lis.fd); + while (lis.accept(stop)) |c| { + relay.closeOnExec(c.fd); + if (!admission.acquire(&f.open, f.max_connections)) { + admission.reject(c.fd); + continue; + } + const slot = admission.peerSlot(&f.peers, f.io, &f.open, f.max_connections, .{}, c.fd, c.peer) orelse continue; + const t = std.Thread.spawn(.{ .stack_size = 8 << 20 }, connection, .{ f, c, loopback_bind, slot }) catch { + admission.release(&f.peers, f.io, &f.open, slot); + _ = std.posix.system.close(c.fd); + continue; + }; + t.detach(); + } + } + + fn connection(f: *Front, accepted: listener_mod.Listener.Accepted, loopback_bind: bool, slot: u16) void { + defer admission.release(&f.peers, f.io, &f.open, slot); + defer _ = std.posix.system.close(accepted.fd); + var peer_buf: [64]u8 = undefined; + var conn = Conn.init(f.gpa, accepted.fd, listener_mod.peerText(&peer_buf, accepted.peer)) catch return; + defer conn.deinit(); + conn.timeouts = f.timeouts; + conn.shed = .{ .open = &f.open, .limit = f.max_connections }; + conn.auth_enabled = f.keys != null and f.keys.?.enabled(); + var browser = f.browser; + browser.loopback_bind = loopback_bind; + var arena: std.heap.ArenaAllocator = .init(f.gpa); + defer arena.deinit(); + var first = true; + while (true) { + _ = arena.reset(.{ .retain_with_limit = arena_limit }); + const a = arena.allocator(); + const outcome = conn.readRequest(a, !first) catch break; + first = false; + switch (outcome) { + .closed => break, + .handled => if (conn.close) break else continue, + .ready => {}, + } + if (!request_guard.allow(&conn, browser, a)) break; + if (!@import("../auth_gate.zig").admit(f.keys, &conn, a)) break; + if (conn.header("Expect")) |expect| if (std.ascii.eqlIgnoreCase(expect, "100-continue") and std.mem.order(u8, conn.version, "HTTP/1.1") != .lt) conn.sendContinue(); + f.dispatch(&conn, a); + if (!conn.response_complete) conn.close = true; + if (conn.close or conn.broken) break; + } + } + + fn dispatch(f: *Front, conn: *Conn, a: Allocator) void { + const route = auth.routePath(conn.path); + if (modelRoute(conn.method, conn.path)) |r| return model_route.serve(f, conn, a, r); + const shape = shapeOf(conn.path); + if (std.mem.eql(u8, conn.method, "POST") or std.mem.eql(u8, conn.method, "PUT") or std.mem.eql(u8, conn.method, "DELETE")) { + _ = http_body.read(conn, a, http_body.limit) catch {}; + const what = std.fmt.allocPrint(a, "{s} {s}", .{ conn.method, route }) catch "this route"; + return replies.send(conn, a, shape, replies.unsupported(a, what, "the router serves model routes, whose body names a model, and lists its models itself")); + } + if (!std.mem.eql(u8, conn.method, "GET")) { + if (!consumeBody(conn, a)) return; + const message = std.fmt.allocPrint(a, "Unsupported method ({s})", .{http_conn.pyRepr(a, conn.method) catch conn.method}) catch return; + return conn.sendError(a, 501, message, null) catch {}; + } + if (!consumeBody(conn, a)) return; + if (route.len == 0 or std.mem.eql(u8, route, "/health")) return listing.health(f, conn, a); + if (std.mem.eql(u8, route, "/api/tags")) return listing.tags(f, conn, a); + if (std.mem.eql(u8, route, "/api/ps")) return listing.ps(f, conn, a); + if (std.mem.eql(u8, route, "/api/version")) return listing.version(f, conn, a); + if (std.mem.endsWith(u8, route, "/models")) return listing.models(f, conn, a); + if (@import("../responses.zig").route(route)) |rid| { + if (rid.len > 0) return replies.send(conn, a, shape, replies.unsupported(a, "GET /v1/responses/{id}", "stored responses stay in the model server that made them; send the whole conversation, or store: false")); + if (@import("../ws_upgrade.zig").requested(conn)) return replies.send(conn, a, shape, replies.unsupported(a, "The Responses WebSocket mode", "send POST /v1/responses over HTTP")); + } + if (std.mem.eql(u8, route, "/metrics") or std.mem.eql(u8, route, "/v1/metrics")) + return replies.send(conn, a, shape, replies.unsupported(a, "GET /metrics", "metrics are per model, and each model's server keeps its own; /health lists the loaded models")); + const what = std.fmt.allocPrint(a, "GET {s}", .{route}) catch "this route"; + replies.send(conn, a, shape, replies.unsupported(a, what, "the router answers /health, /v1/models, /api/tags, /api/ps and /api/version itself")); + } +}; + +/// The model routes the router forwards: POST (and PUT for rerank) with a JSON body that names a model. +pub fn modelRoute(method: []const u8, raw_path: []const u8) ?ModelRoute { + const route = auth.routePath(raw_path); + if (std.mem.eql(u8, method, "PUT") and auth_scope.putRoute(route)) return .{ .shape = .openai }; + if (!std.mem.eql(u8, method, "POST")) return null; + if (std.mem.endsWith(u8, route, "/completions")) return .{ .shape = .openai }; + if (@import("../responses.zig").route(route)) |rid| return if (rid.len == 0) .{ .shape = .openai, .responses = true } else null; + if (@import("../anthropic.zig").route(raw_path)) return .{ .shape = .anthropic }; + for ([_][]const u8{ "/v1/embeddings", "/v1/rerank", "/rerank" } ++ @import("../tokens.zig").paths) |p| if (std.mem.eql(u8, route, p)) return .{ .shape = .openai }; + for ([_][]const u8{ "/api/chat", "/api/generate", "/api/embed", "/api/show" }) |p| if (std.mem.eql(u8, route, p)) return .{ .shape = .ollama }; + return null; +} + +/// The error shape for any path: Ollama's under /api/, Anthropic's for Messages, else OpenAI's. +pub fn shapeOf(raw_path: []const u8) replies.Shape { + if (std.mem.startsWith(u8, auth.routePath(raw_path), "/api/")) return .ollama; + if (@import("../anthropic.zig").route(raw_path)) return .anthropic; + return .openai; +} + +/// A body no route reads, taken to keep the connection in step, as the server takes it. +fn consumeBody(conn: *Conn, a: Allocator) bool { + const body = http_body.read(conn, a, http_body.unread_limit) catch { + conn.close = true; + conn.sendError(a, 500, "out of memory", null) catch {}; + return false; + }; + switch (body) { + .ok => return true, + .refused => |message| { + conn.sendError(a, 400, message, null) catch {}; + return false; + }, + } +} diff --git a/zig/src/server/router/front_test.zig b/zig/src/server/router/front_test.zig new file mode 100644 index 00000000000..a01a49f754c --- /dev/null +++ b/zig/src/server/router/front_test.zig @@ -0,0 +1,288 @@ +//! The router over loopback sockets with fake children: routing, refusals, keys, byte-for-byte streams and crashes. +const std = @import("std"); +const auth = @import("../auth.zig"); +const listener_mod = @import("../listener.zig"); +const tc = @import("test_child.zig"); +const fake = @import("../benchmark_fake.zig"); +const catalog = @import("catalog.zig"); +const pool_mod = @import("pool.zig"); +const front = @import("front.zig"); +const t = std.testing; +const posix = std.posix; +const exchangeWith = tc.exchangeWith; +const dial = tc.dial; +const sendAll = tc.sendAll; +const readUntil = tc.readUntil; +const post = tc.post; +const get = tc.get; +const status = tc.status; +const bodyOf = tc.bodyOf; + +const Spec = struct { id: []const u8, aliases: []const []const u8 = &.{}, routes: []const fake.Route = &.{} }; + +const Harness = struct { + arena: std.heap.ArenaAllocator = .init(t.allocator), + tmp: std.testing.TmpDir = undefined, + children: std.ArrayList(tc.Child) = .empty, + pool: *pool_mod.Pool = undefined, + front: *front.Front = undefined, + store: ?auth.Store = null, + lis: listener_mod.Listener = undefined, + stop: std.atomic.Value(bool) = .init(false), + accept: ?std.Thread = null, + + fn start(h: *Harness, specs: []const Spec, max_loaded: u32, keys: []const []const u8) !void { + const a = h.arena.allocator(); + h.tmp = std.testing.tmpDir(.{}); + var entries: std.ArrayList(catalog.Entry) = .empty; + for (specs) |s| { + const c = try tc.start(a, s.id, s.aliases, s.routes); + try h.children.append(a, c); + try entries.append(a, c.entry); + } + h.pool = try tc.pool(a, &h.tmp, entries.items, .{ .max_loaded = max_loaded, .busy_wait_s = 5, .log_dir = "" }); + var problem: []const u8 = ""; + if (keys.len > 0) h.store = try auth.Store.init(t.allocator, keys, "", null, false, &problem); + h.front = try a.create(front.Front); + h.front.* = .{ .gpa = t.allocator, .io = t.io, .pool = h.pool, .entries = h.pool.entries, .keys = if (h.store) |*s| s else null, .version = "0.0.0-test" }; + h.lis = try listener_mod.Listener.open(.{ .ip4 = .loopback(0) }); + h.accept = try std.Thread.spawn(.{}, front.Front.serve, .{ h.front, h.lis, &h.stop }); + } + + fn deinit(h: *Harness) void { + h.stop.store(true, .release); + if (h.accept) |th| th.join(); + var waited: u32 = 0; + while (h.front.open.load(.acquire) > 0 and waited < 500) : (waited += 1) fake.nap(10); + h.pool.stopAll(); + h.pool.deinit(); + h.lis.close(); + if (h.store) |*s| s.deinit(); + for (h.children.items) |c| c.server.stop(); + h.tmp.cleanup(); + h.arena.deinit(); + } + + /// One whole exchange: ``request`` sent on a new connection, the reply read until the router closes it. + fn exchange(h: *Harness, request: []const u8) ![]const u8 { + return exchangeWith(h.arena.allocator(), h.lis.port(), request); + } + + fn childKey(h: *Harness, i: usize) [64]u8 { + h.pool.mutex.lockUncancelable(t.io); + defer h.pool.mutex.unlock(t.io); + return h.pool.slots[i].key; + } +}; + +fn has(text: []const u8, needle: []const u8) bool { + if (std.mem.indexOf(u8, text, needle) != null) return true; + std.debug.print("missing \"{s}\" in:\n{s}\n", .{ needle, text }); + return false; +} + +fn route(a: std.mem.Allocator, path: []const u8, replies: []const []const fake.Write) !fake.Route { + return .{ .method = "POST", .path = path, .replies = try a.dupe([]const fake.Write, replies) }; +} + +test "serve --router: a request reaches the child its model names, by id or alias, with its body unchanged" { + var h: Harness = .{}; + const a = h.arena.allocator(); + try h.start(&.{ + .{ .id = "alpha", .aliases = &.{"a1"}, .routes = &.{try route(a, "/v1/chat/completions", &.{try fake.jsonReply(a, "200 OK", "{\"id\": \"from-alpha\"}")})} }, + .{ .id = "beta", .routes = &.{try route(a, "/v1/chat/completions", &.{try fake.jsonReply(a, "200 OK", "{\"id\": \"from-beta\"}")})} }, + }, 2, &.{}); + defer h.deinit(); + const body = "{\"model\": \"a1\", \"messages\": [{\"role\": \"user\", \"content\": \"hi\"}]}"; + const first = try h.exchange(try post(a, "/v1/chat/completions", body, "")); + try t.expectEqual(@as(u16, 200), status(first)); + try t.expectEqualStrings("{\"id\": \"from-alpha\"}", bodyOf(first)); + const alpha = h.children.items[0].server; + const seen = alpha.request(alpha.count() - 1); + try t.expectEqualStrings("/v1/chat/completions", seen.path); + try t.expectEqualStrings(body, seen.body); + const second = try h.exchange(try post(a, "/v1/chat/completions", "{\"model\": \"beta\"}", "")); + try t.expectEqualStrings("{\"id\": \"from-beta\"}", bodyOf(second)); + try t.expectEqual(@as(usize, 2), (try h.pool.loaded(a)).len); +} + +test "serve --router: an unknown or missing model is refused in its route's shape and loads nothing" { + var h: Harness = .{}; + const a = h.arena.allocator(); + try h.start(&.{.{ .id = "alpha" }}, 1, &.{}); + defer h.deinit(); + const openai = try h.exchange(try post(a, "/v1/chat/completions", "{\"model\": \"nope\"}", "")); + try t.expectEqual(@as(u16, 404), status(openai)); + try t.expectEqualStrings("{\"error\": {\"message\": \"model 'nope' is not served here; GET /v1/models lists the models this router serves\", \"type\": \"invalid_request_error\", \"param\": \"model\", \"code\": \"model_not_found\"}}", bodyOf(openai)); + const ollama = try h.exchange(try post(a, "/api/chat", "{\"model\": \"nope\"}", "")); + try t.expectEqual(@as(u16, 404), status(ollama)); + try t.expectEqualStrings("{\"error\": \"model 'nope' is not served here; GET /v1/models lists the models this router serves\"}", bodyOf(ollama)); + const messages = try h.exchange(try post(a, "/v1/messages", "{\"model\": \"nope\"}", "")); + try t.expect(status(messages) == 404 and has(bodyOf(messages), "\"type\": \"not_found_error\"")); + const missing = try h.exchange(try post(a, "/v1/completions", "{\"prompt\": \"x\"}", "")); + try t.expect(status(missing) == 400 and has(bodyOf(missing), "\"code\": \"model_required\"")); + const broken = try h.exchange(try post(a, "/v1/embeddings", "{not json", "")); + try t.expectEqual(@as(u16, 400), status(broken)); + try t.expectEqual(@as(usize, 0), (try h.pool.loaded(a)).len); +} + +test "serve --router: the child gets its own key in place of the client's, and no reply carries it" { + var h: Harness = .{}; + const a = h.arena.allocator(); + try h.start(&.{.{ .id = "alpha", .routes = &.{try route(a, "/v1/completions", &.{try fake.jsonReply(a, "200 OK", "{\"ok\": true}")})} }}, 1, &.{"sk-router-example"}); + defer h.deinit(); + const keyed = "Authorization: Bearer sk-router-example\r\nX-Api-Key: sk-router-example\r\nOrigin: http://127.0.0.1\r\n"; + const reply = try h.exchange(try post(a, "/v1/completions", "{\"model\": \"alpha\", \"prompt\": \"x\"}", keyed)); + try t.expectEqual(@as(u16, 200), status(reply)); + const key = h.childKey(0); + const alpha = h.children.items[0].server; + const last = alpha.count() - 1; + try t.expectEqualStrings(try std.fmt.allocPrint(a, "Bearer {s}", .{&key}), alpha.header(last, "authorization").?); + try t.expect(alpha.header(last, "x-api-key") == null and alpha.header(last, "origin") == null); + try t.expect(std.mem.indexOf(u8, alpha.request(last).head, "sk-router-example") == null); + for ([_][]const u8{ "/v1/models", "/health", "/api/ps", "/api/tags" }) |path| { + const listed = try h.exchange(try get(a, path, "Authorization: Bearer sk-router-example\r\n")); + try t.expectEqual(@as(u16, 200), status(listed)); + try t.expect(std.mem.indexOf(u8, listed, &key) == null); + } + try t.expect(std.mem.indexOf(u8, reply, &key) == null); + const open = try h.exchange(try post(a, "/v1/completions", "{\"model\": \"alpha\"}", "")); + try t.expectEqual(@as(u16, 401), status(open)); + try t.expectEqual(@as(u16, 200), status(try h.exchange(try get(a, "/health", "")))); +} + +test "serve --router: a streamed reply passes byte for byte as it arrives, an event split across reads included" { + var h: Harness = .{}; + const a = h.arena.allocator(); + var gate: std.Io.Event = .unset; + const head = try fake.headOf(a, "200 OK", "text/event-stream"); + const part = try std.mem.concat(a, u8, &.{ head, ": keepalive\n\ndata: {\"choices\": [{\"delta\": {\"content\": \"he" }); + const rest = "llo\"}}]}\n\n"; + const done = "data: [DONE]\n\n"; + const writes = try a.dupe(fake.Write, &.{ .{ .bytes = part, .after = &gate }, .{ .bytes = rest, .pause_ms = 30 }, .{ .bytes = done } }); + try h.start(&.{.{ .id = "alpha", .routes = &.{try route(a, "/v1/chat/completions", &.{writes})} }}, 1, &.{}); + defer h.deinit(); + defer gate.set(t.io); // before the fake stops, so a test that fails early never leaves its writer waiting + const fd = try dial(h.lis.port()); + defer _ = posix.system.close(fd); + try sendAll(fd, try post(a, "/v1/chat/completions", "{\"model\": \"alpha\", \"stream\": true}", "")); + var got: std.ArrayList(u8) = .empty; + // the first write ends inside an event and the child then waits: the router must pass it on unfinished + try readUntil(a, fd, &got, part.len, 10_000); + try t.expectEqualStrings(part, got.items); + gate.set(t.io); + try readUntil(a, fd, &got, null, 10_000); + try t.expectEqualStrings(try std.mem.concat(a, u8, &.{ part, rest, done }), got.items); +} + +const Background = struct { + arena: std.heap.ArenaAllocator = .init(t.allocator), + port: u16, + request: []const u8, + reply: ?[]const u8 = null, + + fn run(b: *Background) void { + b.reply = exchangeWith(b.arena.allocator(), b.port, b.request) catch null; + } +}; + +/// Waits until ``server`` has seen ``n`` POSTs to ``path``. +fn posted(server: *fake.Fake, path: []const u8, n: usize) bool { + var waited: u32 = 0; + while (waited < 10_000) : (waited += 10) { + var seen: usize = 0; + for (0..server.count()) |i| { + const r = server.request(i); + seen += @intFromBool(std.mem.eql(u8, r.method, "POST") and std.mem.eql(u8, r.path, path)); + } + if (seen >= n) return true; + fake.nap(10); + } + return false; +} + +test "serve --router: a child that dies answering gives 502 or ends its stream, and the next request starts it again" { + var h: Harness = .{}; + const a = h.arena.allocator(); + var before_head: std.Io.Event = .unset; + var mid_stream: std.Io.Event = .unset; + const partial = try std.mem.concat(a, u8, &.{ try fake.headOf(a, "200 OK", "text/event-stream"), "data: {\"a\"" }); + try h.start(&.{.{ .id = "alpha", .routes = &.{try route(a, "/v1/completions", &.{ + try a.dupe(fake.Write, &.{.{ .bytes = "", .after = &before_head }}), + try a.dupe(fake.Write, &.{.{ .bytes = partial, .after = &mid_stream }}), + try fake.jsonReply(a, "200 OK", "{\"ok\": 3}"), + })} }}, 1, &.{}); + defer h.deinit(); + defer before_head.set(t.io); + defer mid_stream.set(t.io); + const alpha = h.children.items[0].server; + const request = try post(a, "/v1/completions", "{\"model\": \"alpha\"}", ""); + var bg: Background = .{ .port = h.lis.port(), .request = request }; + defer bg.arena.deinit(); + const thread = try std.Thread.spawn(.{}, Background.run, .{&bg}); + try t.expect(posted(alpha, "/v1/completions", 1)); + const first = tc.pid(h.pool, 0).?; + try posix.kill(first, .KILL); + before_head.set(t.io); + thread.join(); + try t.expectEqual(@as(u16, 502), status(bg.reply.?)); + try t.expect(has(bodyOf(bg.reply.?), "the server for model 'alpha' exited while answering; the next request starts it again")); + try t.expect(tc.pid(h.pool, 0) == null); + var bg2: Background = .{ .port = h.lis.port(), .request = request }; + defer bg2.arena.deinit(); + const again = try std.Thread.spawn(.{}, Background.run, .{&bg2}); + try t.expect(posted(alpha, "/v1/completions", 2)); + const second = tc.pid(h.pool, 0).?; + try t.expect(second != first); + try posix.kill(second, .KILL); + mid_stream.set(t.io); + again.join(); + try t.expectEqualStrings(partial, bg2.reply.?); // the stream ends where the child stopped, as a lone server's would + const third = try h.exchange(request); + try t.expectEqualStrings("{\"ok\": 3}", bodyOf(third)); + try t.expect(tc.pid(h.pool, 0).? != second); +} + +test "serve --router: routes it does not serve are refused by name and load nothing" { + var h: Harness = .{}; + const a = h.arena.allocator(); + try h.start(&.{.{ .id = "alpha" }}, 1, &.{}); + defer h.deinit(); + const cases = [_]struct { request: []const u8, says: []const u8 }{ + .{ .request = try get(a, "/v1/responses/resp_1", ""), .says = "GET /v1/responses/{id} is not served through the router in this version" }, + .{ .request = try get(a, "/v1/responses", "Upgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"), .says = "The Responses WebSocket mode is not served through the router" }, + .{ .request = try post(a, "/v1/audio/speech", "{\"model\": \"alpha\"}", ""), .says = "POST /v1/audio/speech is not served through the router" }, + .{ .request = try get(a, "/metrics", ""), .says = "metrics are per model" }, + .{ .request = try get(a, "/v1/models/alpha", ""), .says = "GET /v1/models/alpha is not served through the router" }, + .{ .request = try get(a, "/api/show", ""), .says = "GET /api/show is not served through the router" }, + }; + for (cases) |c| { + const reply = try h.exchange(c.request); + try t.expectEqual(@as(u16, 404), status(reply)); + try t.expect(has(bodyOf(reply), c.says)); + } + try t.expect(has(bodyOf(try h.exchange(try get(a, "/api/show", ""))), "{\"error\": \"")); + try t.expectEqual(@as(usize, 0), (try h.pool.loaded(a)).len); +} + +test "serve --router: /v1/models lists every model with loaded, a ready child's entries as it gives them" { + var h: Harness = .{}; + const a = h.arena.allocator(); + try h.start(&.{ + .{ .id = "alpha", .aliases = &.{"a1"}, .routes = &.{try route(a, "/v1/completions", &.{try fake.jsonReply(a, "200 OK", "{}")})} }, + .{ .id = "beta" }, + }, 1, &.{}); + defer h.deinit(); + const cold = bodyOf(try h.exchange(try get(a, "/v1/models", ""))); + try t.expect(has(cold, "\"id\": \"alpha\"") and has(cold, "\"id\": \"a1\"") and has(cold, "\"id\": \"beta\"")); + try t.expect(std.mem.indexOf(u8, cold, "\"loaded\": true") == null and std.mem.indexOf(u8, cold, "context_length") == null); + _ = try h.exchange(try post(a, "/v1/completions", "{\"model\": \"alpha\"}", "")); + const warm = bodyOf(try h.exchange(try get(a, "/v1/models", ""))); + try t.expect(has(warm, "{\"id\": \"alpha\", \"object\": \"model\", \"created\": 1, \"owned_by\": \"tensorfold\", \"context_length\": 4096, \"loaded\": true}")); + try t.expect(has(warm, "{\"id\": \"a1\", \"object\": \"model\", \"created\": 1, \"owned_by\": \"tensorfold\", \"context_length\": 4096, \"loaded\": true}")); + try t.expect(has(warm, "\"owned_by\": \"tensorfold\", \"loaded\": false}")); + try t.expectEqualStrings("{\"models\": [{\"name\": \"alpha\", \"model\": \"alpha\"}, {\"name\": \"a1\", \"model\": \"a1\"}, {\"name\": \"beta\", \"model\": \"beta\"}]}", bodyOf(try h.exchange(try get(a, "/api/tags", "")))); + try t.expectEqualStrings("{\"models\": [{\"name\": \"alpha\", \"model\": \"alpha\"}]}", bodyOf(try h.exchange(try get(a, "/api/ps", "")))); + try t.expectEqualStrings("{\"status\": \"ok\", \"router\": true, \"models\": 2, \"max_loaded\": 1, \"loaded\": [{\"id\": \"alpha\", \"state\": \"ready\", \"requests_in_progress\": 0}], \"version\": \"0.0.0-test\"}", bodyOf(try h.exchange(try get(a, "/health", "")))); + try t.expectEqualStrings("{\"version\": \"0.0.0-test\"}", bodyOf(try h.exchange(try get(a, "/api/version", "")))); +} diff --git a/zig/src/server/router/listing.zig b/zig/src/server/router/listing.zig new file mode 100644 index 00000000000..42a4802a061 --- /dev/null +++ b/zig/src/server/router/listing.zig @@ -0,0 +1,138 @@ +//! The router's own routes: /health, /v1/models with ``loaded``, and Ollama's /api/tags, /api/ps and /api/version. +const std = @import("std"); +const json = @import("json"); +const stream = @import("../benchmark_stream.zig"); +const routes = @import("../routes.zig"); +const pool_mod = @import("pool.zig"); +const front = @import("front.zig"); +const Conn = @import("../http_conn.zig").Conn; +const Value = json.Value; +const Allocator = std.mem.Allocator; + +/// With keys on, health names no model, as a server's does; draining is a 503 that says so. +pub fn health(f: *front.Front, conn: *Conn, a: Allocator) void { + if (f.draining.load(.acquire)) { + const body = std.fmt.allocPrint(a, "{{\"status\": \"draining\", \"requests_in_progress\": {d}}}", .{f.pool.inFlight()}) catch return; + return routes.sendDraining(conn, body); + } + if (f.keys) |k| if (k.enabled()) return conn.sendJson(200, "{\"status\": \"ok\"}"); + send(conn, a, openHealth(f, a) catch return); +} + +fn openHealth(f: *front.Front, a: Allocator) !Value { + const o = try json.newObject(a); + try o.put(a, "status", .{ .string = "ok" }); + try o.put(a, "router", .{ .bool = true }); + try o.put(a, "models", try json.intValue(a, f.entries.len)); + try o.put(a, "max_loaded", try json.intValue(a, f.pool.options.max_loaded)); + const now = try f.pool.loaded(a); + const list = try a.alloc(Value, now.len); + for (now, list) |s, *slot| { + const child = try json.newObject(a); + try child.put(a, "id", .{ .string = f.entries[s.slot].id }); + try child.put(a, "state", .{ .string = @tagName(s.state) }); + try child.put(a, "requests_in_progress", try json.intValue(a, s.in_flight)); + slot.* = .{ .object = child }; + } + try o.put(a, "loaded", .{ .array = list }); + if (f.version.len > 0) try o.put(a, "version", .{ .string = f.version }); + return .{ .object = o }; +} + +/// Every id and alias, as a server lists its own: a ready child's entries as it gives them, the rest by id alone. +pub fn models(f: *front.Front, conn: *Conn, a: Allocator) void { + const now = f.pool.loaded(a) catch return; + const created = std.Io.Clock.real.now(f.io).toSeconds(); + var data: std.ArrayList(Value) = .empty; + for (f.entries, 0..) |e, i| { + const ready = for (now) |s| { + if (s.slot == i and s.state == .ready) break s; + } else null; + const listed = if (ready) |s| childModels(a, f.io, s.port, &s.key) else null; + for ([_][]const []const u8{ &.{e.id}, e.aliases }) |names| for (names) |name| { + const o = entry(a, listed, name, created, ready != null) catch return; + data.append(a, .{ .object = o }) catch return; + }; + } + const o = json.newObject(a) catch return; + o.put(a, "object", .{ .string = "list" }) catch return; + o.put(a, "data", .{ .array = data.items }) catch return; + send(conn, a, .{ .object = o }); +} + +/// The child's own entry for ``name`` when it gave one, else the OpenAI fields alone; ``loaded`` comes last. +fn entry(a: Allocator, listed: ?Value, name: []const u8, created: i64, loaded: bool) !*json.Object { + const o = if (own(listed, name)) |x| try json.copyObject(a, x) else blk: { + const m = try json.newObject(a); + try m.put(a, "id", .{ .string = name }); + try m.put(a, "object", .{ .string = "model" }); + try m.put(a, "created", try json.intValue(a, created)); + try m.put(a, "owned_by", .{ .string = "tensorfold" }); + break :blk m; + }; + try o.put(a, "loaded", .{ .bool = loaded }); + return o; +} + +/// The object a child's /v1/models gives for ``name``. +fn own(listed: ?Value, name: []const u8) ?*json.Object { + const data = (listed orelse return null).get("data") orelse return null; + if (data != .array) return null; + for (data.array) |x| if (x == .object and std.mem.eql(u8, x.strField("id") orelse "", name)) return x.object; + return null; +} + +/// A ready child's /v1/models, asked with its key; null when it does not answer in time. +fn childModels(a: Allocator, io: std.Io, port: u16, key: []const u8) ?Value { + var client: std.http.Client = .{ .allocator = std.heap.smp_allocator, .io = io }; + client.connection_pool.free_size = 0; + defer client.deinit(); + const url = std.fmt.allocPrint(a, "http://127.0.0.1:{d}/v1/models", .{port}) catch return null; + const got = stream.fetch(a, io, &client, .{ .url = url, .limit = 1 << 20, .timeout_s = 2, .token = key }); + if (got.failed != .none or got.status != 200) return null; + return switch (json.parse(a, got.body) catch return null) { + .ok => |v| v, + .err => null, + }; +} + +/// Ollama's /api/tags: every id and alias, in the server's shape. +pub fn tags(f: *front.Front, conn: *Conn, a: Allocator) void { + var list: std.ArrayList(Value) = .empty; + for (f.entries) |e| for ([_][]const []const u8{ &.{e.id}, e.aliases }) |names| for (names) |name| { + list.append(a, named(a, name) catch return) catch return; + }; + sendModels(conn, a, list.items); +} + +/// Ollama's /api/ps: the ready children, each by its id. +pub fn ps(f: *front.Front, conn: *Conn, a: Allocator) void { + const now = f.pool.loaded(a) catch return; + var list: std.ArrayList(Value) = .empty; + for (now) |s| if (s.state == .ready) list.append(a, named(a, f.entries[s.slot].id) catch return) catch return; + sendModels(conn, a, list.items); +} + +/// Ollama's /api/version: the router's build. +pub fn version(f: *front.Front, conn: *Conn, a: Allocator) void { + const o = json.newObject(a) catch return; + o.put(a, "version", .{ .string = f.version }) catch return; + send(conn, a, .{ .object = o }); +} + +fn named(a: Allocator, name: []const u8) !Value { + const m = try json.newObject(a); + try m.put(a, "name", .{ .string = name }); + try m.put(a, "model", .{ .string = name }); + return .{ .object = m }; +} + +fn sendModels(conn: *Conn, a: Allocator, list: []Value) void { + const o = json.newObject(a) catch return; + o.put(a, "models", .{ .array = list }) catch return; + send(conn, a, .{ .object = o }); +} + +fn send(conn: *Conn, a: Allocator, v: Value) void { + conn.sendJson(200, json.stringify(a, v, .{}) catch return); +} diff --git a/zig/src/server/router/model_route.zig b/zig/src/server/router/model_route.zig new file mode 100644 index 00000000000..23e81038672 --- /dev/null +++ b/zig/src/server/router/model_route.zig @@ -0,0 +1,82 @@ +//! A model route: read the body, pick the child by its ``model``, start it if need be, and relay its reply. +const std = @import("std"); +const json = @import("json"); +const http_body = @import("../http_body.zig"); +const log = @import("../log.zig"); +const catalog = @import("catalog.zig"); +const pool_mod = @import("pool.zig"); +const relay = @import("relay.zig"); +const replies = @import("replies.zig"); +const front = @import("front.zig"); +const Conn = @import("../http_conn.zig").Conn; +const Allocator = std.mem.Allocator; + +/// Seconds a refused client is told to wait while the router stops, as the server tells it while it drains. +const retry_after_s = 30; + +pub fn serve(f: *front.Front, conn: *Conn, a: Allocator, route: front.ModelRoute) void { + const shape = route.shape; + const body = switch (http_body.read(conn, a, http_body.limit) catch return replies.send(conn, a, shape, .{ .status = 500, .kind = "server_error", .message = "out of memory" })) { + .ok => |b| b, + .refused => |message| return replies.send(conn, a, shape, .{ .status = 400, .message = message }), + }; + const value = switch (json.parse(a, if (body.len == 0) "{}" else body) catch return replies.send(conn, a, shape, .{ .status = 500, .kind = "server_error", .message = "out of memory" })) { + .ok => |v| v, + .err => |message| return replies.send(conn, a, shape, .{ .status = 400, .message = message }), + }; + const field = (if (value == .object) value.get("model") else null) orelse + return replies.send(conn, a, shape, .{ .status = 400, .message = "model is required: the router picks a model by the request's model field; GET /v1/models lists them", .param = "model", .code = "model_required" }); + if (field != .string) return replies.send(conn, a, shape, .{ .status = 400, .message = "model must be a string", .param = "model" }); + const i = catalog.find(f.entries, field.string) orelse return replies.send(conn, a, shape, replies.unknownModel(a, field.string)); + // the child's own key has every scope: a restricted key's Responses request must be stateless, as on a server + if (route.responses) if (@import("../auth_scope.zig").responseDenial(conn.key_scopes, value)) |why| return @import("../auth_scope_reply.zig").deny(conn, false, why); + if (f.draining.load(.acquire)) return replies.send(conn, a, shape, refusal(a, f, i, .stopping)); + const lease = switch (f.pool.acquire(a, i)) { + .lease => |l| l, + .refused => |r| return replies.send(conn, a, shape, refusal(a, f, i, r)), + }; + defer f.pool.release(lease); + const id = f.entries[i].id; + const result = relay.forward(conn, a, lease.port, &lease.key, body, f.limits); + switch (result.outcome) { + .done => replies.relayed(conn, result.status, id), + .no_reply => { + const exited = f.pool.lost(lease); + const message = if (exited) + std.fmt.allocPrint(a, "the server for model '{s}' exited while answering; the next request starts it again", .{id}) catch "the model's server exited" + else + std.fmt.allocPrint(a, "the server for model '{s}' closed the connection without a reply", .{id}) catch "the model's server sent no reply"; + replies.send(conn, a, shape, .{ .status = 502, .kind = "server_error", .message = message, .code = "model_server_failed" }); + }, + .cut => { + conn.close = true; + const exited = f.pool.lost(lease); + log.line("{s} \"{s}\" {d} - model={s}: reply cut short ({s})", .{ conn.peer, conn.requestline, result.status, id, if (exited) "its server exited" else "its server stopped sending" }); + }, + .client_gone => conn.close = true, + } +} + +/// The 503 a request gets when the pool gives it no child. +fn refusal(a: Allocator, f: *const front.Front, i: usize, r: pool_mod.Refusal) replies.Refusal { + const id = f.entries[i].id; + const gib = 1 << 30; + return switch (r) { + .stopping => .{ .status = 503, .kind = "server_error", .message = "server restarting: retry shortly", .code = "server_restarting", .retry_after_s = retry_after_s }, + .busy => .{ + .status = 503, + .kind = "server_error", + .message = std.fmt.allocPrint(a, "every loaded model is answering a request, and --max-loaded {d} leaves no room to load '{s}'; retry shortly", .{ f.pool.options.max_loaded, id }) catch "every loaded model is busy", + .code = "models_busy", + .retry_after_s = 10, + }, + .too_large => |t| .{ + .status = 503, + .kind = "server_error", + .message = std.fmt.allocPrint(a, "model '{s}' needs about {d:.1} GiB loaded and this machine has {d:.1} GiB, so it cannot load here", .{ id, @as(f64, @floatFromInt(t.need)) / gib, @as(f64, @floatFromInt(t.have)) / gib }) catch "the model cannot fit in this machine's memory", + .code = "model_too_large", + }, + .failed => |why| .{ .status = 503, .kind = "server_error", .message = std.fmt.allocPrint(a, "model '{s}' could not start: {s}", .{ id, why }) catch "the model could not start", .code = "model_load_failed" }, + .timeout => |s| .{ .status = 503, .kind = "server_error", .message = std.fmt.allocPrint(a, "model '{s}' was not ready within {d} s", .{ id, s }) catch "the model was not ready in time", .code = "model_load_timeout" }, + }; +} diff --git a/zig/src/server/router/pool.zig b/zig/src/server/router/pool.zig new file mode 100644 index 00000000000..f297a4a9299 --- /dev/null +++ b/zig/src/server/router/pool.zig @@ -0,0 +1,357 @@ +//! The router's children: started on demand, leased a request at a time, stopped when idle, crashed or out of room. +const std = @import("std"); +const benchmark_server = @import("../benchmark_server.zig"); +const log = @import("../log.zig"); +const catalog = @import("catalog.zig"); +const room = @import("room.zig"); +const Managed = benchmark_server.Managed; +const Allocator = std.mem.Allocator; + +pub const Options = struct { + max_loaded: u32 = 1, + /// Seconds a child may sit idle before the router stops it (0: never). + idle_s: i64 = 0, + /// Seconds a request waits for a busy model to finish and make room, before its 503. + busy_wait_s: f64 = 300, + /// Each stop's wait after SIGTERM, then after SIGKILL, in milliseconds: past the child's own drain. + grace_ms: u32 = 30_000, + /// The machine's memory in bytes, which loaded floors share; 0 checks no memory. + capacity: u64 = 0, + /// The folder each child's log is made in and unlinked from at once. + log_dir: []const u8, +}; + +/// A request's hold on a ready child: its port and key, released once its reply has gone. +pub const Lease = struct { slot: usize, gen: u32, port: u16, key: [64]u8 }; + +/// Why a request got no child: the router stops, every loaded model is busy, it cannot fit, or its load failed. +pub const Refusal = union(enum) { + stopping, + busy, + too_large: struct { need: u64, have: u64 }, + failed: []const u8, + timeout: f64, +}; + +pub const Acquired = union(enum) { lease: Lease, refused: Refusal }; + +/// One loaded or loading child, as /health and the listings show it. +pub const Status = struct { slot: usize, state: room.State, in_flight: u32, port: u16, key: [64]u8 }; + +const Slot = struct { + state: room.State = .unloaded, + child: ?Managed = null, + port: u16 = 0, + /// The child's API key, new for each start: 32 random bytes as hex. + key: [64]u8 = @splat('0'), + in_flight: u32 = 0, + waiters: u32 = 0, + used_ns: i96 = 0, + /// Counts starts; a request waiting on a load reads ``failure`` when ``failed_gen`` is the start it waited for. + gen: u32 = 0, + failed_gen: u32 = 0, + failure: [512]u8 = undefined, + failure_len: usize = 0, + /// What one start allocates (its log path, environment and lines), freed when its child is gone. + arena: std.heap.ArenaAllocator, +}; + +pub const Pool = struct { + gpa: Allocator, + io: std.Io, + entries: []const catalog.Entry, + env: *const std.process.Environ.Map, + options: Options, + slots: []Slot, + views: []room.View, + mutex: std.Io.Mutex = .init, + cond: std.Io.Condition = .init, + stopping: std.atomic.Value(bool) = .init(false), + reaper: ?std.Thread = null, + + pub fn init(gpa: Allocator, io: std.Io, entries: []const catalog.Entry, env: *const std.process.Environ.Map, options: Options) !*Pool { + const p = try gpa.create(Pool); + errdefer gpa.destroy(p); + const slots = try gpa.alloc(Slot, entries.len); + errdefer gpa.free(slots); + for (slots) |*s| s.* = .{ .arena = .init(gpa) }; + p.* = .{ .gpa = gpa, .io = io, .entries = entries, .env = env, .options = options, .slots = slots, .views = try gpa.alloc(room.View, entries.len) }; + return p; + } + + /// Frees the pool after ``stopAll``. + pub fn deinit(p: *Pool) void { + for (p.slots) |*s| s.arena.deinit(); + p.gpa.free(p.slots); + p.gpa.free(p.views); + p.gpa.destroy(p); + } + + /// A lease on entry ``i``'s child, starting it and making room first when it is not running. + pub fn acquire(p: *Pool, a: Allocator, i: usize) Acquired { + p.mutex.lockUncancelable(p.io); + defer p.mutex.unlock(p.io); + const busy_until = now(p.io) + nanoseconds(p.options.busy_wait_s); + var waited: ?u32 = null; + var load_until: i96 = 0; + while (true) { + if (p.stopping.load(.acquire)) return .{ .refused = .stopping }; + const s = &p.slots[i]; + if (waited) |g| if (s.failed_gen == g) return .{ .refused = .{ .failed = a.dupe(u8, s.failure[0..s.failure_len]) catch "" } }; + switch (s.state) { + .ready => { + if (p.exitedLocked(i)) continue; + s.in_flight += 1; + s.used_ns = now(p.io); + return .{ .lease = .{ .slot = i, .gen = s.gen, .port = s.port, .key = s.key } }; + }, + .loading, .stopping => { + if (s.state == .loading and waited != s.gen) { + waited = s.gen; + load_until = now(p.io) + nanoseconds(p.entries[i].startup_s + 10) + 2 * @as(i96, p.options.grace_ms) * std.time.ns_per_ms; + } + if (s.state == .loading and now(p.io) >= load_until) return .{ .refused = .{ .timeout = p.entries[i].startup_s } }; + s.waiters += 1; + p.pause(); + s.waiters -= 1; + }, + .unloaded => switch (room.decide(p.viewsLocked(), i, p.options.max_loaded, p.options.capacity)) { + .fits => return p.load(a, i), + .stop => |v| p.stopLocked(v, "least recently used, to make room"), + .wait => { + if (now(p.io) >= busy_until) return .{ .refused = .busy }; + p.pause(); + }, + .never => return .{ .refused = .{ .too_large = .{ .need = p.entries[i].floor.?, .have = p.options.capacity } } }, + }, + } + } + } + + /// Ends a lease: one request fewer in flight, and the child's idle time starts again. + pub fn release(p: *Pool, lease: Lease) void { + p.mutex.lockUncancelable(p.io); + defer p.mutex.unlock(p.io); + const s = &p.slots[lease.slot]; + s.in_flight -|= 1; + s.used_ns = now(p.io); + p.cond.broadcast(p.io); + } + + /// After a failed exchange: whether the leased child has exited, waiting briefly as its sockets close first. + pub fn lost(p: *Pool, lease: Lease) bool { + const until = now(p.io) + 2 * std.time.ns_per_s; + while (true) { + { + p.mutex.lockUncancelable(p.io); + defer p.mutex.unlock(p.io); + const s = &p.slots[lease.slot]; + if (s.gen != lease.gen or s.state != .ready) return true; + if (p.exitedLocked(lease.slot)) return true; + } + if (now(p.io) >= until) return false; + p.io.sleep(.fromMilliseconds(50), .awake) catch return false; + } + } + + /// Starts the thread that notices exits and stops children idle past ``idle_s``. + pub fn startReaper(p: *Pool) !void { + p.reaper = try std.Thread.spawn(.{}, reap, .{p}); + } + + /// Stops every child: new leases are refused, a load in progress ends, each child gets SIGTERM, then SIGKILL. + pub fn stopAll(p: *Pool) void { + p.stopping.store(true, .release); + p.mutex.lockUncancelable(p.io); + p.cond.broadcast(p.io); + // every drain starts at once; each stop below then waits on its own child + for (p.slots) |*s| if (s.state == .ready) std.posix.kill(s.child.?.pid, .TERM) catch {}; + const until = now(p.io) + 2 * @as(i96, p.options.grace_ms + 5_000) * std.time.ns_per_ms; + while (true) { + var left = false; + for (p.slots, 0..) |*s, i| { + if (s.state == .ready) p.stopLocked(i, "the router is stopping"); + left = left or s.state != .unloaded; + } + if (!left or now(p.io) >= until) break; + p.pause(); + } + p.mutex.unlock(p.io); + if (p.reaper) |t| t.join(); + p.reaper = null; + } + + /// The children loading, ready or stopping, with each one's port and key. + pub fn loaded(p: *Pool, a: Allocator) ![]const Status { + p.mutex.lockUncancelable(p.io); + defer p.mutex.unlock(p.io); + var out: std.ArrayList(Status) = .empty; + for (p.slots, 0..) |*s, i| if (s.state != .unloaded) + try out.append(a, .{ .slot = i, .state = s.state, .in_flight = s.in_flight, .port = s.port, .key = s.key }); + return out.items; + } + + /// The requests in flight across every child. + pub fn inFlight(p: *Pool) u32 { + p.mutex.lockUncancelable(p.io); + defer p.mutex.unlock(p.io); + var n: u32 = 0; + for (p.slots) |*s| n += s.in_flight; + return n; + } + + fn pause(p: *Pool) void { + p.cond.waitTimeout(p.io, &p.mutex, .{ .duration = .{ .raw = .fromMilliseconds(100), .clock = .awake } }) catch {}; + } + + fn viewsLocked(p: *Pool) []const room.View { + for (p.slots, p.views, p.entries) |*s, *v, e| v.* = .{ .state = s.state, .in_flight = s.in_flight, .waiters = s.waiters, .used_ns = s.used_ns, .floor = e.floor }; + return p.views; + } + + /// Starts entry ``i``'s child with the lock released, then publishes it ready, or the failure its waiters read. + fn load(p: *Pool, a: Allocator, i: usize) Acquired { + const s = &p.slots[i]; + const e = p.entries[i]; + s.state = .loading; + s.gen += 1; + const gen = s.gen; + var raw: [32]u8 = undefined; + p.io.random(&raw); + s.key = std.fmt.bytesToHex(raw, .lower); + _ = s.arena.reset(.free_all); + p.mutex.unlock(p.io); + if (e.floor == null) log.line("loading {s} (no memory estimate: only --max-loaded bounds it)", .{e.id}) else log.line("loading {s}", .{e.id}); + const t0 = now(p.io); + var failure: benchmark_server.Failure = .none; + var tail: []const []const u8 = &.{}; + const got = p.spawn(s.arena.allocator(), e, &s.key, &failure, &tail); + p.mutex.lockUncancelable(p.io); + if (got) |m| { + s.child = m; + s.port = portOf(m.base()); + s.state = .ready; + s.in_flight += 1; + s.used_ns = now(p.io); + p.cond.broadcast(p.io); + log.line("{s} ready in {d:.1} s", .{ e.id, @as(f64, @floatFromInt(s.used_ns - t0)) / 1e9 }); + return .{ .lease = .{ .slot = i, .gen = gen, .port = s.port, .key = s.key } }; + } + const message = describe(s.arena.allocator(), e, failure, tail) catch "it could not start"; + log.line("{s} could not start: {s}", .{ e.id, message }); + for (tail) |line| log.line("{s}: {s}", .{ e.id, line }); + s.failure_len = @min(message.len, s.failure.len); + @memcpy(s.failure[0..s.failure_len], message[0..s.failure_len]); + s.failed_gen = gen; + s.state = .unloaded; + p.cond.broadcast(p.io); + const refusal: Refusal = switch (failure) { + .stopped => .stopping, + .timeout => .{ .timeout = e.startup_s }, + else => .{ .failed = a.dupe(u8, s.failure[0..s.failure_len]) catch "" }, + }; + _ = s.arena.reset(.free_all); + return .{ .refused = refusal }; + } + + /// The benchmark's serve child, as the router runs it: its own key and process group, its log unlinked. + fn spawn(p: *Pool, sa: Allocator, e: catalog.Entry, key: *const [64]u8, failure: *benchmark_server.Failure, tail: *[]const []const u8) ?Managed { + failure.* = .setup; + // the parent's variables a serve would read, less the router's own keys; spawn adds the child's key + const env = benchmark_server.environWithout(sa, p.env, &.{ "TENSORFOLD_API_KEY", "TENSORFOLD_BENCHMARK_TOKEN" }) catch return null; + _ = std.Io.Dir.cwd().createDirPathStatus(p.io, p.options.log_dir, .fromMode(0o700)) catch {}; + var problem: []const u8 = ""; + return Managed.spawn(sa, p.io, p.env, e.argv, .{ + .startup_timeout_s = e.startup_s, + .grace_ms = p.options.grace_ms, + .bench_dir = p.options.log_dir, + .tail = tail, + .served = e.id, + .lock = false, + .own_group = true, + .key = key, + .environ = &env, + .guard = false, + .stop = &p.stopping, + .failure = failure, + }, &problem) catch { + failure.* = .setup; + return null; + }; + } + + /// Stops slot ``v``'s child with the lock released; the slot counts as loaded until it has exited. + fn stopLocked(p: *Pool, v: usize, why: []const u8) void { + const s = &p.slots[v]; + var m = s.child.?; + s.child = null; + s.state = .stopping; + p.mutex.unlock(p.io); + log.line("stopping {s}: {s}", .{ p.entries[v].id, why }); + if (m.stop() != null) log.line("{s} did not exit after SIGKILL; its memory may still be held", .{p.entries[v].id}); + p.mutex.lockUncancelable(p.io); + s.state = .unloaded; + _ = s.arena.reset(.free_all); + p.cond.broadcast(p.io); + } + + /// Whether ready slot ``i``'s child has exited; if so it is unloaded, and its last log lines are logged. + fn exitedLocked(p: *Pool, i: usize) bool { + const s = &p.slots[i]; + const m = &s.child.?; + // the tail is read only once the child has exited, so running out of memory still means it has + const lines = (m.exitedTail(s.arena.allocator()) catch &.{}) orelse return false; + log.line("{s} exited ({s} {d}); the next request starts it again", .{ p.entries[i].id, if (std.posix.W.IFSIGNALED(@bitCast(m.status))) "signal" else "status", exitCode(m.status) }); + for (lines) |line| log.line("{s}: {s}", .{ p.entries[i].id, line }); + _ = m.stop(); + s.child = null; + s.state = .unloaded; + _ = s.arena.reset(.free_all); + p.cond.broadcast(p.io); + return true; + } + + fn reap(p: *Pool) void { + p.mutex.lockUncancelable(p.io); + defer p.mutex.unlock(p.io); + while (!p.stopping.load(.acquire)) { + for (p.slots, 0..) |*s, i| { + if (s.state != .ready or p.exitedLocked(i) or p.options.idle_s <= 0) continue; + const idle = room.isIdle(.{ .state = s.state, .in_flight = s.in_flight, .waiters = s.waiters }); + if (idle and now(p.io) - s.used_ns >= @as(i96, p.options.idle_s) * std.time.ns_per_s) p.stopLocked(i, "idle past --idle-unload"); + } + p.cond.waitTimeout(p.io, &p.mutex, .{ .duration = .{ .raw = .fromMilliseconds(500), .clock = .awake } }) catch {}; + } + } +}; + +/// Why a start gave no child, for the 503 and the log: the child's own last lines when it exited. +fn describe(a: Allocator, e: catalog.Entry, failure: benchmark_server.Failure, tail: []const []const u8) ![]const u8 { + return switch (failure) { + .exited => if (tail.len > 0) std.fmt.allocPrint(a, "its server exited while loading: {s}", .{tail[tail.len - 1]}) else "its server exited while loading", + .timeout => std.fmt.allocPrint(a, "its server was not ready within {d} s", .{e.startup_s}), + .spawn => "its server could not be started; check the TensorFold installation", + .setup => "its server's log could not be created; check the TensorFold directory permissions", + .stopped => "the router is stopping", + .none => "it did not answer its readiness checks", + }; +} + +fn exitCode(status: c_int) u32 { + const s: u32 = @bitCast(status); + return if (std.posix.W.IFSIGNALED(s)) @intCast(@backingInt(std.posix.W.TERMSIG(s))) else std.posix.W.EXITSTATUS(s); +} + +/// ``http://127.0.0.1:PORT``'s port. +fn portOf(base: []const u8) u16 { + const colon = std.mem.lastIndexOfScalar(u8, base, ':') orelse return 0; + return std.fmt.parseInt(u16, base[colon + 1 ..], 10) catch 0; +} + +fn now(io: std.Io) i96 { + return std.Io.Clock.awake.now(io).toNanoseconds(); +} + +fn nanoseconds(seconds: f64) i96 { + return @as(i64, @intFromFloat(@min(@max(seconds, 0), 1e7) * 1e9)); +} diff --git a/zig/src/server/router/pool_test.zig b/zig/src/server/router/pool_test.zig new file mode 100644 index 00000000000..6eaa2cd4ea4 --- /dev/null +++ b/zig/src/server/router/pool_test.zig @@ -0,0 +1,195 @@ +//! pool.zig with /bin/sh children: least recently used stops, busy waits and their timeout, crashes, failures, stops. +const std = @import("std"); +const tc = @import("test_child.zig"); +const catalog = @import("catalog.zig"); +const pool_mod = @import("pool.zig"); +const t = std.testing; + +const Fixture = struct { + arena: std.heap.ArenaAllocator = .init(t.allocator), + tmp: std.testing.TmpDir, + children: std.ArrayList(tc.Child) = .empty, + pool: ?*pool_mod.Pool = null, + + fn init() Fixture { + return .{ .tmp = std.testing.tmpDir(.{}) }; + } + + fn deinit(f: *Fixture) void { + if (f.pool) |p| { + p.stopAll(); + p.deinit(); + } + for (f.children.items) |c| c.server.stop(); + f.tmp.cleanup(); + f.arena.deinit(); + } + + /// Fake children named ``ids`` and a pool over them, with ``extra`` entries after them. + fn start(f: *Fixture, ids: []const []const u8, extra: []const catalog.Entry, options: pool_mod.Options) !*pool_mod.Pool { + const a = f.arena.allocator(); + var entries: std.ArrayList(catalog.Entry) = .empty; + for (ids) |id| { + const c = try tc.start(a, id, &.{}, &.{}); + try f.children.append(a, c); + try entries.append(a, c.entry); + } + try entries.appendSlice(a, extra); + f.pool = try tc.pool(a, &f.tmp, entries.items, options); + return f.pool.?; + } +}; + +fn lease(p: *pool_mod.Pool, a: std.mem.Allocator, i: usize) !pool_mod.Lease { + return switch (p.acquire(a, i)) { + .lease => |l| l, + .refused => |r| { + std.debug.print("refused: {any}\n", .{r}); + return error.TestUnexpectedResult; + }, + }; +} + +test "serve --router: past --max-loaded the least recently used idle child stops, and a busy one is never stopped" { + var f: Fixture = .init(); + defer f.deinit(); + const a = f.arena.allocator(); + const p = try f.start(&.{ "alpha", "beta", "gamma" }, &.{}, .{ .max_loaded = 2, .log_dir = "" }); + p.release(try lease(p, a, 0)); + p.release(try lease(p, a, 1)); + p.release(try lease(p, a, 0)); // alpha is now the more recent + const alpha = tc.pid(p, 0).?; + const beta = tc.pid(p, 1).?; + const held = try lease(p, a, 2); + try t.expect(tc.gone(beta) and !tc.gone(alpha)); + try t.expect(tc.pid(p, 1) == null and tc.pid(p, 2) != null); + // alpha is idle and gamma is held: beta's start stops alpha, not the busy gamma + p.release(try lease(p, a, 1)); + try t.expect(tc.gone(alpha) and tc.pid(p, 2) != null); + p.release(held); + try t.expectEqual(@as(usize, 2), (try p.loaded(a)).len); +} + +const Waiter = struct { + p: *pool_mod.Pool, + a: std.mem.Allocator, + got: ?pool_mod.Acquired = null, + + fn run(w: *Waiter) void { + w.got = w.p.acquire(w.a, 1); + } +}; + +test "serve --router: with every loaded model busy a request waits for one to finish, and past its bound gets busy" { + var f: Fixture = .init(); + defer f.deinit(); + const a = f.arena.allocator(); + const p = try f.start(&.{ "alpha", "beta" }, &.{}, .{ .max_loaded = 1, .busy_wait_s = 0.3, .log_dir = "" }); + const held = try lease(p, a, 0); + const t0 = tc.now(); + const refused = p.acquire(a, 1); + try t.expect(refused == .refused and refused.refused == .busy); + try t.expect(tc.since(t0) >= 0.3 and tc.since(t0) < 5); + try t.expect(tc.pid(p, 0) != null and tc.pid(p, 1) == null); + p.options.busy_wait_s = 10; + var w: Waiter = .{ .p = p, .a = a }; + const thread = try std.Thread.spawn(.{}, Waiter.run, .{&w}); + @import("../benchmark_fake.zig").nap(300); + try t.expect(w.got == null); + const alpha = tc.pid(p, 0).?; + p.release(held); + thread.join(); + try t.expect(w.got.? == .lease); + try t.expect(tc.gone(alpha) and tc.pid(p, 1) != null); + p.release(w.got.?.lease); +} + +test "serve --router: a child that dies is unloaded, a failed exchange learns it, and the next request starts it again" { + var f: Fixture = .init(); + defer f.deinit(); + const a = f.arena.allocator(); + const p = try f.start(&.{"alpha"}, &.{}, .{ .log_dir = "" }); + const first = try lease(p, a, 0); + const before = tc.pid(p, 0).?; + try std.posix.kill(before, .KILL); + try t.expect(p.lost(first)); + p.release(first); + try t.expect(tc.pid(p, 0) == null); + const again = try lease(p, a, 0); + const after = tc.pid(p, 0).?; + try t.expect(after != before and !std.mem.eql(u8, &first.key, &again.key)); + try t.expect(!p.lost(again)); // alive: a failed exchange alone does not unload it + p.release(again); +} + +test "serve --router: a load that exits names the child's last line, and one that never serves times out" { + var f: Fixture = .init(); + defer f.deinit(); + const a = f.arena.allocator(); + const broken = try tc.failing(a, "broken", "tensorfold: example checkpoint is incomplete"); + const mute = try tc.silent(a, "mute", 0.5); + const p = try f.start(&.{}, &.{ broken, mute }, .{ .log_dir = "" }); + const failed = p.acquire(a, 0); + try t.expect(failed == .refused and failed.refused == .failed); + try t.expect(std.mem.indexOf(u8, failed.refused.failed, "example checkpoint is incomplete") != null); + const t0 = tc.now(); + const late = p.acquire(a, 1); + try t.expect(late == .refused and late.refused == .timeout); + try t.expect(tc.since(t0) >= 0.5 and tc.since(t0) < 8); + try t.expectEqual(@as(usize, 0), (try p.loaded(a)).len); +} + +const Loader = struct { + p: *pool_mod.Pool, + a: std.mem.Allocator, + got: ?pool_mod.Acquired = null, + + fn run(l: *Loader) void { + l.got = l.p.acquire(l.a, 1); + } +}; + +test "serve --router: stopping ends a load in progress, stops every child and refuses new leases" { + var f: Fixture = .init(); + defer f.deinit(); + const a = f.arena.allocator(); + const mute = try tc.silent(a, "mute", 30); + const p = try f.start(&.{"alpha"}, &.{mute}, .{ .max_loaded = 2, .log_dir = "" }); + p.release(try lease(p, a, 0)); + const alpha = tc.pid(p, 0).?; + var l: Loader = .{ .p = p, .a = a }; + const thread = try std.Thread.spawn(.{}, Loader.run, .{&l}); + const Loading = struct { + fn check(q: *pool_mod.Pool) bool { + return tc.pid(q, 1) == null and tc.state(q, 1) == .loading; + } + }; + try t.expect(tc.within(5_000, p, Loading.check)); + const t0 = tc.now(); + p.stopAll(); + thread.join(); + try t.expect(tc.since(t0) < 8); + try t.expect(l.got.? == .refused and l.got.?.refused == .stopping); + try t.expect(tc.gone(alpha)); + const after = p.acquire(a, 0); + try t.expect(after == .refused and after.refused == .stopping); +} + +test "serve --router: a child idle past --idle-unload is stopped, and a leased one is kept" { + var f: Fixture = .init(); + defer f.deinit(); + const a = f.arena.allocator(); + const p = try f.start(&.{ "alpha", "beta" }, &.{}, .{ .max_loaded = 2, .idle_s = 1, .log_dir = "" }); + try p.startReaper(); + p.release(try lease(p, a, 0)); + const held = try lease(p, a, 1); + const alpha = tc.pid(p, 0).?; + const Unloaded = struct { + fn check(q: *pool_mod.Pool) bool { + return tc.state(q, 0) == .unloaded; + } + }; + try t.expect(tc.within(5_000, p, Unloaded.check)); + try t.expect(tc.gone(alpha) and tc.pid(p, 1) != null); + p.release(held); +} diff --git a/zig/src/server/router/relay.zig b/zig/src/server/router/relay.zig new file mode 100644 index 00000000000..a0508a89aa0 --- /dev/null +++ b/zig/src/server/router/relay.zig @@ -0,0 +1,302 @@ +//! One request forwarded to a child, and its reply relayed to the client byte for byte as the bytes arrive. +const std = @import("std"); +const http_conn = @import("../http_conn.zig"); +const Conn = http_conn.Conn; +const Allocator = std.mem.Allocator; +const posix = std.posix; + +/// How an exchange ended: the whole reply relayed, the client gone, no reply head from the child, or a reply cut short. +pub const Outcome = enum { done, client_gone, no_reply, cut }; + +pub const Result = struct { outcome: Outcome, status: u16 = 0 }; + +/// Milliseconds the child may send nothing, before its reply's head or between its bytes. +pub const Limits = struct { idle_ms: i64 = 3_600_000 }; + +/// Request headers the router sets or ends itself: hop-by-hop, framing, the host, the keys and the origin it checked. +const dropped = [_][]const u8{ "host", "content-length", "transfer-encoding", "connection", "keep-alive", "proxy-connection", "te", "trailer", "upgrade", "expect", "authorization", "x-api-key", "proxy-authorization", "origin" }; + +/// Sends ``conn``'s request with ``body`` to the child on ``port`` under its ``key``, then relays the reply. +pub fn forward(conn: *Conn, a: Allocator, port: u16, key: []const u8, body: []const u8, limits: Limits) Result { + const fd = connect(port) orelse return .{ .outcome = .no_reply }; + defer _ = posix.system.close(fd); + const head = requestHead(a, conn, port, key, body.len) catch return .{ .outcome = .no_reply }; + if (!send(fd, head) or !send(fd, body)) return .{ .outcome = .no_reply }; + return relay(conn, fd, limits); +} + +/// The forwarded head: the client's method, target, version and end-to-end headers, the child's host and key. +pub fn requestHead(a: Allocator, conn: *const Conn, port: u16, key: []const u8, length: usize) ![]const u8 { + var out: std.ArrayList(u8) = .empty; + try out.print(a, "{s} {s} {s}\r\nHost: 127.0.0.1:{d}\r\n", .{ conn.method, conn.path, conn.version, port }); + for (conn.headers) |h| { + if (listed(&dropped, h.name) or connectionNames(conn, h.name)) continue; + try out.print(a, "{s}: {s}\r\n", .{ h.name, h.value }); + } + try out.print(a, "Authorization: Bearer {s}\r\nContent-Length: {d}\r\n", .{ key, length }); + if (conn.close) try out.appendSlice(a, "Connection: close\r\n"); + try out.appendSlice(a, "\r\n"); + return out.items; +} + +fn listed(names: []const []const u8, name: []const u8) bool { + for (names) |n| if (std.ascii.eqlIgnoreCase(n, name)) return true; + return false; +} + +/// Whether the client's Connection header names ``name`` as hop-by-hop. +fn connectionNames(conn: *const Conn, name: []const u8) bool { + for (conn.headers) |h| if (std.ascii.eqlIgnoreCase(h.name, "connection") and hasToken(h.value, name)) return true; + return false; +} + +fn hasToken(value: []const u8, token: []const u8) bool { + var it = std.mem.splitScalar(u8, value, ','); + while (it.next()) |part| if (std.ascii.eqlIgnoreCase(std.mem.trim(u8, part, " \t"), token)) return true; + return false; +} + +/// Keeps ``fd`` out of the children the router starts, which would otherwise hold its connection open. +pub fn closeOnExec(fd: posix.fd_t) void { + _ = @import("sys").c.fcntl(fd, posix.F.SETFD, @as(c_int, posix.FD_CLOEXEC)); +} + +fn connect(port: u16) ?posix.socket_t { + const rc = posix.system.socket(posix.AF.INET, posix.SOCK.STREAM, 0); + if (posix.errno(rc) != .SUCCESS) return null; + const fd: posix.socket_t = @intCast(rc); + closeOnExec(fd); + var addr: posix.sockaddr.in = .{ .family = posix.AF.INET, .port = std.mem.nativeToBig(u16, port), .addr = std.mem.nativeToBig(u32, 0x7f000001) }; + if (posix.errno(posix.system.connect(fd, @ptrCast(&addr), @sizeOf(posix.sockaddr.in))) != .SUCCESS) { + _ = posix.system.close(fd); + return null; + } + return fd; +} + +fn send(fd: posix.socket_t, bytes: []const u8) bool { + var at: usize = 0; + while (at < bytes.len) { + var fds = [_]posix.pollfd{.{ .fd = fd, .events = posix.POLL.OUT, .revents = 0 }}; + if ((posix.poll(&fds, 30_000) catch return false) == 0) return false; + const rc = posix.system.write(fd, bytes[at..].ptr, bytes.len - at); + switch (posix.errno(rc)) { + .SUCCESS => at += @intCast(rc), + .AGAIN, .INTR => {}, + else => return false, + } + } + return true; +} + +/// The reply head's status and framing. +pub const Head = struct { status: u16, length: ?u64 = null, chunked: bool = false, close: bool = false }; + +/// A reply head through its blank line; null when it is not an HTTP status line with valid framing. +pub fn parseHead(head: []const u8) ?Head { + var lines = std.mem.splitSequence(u8, head, "\r\n"); + const first = lines.next() orelse return null; + if (!std.mem.startsWith(u8, first, "HTTP/1.")) return null; + var words = std.mem.tokenizeScalar(u8, first, ' '); + _ = words.next(); + const code = words.next() orelse return null; + var out: Head = .{ .status = std.fmt.parseInt(u16, code, 10) catch return null, .close = std.mem.startsWith(u8, first, "HTTP/1.0") }; + while (lines.next()) |line| { + const colon = std.mem.indexOfScalar(u8, line, ':') orelse continue; + const name = line[0..colon]; + const value = std.mem.trim(u8, line[colon + 1 ..], " \t"); + if (std.ascii.eqlIgnoreCase(name, "content-length")) { + out.length = std.fmt.parseInt(u64, value, 10) catch return null; + } else if (std.ascii.eqlIgnoreCase(name, "transfer-encoding")) { + out.chunked = hasToken(value, "chunked"); + } else if (std.ascii.eqlIgnoreCase(name, "connection")) { + if (hasToken(value, "close")) out.close = true; + if (hasToken(value, "keep-alive")) out.close = false; + } + } + return out; +} + +/// Where a chunked body ends, read as it passes: the relayed bytes are never decoded or changed. +pub const Chunked = struct { + phase: enum { size, extension, data, data_end, trailer, done } = .size, + size: u64 = 0, + digits: u8 = 0, + left: u64 = 0, + line: usize = 0, + bad: bool = false, + + /// How many of ``bytes`` belong to the body; fewer than all once it has ended. + pub fn feed(c: *Chunked, bytes: []const u8) usize { + var i: usize = 0; + while (i < bytes.len and c.phase != .done) { + if (c.phase == .data) { + const take: usize = @intCast(@min(c.left, bytes.len - i)); + c.left -= take; + i += take; + if (c.left == 0) c.phase = .data_end; + continue; + } + const b = bytes[i]; + i += 1; + switch (c.phase) { + .size => if (std.fmt.charToDigit(b, 16)) |d| { + c.digits += 1; + if (c.digits > 15) c.stopBad(); + c.size = c.size * 16 + d; + } else |_| { + if (b == '\n') c.sized() else if (b != '\r') c.phase = .extension; + }, + .extension => if (b == '\n') c.sized(), + .data_end => if (b == '\n') { + c.phase = .size; + c.size = 0; + c.digits = 0; + }, + .trailer => if (b == '\n') { + if (c.line == 0) c.phase = .done; + c.line = 0; + } else if (b != '\r') { + c.line += 1; + }, + .data, .done => unreachable, + } + } + return i; + } + + fn sized(c: *Chunked) void { + if (c.digits == 0) return c.stopBad(); + if (c.size == 0) { + c.phase = .trailer; + c.line = 0; + } else { + c.phase = .data; + c.left = c.size; + } + } + + fn stopBad(c: *Chunked) void { + c.bad = true; + c.phase = .done; + } +}; + +/// A reply body's end: none, a length, chunks, or the child closing its socket. +const Framing = union(enum) { + none, + length: u64, + chunked: Chunked, + close, + + fn of(head: Head, method: []const u8) Framing { + if (std.mem.eql(u8, method, "HEAD") or head.status / 100 == 1 or head.status == 204 or head.status == 304) return .none; + if (head.chunked) return .{ .chunked = .{} }; + if (head.length) |n| return .{ .length = n }; + return .close; + } + + fn feed(f: *Framing, bytes: []const u8) usize { + switch (f.*) { + .none => return 0, + .length => |*left| { + const take: usize = @intCast(@min(left.*, bytes.len)); + left.* -= take; + return take; + }, + .chunked => |*c| return c.feed(bytes), + .close => return bytes.len, + } + } + + fn done(f: Framing) bool { + return switch (f) { + .none => true, + .length => |left| left == 0, + .chunked => |c| c.phase == .done, + .close => false, + }; + } +}; + +const Read = union(enum) { data: usize, eof, failed, client_gone }; + +/// The child's next bytes, while watching the client for a hangup; nothing for ``idle_ms`` is a failure. +fn read(conn: *Conn, fd: posix.socket_t, into: []u8, limits: Limits, watch: *bool) Read { + var waited: i64 = 0; + while (true) { + var fds = [_]posix.pollfd{ + .{ .fd = fd, .events = posix.POLL.IN, .revents = 0 }, + .{ .fd = if (watch.*) conn.fd else -1, .events = posix.POLL.IN, .revents = 0 }, + }; + const ready = posix.poll(&fds, 1000) catch return .failed; + if (fds[0].revents != 0) { + const n = posix.read(fd, into) catch return .failed; + return if (n == 0) .eof else .{ .data = n }; + } + // a client that sends more without leaving is checked each second, not polled, so its bytes cannot spin this + if (fds[1].revents != 0) watch.* = false; + if (conn.peerGone()) return .client_gone; + if (ready == 0) waited += 1000; + if (waited >= limits.idle_ms) return .failed; + } +} + +/// The reply from the child on ``fd``: its head and body written to the client as they come, then where it ended. +fn relay(conn: *Conn, fd: posix.socket_t, limits: Limits) Result { + var buf: [64 << 10]u8 = undefined; + var got: usize = 0; + var watch = true; + const head_end = while (true) { + if (std.mem.indexOf(u8, buf[0..got], "\r\n\r\n")) |i| break i + 4; + if (got == buf.len) return .{ .outcome = .no_reply }; + switch (read(conn, fd, buf[got..], limits, &watch)) { + .data => |n| got += n, + .eof, .failed => return .{ .outcome = .no_reply }, + .client_gone => return .{ .outcome = .client_gone }, + } + }; + const head = parseHead(buf[0..head_end]) orelse return .{ .outcome = .no_reply }; + var framing = Framing.of(head, conn.method); + const first = head_end + framing.feed(buf[head_end..got]); + conn.writeAll(buf[0..first]) catch return .{ .outcome = .client_gone, .status = head.status }; + while (!framing.done()) { + switch (read(conn, fd, &buf, limits, &watch)) { + .data => |n| conn.writeAll(buf[0..framing.feed(buf[0..n])]) catch return .{ .outcome = .client_gone, .status = head.status }, + .eof => if (framing == .close) break else return .{ .outcome = .cut, .status = head.status }, + .failed => return .{ .outcome = .cut, .status = head.status }, + .client_gone => return .{ .outcome = .client_gone, .status = head.status }, + } + } + if (framing == .chunked and framing.chunked.bad) return .{ .outcome = .cut, .status = head.status }; + if (head.close or framing == .close) conn.close = true; + conn.response_complete = true; + return .{ .outcome = .done, .status = head.status }; +} + +test "serve --router: a chunked body ends after its last chunk and trailers, however the bytes are split" { + const body = "4\r\nWiki\r\n5;x=1\r\npedia\r\n0\r\nX-T: 1\r\n\r\n"; + const then = body ++ "next"; + for (1..body.len + 1) |cut| { + var c: Chunked = .{}; + const first = c.feed(then[0..cut]); + try std.testing.expectEqual(cut, first); + const rest = c.feed(then[cut..]); + try std.testing.expectEqual(body.len - cut, rest); + try std.testing.expect(c.phase == .done and !c.bad); + } + var bad: Chunked = .{}; + _ = bad.feed("zz\r\n"); + try std.testing.expect(bad.bad); +} + +test "serve --router: a reply head gives its status and framing" { + const sse = parseHead("HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n").?; + try std.testing.expect(sse.status == 200 and sse.close and sse.length == null and !sse.chunked); + const json = parseHead("HTTP/1.1 404 Not Found\r\ncontent-length: 12\r\n\r\n").?; + try std.testing.expect(json.status == 404 and json.length.? == 12 and !json.close); + try std.testing.expect(parseHead("HTTP/1.1 200 OK\r\nTransfer-Encoding: gzip, chunked\r\n\r\n").?.chunked); + try std.testing.expect(parseHead("HTTP/1.0 200 OK\r\n\r\n").?.close); + try std.testing.expect(parseHead("SSH-2.0\r\n\r\n") == null); + try std.testing.expect(parseHead("HTTP/1.1 200 OK\r\nContent-Length: x\r\n\r\n") == null); +} diff --git a/zig/src/server/router/replies.zig b/zig/src/server/router/replies.zig new file mode 100644 index 00000000000..766f525b7fb --- /dev/null +++ b/zig/src/server/router/replies.zig @@ -0,0 +1,95 @@ +//! The router's own error replies, in the shape of the API the request came in on. +const std = @import("std"); +const json = @import("json"); +const log = @import("../log.zig"); +const Conn = @import("../http_conn.zig").Conn; +const Allocator = std.mem.Allocator; + +/// The API a route belongs to, which sets its error shape. +pub const Shape = enum { openai, anthropic, ollama }; + +/// One refusal: its status, OpenAI's error type and code, the parameter it names and the words a client reads. +pub const Refusal = struct { + status: u16, + message: []const u8, + kind: []const u8 = "invalid_request_error", + code: ?[]const u8 = null, + param: ?[]const u8 = null, + retry_after_s: ?u32 = null, +}; + +/// The request's model is none the router serves. +pub fn unknownModel(a: Allocator, name: []const u8) Refusal { + const message = std.fmt.allocPrint(a, "model '{s}' is not served here; GET /v1/models lists the models this router serves", .{name}) catch "model not found"; + return .{ .status = 404, .message = message, .code = "model_not_found", .param = "model" }; +} + +/// A route or method the router refuses by name in this version. +pub fn unsupported(a: Allocator, what: []const u8, why: []const u8) Refusal { + const message = std.fmt.allocPrint(a, "{s} is not served through the router in this version: {s}", .{ what, why }) catch "not served through the router"; + return .{ .status = 404, .message = message, .code = "unsupported_route" }; +} + +/// Sends ``r`` in ``shape``: OpenAI's error object, Anthropic's typed error, or Ollama's ``{"error": "..."}``. +pub fn send(conn: *Conn, a: Allocator, shape: Shape, r: Refusal) void { + const body = encode(a, shape, r) catch return conn.sendJson(500, "{\"error\": {\"message\": \"out of memory\"}}"); + var retry: [16]u8 = undefined; + var header: [1][2][]const u8 = undefined; + var extra: []const [2][]const u8 = &.{}; + if (r.retry_after_s) |s| { + header[0] = .{ "Retry-After", std.fmt.bufPrint(&retry, "{d}", .{s}) catch "30" }; + extra = &header; + } + conn.sendJsonWith(r.status, body, extra); +} + +pub fn encode(a: Allocator, shape: Shape, r: Refusal) ![]const u8 { + const o = try json.newObject(a); + switch (shape) { + .openai => { + const e = try json.newObject(a); + try e.put(a, "message", .{ .string = r.message }); + try e.put(a, "type", .{ .string = r.kind }); + try e.put(a, "param", if (r.param) |p| .{ .string = p } else .null); + try e.put(a, "code", if (r.code) |c| .{ .string = c } else .null); + try o.put(a, "error", .{ .object = e }); + }, + .anthropic => { + const e = try json.newObject(a); + try e.put(a, "type", .{ .string = anthropicType(r.status) }); + try e.put(a, "message", .{ .string = r.message }); + try o.put(a, "type", .{ .string = "error" }); + try o.put(a, "error", .{ .object = e }); + }, + .ollama => try o.put(a, "error", .{ .string = r.message }), + } + return json.stringify(a, .{ .object = o }, .{}); +} + +/// Anthropic's error type for a status, as the server's Messages routes name them. +fn anthropicType(status: u16) []const u8 { + return switch (status) { + 400 => "invalid_request_error", + 401 => "authentication_error", + 403 => "permission_error", + 404 => "not_found_error", + 429 => "rate_limit_error", + 503 => "overloaded_error", + else => "api_error", + }; +} + +/// The access line for a relayed reply: the server's line, then the model that answered. +pub fn relayed(conn: *const Conn, status: u16, id: []const u8) void { + log.line("{s} \"{s}\" {d} -{s} model={s}", .{ conn.peer, conn.requestline, status, log.keySuffix(conn), id }); +} + +test "serve --router: a refusal takes the shape of its route's API" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const r = unknownModel(a, "x\"y"); + try std.testing.expectEqualStrings("{\"error\": {\"message\": \"model 'x\\\"y' is not served here; GET /v1/models lists the models this router serves\", \"type\": \"invalid_request_error\", \"param\": \"model\", \"code\": \"model_not_found\"}}", try encode(a, .openai, r)); + try std.testing.expectEqualStrings("{\"type\": \"error\", \"error\": {\"type\": \"not_found_error\", \"message\": \"model 'x\\\"y' is not served here; GET /v1/models lists the models this router serves\"}}", try encode(a, .anthropic, r)); + try std.testing.expectEqualStrings("{\"error\": \"model 'x\\\"y' is not served here; GET /v1/models lists the models this router serves\"}", try encode(a, .ollama, r)); +} diff --git a/zig/src/server/router/room.zig b/zig/src/server/router/room.zig new file mode 100644 index 00000000000..bd5c0785803 --- /dev/null +++ b/zig/src/server/router/room.zig @@ -0,0 +1,85 @@ +//! Whether a model can start now: room under --max-loaded and the machine's memory, or the idle child to stop first. +const std = @import("std"); + +/// A slot's life: a child counts as loaded from the start of its load to the end of its stop. +pub const State = enum { unloaded, loading, ready, stopping }; + +/// What the decision reads of one slot. +pub const View = struct { state: State, in_flight: u32 = 0, waiters: u32 = 0, used_ns: i96 = 0, floor: ?u64 = null }; + +/// Start now; stop that idle child first; wait for a busy one; or never, as the model needs more than the machine. +pub const Room = union(enum) { fits, stop: usize, wait, never }; + +/// The decision for ``want``: at most ``max_loaded`` loaded, their floors within ``capacity`` (0: no memory check). +pub fn decide(views: []const View, want: usize, max_loaded: u32, capacity: u64) Room { + const need = views[want].floor; + if (capacity > 0) if (need) |n| if (n > capacity) return .never; + var loaded: u32 = 0; + var held: u64 = 0; + var idle: u32 = 0; + var freeable: u64 = 0; + var victim: ?usize = null; + for (views, 0..) |v, i| { + if (i == want or v.state == .unloaded) continue; + loaded += 1; + held += v.floor orelse 0; + if (!isIdle(v)) continue; + idle += 1; + freeable += v.floor orelse 0; + if (victim == null or v.used_ns < views[victim.?].used_ns) victim = i; + } + if (loaded < max_loaded and fits(held, need, capacity)) return .fits; + // stop an idle child only when stopping every idle one would make room: a busy one must finish first + if (victim) |v| if (loaded - idle < max_loaded and fits(held - freeable, need, capacity)) return .{ .stop = v }; + return .wait; +} + +/// A ready child with no request in flight and none waiting for it. +pub fn isIdle(v: View) bool { + return v.state == .ready and v.in_flight == 0 and v.waiters == 0; +} + +fn fits(held: u64, need: ?u64, capacity: u64) bool { + const n = need orelse return true; + return capacity == 0 or held + n <= capacity; +} + +test "serve --router: under --max-loaded a model starts, and past it the least recently used idle child stops first" { + const t = std.testing; + var v = [_]View{ .{ .state = .unloaded }, .{ .state = .unloaded }, .{ .state = .unloaded } }; + try t.expectEqual(Room.fits, decide(&v, 0, 2, 0)); + v[0] = .{ .state = .ready, .used_ns = 30 }; + v[1] = .{ .state = .ready, .used_ns = 10 }; + try t.expectEqual(Room{ .stop = 1 }, decide(&v, 2, 2, 0)); + v[1].used_ns = 40; + try t.expectEqual(Room{ .stop = 0 }, decide(&v, 2, 2, 0)); + try t.expectEqual(Room.fits, decide(&v, 2, 3, 0)); + v[0].in_flight = 1; + try t.expectEqual(Room{ .stop = 1 }, decide(&v, 2, 2, 0)); + v[1].waiters = 1; + try t.expectEqual(Room.wait, decide(&v, 2, 2, 0)); + v[1] = .{ .state = .stopping }; + try t.expectEqual(Room.wait, decide(&v, 2, 2, 0)); + v[1] = .{ .state = .loading }; + try t.expectEqual(Room.wait, decide(&v, 2, 2, 0)); +} + +test "serve --router: memory floors bound what loads, a model larger than the machine never starts, an unknown floor passes" { + const t = std.testing; + const gib: u64 = 1 << 30; + var v = [_]View{ + .{ .state = .ready, .used_ns = 1, .floor = 30 * gib }, + .{ .state = .ready, .used_ns = 2, .floor = 10 * gib }, + .{ .state = .unloaded, .floor = 40 * gib }, + }; + try t.expectEqual(Room{ .stop = 0 }, decide(&v, 2, 8, 64 * gib)); + v[0].in_flight = 1; + try t.expectEqual(Room.wait, decide(&v, 2, 8, 64 * gib)); + v[2].floor = 20 * gib; + try t.expectEqual(Room.fits, decide(&v, 2, 8, 64 * gib)); + v[2].floor = 65 * gib; + try t.expectEqual(Room.never, decide(&v, 2, 8, 64 * gib)); + v[2].floor = null; + try t.expectEqual(Room.fits, decide(&v, 2, 8, 64 * gib)); + try t.expectEqual(Room.fits, decide(&v, 2, 8, 0)); +} diff --git a/zig/src/server/router/router.zig b/zig/src/server/router/router.zig new file mode 100644 index 00000000000..44a7385d3bd --- /dev/null +++ b/zig/src/server/router/router.zig @@ -0,0 +1,108 @@ +//! ``tensorfold serve --router``: one address for many models, each a ``tensorfold serve`` child started on demand. +const std = @import("std"); +const cli = @import("../cli.zig"); +const auth = @import("../auth.zig"); +const log = @import("../log.zig"); +const serve = @import("../serve.zig"); +const args_mod = @import("args.zig"); +const config = @import("config.zig"); +const catalog = @import("catalog.zig"); +const pool_mod = @import("pool.zig"); +const front = @import("front.zig"); + +pub const Checkpoints = catalog.Checkpoints; +pub const Memory = catalog.Memory; +pub const wanted = args_mod.wanted; + +/// Routes until a stop signal; the process exit status. ``argv`` is serve's arguments, ``--router`` among them. +pub fn main(init: std.process.Init, argv: []const []const u8, checkpoints: Checkpoints, version: []const u8) !u8 { + const gpa = init.gpa; + const io = init.io; + const a = init.arena.allocator(); + const env = init.environ_map; + if (args_mod.help(argv)) { + try std.Io.File.stdout().writeStreamingAll(io, args_mod.usage_line); + return 0; + } + log.init(io, false); + var u: cli.Usage = .{}; + const settings = args_mod.parse(a, argv, &u) catch |e| switch (e) { + error.Usage => return usage(u.message), + else => |x| return x, + }; + var problem: []const u8 = ""; + const exe = try std.process.executablePathAlloc(io, a); + const entries = if (settings.config) |path| blk: { + const models = config.load(a, path, &u) catch |e| switch (e) { + error.Usage => return usage(u.message), + else => |x| return x, + }; + break :blk try catalog.build(a, io, env, exe, models, checkpoints, &problem) orelse return fail(problem); + } else try catalog.buildCached(a, io, env, exe, try catalog.cached(a, io, env, checkpoints), checkpoints); + if (entries.len == 0) return fail("no models to route: run tensorfold pull OWNER/NAME, or list models in --router-config FILE.toml"); + var store = auth.Store.init(gpa, settings.api_keys, env.get("TENSORFOLD_API_KEY") orelse "", settings.api_key_file, false, &problem) catch + return fail(if (problem.len > 0) problem else "API key file cannot be opened safely"); + defer store.deinit(); + const capacity = std.process.totalSystemMemory() catch 0; + for (entries) |e| note(e, capacity); + const pool = try pool_mod.Pool.init(gpa, io, entries, env, .{ + .max_loaded = settings.max_loaded, + .idle_s = settings.idle_s, + .capacity = capacity, + .log_dir = try std.fs.path.join(a, &.{ env.get("HOME") orelse ".", ".tensorfold", "router" }), + }); + defer pool.deinit(); + const lis = serve.openTcp(io, settings) orelse return 1; + serve.installSignals(store.enabled()); + // without keys a hangup stops the router as a TERM does, so its children never outlive the terminal + if (!store.enabled()) serve.stopOnHangup(); + if (!store.enabled() and !auth.loopback(settings.host)) log.line("warning: non-loopback router has no API key; requests are open", .{}); + var f: front.Front = .{ + .gpa = gpa, + .io = io, + .pool = pool, + .entries = entries, + .keys = if (store.enabled()) &store else null, + .browser = .{ .allowed_hosts = settings.allowed_hosts, .allowed_origins = settings.allowed_origins }, + .version = version, + }; + try pool.startReaper(); + var accept_stop: std.atomic.Value(bool) = .init(false); + const accept = try std.Thread.spawn(.{}, front.Front.serve, .{ &f, lis, &accept_stop }); + var idle_text: [64]u8 = undefined; + const idle = if (settings.idle_s > 0) std.fmt.bufPrint(&idle_text, "; an idle model stops after {d} s", .{settings.idle_s}) catch "" else ""; + log.line("routing {d} model{s} at http://{s}:{d}/v1: at most {d} loaded at once{s}; a request's model field picks one", .{ entries.len, if (entries.len == 1) "" else "s", settings.host, lis.port(), settings.max_loaded, idle }); + while (!serve.stopping()) io.sleep(.fromMilliseconds(50), .awake) catch {}; + f.draining.store(true, .release); + log.line("shutting down ({s}): stopping the loaded models", .{serve.stopName()}); + pool.stopAll(); + accept_stop.store(true, .release); + accept.join(); + lis.close(); + var waited: u32 = 0; + while (f.open.load(.acquire) > 0 and waited < 100) : (waited += 1) io.sleep(.fromMilliseconds(50), .awake) catch {}; + if (f.open.load(.acquire) > 0) { + log.line("shutting down: exiting with {d} connection(s) still open", .{f.open.load(.acquire)}); + std.process.exit(0); // connections still open: end without freeing what they read + } + log.line("shutting down: stopped", .{}); + return 0; +} + +/// A model the memory check cannot bound, or one larger than the machine, said once at startup. +fn note(e: catalog.Entry, capacity: u64) void { + const gib: f64 = 1 << 30; + const floor = e.floor orelse return log.line("{s}: no memory estimate, so only --max-loaded bounds it", .{e.id}); + if (capacity > 0 and floor > capacity) + log.line("{s}: needs about {d:.1} GiB loaded, more than this machine's {d:.1} GiB; requests for it get 503", .{ e.id, @as(f64, @floatFromInt(floor)) / gib, @as(f64, @floatFromInt(capacity)) / gib }); +} + +fn usage(message: []const u8) u8 { + std.debug.print("{s}tensorfold serve: error: {s}\n", .{ args_mod.usage_line, message }); + return 2; +} + +fn fail(message: []const u8) u8 { + std.debug.print("tensorfold: {s}\n", .{message}); + return 1; +} diff --git a/zig/src/server/router/router_test.zig b/zig/src/server/router/router_test.zig new file mode 100644 index 00000000000..39cb36979d4 --- /dev/null +++ b/zig/src/server/router/router_test.zig @@ -0,0 +1,13 @@ +//! The router's tests: every one is named ``serve --router:`` for ``zig build test-router-host``. +const std = @import("std"); + +test { + _ = @import("config_test.zig"); + _ = @import("pool_test.zig"); + _ = @import("front_test.zig"); +} + +test "serve --router: every module compiles, its public declarations included" { + inline for (.{ @import("args.zig"), @import("catalog.zig"), @import("config.zig"), @import("room.zig"), @import("pool.zig"), @import("relay.zig"), @import("replies.zig"), @import("front.zig"), @import("model_route.zig"), @import("listing.zig"), @import("router.zig") }) |m| + std.testing.refAllDecls(m); +} diff --git a/zig/src/server/router/test_child.zig b/zig/src/server/router/test_child.zig new file mode 100644 index 00000000000..ce4de9660ac --- /dev/null +++ b/zig/src/server/router/test_child.zig @@ -0,0 +1,156 @@ +//! The router tests' children: a /bin/sh stand-in that prints serve's line for a fake server in the test process. +const std = @import("std"); +const fake = @import("../benchmark_fake.zig"); +const catalog = @import("catalog.zig"); +const pool_mod = @import("pool.zig"); +const posix = std.posix; +const Allocator = std.mem.Allocator; + +pub const Fake = fake.Fake; +pub const Route = fake.Route; +pub const Write = fake.Write; + +/// One fake model: the server its requests reach, and the entry whose child announces that server's port. +pub const Child = struct { server: *fake.Fake, entry: catalog.Entry }; + +/// A fake child for ``id`` and ``aliases``: ready at once, then answering ``routes`` as scripted. +pub fn start(a: Allocator, id: []const u8, aliases: []const []const u8, routes: []const fake.Route) !Child { + var listed: std.ArrayList(u8) = .empty; + try listed.appendSlice(a, "{\"object\": \"list\", \"data\": ["); + for ([_][]const []const u8{ &.{id}, aliases }) |names| for (names) |name| { + if (listed.items[listed.items.len - 1] == '}') try listed.appendSlice(a, ", "); + try listed.print(a, "{{\"id\": \"{s}\", \"object\": \"model\", \"created\": 1, \"owned_by\": \"tensorfold\", \"context_length\": 4096}}", .{name}); + }; + try listed.appendSlice(a, "]}"); + var all: std.ArrayList(fake.Route) = .empty; + try all.append(a, .{ .method = "GET", .path = "/health", .replies = try a.dupe([]const fake.Write, &.{try fake.jsonReply(a, "200 OK", "{\"status\": \"ok\"}")}) }); + try all.append(a, .{ .method = "GET", .path = "/v1/models", .replies = try a.dupe([]const fake.Write, &.{try fake.jsonReply(a, "200 OK", listed.items)}) }); + try all.appendSlice(a, routes); + const server = try fake.Fake.start(std.testing.allocator, all.items); + const script = try std.fmt.allocPrint(a, "printf '[tensorfold] serving %s at http://127.0.0.1:%s/v1 (x)\\n' '{s}' {d}; exec sleep 60", .{ id, server.port }); + return .{ .server = server, .entry = .{ .id = id, .aliases = aliases, .argv = try a.dupe([]const u8, &.{ "/bin/sh", "-c", script }), .startup_s = 10 } }; +} + +/// A child that exits during its load after printing ``line``. +pub fn failing(a: Allocator, id: []const u8, line: []const u8) !catalog.Entry { + const script = try std.fmt.allocPrint(a, "echo '{s}'; exit 3", .{line}); + return .{ .id = id, .argv = try a.dupe([]const u8, &.{ "/bin/sh", "-c", script }), .startup_s = 10 }; +} + +/// A child that never says it is serving. +pub fn silent(a: Allocator, id: []const u8, startup_s: f64) !catalog.Entry { + return .{ .id = id, .argv = try a.dupe([]const u8, &.{ "/bin/sh", "-c", "exec sleep 60" }), .startup_s = startup_s }; +} + +/// A pool over ``entries`` whose children log under a test folder and stop within two seconds. +pub fn pool(a: Allocator, tmp: *std.testing.TmpDir, entries: []const catalog.Entry, options: pool_mod.Options) !*pool_mod.Pool { + const env = try a.create(std.process.Environ.Map); + env.* = .init(a); + try env.put("PATH", "/usr/bin:/bin"); + var o = options; + o.log_dir = try std.fs.path.join(a, &.{ try fake.tmpPath(a, tmp), "router" }); + o.grace_ms = 2_000; + return pool_mod.Pool.init(std.testing.allocator, std.testing.io, entries, env, o); +} + +/// Whether ``process`` is no longer a process. +pub fn gone(process: posix.pid_t) bool { + posix.kill(process, @fromBackingInt(0)) catch |e| return e == error.ProcessNotFound; + return false; +} + +/// The running child's pid in slot ``i``. +pub fn pid(p: *pool_mod.Pool, i: usize) ?posix.pid_t { + p.mutex.lockUncancelable(p.io); + defer p.mutex.unlock(p.io); + return if (p.slots[i].child) |m| m.pid else null; +} + +/// Slot ``i``'s state. +pub fn state(p: *pool_mod.Pool, i: usize) @import("room.zig").State { + p.mutex.lockUncancelable(p.io); + defer p.mutex.unlock(p.io); + return p.slots[i].state; +} + +/// Seconds since ``t0`` on the awake clock. +pub fn since(t0: i96) f64 { + return @as(f64, @floatFromInt(std.Io.Clock.awake.now(std.testing.io).toNanoseconds() - t0)) / 1e9; +} + +pub fn now() i96 { + return std.Io.Clock.awake.now(std.testing.io).toNanoseconds(); +} + +/// Waits up to ``ms`` for ``f(ctx)``; false when it never held. +pub fn within(ms: u32, ctx: anytype, comptime f: fn (@TypeOf(ctx)) bool) bool { + var waited: u32 = 0; + while (waited < ms) : (waited += 10) { + if (f(ctx)) return true; + fake.nap(10); + } + return f(ctx); +} + +/// One whole exchange on a new connection to ``port``, read until the other side closes it. +pub fn exchangeWith(a: std.mem.Allocator, port: u16, request: []const u8) ![]const u8 { + const fd = try dial(port); + defer _ = posix.system.close(fd); + try sendAll(fd, request); + var out: std.ArrayList(u8) = .empty; + try readUntil(a, fd, &out, null, 10_000); + return out.items; +} + +pub fn dial(port: u16) !posix.socket_t { + 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); + var addr: posix.sockaddr.in = .{ .family = posix.AF.INET, .port = std.mem.nativeToBig(u16, port), .addr = std.mem.nativeToBig(u32, 0x7f000001) }; + if (posix.errno(posix.system.connect(fd, @ptrCast(&addr), @sizeOf(posix.sockaddr.in))) != .SUCCESS) return error.ConnectFailed; + return fd; +} + +pub fn sendAll(fd: posix.socket_t, bytes: []const u8) !void { + var at: usize = 0; + while (at < bytes.len) { + const n = posix.system.write(fd, bytes[at..].ptr, bytes.len - at); + if (posix.errno(n) != .SUCCESS or n <= 0) return error.WriteFailed; + at += @intCast(n); + } +} + +/// Reads into ``out`` until ``want`` bytes are there (null: until EOF), failing after ``ms`` without them. +pub fn readUntil(a: std.mem.Allocator, fd: posix.socket_t, out: *std.ArrayList(u8), want: ?usize, ms: u32) !void { + var waited: u32 = 0; + while (want == null or out.items.len < want.?) { + var fds = [_]posix.pollfd{.{ .fd = fd, .events = posix.POLL.IN, .revents = 0 }}; + if (try posix.poll(&fds, 20) == 0) { + waited += 20; + if (waited >= ms) return error.Timeout; + continue; + } + var buf: [4096]u8 = undefined; + const n = posix.read(fd, &buf) catch 0; + if (n == 0) return if (want == null) {} else error.EndOfStream; + try out.appendSlice(a, buf[0..n]); + } +} + +pub fn post(a: std.mem.Allocator, path: []const u8, body: []const u8, extra: []const u8) ![]const u8 { + return std.fmt.allocPrint(a, "POST {s} HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\nContent-Length: {d}\r\nConnection: close\r\n{s}\r\n{s}", .{ path, body.len, extra, body }); +} + +pub fn get(a: std.mem.Allocator, path: []const u8, extra: []const u8) ![]const u8 { + return std.fmt.allocPrint(a, "GET {s} HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n{s}\r\n", .{ path, extra }); +} + +pub fn status(reply: []const u8) u16 { + if (reply.len < 12) return 0; + return std.fmt.parseInt(u16, reply[9..12], 10) catch 0; +} + +pub fn bodyOf(reply: []const u8) []const u8 { + const at = std.mem.indexOf(u8, reply, "\r\n\r\n") orelse return ""; + return reply[at + 4 ..]; +} diff --git a/zig/src/server/router_serve_test.zig b/zig/src/server/router_serve_test.zig new file mode 100644 index 00000000000..187a0f94b77 --- /dev/null +++ b/zig/src/server/router_serve_test.zig @@ -0,0 +1,79 @@ +//! The router over real serve children: fake_serve as each model's server, its own key, replies and exits. +const std = @import("std"); +const listener_mod = @import("listener.zig"); +const catalog = @import("router/catalog.zig"); +const front = @import("router/front.zig"); +const tc = @import("router/test_child.zig"); +const t = std.testing; +const posix = std.posix; + +/// The scripted engine's checkpoint: the build runs this test from the repository's root. +const fixtures = "zig/tests/server/fixtures"; + +fn entry(a: std.mem.Allocator, id: []const u8, aliases: []const []const u8) !catalog.Entry { + const argv = try catalog.childArgv(a, @import("fake_serve_exe").path, .{ .id = id, .aliases = aliases, .model = fixtures, .flags = &.{"--no-thinking"} }); + return .{ .id = id, .aliases = aliases, .argv = argv, .startup_s = 30 }; +} + +fn chat(a: std.mem.Allocator, model: []const u8, stream: bool) ![]const u8 { + const body = try std.fmt.allocPrint(a, "{{\"model\": \"{s}\", \"messages\": [{{\"role\": \"user\", \"content\": \"hi\"}}], \"stream\": {}}}", .{ model, stream }); + return tc.post(a, "/v1/chat/completions", body, ""); +} + +fn has(text: []const u8, needle: []const u8) bool { + if (std.mem.indexOf(u8, text, needle) != null) return true; + std.debug.print("missing \"{s}\" in:\n{s}\n", .{ needle, text }); + return false; +} + +test "serve --router: real serve children answer under their own keys, give way under --max-loaded and restart" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const entries = [_]catalog.Entry{ try entry(a, "alpha", &.{"a1"}), try entry(a, "beta", &.{}) }; + const pool = try tc.pool(a, &tmp, &entries, .{ .max_loaded = 1, .log_dir = "" }); + defer pool.deinit(); + defer pool.stopAll(); + const f = try a.create(front.Front); + f.* = .{ .gpa = t.allocator, .io = t.io, .pool = pool, .entries = &entries }; + const lis = try listener_mod.Listener.open(.{ .ip4 = .loopback(0) }); + defer lis.close(); + var stop: std.atomic.Value(bool) = .init(false); + const accept = try std.Thread.spawn(.{}, front.Front.serve, .{ f, lis, &stop }); + defer { + stop.store(true, .release); + accept.join(); + var waited: u32 = 0; + while (f.open.load(.acquire) > 0 and waited < 500) : (waited += 1) @import("benchmark_fake.zig").nap(10); + } + const port = lis.port(); + // an alias reaches its model, whose own server answers to the name that was asked + const first = try tc.exchangeWith(a, port, try chat(a, "a1", false)); + try t.expectEqual(@as(u16, 200), tc.status(first)); + try t.expect(has(tc.bodyOf(first), "\"model\": \"a1\"") and has(tc.bodyOf(first), "Hello")); + const child = (try pool.loaded(a))[0]; + const direct = try tc.exchangeWith(a, child.port, try chat(a, "alpha", false)); + try t.expectEqual(@as(u16, 401), tc.status(direct)); + const keyed = try tc.exchangeWith(a, child.port, try tc.get(a, "/v1/models", try std.fmt.allocPrint(a, "Authorization: Bearer {s}\r\n", .{&child.key}))); + try t.expectEqual(@as(u16, 200), tc.status(keyed)); + const streamed = try tc.exchangeWith(a, port, try chat(a, "alpha", true)); + try t.expect(has(streamed, "text/event-stream") and std.mem.endsWith(u8, streamed, "data: [DONE]\n\n")); + const listed = tc.bodyOf(try tc.exchangeWith(a, port, try tc.get(a, "/v1/models", ""))); + try t.expect(has(listed, "\"id\": \"alpha\", \"object\": \"model\"") and has(listed, "\"capabilities\": {") and has(listed, "\"loaded\": true")); + // --max-loaded 1: beta's request stops alpha, and a beta that dies is started again by the next request + const alpha = tc.pid(pool, 0).?; + try t.expectEqual(@as(u16, 200), tc.status(try tc.exchangeWith(a, port, try chat(a, "beta", false)))); + try t.expect(tc.gone(alpha) and tc.pid(pool, 0) == null); + const beta = tc.pid(pool, 1).?; + try posix.kill(beta, .KILL); + const Exited = struct { + fn check(pid: posix.pid_t) bool { + return @import("benchmark_server.zig").ended(pid); + } + }; + try t.expect(tc.within(5_000, beta, Exited.check)); // a request racing the kill would rightly get 502 + try t.expectEqual(@as(u16, 200), tc.status(try tc.exchangeWith(a, port, try chat(a, "beta", false)))); + try t.expect(tc.pid(pool, 1).? != beta); +} diff --git a/zig/src/server/serve.zig b/zig/src/server/serve.zig index a8b3dd8536f..94abd108612 100644 --- a/zig/src/server/serve.zig +++ b/zig/src/server/serve.zig @@ -46,10 +46,21 @@ pub fn installSignals(keys: bool) void { if (keys) auth.installHangup(); } +/// SIGHUP stops the process as SIGTERM does: a router without keys, whose children must not outlive its terminal. +pub fn stopOnHangup() void { + const stop: posix.Sigaction = .{ .handler = .{ .handler = onStop }, .mask = posix.sigemptyset(), .flags = 0 }; + posix.sigaction(.HUP, &stop, null); +} + pub fn stopping() bool { return stop_requested.load(.acquire); } +/// The signal that asked for the stop, by name, for a shutdown line. +pub fn stopName() []const u8 { + return signalName(stop_signal.load(.acquire)); +} + /// The hard limit macOS reads as unlimited. const rlim_infinity: u64 = platform.c.RLIM.INFINITY; @@ -341,7 +352,8 @@ pub fn run(gpa: Allocator, io: std.Io, args: cli.Args, s: Setup) u8 { return 0; } -fn openTcp(io: std.Io, args: anytype) ?listener_mod.Listener { +/// The TCP listener on ``args.host`` and ``args.port``; null after printing why it cannot listen. +pub fn openTcp(io: std.Io, args: anytype) ?listener_mod.Listener { const address = resolve(io, args.host, args.port) orelse { std.debug.print("tensorfold: cannot resolve --host {s}\n", .{args.host}); return null; diff --git a/zig/src/server/server.zig b/zig/src/server/server.zig index eaa53916be6..a9b1ad763a9 100644 --- a/zig/src/server/server.zig +++ b/zig/src/server/server.zig @@ -6,7 +6,6 @@ const json = @import("json"); const errors = @import("errors.zig"); const fields = @import("fields.zig"); const auth = @import("auth.zig"); -const scope = @import("auth_scope.zig"); const request_guard = @import("request_guard.zig"); const metrics = @import("metrics.zig"); const model_text = @import("model_text.zig"); @@ -428,49 +427,10 @@ pub const Server = struct { /// The key gate before any route: 401 for a gated path without a valid key (``Authenticated._authenticate``). fn authenticate(srv: *Server, conn: *http_conn.Conn, a: Allocator) bool { - const keys = srv.keys orelse return true; - if (std.mem.eql(u8, conn.method, "OPTIONS") or !keys.enabled()) return true; - const matched = keys.matchIdentity(a, single(conn, "Authorization"), single(conn, "x-api-key")); - if (matched) |m| { - conn.key_label = m.label; - conn.key_digest = m.digest; - conn.key_scopes = m.scopes; - } - if (!auth.gatedRequest(conn.method, conn.path, keys.metrics_open)) return true; - const path = auth.routePath(conn.path); - // a Responses WebSocket upgrade opens with an inference key; the socket checks each response.create again - const upgrade = @import("ws_upgrade.zig").requested(conn) and std.mem.eql(u8, responses.route(path) orelse "-", ""); - if (matched != null and (scope.allows(conn.key_scopes, conn.method, conn.path) or (upgrade and scope.allowsUpgrade(conn.key_scopes)))) return true; - const messages = for ([_][]const u8{ "/v1/messages", "/v1/messages/count_tokens", "/messages", "/messages/count_tokens" }) |p| { - if (std.mem.eql(u8, path, p)) break true; - } else false; - if (matched != null) { - // a key without this route's scope is refused before its body is read or a parked model wakes - @import("auth_scope_reply.zig").deny(conn, messages, .route); - return false; - } - const body = if (messages) - "{\"type\": \"error\", \"error\": {\"type\": \"authentication_error\", \"message\": \"A valid API key is required\"}}" - else - "{\"error\": {\"message\": \"A valid API key is required\", \"type\": \"invalid_request_error\", \"param\": null, \"code\": \"invalid_api_key\"}}"; - conn.close = true; - conn.startResponse(401, null) catch return false; - conn.addHeader("WWW-Authenticate", "Bearer") catch return false; - conn.addHeader("Content-Type", "application/json") catch return false; - var len: [24]u8 = undefined; - conn.addHeader("Content-Length", std.fmt.bufPrint(&len, "{d}", .{body.len}) catch unreachable) catch return false; - conn.addHeader("Connection", "close") catch return false; - conn.finish(if (std.mem.eql(u8, conn.method, "HEAD")) "" else body) catch {}; - return false; + return @import("auth_gate.zig").admit(srv.keys, conn, a); } }; -/// A header that appears exactly once; none or several read as absent (as the key match reads them). -fn single(conn: *const http_conn.Conn, name: []const u8) ?[]const u8 { - if (conn.headerCount(name) != 1) return null; - return conn.header(name); -} - fn merge(into: *json.Object, cx: *Cx, from: Value) errors.Refused!void { for (from.object.keys(), from.object.values()) |k, v| if (v != .null) try into.put(cx.a, k, v); } diff --git a/zig/src/server/toml_flat.zig b/zig/src/server/toml_flat.zig index d1f32580e68..8ccb4f66147 100644 --- a/zig/src/server/toml_flat.zig +++ b/zig/src/server/toml_flat.zig @@ -1,11 +1,15 @@ -//! A strict subset of TOML 1.0 for flat settings files: top-level ``key = value`` lines, the rest refused by line. +//! A strict subset of TOML 1.0 for flat settings files: ``key = value`` lines, at most one ``[[name]]`` table kind. const std = @import("std"); const Allocator = std.mem.Allocator; /// A number keeps its text, ready to be a flag's value: no ``_``, and no leading ``+`` on an integer. pub const Scalar = union(enum) { string: []const u8, integer: []const u8, float: []const u8, boolean: bool }; pub const Value = union(enum) { scalar: Scalar, array: []const []const u8 }; -pub const Entry = struct { key: []const u8, line: u32, value: Value }; +/// ``table`` counts the ``[[name]]`` headers before the entry from 1; 0 is the top level. +pub const Entry = struct { key: []const u8, line: u32, value: Value, table: u32 = 0 }; + +/// The one ``[[name]]`` array-of-tables header a reader takes; null, the flat reader's, refuses every table. +pub const Shape = struct { table: ?[]const u8 = null }; /// Why a text was refused and on which line (1-based). pub const Problem = struct { line: u32 = 0, message: []const u8 = "" }; @@ -14,6 +18,14 @@ pub const Error = error{ Invalid, OutOfMemory }; /// Top-level ``key = value`` lines in file order; every text this accepts is valid TOML 1.0 with the same meaning. pub fn parse(a: Allocator, text: []const u8, problem: *Problem) Error![]const Entry { + return (try parseShaped(a, text, .{}, problem)).entries; +} + +/// The entries in file order and the line of each ``[[name]]`` header, the first being table 1. +pub const Shaped = struct { entries: []const Entry, tables: []const u32 }; + +/// ``parse`` that also takes ``shape``'s ``[[name]]`` headers, each entry tagged with the table it sits in. +pub fn parseShaped(a: Allocator, text: []const u8, shape: Shape, problem: *Problem) Error!Shaped { var r: Reader = .{ .a = a, .text = text, .problem = problem }; if (std.mem.startsWith(u8, text, "\xef\xbb\xbf")) return r.fail("a byte order mark is not TOML 1.0: save the file without one"); if (!std.unicode.utf8ValidateSlice(text)) { @@ -22,6 +34,8 @@ pub fn parse(a: Allocator, text: []const u8, problem: *Problem) Error![]const En return r.fail("invalid UTF-8"); } var out: std.ArrayList(Entry) = .empty; + var tables: std.ArrayList(u32) = .empty; + var table: u32 = 0; while (true) { r.blanks(); if (r.done()) break; @@ -30,10 +44,16 @@ pub fn parse(a: Allocator, text: []const u8, problem: *Problem) Error![]const En try r.comment(); continue; } - if (r.peek() == '[') return r.fail("tables are not read: every key is a top-level setting"); + if (r.peek() == '[') { + const name = shape.table orelse return r.fail("tables are not read: every key is a top-level setting"); + try tables.append(a, r.line); + try r.header(name, out.items); + table += 1; + continue; + } const line = r.line; const key = try r.key(); - for (out.items) |e| if (std.mem.eql(u8, e.key, key)) return r.fail("key defined twice"); + for (out.items) |e| if (e.table == table and std.mem.eql(u8, e.key, key)) return r.fail("key defined twice"); r.blanks(); if (r.peek() == '.') return r.fail("dotted keys are not read: every key is a top-level setting"); if (r.peek() != '=') return r.fail("expected '=' after the key"); @@ -43,9 +63,9 @@ pub fn parse(a: Allocator, text: []const u8, problem: *Problem) Error![]const En r.blanks(); if (r.peek() == '#') try r.comment(); if (!r.done() and !try r.lineEnd()) return r.fail("unexpected text after the value"); - try out.append(a, .{ .key = key, .line = line, .value = value }); + try out.append(a, .{ .key = key, .line = line, .value = value, .table = table }); } - return out.items; + return .{ .entries = out.items, .tables = tables.items }; } const Reader = struct { @@ -95,6 +115,25 @@ const Reader = struct { if (control(r.peek())) return r.fail("a control character in a comment"); } + /// A ``[[name]]`` header, blanks allowed in its brackets, then the rest of its line; any other table is refused. + fn header(r: *Reader, name: []const u8, before: []const Entry) Error!void { + if (!std.mem.startsWith(u8, r.text[r.at..], "[[")) + return r.fail(try std.fmt.allocPrint(r.a, "a [table] is not read: each item is a [[{s}]] table", .{name})); + r.at += 2; + r.blanks(); + const got = try r.key(); + r.blanks(); + if (r.peek() == '.') return r.fail("dotted table names are not read"); + if (!std.mem.startsWith(u8, r.text[r.at..], "]]")) return r.fail("expected ]] after the table name"); + r.at += 2; + if (!std.mem.eql(u8, got, name)) + return r.fail(try std.fmt.allocPrint(r.a, "unknown table [[{s}]]: this file reads [[{s}]] tables", .{ got, name })); + for (before) |e| if (e.table == 0 and std.mem.eql(u8, e.key, name)) return r.fail("key defined twice"); + r.blanks(); + if (r.peek() == '#') try r.comment(); + if (!r.done() and !try r.lineEnd()) return r.fail("unexpected text after the table header"); + } + fn key(r: *Reader) Error![]const u8 { if (r.peek() == '"' or r.peek() == '\'') return r.string(); const start = r.at; From 20991cac3d9c51f743a64e112e2a5bc816bbe511 Mon Sep 17 00:00:00 2001 From: Ash <71890694+ashhart@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:29:49 +0000 Subject: [PATCH 2/3] cli: tensorfold mcp, a Model Context Protocol server on stdio for this machine's models and local servers An AI coding assistant starts `tensorfold mcp` and calls seven tools: machine (the benchmark's allowlisted host facts), models (the cache scan `tensorfold models` lists), info (info's own lines, and its floor as the router reads it), pull (tensorfold pull's code, its lines as progress notifications), and serve, stop and status. serve starts `tensorfold serve` through the serve child the router and chat use: a free 127.0.0.1 port, a process group of its own and a fresh key, returned with the base URL and the served name. Every server the session started stops when stdin ends or a stop signal arrives. Windows refuses serve by name; the other tools work there. The server speaks MCP 2026-07-28 (per-request revision in _meta, server/discover) and the initialize handshake of 2025-11-25 and 2025-06-18: one JSON-RPC message a line, batches and bad JSON refused with JSON-RPC errors, tool problems as tool errors, and stdout for protocol messages only. --- README.md | 4 + docs/mcp.md | 110 ++++++++++ zig/build/cuda_server_host.zig | 1 + zig/build/mcp_host.zig | 19 ++ zig/src/cli/cli.zig | 6 +- zig/src/server/main.zig | 9 +- zig/src/server/mcp.zig | 343 ++++++++++++++++++++++++++++++ zig/src/server/mcp_cache.zig | 191 +++++++++++++++++ zig/src/server/mcp_fixture.zig | 185 ++++++++++++++++ zig/src/server/mcp_rpc.zig | 181 ++++++++++++++++ zig/src/server/mcp_rpc_test.zig | 264 +++++++++++++++++++++++ zig/src/server/mcp_serve.zig | 331 ++++++++++++++++++++++++++++ zig/src/server/mcp_serve_test.zig | 267 +++++++++++++++++++++++ zig/src/server/mcp_tests.zig | 6 + zig/src/server/mcp_tools.zig | 227 ++++++++++++++++++++ zig/src/server/mcp_tools_test.zig | 214 +++++++++++++++++++ 16 files changed, 2354 insertions(+), 4 deletions(-) create mode 100644 docs/mcp.md create mode 100644 zig/build/mcp_host.zig create mode 100644 zig/src/server/mcp.zig create mode 100644 zig/src/server/mcp_cache.zig create mode 100644 zig/src/server/mcp_fixture.zig create mode 100644 zig/src/server/mcp_rpc.zig create mode 100644 zig/src/server/mcp_rpc_test.zig create mode 100644 zig/src/server/mcp_serve.zig create mode 100644 zig/src/server/mcp_serve_test.zig create mode 100644 zig/src/server/mcp_tests.zig create mode 100644 zig/src/server/mcp_tools.zig create mode 100644 zig/src/server/mcp_tools_test.zig diff --git a/README.md b/README.md index 5b99e712916..10ac8b1da8d 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,10 @@ With the server above still running, `tensorfold chat --url http://127.0.0.1:808 `echo "Say hello." | tensorfold chat --url http://127.0.0.1:8080` prints one reply for a script. See [the chat command](docs/chat.md) for its flags and the serve flags it passes on. +`tensorfold mcp` lets an AI coding assistant such as Claude Code, Codex or Cursor describe this machine, list and +download models, and start and stop local servers through Model Context Protocol tools. Add it to Claude Code with +`claude mcp add tensorfold -- tensorfold mcp`. [The MCP guide](docs/mcp.md) covers the tools and other clients. + ## Docs - [Run guide](docs/run-guide.md): platform setup, requests, parallel requests, exact decoding, context compaction, diff --git a/docs/mcp.md b/docs/mcp.md new file mode 100644 index 00000000000..84a18897c48 --- /dev/null +++ b/docs/mcp.md @@ -0,0 +1,110 @@ +# TensorFold for AI coding assistants (MCP) + +`tensorfold mcp` is a [Model Context Protocol](https://modelcontextprotocol.io) server on stdin and stdout. +An AI coding assistant such as Claude Code, Codex or Cursor starts it and calls its tools to see what this machine +runs, download a model, and start or stop a local TensorFold server, instead of you typing the commands. +It needs no model, GPU or network until a tool asks for one. + +## Add it to a client + +Claude Code: + +```sh +claude mcp add tensorfold -- tensorfold mcp +``` + +Add `--scope user` before the name to have it in every project. + +Codex, in `~/.codex/config.toml`: + +```toml +[mcp_servers.tensorfold] +command = "tensorfold" +args = ["mcp"] +tool_timeout_sec = 3600 +``` + +Cursor reads `~/.cursor/mcp.json` or a project's `.cursor/mcp.json`. It, Claude Desktop and other clients with an +`mcpServers` file take this entry: + +```json +{ + "mcpServers": { + "tensorfold": { "command": "tensorfold", "args": ["mcp"] } + } +} +``` + +A client started from the desktop may not see your shell's `PATH`, so give `command` the full path that +`command -v tensorfold` prints. With a Linux release archive, name `tensorfold-native`. The quick start's `tensorfold` +is a shell function, and a client does not see it. + +`pull` and `serve` can take minutes. Codex stops a tool call after 60 seconds unless you raise `tool_timeout_sec`, as +above. Claude Code limits a call with `MCP_TOOL_TIMEOUT`, and one that reports no progress with +`CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT`. This server reports progress whenever the client's request asks for it. + +## Tools + +| Tool | Arguments | What it does | +| --- | --- | --- | +| `machine` | none | The OS, CPU, memory and GPUs, and the TensorFold version, backend and model types this build serves. It reports the host facts `tensorfold benchmark` records, so no hostname or serial number. | +| `models` | none | The checkpoints in the Hugging Face cache that a TensorFold family serves, as `tensorfold models` lists them, with each revision and size on disk. | +| `info` | `model` | One checkpoint's family, format, context, weights and memory floor, or Flash Next's Metal budgets, as `tensorfold info` prints them. | +| `pull` | `repo`, `revision` (optional) | Downloads a Hugging Face repo with `tensorfold pull`'s own code. It checks the files against the Hub, resumes an interrupted download and refuses a repo no family serves. | +| `serve` | `model`, `context` (optional), `drafter` (optional) | Starts `tensorfold serve` for a cached model and answers once the server does. | +| `stop` | `id` | Stops a server this session started. | +| `status` | none | The servers this session started, with each one's id, model, served name, base URL and whether it still runs. A server that exited on its own shows its last log lines. | + +Every result is plain text for the assistant and the same facts as structured content. A tool that cannot do what it +was asked returns a tool error that says why, so the assistant can correct the call. Nothing a client sends crashes +the server. + +## Servers that `serve` starts + +Each server listens on `127.0.0.1` at a free port and answers to the repo's last part as its model name, as +`tensorfold serve REPO` does. It gets a fresh random API key of 64 hex characters in `TENSORFOLD_API_KEY`, as +`tensorfold chat` gives its own server. Only `serve`'s result carries the key, with the base URL and the served name: + +```sh +curl -fsS http://127.0.0.1:PORT/v1/chat/completions \ + -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \ + -d '{"model":"Qwen3.5-2B-MLX-4bit","messages":[{"role":"user","content":"Say hello."}],"max_tokens":32}' +``` + +Chat completions, Responses and Anthropic Messages are under that base URL. Messages clients send the key as +`x-api-key`. Calling `serve` again for a model and settings already running returns that server and its key instead +of loading a second copy. + +The child inherits your environment as `tensorfold serve --router`'s children do, without your API key or the +benchmark's upload token. It shows no live status line, skips the update check and keeps Hugging Face offline. It runs +in a process group of its own, so a terminal's Ctrl-C reaches this server, which then stops it. Its log is a file under +`~/.tensorfold/mcp`, which the server unlinks once the child starts. + +Every server the session started stops when the session ends. The session ends when the client closes stdin, or on +SIGTERM, SIGINT or SIGHUP, and a server still loading stops too. Nothing can clean up after SIGKILL, so a client +should close stdin first. On Windows, `serve` refuses by name because it stops its servers with POSIX signals. The +other tools work there. + +## What the tools accept + +No tool deletes anything. `pull` takes a Hugging Face repo id, `owner/name`, and an optional branch, tag or commit. +It never takes a path. `info`, `serve` and `drafter` take a repo id already in the cache, or the absolute path of an +existing checkpoint directory, one that holds `config.json`. The tools refuse relative paths, `~` and any `..`, +because the assistant does not choose the server's working directory. Each tool checks its arguments against its JSON +Schema, so an unknown argument, a wrong type or a missing one is a tool error. + +## Protocol + +The server implements MCP revision 2026-07-28. There every request names its revision and client capabilities in +`_meta`, and `server/discover` lists what the server supports. It also speaks the `initialize` handshake of revisions +2025-11-25 and 2025-06-18 to clients that open with it, and answers an `initialize` asking for another revision with +2025-11-25. It answers `ping` under the handshake revisions, which define it. + +- Messages are JSON-RPC 2.0, one to a line, at most 4 MiB. Bad JSON gets `-32700`, a batch or a malformed message + `-32600`, an unknown method `-32601`, and bad parameters, an unknown tool or a request naming no revision `-32602`. + A revision this server does not speak gets 2026-07-28's `-32022` with the supported list. +- A `tools/call` with a `progressToken` in `_meta` gets progress notifications. `pull` reports its lines as + `tensorfold pull` prints them, and `serve` reports every five seconds while a server loads. +- `notifications/cancelled` stops a loading server, and its call answers nothing. A download cannot stop midway, so a + cancelled `pull` goes on and answers nothing. The next `pull` of that repo resumes from where it got to. +- stdout carries protocol messages only. Diagnostics go to stderr. diff --git a/zig/build/cuda_server_host.zig b/zig/build/cuda_server_host.zig index a9559a9b0b3..2d9a1ddcc4d 100644 --- a/zig/build/cuda_server_host.zig +++ b/zig/build/cuda_server_host.zig @@ -124,5 +124,6 @@ pub fn steps(b: *std.Build, host: std.Build.ResolvedTarget, cuda: *std.Build.Mod b.step("test-pdf-worker", "The PDF render worker spawned from tensorfold-native, rendering where libpdfium is found").dependOn(&pdf_worker_run.step); } } + @import("mcp_host.zig").add(b, server_tests, native_modules.engines, @import("cuda.zig").checkpointCli(b, host, .debug, false, native_modules.engines, mods.core), step); return .{ template, server_tests }; } diff --git a/zig/build/mcp_host.zig b/zig/build/mcp_host.zig new file mode 100644 index 00000000000..9949013cd1c --- /dev/null +++ b/zig/build/mcp_host.zig @@ -0,0 +1,19 @@ +//! test-mcp-host: `tensorfold mcp`'s wire, tools and serve children against a temporary cache, fakes and stand-ins. +const std = @import("std"); + +/// The tests' module: the server tests' own imports over the host's engines, as tensorfold-native has them. +pub fn add(b: *std.Build, server_tests: *std.Build.Module, engines: *std.Build.Module, checkpoint_cli: *std.Build.Module, step: *std.Build.Step) void { + if (b.graph.host.result.os.tag == .windows) return; // the serve children and the fakes are POSIX processes and sockets + const host = b.graph.host; + const m = b.createModule(.{ .root_source_file = b.path("zig/src/server/mcp_tests.zig"), .target = host, .optimize = .Debug, .link_libc = true }); + for ([_][]const u8{ "engine_api", "tokenizer", "template", "living", "core" }) |name| m.addImport(name, server_tests.import_table.get(name).?); + m.addImport("native_engines", engines); // so the server's drama prompt is the engines' own, as in the binary + m.addImport("checkpoint_cli", checkpoint_cli); + _ = @import("server.zig").addTo(b, m, host, .Debug); + @import("server.zig").testImports(b, m, host, .Debug); + // only these tests: the server files they import bring their own, which test-server-cpu already runs + const run = b.addRunArtifact(b.addTest(.{ .root_module = m, .filters = &.{"mcp "} })); + run.has_side_effects = true; // child processes and loopback sockets: a cached pass would say nothing about them + b.step("test-mcp-host", "The MCP server's framing, lifecycle and tools against a temporary cache, a fake hub and a stand-in serve child").dependOn(&run.step); + step.dependOn(&run.step); +} diff --git a/zig/src/cli/cli.zig b/zig/src/cli/cli.zig index caaa1507a1b..87ce4bd9084 100644 --- a/zig/src/cli/cli.zig +++ b/zig/src/cli/cli.zig @@ -1,8 +1,10 @@ //! The tensorfold checkpoint subcommands (`models`, `info`, `pull`, `rm`, `plan`, `merge`) and `log`. const std = @import("std"); const models = @import("models.zig"); -const info = @import("info.zig"); -const pull = @import("pull.zig"); +/// The commands `tensorfold mcp` answers its tools with, and the cache helpers they share. +pub const info = @import("info.zig"); +pub const pull = @import("pull.zig"); +pub const hub = @import("hub.zig"); const plan = @import("plan.zig"); const pull_exlr8 = @import("pull_exlr8.zig"); const rm = @import("rm.zig"); diff --git a/zig/src/server/main.zig b/zig/src/server/main.zig index 28a216ce0d3..f08cc7bb27a 100644 --- a/zig/src/server/main.zig +++ b/zig/src/server/main.zig @@ -22,6 +22,7 @@ const web_cli = @import("web_cli.zig"); const chat_cli = @import("chat_cli.zig"); const launch_cli = @import("launch_cli.zig"); const device_cli = @import("device_cli.zig"); +const mcp = @import("mcp.zig"); const usage_line = "usage: tensorfold serve [-h] [--config FILE.toml] [--host HOST] [--port PORT] [--unix-socket PATH] [--name NAME] [--chat-template FILE]" ++ " [--alias ALIAS] [--allowed-host NAME] [--allowed-origin ORIGIN] [--cors-origin ORIGIN] [--api-key API_KEY] [--api-key-file API_KEY_FILE] [--metrics-open] [--dashboard] [--log-json]" ++ @@ -73,7 +74,7 @@ pub fn main(init: std.process.Init) !u8 { // help and a bare run lead with what this machine runs: the saved profile, or a quick scan with no driver if (argv.len == 2 and (std.mem.eql(u8, argv[1], "--help") or std.mem.eql(u8, argv[1], "-h") or std.mem.eql(u8, argv[1], "help"))) { try std.Io.File.stdout().writeStreamingAll(io, device_cli.summary(init)); - try std.Io.File.stdout().writeStreamingAll(io, "usage: tensorfold-native --version | capabilities --json | device [--json] [--rescan] | models [--json] | info MODEL | pull REPO[@REVISION] | rm REPO[@REVISION] | log [list|show ID|follow] [PATH] | slide rollback FOLDER | web [ARGS...] | launch [args...] | slide audit [flags] | serve MODEL [flags] | serve --router [flags] | benchmark MODEL [flags] | chat [MODEL] [flags]\n" ++ usage_line); + try std.Io.File.stdout().writeStreamingAll(io, "usage: tensorfold-native --version | capabilities --json | device [--json] [--rescan] | models [--json] | info MODEL | pull REPO[@REVISION] | rm REPO[@REVISION] | log [list|show ID|follow] [PATH] | slide rollback FOLDER | web [ARGS...] | launch [args...] | slide audit [flags] | serve MODEL [flags] | serve --router [flags] | benchmark MODEL [flags] | chat [MODEL] [flags] | mcp\n" ++ usage_line); return 0; } if (argv.len >= 2 and std.mem.eql(u8, argv[1], "device")) return device_cli.main(init, argv[2..]); @@ -102,6 +103,10 @@ pub fn main(init: std.process.Init) !u8 { } // the checkpoint commands need no model, GPU or driver either if (argv.len >= 2 and checkpoint_cli.wants(@ptrCast(argv[1..]))) return checkpoint_cli.main(init, argv[1..]); + if (argv.len >= 2 and std.mem.eql(u8, argv[1], "mcp")) { + log.init(io, true); // stdout carries protocol messages only, so no [tensorfold] line may reach it + return mcp.main(init, argv[2..], @import("build_options").version, &engines.capabilities); + } if (argv.len >= 2 and std.mem.eql(u8, argv[1], "slide")) return slide_cli.main(init, argv[2..]); log.init(io, false); if (argv.len == 3 and std.mem.eql(u8, argv[1], "capabilities") and std.mem.eql(u8, argv[2], "--json")) { @@ -124,7 +129,7 @@ pub fn main(init: std.process.Init) !u8 { // a chat with a running server works on every platform; chat_cli.zig refuses its own serve child on Windows if (argv.len >= 2 and std.mem.eql(u8, argv[1], "chat")) return chat_cli.main(init, argv[2..]); if (argv.len < 2 or !std.mem.eql(u8, argv[1], "serve")) { - std.debug.print("{s}usage: tensorfold-native capabilities --json | device [--json] [--rescan] | models [--json] | info MODEL | pull REPO[@REVISION] | rm REPO[@REVISION] | log [list|show ID|follow] [PATH] | slide rollback FOLDER | launch [args...] | slide audit [flags] | serve MODEL [flags] | serve --router [flags] | benchmark MODEL [flags] | chat [MODEL] [flags]\n", .{if (argv.len < 2) device_cli.summary(init) else ""}); + std.debug.print("{s}usage: tensorfold-native capabilities --json | device [--json] [--rescan] | models [--json] | info MODEL | pull REPO[@REVISION] | rm REPO[@REVISION] | log [list|show ID|follow] [PATH] | slide rollback FOLDER | launch [args...] | slide audit [flags] | serve MODEL [flags] | serve --router [flags] | benchmark MODEL [flags] | chat [MODEL] [flags] | mcp\n", .{if (argv.len < 2) device_cli.summary(init) else ""}); return 2; } const started = std.Io.Clock.awake.now(io).toNanoseconds(); diff --git a/zig/src/server/mcp.zig b/zig/src/server/mcp.zig new file mode 100644 index 00000000000..87c640ee6c7 --- /dev/null +++ b/zig/src/server/mcp.zig @@ -0,0 +1,343 @@ +//! `tensorfold mcp`: a Model Context Protocol server on stdio for this machine's checkpoints and local servers. +const std = @import("std"); +const builtin = @import("builtin"); +const json = @import("json"); +const cli = @import("cli.zig"); +const rpc = @import("mcp_rpc.zig"); +const tools = @import("mcp_tools.zig"); +const serve = @import("mcp_serve.zig"); +const cache = @import("mcp_cache.zig"); +const posix_only = builtin.os.tag != .windows; +const stream = if (posix_only) @import("benchmark_stream.zig") else struct {}; +const stop = if (posix_only) @import("benchmark_stop.zig") else struct {}; +const Allocator = std.mem.Allocator; +const Value = json.Value; +const none: Value = .null; + +pub const usage_line = "usage: tensorfold mcp (a Model Context Protocol server on stdin and stdout; see docs/mcp.md)\n"; + +/// The pulls and serves that may run at once, each on its own thread. +const max_running = 8; + +const instructions = "TensorFold runs models on this machine. machine describes the machine; models lists the cached " ++ + "checkpoints and info describes one; pull downloads a Hugging Face repo; serve starts a local OpenAI- and " ++ + "Anthropic-compatible server and returns its base URL, served name and API key; status and stop manage the " ++ + "servers this session started, which all stop when the session ends."; + +/// What the tools reach, so a test can run a session with fakes, a temporary home and a stand-in serve child. +pub const Context = struct { + io: std.Io, + /// Thread-safe: calls on their own threads and the server registry allocate from it. + gpa: Allocator, + environ: *const std.process.Environ.Map, + home: []const u8, + version: []const u8, + engines: *const fn (Allocator) cli.Engines, + /// The serve child's executable; null is this process's own. + exe: ?[]const u8 = null, + grace_ms: u32 = 10_000, + /// How long the end of a session, its servers stopped, waits for a pull still running. + drain_s: u32 = 10, +}; + +/// One tools/call: its request, revision, arguments, progress token and whether the client cancelled it. +pub const Call = struct { + session: *Session, + a: Allocator, + id: Value, + version: rpc.Version, + tool: tools.Tool, + args: Value, + token: ?Value, + cancelled: std.atomic.Value(bool) = .init(false), + done: std.atomic.Value(bool) = .init(false), + arena: std.heap.ArenaAllocator, + thread: ?std.Thread = null, + sent: u64 = 0, + + pub fn ctx(c: *const Call) *const Context { + return c.session.ctx; + } + + /// True once the client cancelled this call or the session is ending. + pub fn stopping(c: *const Call) bool { + return c.cancelled.load(.acquire) or c.session.ending.load(.acquire); + } + + /// A progress notification saying ``message``, when the client sent a progress token and still waits. + pub fn report(c: *Call, message: []const u8) void { + const token = c.token orelse return; + if (c.cancelled.load(.acquire)) return; + var arena: std.heap.ArenaAllocator = .init(std.heap.smp_allocator); + defer arena.deinit(); + const a = arena.allocator(); + c.sent += 1; + const p = json.newObject(a) catch return; + p.put(a, "progressToken", token) catch return; + p.put(a, "progress", json.intValue(a, c.sent) catch return) catch return; + p.put(a, "message", .{ .string = message }) catch return; + c.session.wire.send(rpc.notification(a, "notifications/progress", p) catch return); + } + + /// The call's thread: its tool, then its answer unless the client cancelled it. + fn run(c: *Call) void { + defer c.done.store(true, .release); + c.session.answer(c, tools.call(c)); + } +}; + +pub const Session = struct { + ctx: *const Context, + wire: *rpc.Wire, + handshake: ?rpc.Version = null, + ending: std.atomic.Value(bool) = .init(false), + calls: std.ArrayList(*Call) = .empty, + servers: serve.Registry, + pulls: cache.Pulls = .{}, + + pub fn init(ctx: *const Context, wire: *rpc.Wire) Session { + return .{ .ctx = ctx, .wire = wire, .servers = .init(ctx.gpa, ctx.io) }; + } + + pub fn deinit(s: *Session) void { + s.calls.deinit(s.ctx.gpa); + s.pulls.deinit(s.ctx.gpa); + s.servers.deinit(); + } + + /// One line from the client, answered on the wire; pull and serve answer later from their own threads. + pub fn handle(s: *Session, a: Allocator, line: []const u8) !void { + s.reap(); + switch (try rpc.read(a, line)) { + .dropped => |why| if (why.len > 0) std.debug.print("tensorfold mcp: dropped {s}\n", .{why}), + .refused => |r| s.wire.send(try rpc.failure(a, r)), + .notification => |n| s.notified(n), + .request => |r| try s.request(a, r), + } + } + + fn request(s: *Session, a: Allocator, r: rpc.Request) !void { + const modern = (r.params.get("_meta") orelse none).get(rpc.meta_version) != null; + if (!modern and eql(r.method, "initialize")) return s.initialize(a, r); + if (!modern and eql(r.method, "ping")) return s.wire.send(try rpc.result(a, r.id, try json.newObject(a))); + const v = switch (try rpc.version(a, r, s.handshake)) { + .ok => |v| v, + .refused => |why| return s.wire.send(try rpc.failure(a, why)), + }; + if (eql(r.method, "tools/list")) return s.reply(a, r.id, v, try tools.list(a, v)); + if (eql(r.method, "tools/call")) return s.call(a, r, v); + if (eql(r.method, "server/discover") and v.stateless()) return s.reply(a, r.id, v, try discover(a)); + s.wire.send(try rpc.failure(a, .{ .id = r.id, .code = rpc.method_not_found, .message = try std.fmt.allocPrint(a, "Method not found: {s}", .{r.method}) })); + } + + /// The handshake revisions' initialize: the negotiated version, the tools capability and who this server is. + fn initialize(s: *Session, a: Allocator, r: rpc.Request) !void { + const v = rpc.negotiate(r.params.strField("protocolVersion")); + s.handshake = v; + const body = try json.newObject(a); + try body.put(a, "protocolVersion", .{ .string = @tagName(v) }); + try body.put(a, "capabilities", try capabilities(a)); + try body.put(a, "serverInfo", try s.identity(a)); + try body.put(a, "instructions", .{ .string = instructions }); + s.wire.send(try rpc.result(a, r.id, body)); + } + + pub fn identity(s: *const Session, a: Allocator) !Value { + const o = try json.newObject(a); + try o.put(a, "name", .{ .string = "tensorfold" }); + try o.put(a, "title", .{ .string = "TensorFold" }); + try o.put(a, "version", .{ .string = s.ctx.version }); + return .{ .object = o }; + } + + fn reply(s: *Session, a: Allocator, id: Value, v: rpc.Version, body: *json.Object) !void { + try rpc.complete(a, body, v, try s.identity(a)); + s.wire.send(try rpc.result(a, id, body)); + } + + /// tools/call: the envelope checked here, the tool run inline, or on its own thread when it can take minutes. + fn call(s: *Session, a: Allocator, r: rpc.Request, v: rpc.Version) !void { + const name = r.params.strField("name") orelse + return s.wire.send(try rpc.failure(a, .{ .id = r.id, .code = rpc.invalid_params, .message = "Invalid params: tools/call needs a tool name" })); + const tool = std.meta.stringToEnum(tools.Tool, name) orelse + return s.wire.send(try rpc.failure(a, .{ .id = r.id, .code = rpc.invalid_params, .message = try std.fmt.allocPrint(a, "Unknown tool: {s}", .{name}) })); + const args = r.params.get("arguments") orelse none; + if (args != .null and args != .object) + return s.wire.send(try rpc.failure(a, .{ .id = r.id, .code = rpc.invalid_params, .message = "Invalid params: arguments must be an object" })); + if (tool.long() and s.calls.items.len >= max_running) + return s.reply(a, r.id, v, try tools.failed(a, "{d} pulls and serves are running already; call again once one has answered", .{max_running})); + const token = (r.params.get("_meta") orelse none).get("progressToken"); + const c = try s.ctx.gpa.create(Call); + c.* = .{ .session = s, .a = undefined, .id = .null, .version = v, .tool = tool, .args = .null, .token = null, .arena = .init(s.ctx.gpa) }; + c.a = c.arena.allocator(); + errdefer { + c.arena.deinit(); + s.ctx.gpa.destroy(c); + } + c.id = try json.deepCopy(c.a, r.id); + c.args = try json.deepCopy(c.a, args); + if (token) |t| if (t == .string or t == .int) { + c.token = try json.deepCopy(c.a, t); + }; + try s.calls.ensureUnusedCapacity(s.ctx.gpa, 1); + if (tool.long()) if (std.Thread.spawn(.{}, Call.run, .{c})) |t| { + c.thread = t; + s.calls.appendAssumeCapacity(c); + return; + } else |_| {}; + defer { + c.arena.deinit(); + s.ctx.gpa.destroy(c); + } + s.answer(c, tools.call(c)); + } + + /// A call's result, unless the client cancelled it; a tool's own error becomes a tool error, never a crash. + fn answer(s: *Session, c: *Call, got: anyerror!*json.Object) void { + if (c.cancelled.load(.acquire)) return; + const body = got catch |e| tools.failed(c.a, "{s} failed: {t}", .{ @tagName(c.tool), e }) catch return; + s.reply(c.a, c.id, c.version, body) catch return; + } + + fn notified(s: *Session, n: rpc.Notification) void { + if (!eql(n.method, "notifications/cancelled")) return; // initialized and the rest need nothing + const id = n.params.get("requestId") orelse return; + for (s.calls.items) |c| if (json.equal(c.id, id)) c.cancelled.store(true, .release); + } + + /// Joins the calls that finished and frees them. + fn reap(s: *Session) void { + var i: usize = 0; + while (i < s.calls.items.len) { + const c = s.calls.items[i]; + if (!c.done.load(.acquire)) { + i += 1; + continue; + } + if (c.thread) |t| t.join(); + c.arena.deinit(); + s.ctx.gpa.destroy(c); + _ = s.calls.swapRemove(i); + } + } + + /// The end of a session: every server stops first, a loading one stopping itself, then running calls finish. + pub fn finish(s: *Session) void { + s.ending.store(true, .release); + s.servers.stopAll(); + const io = s.ctx.io; + const started = std.Io.Clock.awake.now(io).toNanoseconds(); + // a loading server's own stop takes two grace periods at most; a pull gets drain_s and resumes next time + const serve_ms = 2 * @as(i96, s.ctx.grace_ms) + 1000 * @as(i96, s.ctx.drain_s); + while (true) { + s.reap(); + if (s.calls.items.len == 0) break; + const waited_ms = @divTrunc(std.Io.Clock.awake.now(io).toNanoseconds() - started, std.time.ns_per_ms); + const serving = for (s.calls.items) |c| { + if (c.tool == .serve) break true; + } else false; + if (waited_ms >= (if (serving) serve_ms else 1000 * @as(i96, s.ctx.drain_s))) break; + io.sleep(.fromMilliseconds(20), .awake) catch {}; + } + for (s.calls.items) |c| if (c.thread) |t| t.detach(); // left to the process's exit + s.calls.clearRetainingCapacity(); + } +}; + +fn capabilities(a: Allocator) !Value { + const o = try json.newObject(a); + try o.put(a, "tools", .{ .object = try json.newObject(a) }); + return .{ .object = o }; +} + +/// 2026-07-28's server/discover: the revisions served, the capabilities and the instructions, cacheable an hour. +fn discover(a: Allocator) !*json.Object { + const body = try json.newObject(a); + try body.put(a, "supportedVersions", try rpc.strings(a, &rpc.supported)); + try body.put(a, "capabilities", try capabilities(a)); + try body.put(a, "instructions", .{ .string = instructions }); + try body.put(a, "ttlMs", try json.intValue(a, tools.ttl_ms)); + try body.put(a, "cacheScope", .{ .string = "public" }); + return body; +} + +fn eql(x: []const u8, y: []const u8) bool { + return std.mem.eql(u8, x, y); +} + +const Next = union(enum) { line: []const u8, too_long, end, stopped }; + +/// One line from the client, read as its own task so a stop signal ends the wait, as benchmark's prompts are read. +fn next(io: std.Io, r: *std.Io.Reader) Next { + const Read = struct { + r: *std.Io.Reader, + got: Next = .end, + done: std.atomic.Value(bool) = .init(false), + fn go(t: *@This()) void { + t.got = if (t.r.takeDelimiter('\n')) |line| (if (line) |l| .{ .line = l } else .end) else |e| switch (e) { + error.StreamTooLong => blk: { + _ = t.r.discardDelimiterInclusive('\n') catch {}; + break :blk .too_long; + }, + error.ReadFailed => .end, + }; + } + }; + var task: Read = .{ .r = r }; + if (comptime posix_only) { + switch (stream.bounded(io, null, Read.go, &task)) { + .finished => return task.got, + .stopped, .deadline => return .stopped, + .unavailable => {}, + } + } + task.go(); + return task.got; +} + +/// Serves messages from ``in`` until it ends or a stop signal arrives, then stops what the session started. +pub fn run(ctx: *const Context, in: *std.Io.Reader, out: *std.Io.Writer) !u8 { + var wire: rpc.Wire = .{ .out = out, .io = ctx.io }; + var s: Session = .init(ctx, &wire); + defer s.deinit(); + var arena: std.heap.ArenaAllocator = .init(ctx.gpa); + defer arena.deinit(); + loop: while (true) { + _ = arena.reset(.retain_capacity); + const a = arena.allocator(); + switch (next(ctx.io, in)) { + .line => |line| s.handle(a, line) catch |e| std.debug.print("tensorfold mcp: a message could not be answered ({t})\n", .{e}), + .too_long => wire.send(rpc.failure(a, .{ .code = rpc.invalid_request, .message = "Invalid Request: the message is longer than 4 MiB" }) catch continue), + .end, .stopped => break :loop, + } + } + s.finish(); + if (comptime posix_only) if (stop.requested()) |sig| return stop.exitCode(sig); + return 0; +} + +pub fn main(init: std.process.Init, argv: []const []const u8, version: []const u8, engines: *const fn (Allocator) cli.Engines) !u8 { + const io = init.io; + if (argv.len == 1 and (eql(argv[0], "--help") or eql(argv[0], "-h"))) { + try std.Io.File.stdout().writeStreamingAll(io, usage_line); + return 0; + } + if (argv.len > 0) { + std.debug.print("{s}tensorfold mcp: error: unrecognized arguments: {s}\n", .{ usage_line, argv[0] }); + return 2; + } + if (comptime posix_only) { + stop.install(); // TERM, INT and HUP end the session as stdin's end does, so the servers it started stop too + const ignore: std.posix.Sigaction = .{ .handler = .{ .handler = std.posix.SIG.IGN }, .mask = std.posix.sigemptyset(), .flags = 0 }; + std.posix.sigaction(.PIPE, &ignore, null); // a client gone mid-reply is a write error, not this process's death + } + defer if (comptime posix_only) stop.restore(); + const buf = try init.gpa.alloc(u8, rpc.max_line); + defer init.gpa.free(buf); + var in = std.Io.File.stdin().readerStreaming(io, buf); + var out_buf: [64 << 10]u8 = undefined; + var out = std.Io.File.stdout().writerStreaming(io, &out_buf); + const env = init.environ_map; + const ctx: Context = .{ .io = io, .gpa = init.gpa, .environ = env, .home = env.get("HOME") orelse env.get("USERPROFILE") orelse ".", .version = version, .engines = engines }; + return run(&ctx, &in.interface, &out.interface); +} diff --git a/zig/src/server/mcp_cache.zig b/zig/src/server/mcp_cache.zig new file mode 100644 index 00000000000..264fd69b730 --- /dev/null +++ b/zig/src/server/mcp_cache.zig @@ -0,0 +1,191 @@ +//! The cache tools: models and info read the Hugging Face cache, and pull fills it by `tensorfold pull`'s own code. +const std = @import("std"); +const json = @import("json"); +const checkpoint = @import("checkpoint_cli"); +const mcp = @import("mcp.zig"); +const tools = @import("mcp_tools.zig"); +const rpc = @import("mcp_rpc.zig"); +const Allocator = std.mem.Allocator; +const Value = json.Value; +const hub = checkpoint.hub; + +/// A model argument as a checkpoint directory: a cached repo id, or the absolute path of an existing checkpoint. +pub fn resolve(a: Allocator, io: std.Io, env: *const std.process.Environ.Map, model: []const u8, problem: *[]const u8) !?[]const u8 { + if (std.fs.path.isAbsolute(model)) { + var parts = std.mem.tokenizeAny(u8, model, "/\\"); + while (parts.next()) |part| if (std.mem.eql(u8, part, "..")) { + problem.* = try std.fmt.allocPrint(a, "{s}: a path with .. is refused; name the checkpoint directory itself", .{model}); + return null; + }; + if (!hub.isDir(io, model) or @import("checkpoint_config").optional(a, io, model) == null) { + problem.* = try std.fmt.allocPrint(a, "{s} is not a checkpoint directory (no config.json there)", .{model}); + return null; + } + return model; + } + if (!repoId(model)) { + problem.* = try std.fmt.allocPrint(a, "{s} is neither a Hugging Face repo id (owner/name) nor the absolute path of a checkpoint directory; relative paths are refused", .{model}); + return null; + } + if (try hub.cachedSnapshot(a, io, try hub.cacheDir(a, env, null), model)) |snapshot| return snapshot; + problem.* = try std.fmt.allocPrint(a, "{s} is not in the Hugging Face cache; download it with the pull tool first", .{model}); + return null; +} + +/// A repo id as the Hub names them: owner/name, no ``--`` or ``..``, neither part starting or ending in - or . +pub fn repoId(text: []const u8) bool { + if (!hub.isRepoIdLike(text) or std.mem.indexOf(u8, text, "..") != null or std.mem.indexOf(u8, text, "--") != null) return false; + var parts = std.mem.splitScalar(u8, text, '/'); + while (parts.next()) |part| for ([_]u8{ part[0], part[part.len - 1] }) |end| { + if (end == '-' or end == '.') return false; + }; + return true; +} + +/// The models tool: the cached checkpoints `tensorfold models` lists, with each one's revision and size on disk. +pub fn models(c: *mcp.Call) !*json.Object { + const a = c.a; + const io = c.ctx().io; + const root = try hub.cacheDir(a, c.ctx().environ, null); + const repos = try hub.cachedRepos(a, io, c.ctx().environ); + var text: std.Io.Writer.Allocating = .init(a); + var items: std.ArrayList(Value) = .empty; + for (repos) |repo| { + const snapshot = try hub.cachedSnapshot(a, io, root, repo) orelse continue; + const family = hub.family(hub.modelType(a, io, snapshot)) orelse continue; + const bytes = try hub.sizeOf(a, io, snapshot); + const revision = std.fs.path.basename(snapshot); + // the line `tensorfold models` prints, with the size and revision after it + try text.writer.print("{s}: {s} ({s}), {d:.2} GiB, revision {s}\n", .{ repo, family.title, family.model_type, tools.gib(bytes), revision }); + const o = try json.newObject(a); + try o.put(a, "repo", .{ .string = repo }); + try o.put(a, "family", .{ .string = family.title }); + try o.put(a, "model_type", .{ .string = family.model_type }); + try o.put(a, "revision", .{ .string = revision }); + try o.put(a, "size_bytes", try json.intValue(a, bytes)); + try items.append(a, .{ .object = o }); + } + if (items.items.len == 0) try text.writer.writeAll("no checkpoints in the Hugging Face cache that a TensorFold family serves; download one with the pull tool\n"); + const o = try json.newObject(a); + try o.put(a, "models", .{ .array = items.items }); + return tools.answered(a, text.written(), o); +} + +/// The info tool: the lines `tensorfold info` prints for one checkpoint, and its facts as numbers. +pub fn info(c: *mcp.Call, model: []const u8) !*json.Object { + const a = c.a; + const io = c.ctx().io; + var problem: []const u8 = ""; + const dir = try resolve(a, io, c.ctx().environ, model, &problem) orelse return tools.failed(a, "{s}", .{problem}); + var out: std.Io.Writer.Allocating = .init(a); + const code = try checkpoint.info.run(a, io, &out.writer, c.ctx().environ, null, dir); + const text = try std.mem.replaceOwned(u8, a, out.written(), dir, model); // run names the directory it was given + if (code != 0) return tools.failed(a, "{s}", .{std.mem.trim(u8, text, " \n")}); + const family = hub.family(hub.modelType(a, io, dir)) orelse return tools.failed(a, "{s}", .{std.mem.trim(u8, text, " \n")}); + const details = hub.configDetails(a, io, dir); + const o = try json.newObject(a); + try o.put(a, "model", .{ .string = model }); + try o.put(a, "family", .{ .string = if (details.is_bolt) "Nemotron 3.5 Bolt" else family.title }); // as info titles it + try o.put(a, "model_type", .{ .string = family.model_type }); + if (hub.quantization(a, io, dir)) |q| { + const quantization = try json.newObject(a); + try quantization.put(a, "bits", try json.intValue(a, q.bits)); + try quantization.put(a, "group_size", try json.intValue(a, q.group)); + try o.put(a, "quantization", .{ .object = quantization }); + } else try o.put(a, "quantization", .null); + try o.put(a, "modelopt_formats", if (details.modelopt_formats) |formats| try rpc.strings(a, formats) else .null); + try o.put(a, "context", try tools.optInt(a, hub.configInt(a, io, dir, "max_position_embeddings"))); + const memory = checkpoint.memory(a, io, dir); + try o.put(a, "weights_bytes", try tools.optInt(a, if (memory) |m| m.weights else null)); + try o.put(a, "memory_floor_bytes", try tools.optInt(a, if (memory) |m| m.floor else null)); + return tools.answered(a, text, o); +} + +/// The repos being pulled now: a second pull of one waits for none and is refused, as both would write its blobs. +pub const Pulls = struct { + mutex: std.Io.Mutex = .init, + repos: std.ArrayList([]const u8) = .empty, + + fn claim(p: *Pulls, gpa: Allocator, io: std.Io, repo: []const u8) !bool { + p.mutex.lockUncancelable(io); + defer p.mutex.unlock(io); + for (p.repos.items) |r| if (std.ascii.eqlIgnoreCase(r, repo)) return false; + try p.repos.append(gpa, try gpa.dupe(u8, repo)); + return true; + } + + fn release(p: *Pulls, gpa: Allocator, io: std.Io, repo: []const u8) void { + p.mutex.lockUncancelable(io); + defer p.mutex.unlock(io); + for (p.repos.items, 0..) |r, i| if (std.ascii.eqlIgnoreCase(r, repo)) { + gpa.free(p.repos.swapRemove(i)); + return; + }; + } + + pub fn deinit(p: *Pulls, gpa: Allocator) void { + for (p.repos.items) |r| gpa.free(r); + p.repos.deinit(gpa); + } +}; + +/// Pull's terminal lines as they come: each kept for the answer and sent as a progress notification. +const Lines = struct { + call: *mcp.Call, + text: std.ArrayList(u8) = .empty, + sent: usize = 0, + writer: std.Io.Writer = .{ .vtable = &.{ .drain = drain }, .buffer = &.{} }, + + fn drain(w: *std.Io.Writer, data: []const []const u8, splat: usize) std.Io.Writer.Error!usize { + const l: *Lines = @alignCast(@fieldParentPtr("writer", w)); + var n: usize = 0; + for (data[0 .. data.len - 1]) |d| { + l.text.appendSlice(l.call.a, d) catch return error.WriteFailed; + n += d.len; + } + for (0..splat) |_| { + l.text.appendSlice(l.call.a, data[data.len - 1]) catch return error.WriteFailed; + n += data[data.len - 1].len; + } + while (std.mem.indexOfScalarPos(u8, l.text.items, l.sent, '\n')) |end| { + const line = std.mem.trim(u8, l.text.items[l.sent..end], " \t\r"); + l.sent = end + 1; + if (line.len > 0) l.call.report(line); + } + return n; + } +}; + +/// The pull tool: ``tensorfold pull REPO[@REVISION]`` into the same cache, its lines as progress notifications. +pub fn pull(c: *mcp.Call, repo: []const u8, revision: ?[]const u8) !*json.Object { + const a = c.a; + const ctx = c.ctx(); + if (!repoId(repo)) return tools.failed(a, "{s} is not a Hugging Face repo id (owner/name); pull takes a repo id, never a path", .{repo}); + const spec = if (revision) |r| try std.fmt.allocPrint(a, "{s}@{s}", .{ repo, r }) else repo; + const pulls = &c.session.pulls; + if (!try pulls.claim(ctx.gpa, ctx.io, repo)) return tools.failed(a, "{s} is already being pulled by this session; wait for that pull to finish", .{repo}); + defer pulls.release(ctx.gpa, ctx.io, repo); + var out: Lines = .{ .call = c }; + var err: std.Io.Writer.Allocating = .init(a); + const code = try checkpoint.pull.run(a, ctx.io, &out.writer, &err.writer, ctx.environ, null, spec); + if (code != 0) { + const why = std.mem.trim(u8, err.written(), " \n"); + if (why.len > 0) return tools.failed(a, "pull {s} failed: {s}", .{ spec, why }); + return tools.failed(a, "pull {s} failed: the hub answered with an error or no files, as for a repo or revision that is missing, private or gated", .{spec}); + } + const snapshot = try hub.cachedSnapshot(a, ctx.io, try hub.cacheDir(a, ctx.environ, null), repo) orelse + return tools.failed(a, "pull {s} finished, but the cache holds no snapshot of it", .{spec}); + const model_type = try a.dupe(u8, hub.modelType(a, ctx.io, snapshot)); + const family = hub.family(model_type); + const sha = std.fs.path.basename(snapshot); + const text = if (family) |f| + try std.fmt.allocPrint(a, "Pulled {s} at revision {s}: {s} ({s}); serve it with the serve tool.\n", .{ repo, sha, f.title, f.model_type }) + else + try std.fmt.allocPrint(a, "Pulled {s} at revision {s} (model_type {s}), a drafter for serve's drafter argument.\n", .{ repo, sha, model_type }); + const o = try json.newObject(a); + try o.put(a, "repo", .{ .string = repo }); + try o.put(a, "revision", .{ .string = sha }); + try o.put(a, "family", tools.optString(if (family) |f| f.title else null)); + try o.put(a, "model_type", .{ .string = model_type }); + return tools.answered(a, text, o); +} diff --git a/zig/src/server/mcp_fixture.zig b/zig/src/server/mcp_fixture.zig new file mode 100644 index 00000000000..74f509c082f --- /dev/null +++ b/zig/src/server/mcp_fixture.zig @@ -0,0 +1,185 @@ +//! The MCP tests' world: a temporary home and cache, fake engines, sessions fed lines, and their output read back. +const std = @import("std"); +const json = @import("json"); +const cli = @import("cli.zig"); +const mcp = @import("mcp.zig"); +const rpc = @import("mcp_rpc.zig"); +const Allocator = std.mem.Allocator; +const Value = json.Value; + +pub const version = "0.0.0-test"; +pub const sha = "0123456789abcdef0123456789abcdef01234567"; +pub const lightning = "{\"model_type\": \"nemotron_h\", \"quantization\": {\"bits\": 4, \"group_size\": 64}, \"max_position_embeddings\": 8192}"; + +pub fn engines(_: Allocator) cli.Engines { + return .{ .version = version, .families = &.{.{ .model_type = "nemotron_h", .formats = &.{} }} }; +} + +/// A temporary home whose Hugging Face cache is ``hub/``, and the environment naming them. +pub const Home = struct { + tmp: std.testing.TmpDir, + dir: []const u8, + env: std.process.Environ.Map, + + pub fn init(a: Allocator) !Home { + var tmp = std.testing.tmpDir(.{}); + errdefer tmp.cleanup(); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const dir = try a.dupe(u8, buf[0..try tmp.dir.realPath(std.testing.io, &buf)]); + var env: std.process.Environ.Map = .init(a); + try env.put("PATH", "/usr/bin:/bin"); + try env.put("HOME", dir); + try env.put("HF_HUB_CACHE", try std.fs.path.join(a, &.{ dir, "hub" })); + return .{ .tmp = tmp, .dir = dir, .env = env }; + } + + pub fn deinit(h: *Home) void { + h.tmp.cleanup(); + } + + pub fn context(h: *const Home) mcp.Context { + return .{ .io = std.testing.io, .gpa = std.testing.allocator, .environ = &h.env, .home = h.dir, .version = version, .engines = &engines, .drain_s = 10 }; + } + + /// ``repo`` cached at ``sha`` with ``config`` and a small weights file; returns its snapshot directory. + pub fn checkpoint(h: *const Home, a: Allocator, repo: []const u8, config: []const u8) ![]const u8 { + const io = std.testing.io; + const slash = std.mem.indexOfScalar(u8, repo, '/').?; + const root = try std.fmt.allocPrint(a, "{s}/hub/models--{s}--{s}", .{ h.dir, repo[0..slash], repo[slash + 1 ..] }); + const snapshot = try std.fs.path.join(a, &.{ root, "snapshots", sha }); + const cwd = std.Io.Dir.cwd(); + const weights: [4096]u8 = @splat('x'); + try cwd.createDirPath(io, snapshot); + try cwd.createDirPath(io, try std.fs.path.join(a, &.{ root, "refs" })); + try cwd.writeFile(io, .{ .sub_path = try std.fs.path.join(a, &.{ root, "refs", "main" }), .data = sha }); + try cwd.writeFile(io, .{ .sub_path = try std.fs.path.join(a, &.{ snapshot, "config.json" }), .data = config }); + try cwd.writeFile(io, .{ .sub_path = try std.fs.path.join(a, &.{ snapshot, "model.safetensors" }), .data = &weights }); + return snapshot; + } + + pub fn path(h: *const Home, a: Allocator, name: []const u8) ![]const u8 { + return std.fs.path.join(a, &.{ h.dir, name }); + } +}; + +/// ``input`` through ``mcp.run`` as stdin brings it, to its end; the lines written, each one JSON object. +pub fn exchange(a: Allocator, ctx: *const mcp.Context, input: []const u8) ![]Value { + var fixed: std.Io.Reader = .fixed(input); + var stdin: std.Io.Reader.Limited = .init(&fixed, .unlimited, try a.alloc(u8, rpc.max_line)); + var out: std.Io.Writer.Allocating = .init(a); + try std.testing.expectEqual(@as(u8, 0), try mcp.run(ctx, &stdin.interface, &out.writer)); + return lines(a, out.written()); +} + +/// Every line of ``bytes`` parsed: each a whole JSON object, and the text ends at a line's end. +pub fn lines(a: Allocator, bytes: []const u8) ![]Value { + var out: std.ArrayList(Value) = .empty; + var it = std.mem.splitScalar(u8, bytes, '\n'); + while (it.next()) |line| { + if (line.len == 0) continue; + const v = switch (try json.parse(a, line)) { + .ok => |v| v, + .err => return error.TestUnexpectedResult, + }; + try std.testing.expect(v == .object); + try out.append(a, v); + } + try std.testing.expect(bytes.len == 0 or bytes[bytes.len - 1] == '\n'); + return out.items; +} + +/// The answer to request ``id`` among ``got``, or null. +pub fn find(got: []const Value, id: i64) ?Value { + for (got) |v| if (v.get("id")) |x| if (x.int64() == id) return v; + return null; +} + +/// The JSON-RPC error code an answer carries, or null for a result. +pub fn code(v: Value) ?i64 { + return (v.get("error") orelse return null).get("code").?.int64(); +} + +/// A tool answer's text and whether it is a tool error. +pub fn text(v: Value) []const u8 { + const content = v.get("result").?.get("content").?.array; + return content[0].strField("text").?; +} + +pub fn isError(v: Value) bool { + return v.get("result").?.get("isError").?.bool; +} + +pub fn has(haystack: []const u8, needle: []const u8) bool { + if (std.mem.indexOf(u8, haystack, needle) != null) return true; + std.debug.print("missing \"{s}\" in:\n{s}\n", .{ needle, haystack }); + return false; +} + +/// A session fed line by line, for calls that answer later from their own threads; it must not move once set up. +pub const Live = struct { + out: std.Io.Writer.Allocating, + wire: rpc.Wire, + session: mcp.Session, + arena: std.heap.ArenaAllocator, + + pub fn setUp(l: *Live, ctx: *const mcp.Context) void { + l.out = .init(std.testing.allocator); + l.wire = .{ .out = &l.out.writer, .io = ctx.io }; + l.session = .init(ctx, &l.wire); + l.arena = .init(std.testing.allocator); + } + + /// The session's end, as stdin's end brings it, and everything freed. + pub fn tearDown(l: *Live) void { + l.session.finish(); + l.session.deinit(); + l.arena.deinit(); + l.out.deinit(); + } + + pub fn send(l: *Live, line: []const u8) !void { + _ = l.arena.reset(.retain_capacity); + try l.session.handle(l.arena.allocator(), line); + } + + /// Every line written so far, read under the wire's lock. + pub fn written(l: *Live, a: Allocator) ![]Value { + l.wire.mutex.lockUncancelable(l.wire.io); + const copy = a.dupe(u8, l.out.written()); + l.wire.mutex.unlock(l.wire.io); + return lines(a, try copy); + } + + /// The answer to request ``id``, waited for up to 20 s. + pub fn answer(l: *Live, a: Allocator, id: i64) !Value { + var waited: u32 = 0; + while (waited < 20_000) : (waited += 20) { + if (find(try l.written(a), id)) |v| return v; + std.testing.io.sleep(.fromMilliseconds(20), .awake) catch {}; + } + return error.TestTimedOut; + } + + /// Waits up to 20 s for every running call to finish. + pub fn idle(l: *Live) !void { + var waited: u32 = 0; + while (waited < 20_000) : (waited += 20) { + const busy = for (l.session.calls.items) |c| { + if (!c.done.load(.acquire)) break true; + } else false; + if (!busy) return; + std.testing.io.sleep(.fromMilliseconds(20), .awake) catch {}; + } + return error.TestTimedOut; + } +}; + +/// Waits up to 10 s for ``path`` to exist, as a stand-in child writes its files. +pub fn appears(path: []const u8) !void { + var waited: u32 = 0; + while (waited < 10_000) : (waited += 20) { + if (std.Io.Dir.cwd().access(std.testing.io, path, .{})) |_| return else |_| {} + std.testing.io.sleep(.fromMilliseconds(20), .awake) catch {}; + } + return error.TestTimedOut; +} diff --git a/zig/src/server/mcp_rpc.zig b/zig/src/server/mcp_rpc.zig new file mode 100644 index 00000000000..86c6cff0670 --- /dev/null +++ b/zig/src/server/mcp_rpc.zig @@ -0,0 +1,181 @@ +//! MCP's wire: one JSON-RPC 2.0 message a line, the protocol revisions served and how a request picks one. +const std = @import("std"); +const json = @import("json"); +const Allocator = std.mem.Allocator; +const Value = json.Value; +const none: Value = .null; + +pub const parse_error: i32 = -32700; +pub const invalid_request: i32 = -32600; +pub const method_not_found: i32 = -32601; +pub const invalid_params: i32 = -32602; +pub const internal_error: i32 = -32603; +/// 2026-07-28's UnsupportedProtocolVersionError: the request's revision is not one this server speaks. +pub const unsupported_version: i32 = -32022; + +/// The longest message line read; a longer one is refused and skipped to its newline. +pub const max_line = 4 << 20; + +pub const meta_version = "io.modelcontextprotocol/protocolVersion"; +pub const meta_capabilities = "io.modelcontextprotocol/clientCapabilities"; +pub const meta_server = "io.modelcontextprotocol/serverInfo"; + +/// A revision served: 2026-07-28 names itself in every request's _meta; the others open with an initialize handshake. +pub const Version = enum { + @"2026-07-28", + @"2025-11-25", + @"2025-06-18", + + /// True for the stateless revision, whose results carry resultType and the server's identity. + pub fn stateless(v: Version) bool { + return v == .@"2026-07-28"; + } +}; + +/// Every revision served, newest first, as an UnsupportedProtocolVersionError and server/discover list them. +pub const supported = [_][]const u8{ "2026-07-28", "2025-11-25", "2025-06-18" }; + +/// initialize's answer: the requested handshake revision when served, else the newest one. +pub fn negotiate(requested: ?[]const u8) Version { + const v = std.meta.stringToEnum(Version, requested orelse "") orelse return .@"2025-11-25"; + return if (v.stateless()) .@"2025-11-25" else v; +} + +pub const Request = struct { id: Value, method: []const u8, params: Value }; +pub const Notification = struct { method: []const u8, params: Value }; +/// A message answered with an error: ``id`` is null when the message's own could not be read. +pub const Refusal = struct { id: Value = .null, code: i32, message: []const u8, data: ?Value = null }; + +pub const Message = union(enum) { + request: Request, + notification: Notification, + refused: Refusal, + /// Nothing to answer: a blank line, a client's reply (this server sends no requests) or a bad notification. + dropped: []const u8, +}; + +/// One line as a message; params is an object or null. +pub fn read(a: Allocator, line: []const u8) !Message { + const text = std.mem.trim(u8, line, " \t\r"); + if (text.len == 0) return .{ .dropped = "" }; + const v = switch (try json.parse(a, text)) { + .ok => |v| v, + .err => |why| return refuse(.null, parse_error, try std.fmt.allocPrint(a, "Parse error: {s}", .{why})), + }; + if (v == .array) return refuse(.null, invalid_request, "Invalid Request: batches are not supported; send one message a line"); + if (v != .object) return refuse(.null, invalid_request, "Invalid Request: a message is a JSON object"); + const id = v.get("id"); + const id_ok = if (id) |x| x == .string or x == .int else false; + const echo: Value = if (id_ok) id.? else .null; + if (!std.mem.eql(u8, v.strField("jsonrpc") orelse "", "2.0")) return refuse(echo, invalid_request, "Invalid Request: jsonrpc must be \"2.0\""); + const method = v.get("method") orelse { + if (id != null and (v.has("result") or v.has("error"))) return .{ .dropped = "a reply to no request this server sent" }; + return refuse(echo, invalid_request, "Invalid Request: no method"); + }; + if (method != .string) return refuse(echo, invalid_request, "Invalid Request: method must be a string"); + const params = v.get("params") orelse .null; + if (id == null) { + if (params != .null and params != .object) return .{ .dropped = "a notification whose params are not an object" }; + return .{ .notification = .{ .method = method.string, .params = params } }; + } + if (!id_ok) return refuse(.null, invalid_request, "Invalid Request: id must be a string or an integer"); + if (params != .null and params != .object) return refuse(echo, invalid_params, "Invalid params: params must be an object"); + return .{ .request = .{ .id = id.?, .method = method.string, .params = params } }; +} + +fn refuse(id: Value, code: i32, message: []const u8) Message { + return .{ .refused = .{ .id = id, .code = code, .message = message } }; +} + +pub const Picked = union(enum) { ok: Version, refused: Refusal }; + +/// The revision a request is served under: its _meta's, else the handshake's; a refusal when neither names one. +pub fn version(a: Allocator, r: Request, handshake: ?Version) !Picked { + const meta = r.params.get("_meta") orelse none; + if (meta.get(meta_version)) |named| { + const v: ?Version = if (named == .string) std.meta.stringToEnum(Version, named.string) else null; + if (v == null or !v.?.stateless()) { + const data = try json.newObject(a); + try data.put(a, "supported", try strings(a, &supported)); + try data.put(a, "requested", named); + return .{ .refused = .{ .id = r.id, .code = unsupported_version, .message = "Unsupported protocol version", .data = .{ .object = data } } }; + } + if (meta.get(meta_capabilities) == null or meta.get(meta_capabilities).? != .object) + return .{ .refused = .{ .id = r.id, .code = invalid_params, .message = "Invalid params: _meta names no " ++ meta_capabilities ++ " object" } }; + return .{ .ok = v.? }; + } + if (handshake) |h| return .{ .ok = h }; + return .{ .refused = .{ .id = r.id, .code = invalid_params, .message = "Invalid params: no protocol version; send initialize first, or name " ++ meta_version ++ " in _meta" } }; +} + +pub fn strings(a: Allocator, items: []const []const u8) !Value { + const out = try a.alloc(Value, items.len); + for (out, items) |*o, s| o.* = .{ .string = s }; + return .{ .array = out }; +} + +/// ``{"jsonrpc": "2.0", "id": id, "result": result}``. +pub fn result(a: Allocator, id: Value, body: *json.Object) !Value { + const o = try json.newObject(a); + try o.put(a, "jsonrpc", .{ .string = "2.0" }); + try o.put(a, "id", id); + try o.put(a, "result", .{ .object = body }); + return .{ .object = o }; +} + +/// ``{"jsonrpc": "2.0", "id": id, "error": {"code", "message", "data"}}``. +pub fn failure(a: Allocator, r: Refusal) !Value { + const e = try json.newObject(a); + try e.put(a, "code", try json.intValue(a, r.code)); + try e.put(a, "message", .{ .string = r.message }); + if (r.data) |d| try e.put(a, "data", d); + const o = try json.newObject(a); + try o.put(a, "jsonrpc", .{ .string = "2.0" }); + try o.put(a, "id", r.id); + try o.put(a, "error", .{ .object = e }); + return .{ .object = o }; +} + +/// ``{"jsonrpc": "2.0", "method": method, "params": params}``, a notification needing no answer. +pub fn notification(a: Allocator, method: []const u8, params: *json.Object) !Value { + const o = try json.newObject(a); + try o.put(a, "jsonrpc", .{ .string = "2.0" }); + try o.put(a, "method", .{ .string = method }); + try o.put(a, "params", .{ .object = params }); + return .{ .object = o }; +} + +/// The stateless revision's result fields: ``resultType`` and the server's identity in ``_meta``. +pub fn complete(a: Allocator, body: *json.Object, v: Version, server: Value) !void { + if (!v.stateless()) return; + try body.put(a, "resultType", .{ .string = "complete" }); + const meta = try json.newObject(a); + try meta.put(a, meta_server, server); + try body.put(a, "_meta", .{ .object = meta }); +} + +/// stdout's messages, one whole line at a time under a lock, so call threads and the reader never interleave. +pub const Wire = struct { + out: *std.Io.Writer, + io: std.Io, + mutex: std.Io.Mutex = .init, + broken: bool = false, + + /// ``message`` as one compact ASCII line; a write error is told once on stderr, as the client may be gone. + pub fn send(w: *Wire, message: Value) void { + var arena: std.heap.ArenaAllocator = .init(std.heap.smp_allocator); + defer arena.deinit(); + var line: std.Io.Writer.Allocating = .init(arena.allocator()); + json.write(&line.writer, message, .{ .compact = true }) catch return; + line.writer.writeByte('\n') catch return; + w.mutex.lockUncancelable(w.io); + defer w.mutex.unlock(w.io); + w.out.writeAll(line.written()) catch return w.fail(); + w.out.flush() catch return w.fail(); + } + + fn fail(w: *Wire) void { + if (!w.broken) std.debug.print("tensorfold mcp: stdout is closed; replies are dropped\n", .{}); + w.broken = true; + } +}; diff --git a/zig/src/server/mcp_rpc_test.zig b/zig/src/server/mcp_rpc_test.zig new file mode 100644 index 00000000000..dc509227b12 --- /dev/null +++ b/zig/src/server/mcp_rpc_test.zig @@ -0,0 +1,264 @@ +//! `tensorfold mcp` on the wire: one message a line, JSON-RPC errors, the handshake and per-request revisions. +const std = @import("std"); +const json = @import("json"); +const platform = @import("sys"); +const mcp = @import("mcp.zig"); +const rpc = @import("mcp_rpc.zig"); +const stop = @import("benchmark_stop.zig"); +const fake = @import("benchmark_fake.zig"); +const fixture = @import("mcp_fixture.zig"); +const Value = json.Value; + +const modern = "\"_meta\":{\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28\",\"io.modelcontextprotocol/clientCapabilities\":{}}"; +const initialize = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-11-25\",\"capabilities\":{},\"clientInfo\":{\"name\":\"example-client\",\"version\":\"1.0\"}}}\n" ++ + "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}\n"; + +fn result(v: Value) Value { + return v.get("result").?; +} + +test "mcp wire: initialize answers the handshake revision asked for, else the newest it serves, and names the server" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var home = try fixture.Home.init(a); + defer home.deinit(); + const ctx = home.context(); + const got = try fixture.exchange(a, &ctx, + \\{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"example-client","version":"1.0"}}} + \\{"jsonrpc":"2.0","method":"notifications/initialized"} + \\{"jsonrpc":"2.0","id":"two","method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{}}} + \\{"jsonrpc":"2.0","id":3,"method":"initialize","params":{"protocolVersion":"2026-07-28"}} + \\{"jsonrpc":"2.0","id":4,"method":"initialize","params":{}} + \\{"jsonrpc":"2.0","id":5,"method":"ping"} + \\{"jsonrpc":"2.0","id":6,"method":"initialize","params":{"protocolVersion":"2025-11-25"}} + \\ + ); + try std.testing.expectEqual(@as(usize, 6), got.len); // the notification gets no answer + const first = result(got[0]); + try std.testing.expectEqualStrings("2025-06-18", first.strField("protocolVersion").?); + try std.testing.expectEqualStrings("tensorfold", first.get("serverInfo").?.strField("name").?); + try std.testing.expectEqualStrings(fixture.version, first.get("serverInfo").?.strField("version").?); + try std.testing.expect(first.get("capabilities").?.get("tools").? == .object); + try std.testing.expect(fixture.has(first.strField("instructions").?, "serve")); + try std.testing.expectEqualStrings("two", got[1].strField("id").?); + for (got[1..4]) |v| try std.testing.expectEqualStrings("2025-11-25", result(v).strField("protocolVersion").?); + try std.testing.expectEqual(@as(?i64, 5), got[4].get("id").?.int64()); + try std.testing.expectEqual(@as(usize, 0), result(got[4]).object.count()); // ping's empty result + try std.testing.expectEqualStrings("2025-11-25", result(got[5]).strField("protocolVersion").?); + try std.testing.expect(result(got[0]).get("resultType") == null); // handshake revisions carry no resultType +} + +test "mcp wire: bad JSON, batches, non-objects and bad ids get JSON-RPC errors; replies and blank lines get nothing" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var home = try fixture.Home.init(a); + defer home.deinit(); + const ctx = home.context(); + const got = try fixture.exchange(a, &ctx, "{bad json\n" ++ + \\[{"jsonrpc":"2.0","id":1,"method":"ping"}] + \\[] + \\42 + \\{"jsonrpc":"1.0","id":3,"method":"ping"} + \\{"jsonrpc":"2.0","id":null,"method":"ping"} + \\{"jsonrpc":"2.0","id":1.5,"method":"ping"} + \\{"jsonrpc":"2.0","id":4,"method":"ping","params":[1]} + \\{"jsonrpc":"2.0","id":5} + \\ + \\ + ++ " \t \r\n" ++ + \\{"jsonrpc":"2.0","id":6,"result":{}} + \\{"jsonrpc":"2.0","method":"notifications/progress","params":7} + \\{"jsonrpc":"2.0","id":8,"method":"ping"} + \\{"jsonrpc":"2.0","id":9,"method":7} + ); + const want = [_]struct { id: ?i64, code: ?i64 }{ + .{ .id = null, .code = rpc.parse_error }, + .{ .id = null, .code = rpc.invalid_request }, + .{ .id = null, .code = rpc.invalid_request }, + .{ .id = null, .code = rpc.invalid_request }, + .{ .id = 3, .code = rpc.invalid_request }, + .{ .id = null, .code = rpc.invalid_request }, + .{ .id = null, .code = rpc.invalid_request }, + .{ .id = 4, .code = rpc.invalid_params }, + .{ .id = 5, .code = rpc.invalid_request }, + .{ .id = 8, .code = null }, + .{ .id = 9, .code = rpc.invalid_request }, + }; + try std.testing.expectEqual(want.len, got.len); + for (want, got) |w, v| { + try std.testing.expectEqualStrings("2.0", v.strField("jsonrpc").?); + try std.testing.expectEqual(w.id, if (v.get("id")) |id| id.int64() else return error.TestUnexpectedResult); + try std.testing.expectEqual(w.code, fixture.code(v)); + if (w.code != null) try std.testing.expect(v.get("error").?.strField("message").?.len > 0); + } + try std.testing.expect(fixture.has(got[0].get("error").?.strField("message").?, "Parse error")); + try std.testing.expect(fixture.has(got[1].get("error").?.strField("message").?, "batches are not supported")); +} + +test "mcp wire: a line past 4 MiB is refused and the next one is still served" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var home = try fixture.Home.init(a); + defer home.deinit(); + const ctx = home.context(); + const pad = try a.alloc(u8, rpc.max_line + 16); + @memset(pad, 'x'); + const input = try std.mem.concat(a, u8, &.{ "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\",\"params\":{\"pad\":\"", pad, "\"}}\n", "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"ping\"}\n" }); + const got = try fixture.exchange(a, &ctx, input); + try std.testing.expectEqual(@as(usize, 2), got.len); + try std.testing.expectEqual(@as(?i64, rpc.invalid_request), fixture.code(got[0])); + try std.testing.expect(got[0].get("id").? == .null); + try std.testing.expectEqual(@as(?i64, 2), got[1].get("id").?.int64()); + try std.testing.expectEqual(@as(?i64, null), fixture.code(got[1])); +} + +test "mcp wire: a stop signal while stdin stays open ends the session as its end would, with the signal's exit code" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var home = try fixture.Home.init(a); + defer home.deinit(); + const ctx = home.context(); + var fds: [2]std.posix.fd_t = undefined; + if (platform.c.pipe(&fds) != 0) return error.SkipZigTest; + defer for (fds) |fd| { + _ = platform.c.close(fd); + }; + const greeting = initialize ++ "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"ping\"}\n"; + try std.testing.expectEqual(@as(isize, greeting.len), platform.c.write(fds[1], greeting, greeting.len)); + var stdin = (std.Io.File{ .handle = fds[0], .flags = .{ .nonblocking = false } }).readerStreaming(std.testing.io, try a.alloc(u8, rpc.max_line)); + var out: std.Io.Writer.Allocating = .init(a); + stop.reset(); + defer stop.reset(); + const later = try std.Thread.spawn(.{}, struct { + fn go() void { + fake.nap(300); + stop.request(.TERM); + } + }.go, .{}); + defer later.join(); + try std.testing.expectEqual(stop.exitCode(.TERM), try mcp.run(&ctx, &stdin.interface, &out.writer)); + const got = try fixture.lines(a, out.written()); + try std.testing.expectEqual(@as(usize, 2), got.len); // both lines answered, then the signal, with stdin still open + try std.testing.expectEqual(@as(?i64, 2), got[1].get("id").?.int64()); +} + +test "mcp wire: 2026-07-28 requests name their revision in _meta; others before initialize are refused" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var home = try fixture.Home.init(a); + defer home.deinit(); + const ctx = home.context(); + const got = try fixture.exchange(a, &ctx, "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\"}\n" ++ + "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"server/discover\",\"params\":{" ++ modern ++ "}}\n" ++ + "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/list\",\"params\":{" ++ modern ++ "}}\n" ++ + "{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"tools/list\",\"params\":{\"_meta\":{\"io.modelcontextprotocol/protocolVersion\":\"2099-01-01\",\"io.modelcontextprotocol/clientCapabilities\":{}}}}\n" ++ + "{\"jsonrpc\":\"2.0\",\"id\":5,\"method\":\"tools/list\",\"params\":{\"_meta\":{\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28\"}}}\n" ++ + "{\"jsonrpc\":\"2.0\",\"id\":6,\"method\":\"ping\",\"params\":{" ++ modern ++ "}}\n" ++ + "{\"jsonrpc\":\"2.0\",\"id\":7,\"method\":\"resources/list\",\"params\":{" ++ modern ++ "}}\n" ++ + "{\"jsonrpc\":\"2.0\",\"id\":8,\"method\":\"server/discover\"}\n" ++ + "{\"jsonrpc\":\"2.0\",\"id\":9,\"method\":\"tools/call\",\"params\":{\"name\":\"status\",\"arguments\":{}," ++ modern ++ "}}\n"); + try std.testing.expectEqual(@as(usize, 9), got.len); + try std.testing.expectEqual(@as(?i64, rpc.invalid_params), fixture.code(fixture.find(got, 1).?)); + const found = result(fixture.find(got, 2).?); + try std.testing.expectEqualStrings("complete", found.strField("resultType").?); + try std.testing.expectEqual(@as(usize, 3), found.get("supportedVersions").?.array.len); + try std.testing.expectEqualStrings("2026-07-28", found.get("supportedVersions").?.array[0].string); + try std.testing.expect(found.get("capabilities").?.get("tools").? == .object); + try std.testing.expectEqualStrings("tensorfold", found.get("_meta").?.get(rpc.meta_server).?.strField("name").?); + const listed = result(fixture.find(got, 3).?); + try std.testing.expectEqualStrings("complete", listed.strField("resultType").?); + try std.testing.expectEqual(@as(usize, 7), listed.get("tools").?.array.len); + try std.testing.expectEqual(@as(?i64, 3_600_000), listed.get("ttlMs").?.int64()); + try std.testing.expectEqualStrings("public", listed.strField("cacheScope").?); + const unsupported = fixture.find(got, 4).?; + try std.testing.expectEqual(@as(?i64, rpc.unsupported_version), fixture.code(unsupported)); + const data = unsupported.get("error").?.get("data").?; + try std.testing.expectEqualStrings("2099-01-01", data.strField("requested").?); + try std.testing.expectEqual(@as(usize, 3), data.get("supported").?.array.len); + try std.testing.expectEqual(@as(?i64, rpc.invalid_params), fixture.code(fixture.find(got, 5).?)); + for ([_]i64{ 6, 7 }) |id| try std.testing.expectEqual(@as(?i64, rpc.method_not_found), fixture.code(fixture.find(got, id).?)); + try std.testing.expectEqual(@as(?i64, rpc.invalid_params), fixture.code(fixture.find(got, 8).?)); // a dual-era probe falls back + const called = result(fixture.find(got, 9).?); + try std.testing.expectEqualStrings("complete", called.strField("resultType").?); + try std.testing.expect(called.get("isError").?.bool == false); +} + +test "mcp tools/list: seven tools in a fixed order, each an object schema with no extra properties and its hints" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var home = try fixture.Home.init(a); + defer home.deinit(); + const ctx = home.context(); + const got = try fixture.exchange(a, &ctx, initialize ++ "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\",\"params\":{}}\n"); + const listed = result(fixture.find(got, 2).?); + try std.testing.expect(listed.get("resultType") == null and listed.get("ttlMs") == null); + const tools = listed.get("tools").?.array; + const names = [_][]const u8{ "machine", "models", "info", "pull", "serve", "stop", "status" }; + const required = [_]?[]const u8{ null, null, "model", "repo", "model", "id", null }; + const read_only = [_]bool{ true, true, true, false, false, false, true }; + try std.testing.expectEqual(names.len, tools.len); + for (tools, names, required, read_only) |t, name, need, ro| { + try std.testing.expectEqualStrings(name, t.strField("name").?); + try std.testing.expect(t.strField("title").?.len > 0 and t.strField("description").?.len > 0); + const schema = t.get("inputSchema").?; + try std.testing.expectEqualStrings("object", schema.strField("type").?); + try std.testing.expect(schema.get("properties").? == .object); + try std.testing.expect(schema.get("additionalProperties").?.bool == false); + if (need) |n| try std.testing.expectEqualStrings(n, schema.get("required").?.array[0].string) else try std.testing.expect(schema.get("required") == null); + try std.testing.expectEqual(ro, t.get("annotations").?.get("readOnlyHint").?.bool); + } + const serve_props = tools[4].get("inputSchema").?.get("properties").?; + try std.testing.expectEqualStrings("integer", serve_props.get("context").?.strField("type").?); + try std.testing.expectEqual(@as(?i64, 1), serve_props.get("context").?.get("minimum").?.int64()); + try std.testing.expect(tools[5].get("annotations").?.get("destructiveHint").?.bool); + try std.testing.expect(tools[3].get("annotations").?.get("openWorldHint").?.bool); +} + +test "mcp tools/call: an unknown tool or a malformed call is a protocol error; bad arguments are tool errors" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var home = try fixture.Home.init(a); + defer home.deinit(); + const ctx = home.context(); + const got = try fixture.exchange(a, &ctx, initialize ++ + \\{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"nope"}} + \\{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{}} + \\{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"info","arguments":[1]}} + \\{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"info"}} + \\{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"status","arguments":{"verbose":true}}} + \\{"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"serve","arguments":{"model":"Org/Flash","context":0}}} + \\{"jsonrpc":"2.0","id":8,"method":"tools/call","params":{"name":"info","arguments":{"model":7}}} + \\{"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"name":"status","arguments":{}}} + \\{"jsonrpc":"2.0","id":10,"method":"tools/call","params":{"name":"stop","arguments":{"id":"9"}}} + \\{"jsonrpc":"2.0","id":11,"method":"tools/call","params":{"name":"pull","arguments":{"repo":"Org/Flash","revision":null,"extra":1}}} + \\ + ); + try std.testing.expectEqual(@as(usize, 11), got.len); + for ([_]i64{ 2, 3, 4 }) |id| try std.testing.expectEqual(@as(?i64, rpc.invalid_params), fixture.code(fixture.find(got, id).?)); + try std.testing.expect(fixture.has(fixture.find(got, 2).?.get("error").?.strField("message").?, "Unknown tool: nope")); + const refusals = [_]struct { id: i64, says: []const u8 }{ + .{ .id = 5, .says = "info needs model" }, + .{ .id = 6, .says = "status takes no argument named verbose; it takes no arguments" }, + .{ .id = 7, .says = "context must be a whole number from 1" }, + .{ .id = 8, .says = "model must be a non-empty string" }, + .{ .id = 10, .says = "started no server 9" }, + .{ .id = 11, .says = "pull takes no argument named extra; it takes repo, revision" }, + }; + for (refusals) |r| { + const v = fixture.find(got, r.id).?; + try std.testing.expect(fixture.isError(v)); + try std.testing.expect(fixture.has(fixture.text(v), r.says)); + try std.testing.expect(result(v).get("structuredContent") == null); + } + const status = fixture.find(got, 9).?; + try std.testing.expect(!fixture.isError(status)); + try std.testing.expect(fixture.has(fixture.text(status), "started no servers")); + try std.testing.expectEqual(@as(usize, 0), result(status).get("structuredContent").?.get("servers").?.array.len); +} diff --git a/zig/src/server/mcp_serve.zig b/zig/src/server/mcp_serve.zig new file mode 100644 index 00000000000..a59a1d6cc44 --- /dev/null +++ b/zig/src/server/mcp_serve.zig @@ -0,0 +1,331 @@ +//! The serve, stop and status tools: `tensorfold serve` children on loopback, each with its own key. +const std = @import("std"); +const builtin = @import("builtin"); +const json = @import("json"); +const checkpoint = @import("checkpoint_cli"); +const mcp = @import("mcp.zig"); +const rpc = @import("mcp_rpc.zig"); +const tools = @import("mcp_tools.zig"); +const cache = @import("mcp_cache.zig"); +const cli = @import("cli.zig"); +const hub = @import("hub.zig"); +const posix_only = builtin.os.tag != .windows; +const server = if (posix_only) @import("benchmark_server.zig") else struct {}; +const weights = if (posix_only) @import("benchmark_model.zig") else struct {}; +const child = if (posix_only) @import("chat_cli_child.zig") else struct {}; +const Allocator = std.mem.Allocator; +const Value = json.Value; + +/// The serve child as `tensorfold benchmark` runs it; Windows has none, as it stops children by POSIX signals. +const Child = if (posix_only) server.Managed else void; + +/// How often a loading server's progress is reported, in seconds. +const report_every_s = 5; + +/// What a server this session starts says when it cannot start or stop. +const words = if (posix_only) server.Words{ + .log = "tensorfold serve could not start: its log under ~/.tensorfold/mcp could not be created", + .spawn = "tensorfold serve could not start; check the TensorFold installation", + .exited = "tensorfold serve exited while loading", + .timed_out = "tensorfold serve did not answer within", + .stuck = "tensorfold serve did not exit after SIGTERM and SIGKILL; cleanup is incomplete", +} else {}; + +pub const State = enum { starting, running, exited, stopped }; + +pub const Entry = struct { + id: []const u8, + model: []const u8, + name: []const u8, + dir: []const u8, + context: ?u32, + drafter: ?[]const u8, + key: []const u8, + url: []const u8 = "", + state: State = .starting, + child: ?Child = null, + /// An exited child's last log lines. + last: []const []const u8 = &.{}, + /// The loading child's stop: set by stop, by the session's end and by the client's cancel. + cancel: std.atomic.Value(bool) = .init(false), +}; + +/// The servers this session started, under one lock that every tool call and the session's end take. +pub const Registry = struct { + io: std.Io, + mutex: std.Io.Mutex = .init, + arena: std.heap.ArenaAllocator, + entries: std.ArrayList(*Entry) = .empty, + next: u32 = 1, + ending: bool = false, + + pub fn init(gpa: Allocator, io: std.Io) Registry { + return .{ .io = io, .arena = .init(gpa) }; + } + + pub fn deinit(r: *Registry) void { + r.arena.deinit(); + } + + /// The session's end: every server stops, and one a call registers later is stopped on arrival. + pub fn stopAll(r: *Registry) void { + r.mutex.lockUncancelable(r.io); + defer r.mutex.unlock(r.io); + r.ending = true; + for (r.entries.items) |e| { + e.cancel.store(true, .release); + _ = halt(e); + } + } + + const Claim = union(enum) { new: *Entry, same: *Entry, loading: *Entry, ending }; + + /// A new entry for these settings, or the server already running or loading them. + fn claim(r: *Registry, model: []const u8, name: []const u8, dir: []const u8, context: ?u32, drafter: ?[]const u8) !Claim { + r.mutex.lockUncancelable(r.io); + defer r.mutex.unlock(r.io); + if (r.ending) return .ending; + const a = r.arena.allocator(); + for (r.entries.items) |e| { + const same = std.mem.eql(u8, e.dir, dir) and e.context == context and std.mem.eql(u8, e.drafter orelse "", drafter orelse ""); + if (!same) continue; + if (e.state == .starting) return .{ .loading = e }; + if (e.state == .running and alive(e, a)) return .{ .same = e }; + } + const e = try a.create(Entry); + e.* = .{ + .id = try std.fmt.allocPrint(a, "{d}", .{r.next}), + .model = try a.dupe(u8, model), + .name = try a.dupe(u8, name), + .dir = try a.dupe(u8, dir), + .context = context, + .drafter = if (drafter) |d| try a.dupe(u8, d) else null, + .key = try child.freshKey(a, r.io), + }; + try r.entries.append(a, e); + r.next += 1; + return .{ .new = e }; + } + + /// A started child into its entry; false when stop or the session's end came first, and the child is stopped. + fn register(r: *Registry, e: *Entry, started: Child) !bool { + r.mutex.lockUncancelable(r.io); + defer r.mutex.unlock(r.io); + e.child = started; + errdefer _ = halt(e); + if (r.ending or e.cancel.load(.acquire)) { + _ = halt(e); + return false; + } + const a = r.arena.allocator(); + e.child.?.base_url = try a.dupe(u8, started.base_url); // the call's arena ends with the call + e.url = try std.fmt.allocPrint(a, "{s}/v1", .{e.child.?.base_url}); + e.state = .running; + return true; + } + + fn drop(r: *Registry, e: *Entry) void { + r.mutex.lockUncancelable(r.io); + defer r.mutex.unlock(r.io); + for (r.entries.items, 0..) |x, i| if (x == e) { + _ = r.entries.orderedRemove(i); + return; + }; + } +}; + +/// Whether the entry's child still runs; an exit seen here marks it exited with its last log lines, kept in ``a``. +fn alive(e: *Entry, a: Allocator) bool { + if (comptime !posix_only) return false; + const m = if (e.child) |*m| m else return false; + if (m.closed) return false; + const lines = (m.exitedTail(a) catch return true) orelse return true; + if (e.state == .running) { + e.state = .exited; + e.last = lines; + } + return false; +} + +/// Stops the entry's child, if it runs; null when it is gone, else why it is not. +fn halt(e: *Entry) ?[]const u8 { + if (comptime !posix_only) return null; + const why = if (e.child) |*m| m.stop() else null; + if (e.state != .exited) e.state = .stopped; + return why; +} + +/// serve's arguments, checked against its schema. +pub const Wanted = struct { model: []const u8, context: ?i64, drafter: ?[]const u8 }; + +/// While a server loads: the client's cancel passed on as its stop, and its progress every few seconds. +const Loading = struct { + call: *mcp.Call, + entry: *Entry, + done: std.atomic.Value(bool) = .init(false), + + fn watch(l: *Loading) void { + const io = l.call.ctx().io; + var polls: u32 = 0; + while (!l.done.load(.acquire)) : (polls += 1) { + if (l.call.stopping()) l.entry.cancel.store(true, .release); + if (polls > 0 and polls % (5 * report_every_s) == 0) { + var buf: [512]u8 = undefined; + l.call.report(std.fmt.bufPrint(&buf, "loading {s}: {d} s", .{ l.entry.model, polls / 5 }) catch "loading"); + } + io.sleep(.fromMilliseconds(200), .awake) catch {}; + } + } +}; + +/// The serve tool: a cached model served on 127.0.0.1 with a fresh key, answered once it answers requests. +pub fn start(c: *mcp.Call, w: Wanted) !*json.Object { + const a = c.a; + if (comptime !posix_only) + return tools.failed(a, "serve is not supported on Windows yet, as it stops its servers with POSIX signals; run tensorfold serve {s} in a terminal instead", .{w.model}); + const ctx = c.ctx(); + var problem: []const u8 = ""; + const dir = try cache.resolve(a, ctx.io, ctx.environ, w.model, &problem) orelse return tools.failed(a, "{s}", .{problem}); + const model_type = checkpoint.hub.modelType(a, ctx.io, dir); + if (checkpoint.hub.family(model_type) == null) return tools.failed(a, "{s}: no TensorFold family in this build serves model_type {s}", .{ w.model, model_type }); + const drafter = if (w.drafter) |d| try cache.resolve(a, ctx.io, ctx.environ, d, &problem) orelse return tools.failed(a, "drafter: {s}", .{problem}) else null; + const context: ?u32 = if (w.context) |n| @intCast(n) else null; + const r = &c.session.servers; + const e = switch (try r.claim(w.model, hub.servedName("", w.model, dir), dir, context, drafter)) { + .new => |e| e, + .same => |e| return served(a, e, true), + .loading => |e| return tools.failed(a, "{s} is already loading as server {s}; status shows when it runs", .{ w.model, e.id }), + .ending => return tools.failed(a, "the session is ending, so no server starts", .{}), + }; + errdefer r.drop(e); + var extra: std.ArrayList([]const u8) = .empty; + try extra.append(a, "--no-update-check"); + if (context) |n| try extra.appendSlice(a, &.{ "--context", try std.fmt.allocPrint(a, "{d}", .{n}) }); + if (drafter) |d| try extra.appendSlice(a, &.{ "--drafter", d }); + const argv = try child.argv(a, ctx.exe orelse try std.process.executablePathAlloc(ctx.io, a), dir, e.name, extra.items); + var u: cli.Usage = .{}; + _ = cli.parse(a, argv[2..], &u) catch |err| switch (err) { + error.Usage => { + r.drop(e); + return tools.failed(a, "tensorfold serve refuses these settings: {s}", .{u.message}); + }, + else => |x| return x, + }; + // the parent's variables a serve reads, less its own key and the benchmark's upload token, as the router has them + const env = try server.environWithout(a, ctx.environ, &.{ "TENSORFOLD_API_KEY", "TENSORFOLD_BENCHMARK_TOKEN" }); + const logs = try std.fs.path.join(a, &.{ ctx.home, ".tensorfold", "mcp" }); + _ = std.Io.Dir.cwd().createDirPathStatus(ctx.io, logs, .fromMode(0o700)) catch {}; + var failure: server.Failure = .none; + var tail: []const []const u8 = &.{}; + const timeout_s = server.startupTimeout(weights.weightBytes(ctx.io, dir)); + c.report(try std.fmt.allocPrint(a, "starting tensorfold serve for {s}", .{w.model})); + var loading: Loading = .{ .call = c, .entry = e }; + const watcher = std.Thread.spawn(.{}, Loading.watch, .{&loading}) catch null; + const started = server.Managed.spawn(a, ctx.io, ctx.environ, argv, .{ + .startup_timeout_s = timeout_s, + .grace_ms = ctx.grace_ms, + .bench_dir = logs, + .tail = &tail, + .served = e.name, + .lock = false, + .own_group = true, + .key = e.key, + .words = words, + .environ = &env, + .guard = false, + .stop = &e.cancel, + .failure = &failure, + }, &problem); + loading.done.store(true, .release); // no progress may follow the answer + if (watcher) |t| t.join(); + if (try started) |m| { + if (c.cancelled.load(.acquire)) e.cancel.store(true, .release); // its client will never learn the key + if (try r.register(e, m)) return served(a, e, false); + return tools.failed(a, "server {s} was stopped while {s} loaded", .{ e.id, w.model }); + } + r.drop(e); + return switch (failure) { + .exited => tools.failed(a, "tensorfold serve exited while loading {s}{s}", .{ w.model, try lastLog(a, tail) }), + .timeout => tools.failed(a, "{s} did not answer within {d} s of starting, so it was stopped; check the checkpoint, memory and backend", .{ w.model, timeout_s }), + .stopped => tools.failed(a, "{s} was stopped while it loaded", .{w.model}), + .setup, .spawn, .none => tools.failed(a, "{s}", .{problem}), + }; +} + +fn lastLog(a: Allocator, tail: []const []const u8) ![]const u8 { + if (tail.len == 0) return ""; + return std.fmt.allocPrint(a, "; its last log lines: {s}", .{try std.mem.join(a, " | ", tail)}); +} + +fn served(a: Allocator, e: *const Entry, again: bool) !*json.Object { + const text = try std.fmt.allocPrint(a, "{s} {s} as {s} at {s} (server {s}).\nAPI key: {s}; send it as Authorization: Bearer KEY, or as x-api-key to /v1/messages.\n" ++ + "Chat completions, Responses and Anthropic Messages are under that base URL with model {s}; stop it with stop and id {s}.\n", .{ if (again) "Already serving" else "Serving", e.model, e.name, e.url, e.id, e.key, e.name, e.id }); + const o = try json.newObject(a); + try o.put(a, "id", .{ .string = e.id }); + try o.put(a, "model", .{ .string = e.model }); + try o.put(a, "name", .{ .string = e.name }); + try o.put(a, "base_url", .{ .string = e.url }); + try o.put(a, "api_key", .{ .string = e.key }); + try o.put(a, "context", try tools.optInt(a, if (e.context) |n| @as(u64, n) else null)); + try o.put(a, "already_running", .{ .bool = again }); + return tools.answered(a, text, o); +} + +/// The stop tool: the server ``id`` stopped, or its loading cancelled; never a process this session did not start. +pub fn stop(c: *mcp.Call, id: []const u8) !*json.Object { + const a = c.a; + const r = &c.session.servers; + r.mutex.lockUncancelable(r.io); + defer r.mutex.unlock(r.io); + const e = for (r.entries.items) |e| { + if (std.mem.eql(u8, e.id, id)) break e; + } else return tools.failed(a, "this session started no server {s}; status lists the ones it did", .{id}); + const o = try json.newObject(a); + try o.put(a, "id", .{ .string = e.id }); + try o.put(a, "model", .{ .string = e.model }); + const text = switch (e.state) { + .starting => blk: { + e.cancel.store(true, .release); + break :blk try std.fmt.allocPrint(a, "Server {s} ({s}) was still loading; it stops instead of serving.\n", .{ e.id, e.model }); + }, + .running => blk: { + if (!alive(e, r.arena.allocator())) break :blk try std.fmt.allocPrint(a, "Server {s} ({s}) had already exited.\n", .{ e.id, e.model }); + if (halt(e)) |why| return tools.failed(a, "server {s}: {s}", .{ e.id, why }); + break :blk try std.fmt.allocPrint(a, "Stopped server {s} ({s} at {s}).\n", .{ e.id, e.model, e.url }); + }, + .exited => try std.fmt.allocPrint(a, "Server {s} ({s}) had already exited.\n", .{ e.id, e.model }), + .stopped => try std.fmt.allocPrint(a, "Server {s} ({s}) was already stopped.\n", .{ e.id, e.model }), + }; + try o.put(a, "state", .{ .string = @tagName(if (e.state == .starting) State.stopped else e.state) }); + return tools.answered(a, text, o); +} + +/// The status tool: every server this session started, whether each still runs, and an exited one's last log lines. +pub fn status(c: *mcp.Call) !*json.Object { + const a = c.a; + const r = &c.session.servers; + r.mutex.lockUncancelable(r.io); + defer r.mutex.unlock(r.io); + var text: std.Io.Writer.Allocating = .init(a); + const items = try a.alloc(Value, r.entries.items.len); + for (r.entries.items, items) |e, *slot| { + const running = e.state == .running and alive(e, r.arena.allocator()); + try text.writer.print("server {s}: {s} as {s}, {t}", .{ e.id, e.model, e.name, e.state }); + if (e.url.len > 0) try text.writer.print(", {s}", .{e.url}); + if (e.state == .exited and e.last.len > 0) try text.writer.print("; last log: {s}", .{try std.mem.join(a, " | ", e.last)}); + try text.writer.writeAll("\n"); + const o = try json.newObject(a); + try o.put(a, "id", .{ .string = e.id }); + try o.put(a, "model", .{ .string = e.model }); + try o.put(a, "name", .{ .string = e.name }); + try o.put(a, "base_url", if (e.url.len > 0) .{ .string = e.url } else .null); + try o.put(a, "state", .{ .string = @tagName(e.state) }); + try o.put(a, "running", .{ .bool = running }); + if (e.state == .exited) try o.put(a, "last_log", try rpc.strings(a, e.last)); + slot.* = .{ .object = o }; + } + if (items.len == 0) try text.writer.writeAll("this session has started no servers\n"); + const o = try json.newObject(a); + try o.put(a, "servers", .{ .array = items }); + return tools.answered(a, text.written(), o); +} diff --git a/zig/src/server/mcp_serve_test.zig b/zig/src/server/mcp_serve_test.zig new file mode 100644 index 00000000000..1c5769a9b27 --- /dev/null +++ b/zig/src/server/mcp_serve_test.zig @@ -0,0 +1,267 @@ +//! The serve, stop and status tools with a stand-in serve child, and every server stopped at the session's end. +const std = @import("std"); +const json = @import("json"); +const fixture = @import("mcp_fixture.zig"); +const fake = @import("benchmark_fake.zig"); +const Value = json.Value; +const Allocator = std.mem.Allocator; +const posix = std.posix; + +const initialize = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-11-25\",\"capabilities\":{}}}\n"; + +fn call(a: Allocator, id: i64, tool: []const u8, args: []const u8) ![]const u8 { + return std.fmt.allocPrint(a, "{{\"jsonrpc\":\"2.0\",\"id\":{d},\"method\":\"tools/call\",\"params\":{{\"name\":\"{s}\",\"arguments\":{s}}}}}\n", .{ id, tool, args }); +} + +fn structured(v: Value) Value { + return v.get("result").?.get("structuredContent").?; +} + +const How = enum { serves, serves_then_dies, exits, hangs }; + +/// A stand-in for this executable: it records its pid, arguments and key, then serves, exits or hangs as told. +const World = struct { + home: fixture.Home, + f: *fake.Fake, + pidfile: []const u8, + argsfile: []const u8, + keyfile: []const u8, + ctx: @import("mcp.zig").Context, + + fn init(w: *World, a: Allocator, how: How) !void { + w.home = try fixture.Home.init(a); + w.pidfile = try w.home.path(a, "pid"); + w.argsfile = try w.home.path(a, "args"); + w.keyfile = try w.home.path(a, "key"); + const routes = try a.dupe(fake.Route, &.{ + .{ .method = "GET", .path = "/health", .replies = try a.dupe([]const fake.Write, &.{try fake.jsonReply(a, "200 OK", "{\"status\": \"ok\"}")}) }, + .{ .method = "GET", .path = "/v1/models", .replies = try a.dupe([]const fake.Write, &.{try fake.jsonReply(a, "200 OK", "{\"data\": [{\"id\": \"Lightning\"}]}")}) }, + }); + w.f = try fake.Fake.startKeyed(std.testing.allocator, routes, w.keyfile); // wants the key the child was given + const serving = try std.fmt.allocPrint(a, "printf '[tensorfold] serving %s at http://127.0.0.1:{d}/v1 (x)\\n' \"$name\"\n", .{w.f.port}); + const then = switch (how) { + .serves => try std.mem.concat(a, u8, &.{ serving, "exec sleep 30\n" }), + .serves_then_dies => try std.mem.concat(a, u8, &.{ serving, "sleep 2\nprintf 'error: the GPU ran out of memory\\n'\nexit 1\n" }), + .exits => "printf 'loading\\nerror: cannot read tokenizer.json\\n'\nexit 3\n", + .hangs => "exec sleep 30\n", + }; + const script = try std.fmt.allocPrint(a, "#!/bin/sh\necho $$ > '{s}'\nprintf '%s\\n' \"$@\" > '{s}'\nprintf '%s' \"$TENSORFOLD_API_KEY\" > '{s}'\n" ++ + "while [ $# -gt 0 ]; do if [ \"$1\" = --name ]; then name=$2; fi; shift; done\n{s}", .{ w.pidfile, w.argsfile, w.keyfile, then }); + const exe = try w.home.path(a, "tensorfold-stand-in"); + try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = exe, .data = script, .flags = .{ .permissions = .fromMode(0o755) } }); + _ = try w.home.checkpoint(a, "Org/Lightning", fixture.lightning); + w.ctx = w.home.context(); + w.ctx.exe = exe; + } + + fn deinit(w: *World) void { + w.f.stop(); + w.home.deinit(); + } + + /// The stand-in's pid, once it has written it. + fn pid(w: *const World, a: Allocator) !posix.pid_t { + try fixture.appears(w.pidfile); + var waited: u32 = 0; + while (waited < 10_000) : (waited += 20) { + const text = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, w.pidfile, a, .limited(64)); + if (std.mem.indexOfScalar(u8, text, '\n') != null) return std.fmt.parseInt(posix.pid_t, std.mem.trim(u8, text, " \n"), 10); + std.testing.io.sleep(.fromMilliseconds(20), .awake) catch {}; + } + return error.TestTimedOut; + } +}; + +extern "c" fn getpgid(pid: posix.pid_t) posix.pid_t; + +fn gone(pid: posix.pid_t) bool { + posix.kill(pid, @fromBackingInt(0)) catch |e| return e == error.ProcessNotFound; + return false; +} + +test "mcp serve: a cached model served on loopback with its own key, listed by status and stopped by stop" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var w: World = undefined; + try w.init(a, .serves); + defer w.deinit(); + var live: fixture.Live = undefined; + live.setUp(&w.ctx); + defer live.tearDown(); + try live.send(initialize); + try live.send("{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",\"params\":{\"name\":\"serve\",\"arguments\":{\"model\":\"Org/Lightning\",\"context\":4096},\"_meta\":{\"progressToken\":7}}}\n"); + const served = try live.answer(a, 2); + try std.testing.expect(!fixture.isError(served)); + const s = structured(served); + const base = try std.fmt.allocPrint(a, "http://127.0.0.1:{d}/v1", .{w.f.port}); + try std.testing.expectEqualStrings(base, s.strField("base_url").?); + try std.testing.expectEqualStrings("Lightning", s.strField("name").?); + try std.testing.expectEqualStrings("1", s.strField("id").?); + const key = s.strField("api_key").?; + try std.testing.expectEqual(@as(usize, 64), key.len); + for (key) |ch| try std.testing.expect(std.ascii.isDigit(ch) or (ch >= 'a' and ch <= 'f')); + try std.testing.expect(fixture.has(fixture.text(served), key) and fixture.has(fixture.text(served), base)); + try std.testing.expectEqualStrings(key, try std.Io.Dir.cwd().readFileAlloc(std.testing.io, w.keyfile, a, .limited(256))); + const args = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, w.argsfile, a, .limited(64 << 10)); + try std.testing.expect(fixture.has(args, "serve\n")); + try std.testing.expect(fixture.has(args, "/hub/models--Org--Lightning/snapshots/" ++ fixture.sha ++ "\n--host\n127.0.0.1\n--port\n0\n--name\nLightning\n--no-update-check\n--context\n4096\n")); + var probed = false; // the readiness probe asked the models route with the child's own key + for (0..w.f.count()) |i| if (std.mem.eql(u8, w.f.request(i).path, "/v1/models")) { + try std.testing.expectEqualStrings(try std.fmt.allocPrint(a, "Bearer {s}", .{key}), w.f.header(i, "authorization").?); + probed = true; + }; + try std.testing.expect(probed and w.f.refusals() == 0); + const note = (try live.written(a))[1]; // the progress the token asked for, before the answer + try std.testing.expectEqualStrings("notifications/progress", note.strField("method").?); + try std.testing.expectEqual(@as(?i64, 7), note.get("params").?.get("progressToken").?.int64()); + const pid = try w.pid(a); + try std.testing.expectEqual(pid, getpgid(pid)); // a process group of its own: a terminal's Ctrl-C reaches only the session + + try live.send(try call(a, 3, "serve", "{\"model\":\"Org/Lightning\",\"context\":4096}")); + const again = structured(try live.answer(a, 3)); + try std.testing.expect(again.get("already_running").?.bool); + try std.testing.expectEqualStrings(key, again.strField("api_key").?); + try live.send(try call(a, 4, "status", "{}")); + const listed = structured(try live.answer(a, 4)).get("servers").?.array; + try std.testing.expectEqual(@as(usize, 1), listed.len); + try std.testing.expect(listed[0].get("running").?.bool); + try std.testing.expectEqualStrings(base, listed[0].strField("base_url").?); + try std.testing.expect(listed[0].get("api_key") == null); // status names no key + + try live.send(try call(a, 5, "stop", "{\"id\":\"1\"}")); + const stopped = try live.answer(a, 5); + try std.testing.expectEqualStrings("stopped", structured(stopped).strField("state").?); + try std.testing.expect(gone(pid)); + try live.send(try call(a, 6, "status", "{}")); + try std.testing.expect(!structured(try live.answer(a, 6)).get("servers").?.array[0].get("running").?.bool); + try live.send(try call(a, 7, "stop", "{\"id\":\"1\"}")); + try std.testing.expect(fixture.has(fixture.text(try live.answer(a, 7)), "was already stopped")); +} + +test "mcp serve: the session's end, as stdin's end brings it, stops every server it started" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var w: World = undefined; + try w.init(a, .serves); + defer w.deinit(); + var live: fixture.Live = undefined; + live.setUp(&w.ctx); + var ended = false; + defer if (!ended) live.tearDown(); + try live.send(initialize); + try live.send(try call(a, 2, "serve", "{\"model\":\"Org/Lightning\"}")); + try std.testing.expect(!fixture.isError(try live.answer(a, 2))); + const pid = try w.pid(a); + try std.testing.expect(!gone(pid)); + ended = true; + live.tearDown(); + try std.testing.expect(gone(pid)); +} + +test "mcp serve: a server that exits on its own shows as exited in status, with its last log line" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var w: World = undefined; + try w.init(a, .serves_then_dies); + defer w.deinit(); + var live: fixture.Live = undefined; + live.setUp(&w.ctx); + defer live.tearDown(); + try live.send(initialize); + try live.send(try call(a, 2, "serve", "{\"model\":\"Org/Lightning\"}")); + try std.testing.expect(!fixture.isError(try live.answer(a, 2))); + var id: i64 = 3; + const exited = while (id < 503) : (id += 1) { // status reaps the child once it has exited + try live.send(try call(a, id, "status", "{}")); + const servers = structured(try live.answer(a, id)).get("servers").?.array; + if (std.mem.eql(u8, servers[0].strField("state").?, "exited")) break servers[0]; + std.testing.io.sleep(.fromMilliseconds(20), .awake) catch {}; + } else return error.TestTimedOut; + try std.testing.expect(!exited.get("running").?.bool); + try std.testing.expectEqualStrings("error: the GPU ran out of memory", exited.get("last_log").?.array[0].string); + try live.send(try call(a, 600, "stop", "{\"id\":\"1\"}")); + try std.testing.expect(fixture.has(fixture.text(try live.answer(a, 600)), "had already exited")); +} + +test "mcp serve: a child that exits while loading is a tool error with its last log line, and leaves no entry" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var w: World = undefined; + try w.init(a, .exits); + defer w.deinit(); + var live: fixture.Live = undefined; + live.setUp(&w.ctx); + defer live.tearDown(); + try live.send(initialize); + try live.send(try call(a, 2, "serve", "{\"model\":\"Org/Lightning\"}")); + const v = try live.answer(a, 2); + try std.testing.expect(fixture.isError(v)); + try std.testing.expect(fixture.has(fixture.text(v), "tensorfold serve exited while loading Org/Lightning; its last log lines: error: cannot read tokenizer.json")); + try live.send(try call(a, 3, "status", "{}")); + try std.testing.expectEqual(@as(usize, 0), structured(try live.answer(a, 3)).get("servers").?.array.len); +} + +test "mcp serve: a cancelled serve stops its loading child and answers nothing; stop ends a loading one too" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var w: World = undefined; + try w.init(a, .hangs); + defer w.deinit(); + var live: fixture.Live = undefined; + live.setUp(&w.ctx); + defer live.tearDown(); + try live.send(initialize); + try live.send(try call(a, 2, "serve", "{\"model\":\"Org/Lightning\"}")); + const first = try w.pid(a); + try live.send("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/cancelled\",\"params\":{\"requestId\":2,\"reason\":\"example\"}}\n"); + try live.idle(); + try std.testing.expect(gone(first)); + try std.testing.expect(fixture.find(try live.written(a), 2) == null); + + try std.Io.Dir.cwd().deleteFile(std.testing.io, w.pidfile); + try live.send(try call(a, 3, "serve", "{\"model\":\"Org/Lightning\"}")); + const second = try w.pid(a); + try live.send(try call(a, 4, "status", "{}")); + const loading = structured(try live.answer(a, 4)).get("servers").?.array; + try std.testing.expectEqualStrings("starting", loading[0].strField("state").?); + try std.testing.expect(loading[0].get("base_url").? == .null); + try live.send(try call(a, 5, "stop", try std.fmt.allocPrint(a, "{{\"id\":\"{s}\"}}", .{loading[0].strField("id").?}))); + try std.testing.expect(fixture.has(fixture.text(try live.answer(a, 5)), "was still loading")); + const ended = try live.answer(a, 3); + try std.testing.expect(fixture.isError(ended)); + try std.testing.expect(fixture.has(fixture.text(ended), "was stopped while it loaded")); + try std.testing.expect(gone(second)); +} + +test "mcp serve: models it cannot serve, paths it refuses and settings serve refuses are tool errors; nothing starts" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var w: World = undefined; + try w.init(a, .serves); + defer w.deinit(); + _ = try w.home.checkpoint(a, "Org/Draft", "{\"model_type\": \"gemma3n\"}"); + const cases = [_]struct { args: []const u8, says: []const u8 }{ + .{ .args = "{\"model\":\"Org/Missing\"}", .says = "not in the Hugging Face cache" }, + .{ .args = "{\"model\":\"Org/Draft\"}", .says = "no TensorFold family in this build serves model_type gemma3n" }, + .{ .args = "{\"model\":\"plain-name\"}", .says = "relative paths are refused" }, + .{ .args = "{\"model\":\"Org/..\"}", .says = "neither a Hugging Face repo id" }, + .{ .args = try std.fmt.allocPrint(a, "{{\"model\":\"{s}\"}}", .{w.home.dir}), .says = "is not a checkpoint directory" }, + .{ .args = "{\"model\":\"Org/Lightning\",\"drafter\":\"Org/Missing\"}", .says = "drafter: Org/Missing is not in the Hugging Face cache" }, + }; + var input: std.ArrayList(u8) = .empty; + try input.appendSlice(a, initialize); + for (cases, 2..) |c, id| try input.appendSlice(a, try call(a, @intCast(id), "serve", c.args)); + const got = try fixture.exchange(a, &w.ctx, input.items); + for (cases, 2..) |c, id| { + const v = fixture.find(got, @intCast(id)).?; + try std.testing.expect(fixture.isError(v)); + try std.testing.expect(fixture.has(fixture.text(v), c.says)); + } + try std.testing.expectError(error.FileNotFound, std.Io.Dir.cwd().access(std.testing.io, w.pidfile, .{})); +} diff --git a/zig/src/server/mcp_tests.zig b/zig/src/server/mcp_tests.zig new file mode 100644 index 00000000000..cc74f176498 --- /dev/null +++ b/zig/src/server/mcp_tests.zig @@ -0,0 +1,6 @@ +//! Test root for `tensorfold mcp`: the wire and lifecycle, the cache tools, and the serve children. +test { + _ = @import("mcp_rpc_test.zig"); + _ = @import("mcp_tools_test.zig"); + _ = @import("mcp_serve_test.zig"); +} diff --git a/zig/src/server/mcp_tools.zig b/zig/src/server/mcp_tools.zig new file mode 100644 index 00000000000..ef460f878b0 --- /dev/null +++ b/zig/src/server/mcp_tools.zig @@ -0,0 +1,227 @@ +//! The tools `tensorfold mcp` offers: names, schemas and hints, the argument checks, and each call's answer. +const std = @import("std"); +const builtin = @import("builtin"); +const json = @import("json"); +const rpc = @import("mcp_rpc.zig"); +const mcp = @import("mcp.zig"); +const cache = @import("mcp_cache.zig"); +const serve = @import("mcp_serve.zig"); +const host = @import("benchmark_host.zig"); +const server = @import("benchmark_server.zig"); +const Allocator = std.mem.Allocator; +const Value = json.Value; +const none: Value = .null; + +pub const Tool = enum { + machine, + models, + info, + pull, + serve, + stop, + status, + + /// pull and serve can take minutes, so each runs on its own thread while the session keeps reading. + pub fn long(t: Tool) bool { + return t == .pull or t == .serve; + } +}; + +/// How long a 2026-07-28 client may keep the tool list: it changes only with the binary. +pub const ttl_ms: u64 = 3_600_000; + +const Kind = enum { string, integer }; +const Param = struct { name: []const u8, kind: Kind = .string, required: bool = false, about: []const u8 }; +const Hints = struct { read_only: bool = false, destructive: bool = false, idempotent: bool = true, open_world: bool = false }; +const Spec = struct { tool: Tool, title: []const u8, about: []const u8, params: []const Param = &.{}, hints: Hints }; + +const model_about = "A cached Hugging Face repo id (owner/name), or the absolute path of an existing checkpoint directory"; + +/// The tools in the order tools/list gives them, which never varies. +const specs = [_]Spec{ + .{ .tool = .machine, .title = "Describe this machine", .about = "This machine: OS, CPU, memory and GPUs, and the TensorFold version, backend and model types that serve here.", .hints = .{ .read_only = true } }, + .{ .tool = .models, .title = "List cached models", .about = "The checkpoints in the local Hugging Face cache that a TensorFold family serves, with their revisions and sizes on disk.", .hints = .{ .read_only = true } }, + .{ .tool = .info, .title = "Describe a model", .about = "One checkpoint's family, format, context, weights and the memory it needs to start, as tensorfold info prints them.", .params = &.{.{ .name = "model", .required = true, .about = model_about }}, .hints = .{ .read_only = true } }, + .{ .tool = .pull, .title = "Download a model", .about = "Downloads a Hugging Face repo into the local cache as tensorfold pull does: checked against the Hub, resumable, and refused when no TensorFold family serves it. Reports progress when the request asks for it.", .params = &.{ + .{ .name = "repo", .required = true, .about = "The Hugging Face repo id, owner/name" }, + .{ .name = "revision", .about = "A branch, tag or 40-hex commit; main when left out" }, + }, .hints = .{ .open_world = true } }, + .{ .tool = .serve, .title = "Start a local server", .about = "Starts tensorfold serve for a cached model on a free 127.0.0.1 port with a fresh API key, waits until it answers, and returns its base URL, served name and key. Serving the same model and settings again returns the server already running.", .params = &.{ + .{ .name = "model", .required = true, .about = model_about }, + .{ .name = "context", .kind = .integer, .about = "The context length in tokens; the model family's default when left out" }, + .{ .name = "drafter", .about = "A drafter checkpoint for faster decoding, named as model is" }, + }, .hints = .{} }, + .{ .tool = .stop, .title = "Stop a local server", .about = "Stops a server this session started, by the id serve gave.", .params = &.{.{ .name = "id", .required = true, .about = "The server's id from serve or status" }}, .hints = .{ .destructive = true } }, + .{ .tool = .status, .title = "List local servers", .about = "The servers this session started: id, model, served name, base URL and whether each still runs.", .hints = .{ .read_only = true } }, +}; + +fn specOf(t: Tool) Spec { + for (specs) |s| if (s.tool == t) return s; + unreachable; +} + +/// tools/list's result: every tool with its input schema and hints, cacheable for an hour under 2026-07-28. +pub fn list(a: Allocator, v: rpc.Version) !*json.Object { + const items = try a.alloc(Value, specs.len); + for (specs, items) |s, *item| item.* = try describe(a, s); + const body = try json.newObject(a); + try body.put(a, "tools", .{ .array = items }); + if (v.stateless()) { + try body.put(a, "ttlMs", try json.intValue(a, ttl_ms)); + try body.put(a, "cacheScope", .{ .string = "public" }); + } + return body; +} + +fn describe(a: Allocator, s: Spec) !Value { + const props = try json.newObject(a); + var required: std.ArrayList(Value) = .empty; + for (s.params) |p| { + const prop = try json.newObject(a); + try prop.put(a, "type", .{ .string = @tagName(p.kind) }); + if (p.kind == .integer) try prop.put(a, "minimum", try json.intValue(a, 1)); + try prop.put(a, "description", .{ .string = p.about }); + try props.put(a, p.name, .{ .object = prop }); + if (p.required) try required.append(a, .{ .string = p.name }); + } + const schema = try json.newObject(a); + try schema.put(a, "type", .{ .string = "object" }); + try schema.put(a, "properties", .{ .object = props }); + if (required.items.len > 0) try schema.put(a, "required", .{ .array = required.items }); + try schema.put(a, "additionalProperties", .{ .bool = false }); + const hints = try json.newObject(a); + try hints.put(a, "title", .{ .string = s.title }); + try hints.put(a, "readOnlyHint", .{ .bool = s.hints.read_only }); + try hints.put(a, "destructiveHint", .{ .bool = s.hints.destructive }); + try hints.put(a, "idempotentHint", .{ .bool = s.hints.idempotent }); + try hints.put(a, "openWorldHint", .{ .bool = s.hints.open_world }); + const o = try json.newObject(a); + try o.put(a, "name", .{ .string = @tagName(s.tool) }); + try o.put(a, "title", .{ .string = s.title }); + try o.put(a, "description", .{ .string = s.about }); + try o.put(a, "inputSchema", .{ .object = schema }); + try o.put(a, "annotations", .{ .object = hints }); + return .{ .object = o }; +} + +/// A call checked against its tool's schema, then run; an argument problem is a tool error the model can correct. +pub fn call(c: *mcp.Call) !*json.Object { + if (try check(c.a, specOf(c.tool), c.args)) |why| return failed(c.a, "{s}", .{why}); + const args = c.args; + return switch (c.tool) { + .machine => machine(c), + .models => cache.models(c), + .info => cache.info(c, args.strField("model").?), + .pull => cache.pull(c, args.strField("repo").?, args.strField("revision")), + .serve => serve.start(c, .{ .model = args.strField("model").?, .context = if (args.get("context")) |n| n.int64() else null, .drafter = args.strField("drafter") }), + .stop => serve.stop(c, args.strField("id").?), + .status => serve.status(c), + }; +} + +/// The first way ``args`` breaks the tool's schema: an unknown or empty argument, a wrong type, a missing one. +fn check(a: Allocator, s: Spec, args: Value) !?[]const u8 { + const tool = @tagName(s.tool); + if (args == .object) for (args.object.keys(), args.object.values()) |key, v| { + const p = for (s.params) |p| { + if (std.mem.eql(u8, p.name, key)) break p; + } else return try std.fmt.allocPrint(a, "{s} takes no argument named {s}{s}", .{ tool, key, try takes(a, s) }); + if (v == .null and !p.required) continue; // an optional argument sent as null is left out + switch (p.kind) { + .string => if (v != .string or v.string.len == 0) return try std.fmt.allocPrint(a, "{s}: {s} must be a non-empty string", .{ tool, key }), + .integer => if ((v.int64() orelse 0) < 1 or (v.int64() orelse 0) > std.math.maxInt(u32)) + return try std.fmt.allocPrint(a, "{s}: {s} must be a whole number from 1 to {d}", .{ tool, key, std.math.maxInt(u32) }), + } + }; + for (s.params) |p| if (p.required and (args.get(p.name) orelse none) == .null) + return try std.fmt.allocPrint(a, "{s} needs {s}: {s}", .{ tool, p.name, p.about }); + return null; +} + +fn takes(a: Allocator, s: Spec) ![]const u8 { + if (s.params.len == 0) return "; it takes no arguments"; + var names: std.ArrayList(u8) = .empty; + for (s.params, 0..) |p, i| try names.print(a, "{s}{s}", .{ if (i == 0) "" else ", ", p.name }); + return std.fmt.allocPrint(a, "; it takes {s}", .{names.items}); +} + +/// A tool's answer: ``text`` for the model, and the same facts as structured content. +pub fn answered(a: Allocator, text: []const u8, structured: *json.Object) !*json.Object { + const body = try json.newObject(a); + try body.put(a, "content", try textContent(a, text)); + try body.put(a, "structuredContent", .{ .object = structured }); + try body.put(a, "isError", .{ .bool = false }); + return body; +} + +/// A tool error: the reason as text with ``isError`` set, so the model sees it and can correct the call. +pub fn failed(a: Allocator, comptime fmt: []const u8, args: anytype) !*json.Object { + const body = try json.newObject(a); + try body.put(a, "content", try textContent(a, try std.fmt.allocPrint(a, fmt, args))); + try body.put(a, "isError", .{ .bool = true }); + return body; +} + +fn textContent(a: Allocator, text: []const u8) !Value { + const part = try json.newObject(a); + try part.put(a, "type", .{ .string = "text" }); + try part.put(a, "text", .{ .string = text }); + const items = try a.alloc(Value, 1); + items[0] = .{ .object = part }; + return .{ .array = items }; +} + +pub fn optString(s: ?[]const u8) Value { + return if (s) |x| .{ .string = x } else .null; +} + +pub fn optInt(a: Allocator, n: ?u64) !Value { + return if (n) |x| json.intValue(a, x) else .null; +} + +pub fn gib(bytes: u64) f64 { + return @as(f64, @floatFromInt(bytes)) / (1 << 30); +} + +/// The machine tool: the benchmark's allowlisted host facts (no hostname or serials), with this build's version. +fn machine(c: *mcp.Call) !*json.Object { + const a = c.a; + const ctx = c.ctx(); + const engines = ctx.engines(a); + const backend = server.buildBackend(); + const probe = host.detect(a, ctx.io, ctx.environ, backend); + const h = probe.hardware; + var text: std.Io.Writer.Allocating = .init(a); + const w = &text.writer; + try w.print("TensorFold {s} ({s} backend) on {t} {t}\n", .{ ctx.version, backend, builtin.os.tag, builtin.cpu.arch }); + try w.print("CPU: {s}\n", .{h.cpu_model orelse "unknown"}); + if (h.system_memory_bytes) |m| try w.print("memory: {d:.1} GiB ({s})\n", .{ gib(m), h.memory_type }) else try w.writeAll("memory: unknown\n"); + const gpus = try a.alloc(Value, h.gpus.len); + for (h.gpus, gpus) |g, *slot| { + try w.print("GPU: {s}", .{g.name}); + if (g.memory_bytes) |m| try w.print(", {d:.1} GiB", .{gib(m)}); + if (g.cores) |n| try w.print(", {d} cores", .{n}); + try w.writeAll("\n"); + const o = try json.newObject(a); + try o.put(a, "name", .{ .string = g.name }); + try o.put(a, "memory_bytes", try optInt(a, g.memory_bytes)); + try o.put(a, "cores", try optInt(a, g.cores)); + slot.* = .{ .object = o }; + } + if (h.gpus.len == 0) try w.writeAll("GPU: none found\n"); + const types = try a.alloc(Value, engines.families.len); + for (engines.families, types) |f, *slot| slot.* = .{ .string = f.model_type }; + try w.print("model types served: {d}\n", .{types.len}); + const o = try json.newObject(a); + try o.put(a, "os", .{ .string = @tagName(builtin.os.tag) }); + try o.put(a, "arch", .{ .string = @tagName(builtin.cpu.arch) }); + try o.put(a, "cpu", optString(h.cpu_model)); + try o.put(a, "memory_bytes", try optInt(a, h.system_memory_bytes)); + try o.put(a, "memory_type", .{ .string = h.memory_type }); + try o.put(a, "gpus", .{ .array = gpus }); + try o.put(a, "driver", optString(probe.driver)); + try o.put(a, "tensorfold_version", .{ .string = ctx.version }); + try o.put(a, "backend", .{ .string = backend }); + try o.put(a, "model_types", .{ .array = types }); + return answered(a, text.written(), o); +} diff --git a/zig/src/server/mcp_tools_test.zig b/zig/src/server/mcp_tools_test.zig new file mode 100644 index 00000000000..13595084ce3 --- /dev/null +++ b/zig/src/server/mcp_tools_test.zig @@ -0,0 +1,214 @@ +//! The machine, models, info and pull tools against a temporary cache and a fake hub on 127.0.0.1. +const std = @import("std"); +const json = @import("json"); +const fixture = @import("mcp_fixture.zig"); +const cache = @import("mcp_cache.zig"); +const fake = @import("benchmark_fake.zig"); +const Value = json.Value; +const Allocator = std.mem.Allocator; + +const initialize = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-11-25\",\"capabilities\":{}}}\n"; + +fn call(a: Allocator, id: i64, tool: []const u8, args: []const u8) ![]const u8 { + return std.fmt.allocPrint(a, "{{\"jsonrpc\":\"2.0\",\"id\":{d},\"method\":\"tools/call\",\"params\":{{\"name\":\"{s}\",\"arguments\":{s}}}}}\n", .{ id, tool, args }); +} + +fn structured(v: Value) Value { + return v.get("result").?.get("structuredContent").?; +} + +test "mcp repo ids: owner/name as the Hub allows them, with no room for a path" { + for ([_][]const u8{ "Org/Lightning", "mlx-community/Qwen3.5-2B-MLX-4bit", "a_b/c.d", "Org/x_" }) |id| try std.testing.expect(cache.repoId(id)); + for ([_][]const u8{ "Org/..", "../x", "./x", "Org/a..b", "Org/a--b", "-org/x", "org/x.", "a/b/c", "plain", "/abs/x", "Org/x@main", "" }) |id| + try std.testing.expect(!cache.repoId(id)); +} + +test "mcp machine: this host's allowlisted facts with the build's version and the model types it serves" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var home = try fixture.Home.init(a); + defer home.deinit(); + const ctx = home.context(); + const got = try fixture.exchange(a, &ctx, try std.mem.concat(a, u8, &.{ initialize, try call(a, 2, "machine", "{}") })); + const v = fixture.find(got, 2).?; + try std.testing.expect(!fixture.isError(v)); + try std.testing.expect(fixture.has(fixture.text(v), "TensorFold " ++ fixture.version)); + const facts = structured(v); + try std.testing.expectEqualStrings(@tagName(@import("builtin").os.tag), facts.strField("os").?); + try std.testing.expectEqualStrings(fixture.version, facts.strField("tensorfold_version").?); + try std.testing.expectEqualStrings("nemotron_h", facts.get("model_types").?.array[0].string); + try std.testing.expect(facts.get("gpus").? == .array and facts.strField("memory_type") != null); + try std.testing.expect(facts.get("memory_bytes").? == .int or facts.get("memory_bytes").? == .null); +} + +test "mcp models and info: the cached checkpoints a family serves, and one checkpoint's facts" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var home = try fixture.Home.init(a); + defer home.deinit(); + const ctx = home.context(); + const empty = try fixture.exchange(a, &ctx, try std.mem.concat(a, u8, &.{ initialize, try call(a, 2, "models", "{}") })); + try std.testing.expect(fixture.has(fixture.text(fixture.find(empty, 2).?), "download one with the pull tool")); + const snapshot = try home.checkpoint(a, "Org/Lightning", fixture.lightning); + _ = try home.checkpoint(a, "Org/Draft", "{\"model_type\": \"gemma3n\"}"); + const outside = try home.path(a, "not-a-checkpoint"); + try std.Io.Dir.cwd().createDirPath(std.testing.io, outside); + const input = try std.mem.concat(a, u8, &.{ + initialize, + try call(a, 2, "models", "{}"), + try call(a, 3, "info", "{\"model\":\"Org/Lightning\"}"), + try call(a, 4, "info", try std.fmt.allocPrint(a, "{{\"model\":\"{s}\"}}", .{snapshot})), + try call(a, 5, "info", "{\"model\":\"Org/Draft\"}"), + try call(a, 6, "info", "{\"model\":\"Org/Missing\"}"), + try call(a, 7, "info", "{\"model\":\"Org/..\"}"), + try call(a, 8, "info", "{\"model\":\"relative-dir\"}"), + try call(a, 9, "info", try std.fmt.allocPrint(a, "{{\"model\":\"{s}\"}}", .{outside})), + try call(a, 10, "info", try std.fmt.allocPrint(a, "{{\"model\":\"{s}/../not-a-checkpoint\"}}", .{home.dir})), + }); + const got = try fixture.exchange(a, &ctx, input); + const listed = structured(fixture.find(got, 2).?).get("models").?.array; + try std.testing.expectEqual(@as(usize, 1), listed.len); + try std.testing.expectEqualStrings("Org/Lightning", listed[0].strField("repo").?); + try std.testing.expectEqualStrings("Nemotron 3.5 Lightning", listed[0].strField("family").?); + try std.testing.expectEqualStrings("nemotron_h", listed[0].strField("model_type").?); + try std.testing.expectEqualStrings(fixture.sha, listed[0].strField("revision").?); + try std.testing.expectEqual(@as(?i64, 4096 + fixture.lightning.len), listed[0].get("size_bytes").?.int64()); + try std.testing.expect(fixture.has(fixture.text(fixture.find(got, 2).?), "Org/Lightning: Nemotron 3.5 Lightning (nemotron_h)")); + for ([_]i64{ 3, 4 }) |id| { + const v = fixture.find(got, id).?; + try std.testing.expect(!fixture.isError(v)); + try std.testing.expect(fixture.has(fixture.text(v), "family: Nemotron 3.5 Lightning (nemotron_h)\nformat: 4-bit, group 64\ncontext: 8192\n")); + const facts = structured(v); + try std.testing.expectEqual(@as(?i64, 4), facts.get("quantization").?.get("bits").?.int64()); + try std.testing.expectEqual(@as(?i64, 64), facts.get("quantization").?.get("group_size").?.int64()); + try std.testing.expect(facts.get("modelopt_formats").? == .null); + try std.testing.expect(std.mem.indexOf(u8, fixture.text(v), "snapshots") == null); // the answer names the model, not its path + try std.testing.expectEqual(@as(?i64, 8192), facts.get("context").?.int64()); + try std.testing.expectEqual(@as(?i64, 4096 + fixture.lightning.len), facts.get("weights_bytes").?.int64()); + try std.testing.expect(facts.get("memory_floor_bytes").?.int64().? > facts.get("weights_bytes").?.int64().?); + } + const refused = [_]struct { id: i64, says: []const u8 }{ + .{ .id = 5, .says = "Org/Draft: no registered Zig family serves model_type gemma3n" }, // named as asked, not by its path + .{ .id = 6, .says = "Org/Missing is not in the Hugging Face cache; download it with the pull tool first" }, + .{ .id = 7, .says = "neither a Hugging Face repo id" }, + .{ .id = 8, .says = "relative paths are refused" }, + .{ .id = 9, .says = "is not a checkpoint directory" }, + .{ .id = 10, .says = "a path with .. is refused" }, + }; + for (refused) |r| { + const v = fixture.find(got, r.id).?; + try std.testing.expect(fixture.isError(v)); + try std.testing.expect(fixture.has(fixture.text(v), r.says)); + } +} + +/// A fake hub serving Org/Lightning (a family this build serves) and Org/Draft (one it does not). +fn hub(a: Allocator, gate: ?*std.Io.Event) !*fake.Fake { + const weights: [300]u8 = @splat('w'); + const tree = try std.fmt.allocPrint(a, "[{{\"type\": \"file\", \"path\": \"config.json\", \"size\": {d}}}, {{\"type\": \"file\", \"path\": \"model.safetensors\", \"size\": {d}}}]", .{ fixture.lightning.len, weights.len }); + const draft = "{\"model_type\": \"gemma3n\"}"; + const draft_tree = try std.fmt.allocPrint(a, "[{{\"type\": \"file\", \"path\": \"config.json\", \"size\": {d}}}]", .{draft.len}); + const revision = "{\"sha\": \"" ++ fixture.sha ++ "\"}"; + const slow: []const fake.Write = if (gate) |g| try a.dupe(fake.Write, &.{ + .{ .bytes = try std.fmt.allocPrint(a, "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {d}\r\nConnection: close\r\n\r\n", .{revision.len}), .after = g }, + .{ .bytes = revision }, + }) else try fake.jsonReply(a, "200 OK", revision); + const routes = try a.dupe(fake.Route, &.{ + .{ .method = "GET", .path = "/api/models/Org/Lightning/revision/main", .replies = try a.dupe([]const fake.Write, &.{slow}) }, + .{ .method = "GET", .path = "/api/models/Org/Lightning/tree/" ++ fixture.sha ++ "?recursive=true", .replies = try a.dupe([]const fake.Write, &.{try fake.jsonReply(a, "200 OK", tree)}) }, + .{ .method = "GET", .path = "/Org/Lightning/resolve/" ++ fixture.sha ++ "/config.json", .replies = try a.dupe([]const fake.Write, &.{try fake.jsonReply(a, "200 OK", fixture.lightning)}) }, + .{ .method = "GET", .path = "/Org/Lightning/resolve/" ++ fixture.sha ++ "/model.safetensors", .replies = try a.dupe([]const fake.Write, &.{try fake.jsonReply(a, "200 OK", &weights)}) }, + .{ .method = "GET", .path = "/api/models/Org/Draft/revision/main", .replies = try a.dupe([]const fake.Write, &.{try fake.jsonReply(a, "200 OK", revision)}) }, + .{ .method = "GET", .path = "/api/models/Org/Draft/tree/" ++ fixture.sha ++ "?recursive=true", .replies = try a.dupe([]const fake.Write, &.{try fake.jsonReply(a, "200 OK", draft_tree)}) }, + .{ .method = "GET", .path = "/Org/Draft/resolve/" ++ fixture.sha ++ "/config.json", .replies = try a.dupe([]const fake.Write, &.{try fake.jsonReply(a, "200 OK", draft)}) }, + }); + return fake.Fake.start(std.testing.allocator, routes); +} + +test "mcp pull: tensorfold pull's download, its lines as progress notifications when asked, and its refusals" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var home = try fixture.Home.init(a); + defer home.deinit(); + const f = try hub(a, null); + defer f.stop(); + try home.env.put("HF_ENDPOINT", try f.url(a, "")); + const ctx = home.context(); + var live: fixture.Live = undefined; + live.setUp(&ctx); + defer live.tearDown(); + try live.send(initialize); + try live.send("{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",\"params\":{\"name\":\"pull\",\"arguments\":{\"repo\":\"Org/Lightning\"},\"_meta\":{\"progressToken\":\"p-2\"}}}\n"); + _ = try live.answer(a, 2); + for ([_][]const u8{ "{\"repo\":\"Org/Lightning\",\"revision\":\"main\"}", "{\"repo\":\"Org/Draft\"}", "{\"repo\":\"Org/Lightning@main\"}", "{\"repo\":\"../etc/x\"}", "{\"repo\":\"Org/Lightning\",\"revision\":\"../main\"}", "{\"repo\":\"Org/Missing\"}" }, 3..) |args, id| { + try live.send(try call(a, @intCast(id), "pull", args)); // one at a time: two pulls of one repo never overlap here + _ = try live.answer(a, @intCast(id)); + } + const got = try live.written(a); + var notes: std.ArrayList(Value) = .empty; + var answered_at: ?usize = null; + for (got, 0..) |v, i| { + if (v.get("method")) |m| { + try std.testing.expectEqualStrings("notifications/progress", m.string); + try std.testing.expectEqualStrings("p-2", v.get("params").?.strField("progressToken").?); + try notes.append(a, v); + } else if (v.get("id").?.int64() == 2) answered_at = i; + } + try std.testing.expect(notes.items.len >= 3); + for (notes.items, 1..) |n, i| try std.testing.expectEqual(@as(?i64, @intCast(i)), n.get("params").?.get("progress").?.int64()); + try std.testing.expect(fixture.has(notes.items[0].get("params").?.strField("message").?, "downloading Org/Lightning@main")); + try std.testing.expect(answered_at.? > 0 and got[answered_at.? - 1].get("method") != null); // the notes come first + const pulled = fixture.find(got, 2).?; + try std.testing.expect(!fixture.isError(pulled)); + try std.testing.expectEqualStrings(fixture.sha, structured(pulled).strField("revision").?); + try std.testing.expectEqualStrings("Nemotron 3.5 Lightning", structured(pulled).strField("family").?); + const config = try home.path(a, "hub/models--Org--Lightning/snapshots/" ++ fixture.sha ++ "/config.json"); + try std.testing.expectEqualStrings(fixture.lightning, try std.Io.Dir.cwd().readFileAlloc(std.testing.io, config, a, .limited(1 << 20))); + const again = fixture.find(got, 3).?; // no progress token: the answer only + try std.testing.expect(!fixture.isError(again)); + try std.testing.expect(fixture.has(fixture.text(again), "Pulled Org/Lightning at revision " ++ fixture.sha)); + const refused = [_]struct { id: i64, says: []const u8 }{ + .{ .id = 4, .says = "model_type gemma3n" }, + .{ .id = 5, .says = "is not a Hugging Face repo id (owner/name)" }, + .{ .id = 6, .says = "is not a Hugging Face repo id (owner/name)" }, + .{ .id = 7, .says = "not a revision Hugging Face names" }, + .{ .id = 8, .says = "pull Org/Missing failed: the hub answered with an error or no files" }, + }; + for (refused) |r| { + const v = fixture.find(got, r.id).?; + try std.testing.expect(fixture.isError(v)); + try std.testing.expect(fixture.has(fixture.text(v), r.says)); + } + for (0..f.count()) |i| try std.testing.expect(std.mem.indexOf(u8, f.request(i).path, "..") == null and std.mem.indexOfScalar(u8, f.request(i).path, '@') == null); +} + +test "mcp pull: a second pull of a repo already downloading is refused while the first goes on" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var home = try fixture.Home.init(a); + defer home.deinit(); + var gate: std.Io.Event = .unset; + const f = try hub(a, &gate); + defer f.stop(); + try home.env.put("HF_ENDPOINT", try f.url(a, "")); + const ctx = home.context(); + var live: fixture.Live = undefined; + live.setUp(&ctx); + defer live.tearDown(); + defer gate.set(std.testing.io); // before the session's end, which waits for the first pull + try live.send(initialize); + try live.send(try call(a, 2, "pull", "{\"repo\":\"Org/Lightning\"}")); + var waited: u32 = 0; + while (f.count() == 0 and waited < 10_000) : (waited += 10) fake.nap(10); // the first pull is at the hub + try live.send(try call(a, 3, "pull", "{\"repo\":\"org/lightning\"}")); + const second = try live.answer(a, 3); + try std.testing.expect(fixture.isError(second)); + try std.testing.expect(fixture.has(fixture.text(second), "already being pulled by this session")); + try std.testing.expect(fixture.find(try live.written(a), 2) == null); + gate.set(std.testing.io); + try std.testing.expect(!fixture.isError(try live.answer(a, 2))); +} From 8b06491473e4ad7f194b3e0d583d822be0d98d1d Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 22 Nov 2026 07:13:31 +0000 Subject: [PATCH 3/3] router, mcp: a serve child does not inherit the request journal, whose lock one server holds --- zig/src/server/mcp_serve.zig | 2 +- zig/src/server/router/pool.zig | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/zig/src/server/mcp_serve.zig b/zig/src/server/mcp_serve.zig index a59a1d6cc44..4080e7aba0d 100644 --- a/zig/src/server/mcp_serve.zig +++ b/zig/src/server/mcp_serve.zig @@ -212,7 +212,7 @@ pub fn start(c: *mcp.Call, w: Wanted) !*json.Object { else => |x| return x, }; // the parent's variables a serve reads, less its own key and the benchmark's upload token, as the router has them - const env = try server.environWithout(a, ctx.environ, &.{ "TENSORFOLD_API_KEY", "TENSORFOLD_BENCHMARK_TOKEN" }); + const env = try server.environWithout(a, ctx.environ, &.{ "TENSORFOLD_API_KEY", "TENSORFOLD_REQUEST_JOURNAL", "TENSORFOLD_BENCHMARK_TOKEN" }); const logs = try std.fs.path.join(a, &.{ ctx.home, ".tensorfold", "mcp" }); _ = std.Io.Dir.cwd().createDirPathStatus(ctx.io, logs, .fromMode(0o700)) catch {}; var failure: server.Failure = .none; diff --git a/zig/src/server/router/pool.zig b/zig/src/server/router/pool.zig index f297a4a9299..7c5204efc82 100644 --- a/zig/src/server/router/pool.zig +++ b/zig/src/server/router/pool.zig @@ -258,7 +258,7 @@ pub const Pool = struct { fn spawn(p: *Pool, sa: Allocator, e: catalog.Entry, key: *const [64]u8, failure: *benchmark_server.Failure, tail: *[]const []const u8) ?Managed { failure.* = .setup; // the parent's variables a serve would read, less the router's own keys; spawn adds the child's key - const env = benchmark_server.environWithout(sa, p.env, &.{ "TENSORFOLD_API_KEY", "TENSORFOLD_BENCHMARK_TOKEN" }) catch return null; + const env = benchmark_server.environWithout(sa, p.env, &.{ "TENSORFOLD_API_KEY", "TENSORFOLD_REQUEST_JOURNAL", "TENSORFOLD_BENCHMARK_TOKEN" }) catch return null; _ = std.Io.Dir.cwd().createDirPathStatus(p.io, p.options.log_dir, .fromMode(0o700)) catch {}; var problem: []const u8 = ""; return Managed.spawn(sa, p.io, p.env, e.argv, .{