diff --git a/CHANGELOG.md b/CHANGELOG.md index aae7458ef6f..047026a5fa3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,16 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Qwen3.5 on CUDA: `qwen3_5` and `qwen3_5_moe` declare warm turns, so the server prefills a follow-up's prompt in the background and the next turn resumes past the previous reply, with replies unchanged (#2824). Thanks to @devopsfortunato. + +- Server: tool-call markup quoted in Markdown inline code spans and fenced code blocks stays prose, in whole replies and in streaming, instead of opening, hiding or running as a live tool call (#3588). Thanks to @gilby. + +- Lanes: shared draft pricing prices a chain-cut, unmeasured tail by the rule's rates instead of as a measured zero, and the cache's cut marker survives allocation errors (#2979). Thanks to @devopsfortunato. + +- Docs: the Nemotron 3.5 Lightning recipe gains a "Native HIP on a Strix Halo iGPU" section with its configuration, memory footprint, throughput, prefill and exactness checks, and the intro lists HIP beside Metal and CUDA (#3560). Thanks to @gilby. + +- Qwen3.5-2B on Metal: the engine declares `warm_turns` from its prompt cache, so a follow-up that re-renders earlier rows resumes the reply instead of prefilling the whole conversation again (#3457). Thanks to @EugeneClaw. + - Kolibri-1: the tree-attention cache offsets are signed, so a server with default flags no longer panics with an integer overflow on its first request when a cache sits below the origin (#3561). Thanks to @jschmied. - H3 on Metal: `Model.load` reads every transformer shard ahead of its mappings and fails the load on a missing or short shard; `TF_LOAD_PREFETCH` sets the reader count and `0` turns read-ahead off (#2999). Thanks to @plotarmordev. diff --git a/docs/recipes/nemotron-3.5.md b/docs/recipes/nemotron-3.5.md index 6c104380a39..4398789ba46 100644 --- a/docs/recipes/nemotron-3.5.md +++ b/docs/recipes/nemotron-3.5.md @@ -1,7 +1,7 @@ # Nemotron 3.5 Lightning -The model combines Mamba-2, attention and MoE blocks. The native family is `zig/src/families/nemotron/`, on Metal -and CUDA; the native prompt reuse, routed experts and shared rounds sections below describe it, and the +The model combines Mamba-2, attention and MoE blocks. The native family is `zig/src/families/nemotron/`, on Metal, +CUDA and HIP; the native prompt reuse, routed experts, shared rounds and HIP sections below describe it, and the [README](../../README.md#qualified-models) lists its qualified checkpoints and hardware. The MLX execution, CUDA, draft vocabulary and measurements sections describe the Python engine, @@ -21,7 +21,7 @@ The checkpoint includes `mtp-4bit.safetensors`; `pull` and `serve` check that it `--no-drafts` or request field `"draft": false` selects serial decoding. In the Python engine, MLX supports affine 4-bit projections and experts in groups of 32 or 64; unsupported formats are refused before weight downloads and checked again at load. CUDA supports the named 4-bit/group-64 checkpoint. The native engine serves the named -checkpoint on Metal and CUDA, and NVIDIA's NVFP4 export on CUDA. +checkpoint on Metal, CUDA and HIP, and NVIDIA's NVFP4 export on CUDA. On Metal the native engine also serves MLX checkpoints at a width per module (2, 3, 4, 5, 6 or 8 bits, not 7, in groups of 32, 64 or 128), such as `TensorFold/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-oQ4`, `-oQ6` and `-oQ8`, the three @@ -31,8 +31,8 @@ width-general gathers; dense matrices in other groups stay on the row kernels. T `mtp-4bit.safetensors` from the 4-bit checkpoint into the folder to draft; without it each round decodes one token. With the head on an M3 Ultra, greedy prose decodes at 162 tok/s with oQ4, 117 with oQ6 and 111 with oQ8, against 188 with the 4-bit checkpoint, and prompts of 8,192 to 32,768 tokens read at 0.96x to 0.99x mlx_lm's rate on the same checkpoint; a -server's first 2,048-token prompt after it starts reads at 0.78x to 0.90x. For MLX affine checkpoints, CUDA, the Intel -GPU engine and `--slide` refuse widths other than 4-bit group 64 and name the first such module. +server's first 2,048-token prompt after it starts reads at 0.78x to 0.90x. For MLX affine checkpoints, CUDA, HIP, the +Intel GPU engine and `--slide` refuse widths other than 4-bit group 64 and name the first such module. ## MLX execution and exactness @@ -92,8 +92,8 @@ for checkpoint requirements, request parts, limits and qualification status. This section describes the Python 0.6.6 engine's list, [`src/tensorfold/families/nemotron_h/draft_ids.txt`](https://github.com/ashhart/TensorFold/blob/v0.6.6/src/tensorfold/families/nemotron_h/draft_ids.txt). -The native engine embeds its own 49,152-ID list, `zig/src/families/nemotron/draft_ids.txt`, on Metal and CUDA; the -rebuild below does not produce it. +The native engine embeds its own 49,152-ID list, `zig/src/families/nemotron/draft_ids.txt`, on Metal, CUDA and HIP; +the rebuild below does not produce it. The shipped `draft_ids.txt` contains 32,768 sorted IDs. It can be rebuilt byte for byte from CPython 3.14.5's standard-library Python files, excluding `site-packages`, plus tracked Python and Markdown @@ -233,3 +233,33 @@ with 4,096 reply tokens takes 13 pages (45.5 MiB) instead of a whole window. A r until a stream ends. The attention kernels read the pages through a table at a fixed device address, so the graphs keep their addresses. The startup line shows the pool. `TF_KV_PAGES=0` gives every stream a window again; `TF_KV_PAGES=all` puts every stream on pages (for checks). + +## Native HIP on a Strix Halo iGPU + +The native HIP build serves `TensorFold/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-MLX-4bit` (`d9d758fb`, MLX affine 4-bit +in groups of 64 with `mtp-4bit.safetensors`) on gfx1151 (AMD Ryzen AI MAX+ 395, Radeon 8060S, 128 GB unified +LPDDR5X-8000, 512 MiB carve-out + 115 GiB GTT). At `--context 131072 --parallel 4 --prompt-cache-gib 0`, it plans +17.34 GiB of model weights plus 1.15 GiB per stream (24.42 GiB GTT in use after load), runs 4-row verify windows with +up to 3 MTP drafts sized by measured costs, prefills prompts in 2,048-row chunks (`prefill_step=4096` default +clamped to the family's chunk width), and replays captured round graphs on lone-stream rounds. `--mtp-drafts` caps +the draft count at up to 3. `--mtp-confidence` and mixed-width oQ checkpoints are refused by name on main. + +```bash +zig build native-hip -Dhip=true -Dhip-arch=gfx1151 -Dhipcc=/usr/bin/hipcc -Doptimize=ReleaseFast +TENSORFOLD_MEMORY_RESERVE_GIB=4 ./zig-out/native-hip/bin/tensorfold-native serve \ + ./NVIDIA-Nemotron-3.5-Lightning-30B-A3B-MLX-4bit --context 131072 --parallel 4 --prompt-cache-gib 0 +``` + +Measured on TensorFold `6c5cef894` (HIP 7.1, clang 21, Zig 0.17.0, power mode `performance`, fresh servers with the page +cache dropped before each run; `tools/bench_openai.py --tokens 256 --reps 3`, +`tools/bench_concurrent.py --levels 1,2,4 --reps 3 --alone --serial --temperatures 1.0,0 --prompts tools/bench_prompts.json`, +and `tools/bench_cache.py --require-cold --tokens 16 --repeats 1` over raw Nemotron-tokenized prompts; two full +servers plus one `--no-drafts` server): + +| Workload | Metric | T=1.0 | T=0 | Notes | +|---|---|---|---|---| +| `bench_openai` code (drafts on) | median tok/s | 117.1 / 117.1 | 122.7 / 124.6 | 2.78 / 2.84 (`T=1.0`) and 2.84 / 2.56 (`T=0`) tokens/round | +| `bench_openai` chat (drafts on) | median tok/s | 92.4 / 91.8 | 99.0 / 98.5 | 1.68 (`T=1.0`) and 1.84 (`T=0`) tokens/round | +| `bench_openai` code / chat (`--no-drafts`) | median tok/s | 86.2 / 86.1 | 87.9 / 87.9 | 1.00 token/round (1.828 GB read/token, ~160.7 GB/s greedy) | +| `bench_concurrent` 1 / 2 / 4 streams | aggregate tok/s | 124.4 / 136.0-137.0 / 168.4-168.9 | 131.5-132.4 / 146.5 / 175.5-176.4 | 84/84 concurrent=alone; 48/48 alone=`"draft": false` | +| `bench_cache` 2,048 / 7,099 / 28,333 tokens | cold TTFT (s) | — | 0.731-0.732 / 2.672-2.676 / 13.130-13.205 | 2,797-2,800 / 2,653-2,657 / 2,146-2,158 tok/s (repeated cold) | diff --git a/zig/build/cuda_family_host.zig b/zig/build/cuda_family_host.zig index f8e304e1b19..b819922aed6 100644 --- a/zig/build/cuda_family_host.zig +++ b/zig/build/cuda_family_host.zig @@ -23,6 +23,9 @@ pub fn steps(b: *std.Build, cuda: *std.Build.Module, mods: anytype, step: *std.B const prefill = b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{ "Qwen stepped prefill:", "Qwen whole prefill:", "Qwen prefill opening:", "a yielded pass keeps its completed prefix" } })); b.step("test-qwen35-prefill-host", "Stepped, whole, opening and interrupted prompt lifecycle without devices").dependOn(&prefill.step); step.dependOn(&prefill.step); + const warm_turns = b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{"Qwen warm turns:"} })); + b.step("test-qwen35-warm-turns-host", "Qwen3.5's warm turn wait and usable ends declared for both CUDA entry points without devices").dependOn(&warm_turns.step); + step.dependOn(&warm_turns.step); const draft_config = b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{"Qwen DFlash2 config:"} })); b.step("test-qwen35-draft-config-host", "DFlash2 attention declarations agree with the CUDA kernels before loading").dependOn(&draft_config.step); step.dependOn(&draft_config.step); @@ -216,6 +219,9 @@ pub fn steps(b: *std.Build, cuda: *std.Build.Module, mods: anytype, step: *std.B pub fn registerCopyFamilies(b: *std.Build, native: *std.Build.Module, step: *std.Build.Step) void { b.step("test-glm-formats-host", "CUDA GLM EXL3 offer reaches the published family registry without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{"GLM capabilities:"} })).step); b.step("test-request-starts-host", "Opt-in CUDA message starts without GPU execution").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{"request starts:"} })).step); + const warm_rules = b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{"CUDA warm rules:"} })); + b.step("test-cuda-warm-rules-host", "A family's warm rules and its own quiet wait without devices").dependOn(&warm_rules.step); + step.dependOn(&warm_rules.step); b.step("test-glm-window-prices-host", "GLM timed lone and unchanged shared price values without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{"GLM window prices:"} })).step); const family_copies = b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{"CUDA lane copies:"} })); b.step("test-family-copies-host", "Actual CUDA family copy policies through the lane core").dependOn(&family_copies.step); diff --git a/zig/qwen35_cost_open_host.zig b/zig/qwen35_cost_open_host.zig index 98a0689a652..b918a25b0c4 100644 --- a/zig/qwen35_cost_open_host.zig +++ b/zig/qwen35_cost_open_host.zig @@ -62,7 +62,7 @@ fn open(root: []const u8, expected: usize, capacity: usize) ![64]f64 { h.* = .{ .gpa = a, .gpu = null, .family = &probe, .release = Probe.release, .inner = backend.backend(), .vtable = undefined, .cfg = undefined, .clock = undefined, .core = undefined, .host = undefined, .served = .{ .backend = backend.backend(), .facts = facts, .stream_bytes = 0, .prepare = .{ .ctx = &probe, .run = Probe.run } } }; Probe.opening = true; defer Probe.opening = false; - try h.serve(io, facts, 64, .{ .lanes = 1 }, null); + try h.serve(io, facts, 64, .{ .lanes = 1 }, null, 0); defer { h.host.stop(); h.core.deinit(); diff --git a/zig/src/core/lane_host.zig b/zig/src/core/lane_host.zig index a4e73a0bb8a..c0cf7231390 100644 --- a/zig/src/core/lane_host.zig +++ b/zig/src/core/lane_host.zig @@ -160,6 +160,12 @@ pub const LaneHost = struct { return .{ .ctx = h, .vtable = if (vt.score != null and vt.decide != null) &decided_vtable else if (vt.score != null) &scored_vtable else &plain_vtable }; } + /// Advertise the cache capabilities: warm turns follow the store, so a cache-less start claims none. + pub fn advertiseCache(h: *LaneHost, store: ?*pc.Store) void { + h.info_.prompt_cache = store != null; + h.info_.warm_turns = store != null; + } + const plain_vtable: Engine.VTable = .{ .info = infoFn, .submit = submitFn, diff --git a/zig/src/core/lane_host_warm_test.zig b/zig/src/core/lane_host_warm_test.zig index d987e1bfb5e..3d2d2b97054 100644 --- a/zig/src/core/lane_host_warm_test.zig +++ b/zig/src/core/lane_host_warm_test.zig @@ -3,6 +3,7 @@ const std = @import("std"); const lanes = @import("lanes"); const api = @import("engine_api.zig"); const LaneHost = @import("lane_host.zig").LaneHost; +const prompt_cache = @import("prompt_cache.zig"); const Reason = api.Reason; const Id = api.Id; const Event = api.Event; @@ -235,6 +236,58 @@ test "a warm_usable store keeps a warm pass's grid mark but not its end off the } } +test "a one-snapshot store keeps the warm pass's usable mark over an unusable end; the next request resumes the mark" { + const gpa = std.testing.allocator; + const pc = api.prompt_cache; + const Snaps = struct { + fn bytes(_: *anyopaque, at: u32) u64 { + return 64 + 4 * @as(u64, at); + } + fn save(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!pc.Saved { + const f: *lanes.fake.Fake = @ptrCast(@alignCast(ptr)); + return f.save(@ptrCast(@alignCast(owner.?)), at); + } + fn restore(_: *anyopaque, _: ?*anyopaque, _: pc.Saved) anyerror!void { + return error.BackendRestores; + } + fn drop(ptr: *anyopaque, saved: pc.Saved) void { + const f: *lanes.fake.Fake = @ptrCast(@alignCast(ptr)); + f.drop(saved); + } + }; + for ([_]bool{ true, false }) |usable| { + var cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); + defer cfg.deinit(gpa); + var target: lanes.fake.Fake = .{ .gpa = gpa }; + defer target.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var core = lanes.Engine.init(gpa, &cfg, target.backend(), clock.clock()); + defer core.deinit(); + + // The 128-row cut and 192-row warm end, scaled to a grid of 4: the end at 6 is off it. + + // A budget of one snapshot (88 B) fits either state, never both. + var store = pc.Store.init(gpa, .{ .ptr = &target, .vtable = &.{ .bytes = Snaps.bytes, .save = Snaps.save, .restore = Snaps.restore, .drop = Snaps.drop } }, .{ .planned = true, .grid = 4, .warm = .on, .warm_usable = usable }, 100); + defer store.deinit(); + var host = LaneHost.init(gpa, std.testing.io, &core, .{ .lanes = 2, .warm_turns = true }); + host.cache = &store; + try host.start(); + defer host.stop(); + const prompt = [_]u32{ 2, 7, 1, 8, 2, 8 }; + var warm: Box = .{}; + const warm_request: Request = .{ .prompt = &prompt, .max_tokens = 0, .background = true, .history_len = prompt.len, .born = 4 }; + try host.engine().submit(1, &warm_request, .{ .ctx = &warm, .event = Box.event }); + try std.testing.expectEqual(Reason.length, warm.wait()); + host.engine().drain(); + + // The unusable end must not cost the usable mark: a follow-up resumes the grid mark, or nothing. + const longer = [_]u32{ 2, 7, 1, 8, 2, 8, 3, 1 }; + const follow = try store.lookup(gpa, &longer, longer.len, &.{}, &.{}, &.{}); + defer gpa.free(follow.marks); + try std.testing.expectEqual(if (usable) @as(u32, 4) else @as(u32, 0), if (follow.entry) |e| e.at else 0); + } +} + /// Status polls taken at each prompt chunk, the warm pass's apart from the request's. const FillPolls = struct { engine: Engine = undefined, @@ -373,3 +426,13 @@ test "a kept warm end supersedes its history at either lookahead and regeneratio try std.testing.expect(got.same); } } + +test "a host advertises warm turns only beside a kept-state store" { + var host: LaneHost = undefined; + host.info_ = .{}; + host.advertiseCache(null); + try std.testing.expect(!host.info_.prompt_cache and !host.info_.warm_turns); + var store: prompt_cache.Store = undefined; + host.advertiseCache(&store); + try std.testing.expect(host.info_.prompt_cache and host.info_.warm_turns); +} diff --git a/zig/src/core/lanes/backend.zig b/zig/src/core/lanes/backend.zig index 48e2c8ffa23..8e8d9e6a628 100644 --- a/zig/src/core/lanes/backend.zig +++ b/zig/src/core/lanes/backend.zig @@ -117,7 +117,7 @@ pub const Backend = struct { clear_proposals: ?*const fn (*anyopaque, *Stream) void = null, /// Undo an early speculation whose round was cut (the drafts come from a late request instead). unspeculate: ?*const fn (ptr: *anyopaque, s: *Stream) anyerror!void = null, - /// Each held draft's chance of landing, for heads that give them; false when it has none. + /// Each held draft's chance, or false; also marks s.draft_chances_cut at the first unmeasured chance. probabilities: ?*const fn (ptr: *anyopaque, s: *Stream, out: []f64) anyerror!bool = null, /// A tree head's held drafts as host tokens and parents (gpa-owned), read where Python reads them. tree: ?*const fn (ptr: *anyopaque, s: *Stream, gpa: std.mem.Allocator) anyerror!?Held = null, diff --git a/zig/src/core/lanes/lanes.zig b/zig/src/core/lanes/lanes.zig index 79e83a57eb2..f9b284af8ae 100644 --- a/zig/src/core/lanes/lanes.zig +++ b/zig/src/core/lanes/lanes.zig @@ -79,6 +79,7 @@ test { _ = @import("root_copy_test.zig"); _ = @import("drafted_grammar_test.zig"); _ = @import("windows_grammar_test.zig"); + _ = @import("windows_chances_test.zig"); _ = @import("grammar_time_test.zig"); _ = @import("grammar_parallel_test.zig"); _ = @import("pricing_test.zig"); diff --git a/zig/src/core/lanes/shared_drafts.zig b/zig/src/core/lanes/shared_drafts.zig index d0b005bb997..f886081ceac 100644 --- a/zig/src/core/lanes/shared_drafts.zig +++ b/zig/src/core/lanes/shared_drafts.zig @@ -37,10 +37,10 @@ pub fn budgets(e: *Engine, plans: []const win.Plan, heads: []const usize, out: [ if (most == 0) continue; head.* = true; const cached = s.draft_chances.items; - // a legacy cap prices by the rule's rates; granted depths keep the drafter's own chances under their bound - if (cached.len > 0 and (limits == null or e.cfg.granted_depth)) { + // a legacy cap prices by the rule's rates; a cut never starts the tail, so the measured prefix prices the rest + const known = @min(s.draft_chances_cut orelse cached.len, cached.len, most); + if (known > 0 and (limits == null or e.cfg.granted_depth)) { const prices = try a.alloc(f64, most); - const known = @min(cached.len, most); @memcpy(prices[0..known], cached[0..known]); const rates = try e.rule.rates(win.who(s)); var chance = cached[known - 1]; @@ -187,3 +187,36 @@ test "shared draft prices: plain forced streams cost one row and paused streams try budgets(&e, &plans, &.{0}, &out); try std.testing.expectEqual(@as(i64, 7), out[0]); } + +test "shared draft prices: a cut chance tail prices by the rule's rates, not as a measured zero" { + const a = std.testing.allocator; + const Cfg = @import("config.zig"); + const S = @import("stream.zig").Stream; + var cfg = try Cfg.Config.init(a, .{ .exact_width = 32, .drafts = 5, .batch_rows = 11 }, 32, 5); + defer cfg.deinit(a); + var fake: @import("fake.zig").Fake = .{ .gpa = a }; + defer fake.deinit(); + var clock: @import("fake.zig").FixedClock = .{}; + var e = Engine.init(a, &cfg, fake.backend(), clock.clock()); + defer e.deinit(); + var cut = try S.init(a, .{ .id = "cut", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer cut.deinit(a); + var zero = try S.init(a, .{ .id = "zero", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer zero.deinit(a); + var grown = try S.init(a, .{ .id = "grown", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer grown.deinit(a); + try cut.draft_chances.appendSlice(a, &.{ 0.9, 0.4, 0, 0, 0 }); + cut.draft_chances_cut = 2; // the chain cut left the last three chances unknown + try zero.draft_chances.appendSlice(a, &.{ 0.9, 0.4, 0, 0, 0 }); // main's rule: that tail priced as measured zeros + const rates = try e.rule.rates(win.who(&grown)); + var continuation = [_]f64{ 0.9, 0.4, 0, 0, 0 }; + for (continuation[2..], 2..) |*c, j| c.* = continuation[j - 1] * rates[@min(j, rates.len - 1)]; + try grown.draft_chances.appendSlice(a, &continuation); + const cutp: win.Plan = .{ .stream = &cut, .position = 0, .kind = .none }; + const zerop: win.Plan = .{ .stream = &zero, .position = 0, .kind = .none }; + const grownp: win.Plan = .{ .stream = &grown, .position = 0, .kind = .none }; + var out: [3]i64 = undefined; + try budgets(&e, &.{ cutp, grownp, zerop }, &.{ 0, 1, 2 }, &out); + try std.testing.expect(out[0] > out[2]); // main's rule prices the cut tail as measured zeros + try std.testing.expectEqual(out[1], out[0]); // the cut stream prices as the rate continuation +} diff --git a/zig/src/core/lanes/stream.zig b/zig/src/core/lanes/stream.zig index baff3bd3100..2c0c773add5 100644 --- a/zig/src/core/lanes/stream.zig +++ b/zig/src/core/lanes/stream.zig @@ -245,6 +245,7 @@ pub const Stream = struct { grant_short: bool = false, // the last grant verified fewer drafts than the stream held grant_gain: ?f64 = null, // the drafts its last grant expected to keep (the chances it was priced by) draft_chances: std.ArrayList(f64) = .empty, // last full head prices, retained through zero-row rounds + draft_chances_cut: ?usize = null, // first chance a cut left unknown (null: measured); a chances hook marks it copy_width: ?u32 = null, pub fn init(gpa: Allocator, spec: Spec) !Stream { @@ -319,6 +320,7 @@ pub const Stream = struct { s.grant_gain = null; s.draft_chances.deinit(gpa); s.draft_chances = .empty; + s.draft_chances_cut = null; s.copy_width = null; s.proposal_depth = null; } diff --git a/zig/src/core/lanes/windows.zig b/zig/src/core/lanes/windows.zig index f9f0b3ddb72..75c1db8788b 100644 --- a/zig/src/core/lanes/windows.zig +++ b/zig/src/core/lanes/windows.zig @@ -254,7 +254,11 @@ pub fn allocate(e: *Engine, plans: []Plan) !void { const a = e.arena.allocator(); const fixed = try a.alloc(u32, plans.len); const probs = try a.alloc([]const f64, plans.len); - for (plans, fixed, probs) |p, *fx, *pr| { + const cuts = try a.alloc(?usize, plans.len); // the cut each plan's chances hook marked, committed with its cache + for (plans, fixed, probs, cuts) |p, *fx, *pr, *mark| { + const prior = p.stream.draft_chances_cut; + p.stream.draft_chances_cut = null; + errdefer p.stream.draft_chances_cut = prior; const n = p.count(); if (p.kind == .forced or n == 0) { fx.* = 1 + @as(u32, @intCast(if (p.kind == .forced) n else 0)); @@ -269,15 +273,19 @@ pub fn allocate(e: *Engine, plans: []Plan) !void { const controls = @import("mtp_policy.zig").Controls{ .cap = e.cfg.most_drafts, .floor = e.cfg.draft_confidence }; pr.* = if (p.kind == .head and e.cfg.draft_confidence != null) chances[0..controls.prefix(chances)] else chances; } + mark.* = p.stream.draft_chances_cut; + p.stream.draft_chances_cut = prior; } - if (e.cfg.allocate_shared_drafts) for (plans, probs) |p, chances| { + if (e.cfg.allocate_shared_drafts) for (plans, probs, cuts) |p, chances, mark| { if (p.kind == .copy or p.context_copy) { p.stream.draft_chances.clearRetainingCapacity(); + p.stream.draft_chances_cut = null; continue; } if (p.kind != .head or chances.len == 0) continue; p.stream.draft_chances.clearRetainingCapacity(); try p.stream.draft_chances.appendSlice(e.gpa, chances); + p.stream.draft_chances_cut = if (mark) |first| @min(first, chances.len) else null; }; const untimed: @import("table.zig").Table = .{}; const explicit = e.cfg.draft_confidence != null; diff --git a/zig/src/core/lanes/windows_chances_test.zig b/zig/src/core/lanes/windows_chances_test.zig new file mode 100644 index 00000000000..88d116f4898 --- /dev/null +++ b/zig/src/core/lanes/windows_chances_test.zig @@ -0,0 +1,224 @@ +//! windows.allocate's shared-round commit of a stream's cached draft chances and their cut marker, per window kind. +const std = @import("std"); +const Config = @import("config.zig").Config; +const Model = @import("config.zig").Model; +const Engine = @import("engine.zig").Engine; +const Stream = @import("stream.zig").Stream; +const be = @import("backend.zig"); +const fake = @import("fake.zig"); +const win = @import("windows.zig"); + +const a = std.testing.allocator; + +/// The chain chances a three-draft head reports, the two its confidence prefix keeps, and a stream's earlier prices. +const chain = [_]f64{ 0.9, 0.8, 0.7 }; +const prefix = [_]f64{ 0.9, 0.8 }; +const earlier = [_]f64{ 0.25, 0.2 }; + +const Hook = *const fn (ptr: *anyopaque, s: *Stream, out: []f64) anyerror!bool; + +/// A three-draft head's chances, marking the third as the first one a cut left unmeasured. +fn chainChances(_: *anyopaque, s: *Stream, out: []f64) anyerror!bool { + if (out.len != chain.len) return false; + @memcpy(out, &chain); + s.draft_chances_cut = 2; + return true; +} + +/// Five cumulative chances whose mark sits past the confidence prefix, so the commit has to clamp it. +fn deepChances(_: *anyopaque, s: *Stream, out: []f64) anyerror!bool { + const all = [_]f64{ 0.9, 0.8, 0.4, 0.3, 0.2 }; + if (out.len != all.len) return false; + @memcpy(out, &all); + s.draft_chances_cut = 5; + return true; +} + +/// A head that marks its cut and then fails, as a partially read logits buffer does. +fn markThenFail(_: *anyopaque, s: *Stream, out: []f64) anyerror!bool { + _ = out; + s.draft_chances_cut = 3; + return error.NoDraftProbabilities; +} + +/// A head with no chances to give, which a confidence floor turns into a refusal. +fn noChances(_: *anyopaque, _: *Stream, _: []f64) anyerror!bool { + return false; +} + +/// One engine on the fake target with this round's chances hook, and the shared commit enabled. +const Round = struct { + cfg: Config = undefined, + target: fake.Fake = undefined, + clock: fake.FixedClock = .{}, + vtable: be.Backend.VTable = undefined, + engine: Engine = undefined, + + fn start(r: *Round, m: Model, max_draft: u32, hook: ?Hook) !void { + r.cfg = try Config.init(a, m, 32, max_draft); + r.target = .{ .gpa = a }; + const plain = r.target.backend(); + r.vtable = plain.vtable.*; + r.vtable.probabilities = hook; + r.engine = Engine.init(a, &r.cfg, .{ .ptr = plain.ptr, .vtable = &r.vtable, .chunk_invariant = plain.chunk_invariant }, r.clock.clock()); + } + + fn finish(r: *Round) void { + r.engine.deinit(); + r.target.deinit(); + r.cfg.deinit(a); + } +}; + +/// The shared-round model: the head prices its drafts and their prices are committed per stream. +const shared_model = Model{ .exact_width = 32, .drafts = 5, .batch_rows = 32, .allocate_shared_drafts = true, .draft_probabilities = true }; + +fn headStream(s: *Stream) !void { + try s.draft_chances.appendSlice(a, &earlier); + s.draft_chances_cut = 1; +} + +test "cached draft cuts: a head round commits the head's chances and its marked cut" { + var r: Round = .{}; + try r.start(shared_model, 5, chainChances); + defer r.finish(); + var s = try Stream.init(a, .{ .id = "head", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer s.deinit(a); + try headStream(&s); + const tokens = [_]u32{ 11, 12, 13 }; + var plans = [_]win.Plan{.{ .stream = &s, .position = 3, .kind = .head, .tokens = &tokens }}; + try win.allocate(&r.engine, &plans); + try std.testing.expectEqualSlices(f64, &chain, s.draft_chances.items); + try std.testing.expectEqual(@as(?usize, 2), s.draft_chances_cut); +} + +test "cached draft cuts: a confidence prefix commits its rows and clamps the marker to them" { + var r: Round = .{}; + var m = shared_model; + m.draft_confidence = 0.5; // keeps 0.9 and 0.8, so the head's mark of 5 is past what was committed + try r.start(m, 5, deepChances); + defer r.finish(); + var s = try Stream.init(a, .{ .id = "floor", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer s.deinit(a); + try headStream(&s); + const tokens = [_]u32{ 11, 12, 13, 14, 15 }; + var plans = [_]win.Plan{.{ .stream = &s, .position = 5, .kind = .head, .tokens = &tokens }}; + try win.allocate(&r.engine, &plans); + try std.testing.expectEqualSlices(f64, &prefix, s.draft_chances.items); + try std.testing.expectEqual(@as(?usize, 2), s.draft_chances_cut); +} + +test "cached draft cuts: a forced round keeps the previous chances and marker" { + var r: Round = .{}; + try r.start(shared_model, 5, chainChances); + defer r.finish(); + var s = try Stream.init(a, .{ .id = "forced", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer s.deinit(a); + try headStream(&s); + const tokens = [_]u32{ 11, 12 }; + var plans = [_]win.Plan{.{ .stream = &s, .position = 2, .kind = .forced, .tokens = &tokens, .forced = &tokens }}; + try win.allocate(&r.engine, &plans); + try std.testing.expectEqualSlices(f64, &earlier, s.draft_chances.items); + try std.testing.expectEqual(@as(?usize, 1), s.draft_chances_cut); +} + +test "cached draft cuts: an empty round keeps the previous chances and marker" { + var r: Round = .{}; + try r.start(shared_model, 5, chainChances); + defer r.finish(); + var s = try Stream.init(a, .{ .id = "empty", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer s.deinit(a); + try headStream(&s); + var plans = [_]win.Plan{.{ .stream = &s, .position = 1, .kind = .none }}; + try win.allocate(&r.engine, &plans); + try std.testing.expectEqualSlices(f64, &earlier, s.draft_chances.items); + try std.testing.expectEqual(@as(?usize, 1), s.draft_chances_cut); +} + +test "cached draft cuts: a grafted round is no head, so it keeps the previous chances and marker" { + var r: Round = .{}; + try r.start(shared_model, 5, chainChances); + defer r.finish(); + var s = try Stream.init(a, .{ .id = "fill", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer s.deinit(a); + try headStream(&s); + const tokens = [_]u32{ 11, 12, 13 }; + var plans = [_]win.Plan{.{ .stream = &s, .position = 3, .kind = .fill, .tokens = &tokens }}; + try win.allocate(&r.engine, &plans); + try std.testing.expectEqualSlices(f64, &earlier, s.draft_chances.items); + try std.testing.expectEqual(@as(?usize, 1), s.draft_chances_cut); +} + +test "cached draft cuts: a head with no priced rows keeps the previous chances and marker" { + var r: Round = .{}; + var m = shared_model; + m.draft_confidence = 0.5; + try r.start(m, 0, chainChances); // most_drafts 0: the confidence prefix keeps nothing for this head + defer r.finish(); + var s = try Stream.init(a, .{ .id = "unpriced", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer s.deinit(a); + try headStream(&s); + const tokens = [_]u32{ 11, 12, 13 }; + var plans = [_]win.Plan{.{ .stream = &s, .position = 3, .kind = .head, .tokens = &tokens }}; + try win.allocate(&r.engine, &plans); + try std.testing.expectEqualSlices(f64, &earlier, s.draft_chances.items); + try std.testing.expectEqual(@as(?usize, 1), s.draft_chances_cut); +} + +test "cached draft cuts: a copy round clears both the chances and the marker" { + var r: Round = .{}; + try r.start(shared_model, 5, chainChances); + defer r.finish(); + var s = try Stream.init(a, .{ .id = "copy", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer s.deinit(a); + try headStream(&s); + const tokens = [_]u32{ 11, 12 }; + var plans = [_]win.Plan{.{ .stream = &s, .position = 2, .kind = .copy, .tokens = &tokens }}; + try win.allocate(&r.engine, &plans); + try std.testing.expectEqual(@as(usize, 0), s.draft_chances.items.len); + try std.testing.expectEqual(@as(?usize, null), s.draft_chances_cut); +} + +test "cached draft cuts: a context copy clears both the chances and the marker" { + var r: Round = .{}; + try r.start(shared_model, 5, chainChances); + defer r.finish(); + var s = try Stream.init(a, .{ .id = "context", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer s.deinit(a); + try headStream(&s); + const tokens = [_]u32{ 11, 12, 13 }; + var plans = [_]win.Plan{.{ .stream = &s, .position = 3, .kind = .head, .tokens = &tokens, .context_copy = true }}; + try win.allocate(&r.engine, &plans); + try std.testing.expectEqual(@as(usize, 0), s.draft_chances.items.len); + try std.testing.expectEqual(@as(?usize, null), s.draft_chances_cut); +} + +test "cached draft cuts: a failing chances hook restores the previous marker" { + var r: Round = .{}; + try r.start(shared_model, 5, markThenFail); + defer r.finish(); + var s = try Stream.init(a, .{ .id = "failed", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer s.deinit(a); + try headStream(&s); + const tokens = [_]u32{ 11, 12, 13 }; + var plans = [_]win.Plan{.{ .stream = &s, .position = 3, .kind = .head, .tokens = &tokens }}; + try std.testing.expectError(error.NoDraftProbabilities, win.allocate(&r.engine, &plans)); + try std.testing.expectEqualSlices(f64, &earlier, s.draft_chances.items); + try std.testing.expectEqual(@as(?usize, 1), s.draft_chances_cut); +} + +test "cached draft cuts: a head without chances under a floor restores the previous marker" { + var r: Round = .{}; + var m = shared_model; + m.draft_confidence = 0.5; + try r.start(m, 5, noChances); + defer r.finish(); + var s = try Stream.init(a, .{ .id = "refused", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer s.deinit(a); + try headStream(&s); + const tokens = [_]u32{ 11, 12, 13 }; + var plans = [_]win.Plan{.{ .stream = &s, .position = 3, .kind = .head, .tokens = &tokens }}; + try std.testing.expectError(error.NoDraftProbabilities, win.allocate(&r.engine, &plans)); + try std.testing.expectEqualSlices(f64, &earlier, s.draft_chances.items); + try std.testing.expectEqual(@as(?usize, 1), s.draft_chances_cut); +} diff --git a/zig/src/families/qwen3_5/cuda.zig b/zig/src/families/qwen3_5/cuda.zig index 6c74c7e2616..2b6b8c30e04 100644 --- a/zig/src/families/qwen3_5/cuda.zig +++ b/zig/src/families/qwen3_5/cuda.zig @@ -54,6 +54,7 @@ test { _ = @import("cuda_prefix_fault_test.zig"); _ = @import("cuda_pend_test.zig"); _ = @import("cuda_reuse_pages_test.zig"); + _ = @import("cuda_warm_turns_test.zig"); } pub const slide = @import("cuda_slide.zig"); diff --git a/zig/src/families/qwen3_5/cuda_admit_test.zig b/zig/src/families/qwen3_5/cuda_admit_test.zig index 8fff7322d70..f0193616a40 100644 --- a/zig/src/families/qwen3_5/cuda_admit_test.zig +++ b/zig/src/families/qwen3_5/cuda_admit_test.zig @@ -112,3 +112,11 @@ pub fn refusals() !void { try t.expectError(error.QwenShareNeedsPages, refused(false, null, "16")); try t.expectError(error.QwenShareNeedsPages, refused(false, "100", "16")); } + +test "Qwen share faults: --parallel N admits N streams at once with every stream on pages" { + try admits(native.Lanes); +} + +test "Qwen pages default: --parallel a cap with TF_QWEN_KV_PAGES set, a request waits for pages; unset, a window each" { + try caps(native.Lanes); +} diff --git a/zig/src/families/qwen3_5/cuda_native.zig b/zig/src/families/qwen3_5/cuda_native.zig index 20ab6df6250..b8c0b84dd31 100644 --- a/zig/src/families/qwen3_5/cuda_native.zig +++ b/zig/src/families/qwen3_5/cuda_native.zig @@ -53,6 +53,10 @@ pub const snap_drop = reuse.drop; pub const snap_host = true; pub const snap_lookahead: u32 = 0; pub const snap_grid: u32 = E.max_rows; +/// Nanoseconds a reply's background warm pass waits for the next request before its first chunk. +pub const warm_quiet: u64 = 150 * std.time.ns_per_ms; +/// Keep a warm pass's end only where a resume can use it. +pub const warm_usable = true; /// --learn-conversations: the kept states' disk image, the probe their identity hashes, the facts they depend on. pub const kept_disk = @import("cuda_disk.zig"); @@ -579,14 +583,6 @@ pub const Lanes = struct { } }; -test "Qwen share faults: --parallel N admits N streams at once with every stream on pages" { - try @import("cuda_admit_test.zig").admits(Lanes); -} - -test "Qwen pages default: --parallel a cap with TF_QWEN_KV_PAGES set, a request waits for pages; unset, a window each" { - try @import("cuda_admit_test.zig").caps(Lanes); -} - test "Qwen stepped prefill: cancel between host iterations retains only the last completed cut" { try @import("cuda_prefill_test.zig").cancelled(Lanes, Lanes.backend); } @@ -596,5 +592,6 @@ test "Qwen stepped prefill: a cap (the flag's or fcfs's) cuts on the 128 grid in } test { + _ = @import("cuda_admit_test.zig"); _ = @import("cuda_mtp_budget.zig"); } diff --git a/zig/src/families/qwen3_5/cuda_native_moe.zig b/zig/src/families/qwen3_5/cuda_native_moe.zig index a67ab344581..7cda3556745 100644 --- a/zig/src/families/qwen3_5/cuda_native_moe.zig +++ b/zig/src/families/qwen3_5/cuda_native_moe.zig @@ -27,6 +27,9 @@ pub const snap_host = native.snap_host; pub const snap_lookahead = native.snap_lookahead; pub const snap_grid = native.snap_grid; pub const kept_disk = native.kept_disk; +/// The dense family's warm pass: its wait for the next request and the ends a resume can use. +pub const warm_quiet = native.warm_quiet; +pub const warm_usable = native.warm_usable; pub const request_starts = native.request_starts; pub const request_starts_switch = native.request_starts_switch; diff --git a/zig/src/families/qwen3_5/cuda_warm_turns_test.zig b/zig/src/families/qwen3_5/cuda_warm_turns_test.zig new file mode 100644 index 00000000000..4e977a0e52d --- /dev/null +++ b/zig/src/families/qwen3_5/cuda_warm_turns_test.zig @@ -0,0 +1,11 @@ +//! Qwen3.5 CUDA's warm turns: the dense family and its MoE wrapper declare the wait and a usable end. +const std = @import("std"); +const native = @import("cuda_native.zig"); +const moe = @import("cuda_native_moe.zig"); + +test "Qwen warm turns: the dense family and its MoE wrapper share the wait and keep only usable ends" { + try std.testing.expectEqual(@as(u64, 150 * std.time.ns_per_ms), native.warm_quiet); + try std.testing.expect(native.warm_usable); + try std.testing.expectEqual(@as(u64, 150 * std.time.ns_per_ms), moe.warm_quiet); + try std.testing.expect(moe.warm_usable); +} diff --git a/zig/src/families/qwen3_5/prefill.zig b/zig/src/families/qwen3_5/prefill.zig index 0be0f2127e4..f5b7c9b61da 100644 --- a/zig/src/families/qwen3_5/prefill.zig +++ b/zig/src/families/qwen3_5/prefill.zig @@ -25,6 +25,12 @@ pub fn run(cache: *st.Cache, stream: *lanes.Stream, chunk: usize, ctx: anytype, stream.keepInterruptedPrefill(@intCast(at)); return error.Cancelled; } + + // A background pass steps aside when real work waits: the kept prefix is what the next pass resumes. + if (stream.yields()) { + stream.keepInterruptedPrefill(@intCast(at)); + return error.Yielded; + } var end = @min(ids.len, at + chunk); for (stream.chunks) |boundary| if (boundary > at) { end = @min(end, boundary); diff --git a/zig/src/native/cuda.zig b/zig/src/native/cuda.zig index 7b32be53886..12855f5cf5a 100644 --- a/zig/src/native/cuda.zig +++ b/zig/src/native/cuda.zig @@ -105,8 +105,8 @@ pub const Host = struct { } } /// The round loop and the lane host over the family's backend, its thread started. - pub fn serve(h: *Host, io: std.Io, facts: lanes.Model, rows: u32, info: api.Info, explain: ?api.Explain) !void { - return @import("cuda_startup_phase.zig").serve(h, io, facts, rows, info, explain, .{ + pub fn serve(h: *Host, io: std.Io, facts: lanes.Model, rows: u32, info: api.Info, explain: ?api.Explain, warm_quiet: u64) !void { + return @import("cuda_startup_phase.zig").serve(h, io, facts, rows, info, explain, warm_quiet, .{ .bound = &bound, .backend = backend, .initThread = initThread, @@ -472,7 +472,7 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O .slide_conversations = conversations, .readouts = readouts, .text_generation = readouts == null, // a readout engine answers its readouts only (Clef's /v1/systemone) - }), .{ .ctx = loaded.ctx, .text = F.explain }); + }), .{ .ctx = loaded.ctx, .text = F.explain }, snaps.warmQuiet(F)); opened = true; kv_pages.warnCapacity(cache_capacity, o.keep == 0 or o.prompt_cache_gib == 0 or share, if (paged) |p| p.taken else 0, std.log); // TF_KV_SHARE: no copied rows if (@hasField(@TypeOf(loaded), "follow")) if (loaded.follow) |f| { diff --git a/zig/src/native/cuda_health_test.zig b/zig/src/native/cuda_health_test.zig index c61ecf80248..e9483ec703f 100644 --- a/zig/src/native/cuda_health_test.zig +++ b/zig/src/native/cuda_health_test.zig @@ -34,7 +34,7 @@ pub fn check(comptime Host: type, comptime readiness: anytype, comptime serve: a try std.testing.expect(h.health == null); try std.testing.expect(h.startup_phase == null); readiness(h, Family); - try serve(h, std.testing.io, .{ .exact_width = 8 }, 8, .{ .lanes = 2 }, null); + try serve(h, std.testing.io, .{ .exact_width = 8 }, 8, .{ .lanes = 2 }, null, 0); try std.testing.expectEqual(@as(usize, 2), family.notes); try std.testing.expectEqual(Phase.calibration, family.phases[0]); try std.testing.expectEqual(Phase.ready, family.phases[1]); @@ -86,7 +86,7 @@ fn eager(comptime Host: type, comptime serve: anytype) !void { h.* = .{ .gpa = gpa, .gpu = null, .family = &probe, .release = Probe.release, .inner = backend.backend(), .vtable = undefined, .cfg = undefined, .clock = undefined, .core = undefined, .host = undefined, .served = .{ .backend = backend.backend(), .facts = facts, .stream_bytes = 0, .prepare = .{ .ctx = &probe, .run = Probe.run } } }; Probe.opening = true; defer Probe.opening = false; - try serve(h, std.testing.io, facts, 64, .{ .lanes = 1 }, null); + try serve(h, std.testing.io, facts, 64, .{ .lanes = 1 }, null, 0); defer { h.host.stop(); h.core.deinit(); @@ -142,7 +142,7 @@ pub fn context(comptime H: type, comptime serve: anytype) !void { defer backend.deinit(); var dummy: u8 = 0; var h: H = .{ .gpa = a, .gpu = &gpu, .family = &dummy, .release = undefined, .inner = backend.backend(), .vtable = undefined, .cfg = undefined, .clock = undefined, .core = undefined, .host = undefined }; - try serve(&h, std.testing.io, .{}, 1, .{ .lanes = 1 }, null); + try serve(&h, std.testing.io, .{}, 1, .{ .lanes = 1 }, null, 0); defer { h.host.stop(); h.core.deinit(); @@ -189,7 +189,7 @@ fn failedStartup(comptime Host: type, comptime readiness: anytype, comptime serv const facts: lanes.Model = .{ .exact_width = 8 }; h.* = .{ .gpa = a, .gpu = null, .family = &family, .release = Family.release, .inner = backend.backend(), .vtable = undefined, .cfg = undefined, .clock = undefined, .core = undefined, .host = undefined, .served = .{ .backend = backend.backend(), .facts = facts, .stream_bytes = 0, .prepare = .{ .ctx = &family, .run = Family.prepare } } }; readiness(h, Family); - try std.testing.expectError(error.InjectedCalibration, serve(h, std.testing.io, facts, 8, .{ .lanes = 2 }, null)); + try std.testing.expectError(error.InjectedCalibration, serve(h, std.testing.io, facts, 8, .{ .lanes = 2 }, null, 0)); try std.testing.expectEqual(@as(usize, 2), family.count); try std.testing.expectEqualSlices(Phase, &.{ .calibration, .failed }, &family.phases); } diff --git a/zig/src/native/cuda_ledger.zig b/zig/src/native/cuda_ledger.zig index 8bafd878cde..b19eae6ddb1 100644 --- a/zig/src/native/cuda_ledger.zig +++ b/zig/src/native/cuda_ledger.zig @@ -40,7 +40,7 @@ pub fn declared(loaded: anytype) ?PerRequest { /// Whether this load serves from the ledger: the family allocates per request and nothing it loaded escapes the cost. pub fn wanted(comptime F: type, loaded: anytype, served_stream_bytes: u64) bool { if (declared(loaded) == null) return false; - // no path yet routes a warm pass's or a lone driver's LaneMemory back to the queue + // a family that declares warm turns serves off the ledger: its warm pass's LaneMemory ends the job, no requeue if (comptime @hasDecl(F, "warm_quiet")) return false; const L = @TypeOf(loaded); if (comptime @hasField(L, "lone")) if (loaded.lone != null) return false; diff --git a/zig/src/native/cuda_prompt_cancel_test.zig b/zig/src/native/cuda_prompt_cancel_test.zig index f7ec3234543..a4db1b697fb 100644 --- a/zig/src/native/cuda_prompt_cancel_test.zig +++ b/zig/src/native/cuda_prompt_cancel_test.zig @@ -13,7 +13,7 @@ pub fn check(comptime Host: type, comptime serve: anytype) !void { const h = try gpa.create(Host); defer gpa.destroy(h); h.* = .{ .gpa = gpa, .gpu = null, .family = &target, .release = Nothing.release, .inner = target.backend(), .vtable = undefined, .cfg = undefined, .clock = undefined, .core = undefined, .host = undefined }; - try serve(h, std.testing.io, .{ .exact_width = 8, .mtp = true, .speculate = true, .drafts = 7, .hidden_rows = true }, 8, .{ .lanes = 2 }, null); + try serve(h, std.testing.io, .{ .exact_width = 8, .mtp = true, .speculate = true, .drafts = 7, .hidden_rows = true }, 8, .{ .lanes = 2 }, null, 0); defer { h.host.stop(); h.core.deinit(); diff --git a/zig/src/native/cuda_snaps.zig b/zig/src/native/cuda_snaps.zig index df4527771b9..e915e1e91c3 100644 --- a/zig/src/native/cuda_snaps.zig +++ b/zig/src/native/cuda_snaps.zig @@ -7,6 +7,7 @@ pub fn cacheRules(comptime F: type) api.prompt_cache.Rules { var rules: api.prompt_cache.Rules = .{ .lookahead = 1, .min_prompt = 0 }; if (@hasDecl(F, "snap_lookahead")) rules.lookahead = F.snap_lookahead; if (@hasDecl(F, "warm_quiet")) rules.warm = .waits; + if (@hasDecl(F, "warm_usable")) rules.warm_usable = F.warm_usable; if (@hasDecl(F, "snap_fork")) rules.fork = F.snap_fork; // opt-in, a family at a time after its device check if (@hasDecl(F, "snap_tail")) rules.tail = if (@import("core").profile.lookup(F.snap_tail)) |v| std.mem.eql(u8, v, "1") else false; if (@hasDecl(F, "snap_intermediate")) { // a chunk-invariant family's opt-in ladder of intermediate checkpoints @@ -20,6 +21,11 @@ pub fn cacheRules(comptime F: type) api.prompt_cache.Rules { return rules; } +/// The family's own wait before a warm pass's first chunk (0: it declares none). +pub fn warmQuiet(comptime F: type) u64 { + return if (@hasDecl(F, "warm_quiet")) F.warm_quiet else 0; +} + /// Native CUDA families own their grid, independently of the server's template chunk starts. pub fn passRules(comptime F: type, prompt_rows: u32) api.prompt_cache.Rules { var rules = cacheRules(F); diff --git a/zig/src/native/cuda_snaps_test.zig b/zig/src/native/cuda_snaps_test.zig index f167c7c9ac0..b5c2f649de4 100644 --- a/zig/src/native/cuda_snaps_test.zig +++ b/zig/src/native/cuda_snaps_test.zig @@ -2,6 +2,7 @@ const std = @import("std"); const api = @import("engine_api"); const cacheRules = @import("cuda_snaps.zig").cacheRules; +const warmQuiet = @import("cuda_snaps.zig").warmQuiet; /// Copies that hold nothing: a store keys its states by tokens and position, all that its plans read. const Held = struct { @@ -85,3 +86,22 @@ test "snap fork: a family that opts in keeps where the questions part, and the n try std.testing.expectEqualSlices(u32, &.{ 16, 20 }, planned.marks[1]); try std.testing.expectEqual(@as(u32, 16), planned.from[2]); } + +test "CUDA warm rules: a warm end stays usable only where a family declares it, and its own wait comes through" { + const Both = struct { + pub const warm_quiet: u64 = 7; + pub const warm_usable = true; + }; + const Ends = struct { + pub const warm_quiet: u64 = 7; + }; + try std.testing.expectEqual(@as(u64, 7), warmQuiet(Both)); + try std.testing.expectEqual(@as(u64, 7), warmQuiet(Ends)); + try std.testing.expectEqual(@as(u64, 0), warmQuiet(struct {})); + // A family's wait and the rule that follows it come from one declaration: a nonzero wait is a waiting family. + inline for (@import("cuda.zig").registry) |F| { + try std.testing.expectEqual(warmQuiet(F) > 0, cacheRules(F).warm == .waits); + } + try std.testing.expect(cacheRules(Both).warm_usable); + try std.testing.expect(!cacheRules(Ends).warm_usable); +} diff --git a/zig/src/native/cuda_startup_phase.zig b/zig/src/native/cuda_startup_phase.zig index 42b3626d882..6a680b3efb5 100644 --- a/zig/src/native/cuda_startup_phase.zig +++ b/zig/src/native/cuda_startup_phase.zig @@ -16,7 +16,7 @@ fn note(h: anytype, phase: cuda.startup_watch.Phase) void { if (h.startup_phase) |callback| callback(h.family, phase); } -pub fn serve(h: anytype, io: std.Io, facts: lanes.Model, rows: u32, info: api.Info, explain: ?api.Explain, callbacks: anytype) !void { +pub fn serve(h: anytype, io: std.Io, facts: lanes.Model, rows: u32, info: api.Info, explain: ?api.Explain, warm_quiet: u64, callbacks: anytype) !void { note(h, .calibration); errdefer note(h, .failed); h.cfg = try lanes.Config.init(h.gpa, facts, rows, rows - 1); @@ -34,7 +34,7 @@ pub fn serve(h: anytype, io: std.Io, facts: lanes.Model, rows: u32, info: api.In h.host.explain = explain; h.host.health = @import("cuda_readiness.zig").source(h); h.host.cache = h.store; - h.host.warm_quiet = if (info.warm_turns) nemotron.native.warm_quiet else 0; + h.host.warm_quiet = if (info.warm_turns) warm_quiet else 0; if (h.lone != null) h.host.lone = .{ .ctx = h, .run = callbacks.loneRun, .sampled = true, .logprobs = h.inner.vtable.first_row != null, .structures = h.inner.vtable.first_masked != null, .min_budget = nemotron.native.lone_min_budget, .resumes = true }; if (h.learn != null) h.host.learner = callbacks.learner(h); kv_pages.install(&h.kv, &h.host); // the pool's first census, before the engine thread owns the pool diff --git a/zig/src/native/dense_trainer_close_test.zig b/zig/src/native/dense_trainer_close_test.zig index aa2dd9261bd..7aa56ca3b6c 100644 --- a/zig/src/native/dense_trainer_close_test.zig +++ b/zig/src/native/dense_trainer_close_test.zig @@ -147,7 +147,7 @@ pub fn close(comptime Host: type, comptime serve: anytype, comptime closeHost: a defer backend.deinit(); const h = try a.create(Host); h.* = .{ .gpa = a, .gpu = null, .family = e, .release = F.family, .inner = backend.backend(), .vtable = undefined, .cfg = undefined, .clock = undefined, .core = undefined, .host = undefined }; - try serve(h, std.testing.io, .{ .exact_width = 8 }, 8, .{ .lanes = 1 }, null); + try serve(h, std.testing.io, .{ .exact_width = 8 }, 8, .{ .lanes = 1 }, null, 0); h.served = .{ .backend = backend.backend(), .facts = .{ .exact_width = 8 }, .stream_bytes = 0 }; adapter.learner.pockets.save_pending = true; const hook = adapter.hook(); diff --git a/zig/src/native/nemotron_trainer_test.zig b/zig/src/native/nemotron_trainer_test.zig index 9ce405c8a92..16dac6299bd 100644 --- a/zig/src/native/nemotron_trainer_test.zig +++ b/zig/src/native/nemotron_trainer_test.zig @@ -168,7 +168,7 @@ pub fn close(comptime Host: type, comptime serve: anytype, comptime closeHost: a defer backend.deinit(); const h = try a.create(Host); h.* = .{ .gpa = a, .gpu = null, .family = e, .release = F.family, .inner = backend.backend(), .vtable = undefined, .cfg = undefined, .clock = undefined, .core = undefined, .host = undefined }; - try serve(h, std.testing.io, .{ .exact_width = 8 }, 8, .{ .lanes = 1 }, null); + try serve(h, std.testing.io, .{ .exact_width = 8 }, 8, .{ .lanes = 1 }, null, 0); h.served = .{ .backend = backend.backend(), .facts = .{ .exact_width = 8 }, .stream_bytes = 0 }; h.slide = adapter; h.slide_free = struct { diff --git a/zig/src/native/qwen35.zig b/zig/src/native/qwen35.zig index d896988e90c..f2aaa8f1044 100644 --- a/zig/src/native/qwen35.zig +++ b/zig/src/native/qwen35.zig @@ -134,11 +134,11 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope h.cache = api.prompt_cache.Store.init(gpa, .{ .ptr = h.metal, .vtable = &.{ .bytes = S.bytes, .save = S.save, .restore = S.restore, .drop = S.drop }, - }, .{ .planned = true, .grid = chunk, .chunk = chunk }, plan.budget_bytes); + }, .{ .planned = true, .grid = chunk, .chunk = chunk, .warm_usable = true }, plan.budget_bytes); h.host.cache = &h.cache.?; - h.host.info_.prompt_cache = true; } } + h.host.advertiseCache(if (h.cache) |*store| store else null); errdefer if (h.cache) |*store| store.deinit(); try mtl.resident.streams.hold(h, io, "qwen3.5"); errdefer mtl.resident.streams.drop(h); diff --git a/zig/src/native/trainer_close_test.zig b/zig/src/native/trainer_close_test.zig index 1669e2cea12..bef242c14e9 100644 --- a/zig/src/native/trainer_close_test.zig +++ b/zig/src/native/trainer_close_test.zig @@ -145,7 +145,7 @@ pub fn close(comptime Host: type, comptime serve: anytype, comptime closeHost: a defer backend.deinit(); const h = try a.create(Host); h.* = .{ .gpa = a, .gpu = null, .family = e, .release = F.family, .inner = backend.backend(), .vtable = undefined, .cfg = undefined, .clock = undefined, .core = undefined, .host = undefined, .served = .{ .backend = backend.backend(), .facts = .{ .exact_width = 8 }, .stream_bytes = 0 } }; - try serve(h, std.testing.io, .{ .exact_width = 8 }, 8, .{ .lanes = 1 }, null); + try serve(h, std.testing.io, .{ .exact_width = 8 }, 8, .{ .lanes = 1 }, null, 0); adapter.learner.pockets.save_pending = true; const hook = adapter.hook(); try std.testing.expect(hook.step(hook.ctx).stale); diff --git a/zig/src/qwen35_cache_test.zig b/zig/src/qwen35_cache_test.zig index 2918c37fc06..2a23ab2ab4b 100644 --- a/zig/src/qwen35_cache_test.zig +++ b/zig/src/qwen35_cache_test.zig @@ -186,6 +186,7 @@ const Harness = struct { store: pc.Store = undefined, active: ?*st.Cache = null, cancel_at: ?usize = null, + yield_at: ?usize = null, fail_at: ?usize = null, fn init(h: *Harness) void { @@ -206,6 +207,10 @@ const Harness = struct { const h: *Harness = @ptrCast(@alignCast(ptr)); return if (h.cancel_at) |at| h.active.?.len >= at else false; } + fn waits(ptr: *anyopaque) bool { + const h: *Harness = @ptrCast(@alignCast(ptr)); + return if (h.yield_at) |at| h.active.?.len >= at else false; + } fn advance(h: *Harness, cache: *st.Cache, ids: []const u32) !void { if (h.fail_at) |at| if (cache.len >= at) return error.FakeForward; try step({}, cache, ids); @@ -213,7 +218,7 @@ const Harness = struct { fn pass(h: *Harness, cache: *st.Cache, ids: []const u32, cuts: []const u32) !u32 { const lookup = try h.store.lookup(a, ids, 128, &.{}, cuts, &.{}); defer a.free(lookup.marks); - var stream = try lanes.Stream.init(a, .{ .id = "fixture", .prompt = ids, .max_new = 8, .chunks = cuts, .cancel_check = .{ .ptr = h, .check = cancelled }, .reuse = .{ + var stream = try lanes.Stream.init(a, .{ .id = "fixture", .prompt = ids, .max_new = 8, .chunks = cuts, .cancel_check = .{ .ptr = h, .check = cancelled }, .yield_check = .{ .ptr = h, .check = waits }, .reuse = .{ .saved = if (lookup.entry) |entry| entry.saved else null, .at = if (lookup.entry) |entry| entry.at else 0, .marks = lookup.marks, @@ -289,6 +294,28 @@ test "Qwen retained: cancellation after restore preserves the valid prefix and a try t.expect(h.store.counts.failed > 0); } +test "Qwen retained: foreground work arriving after a chunk yields at the boundary and keeps the prefix" { + var allocations: mtl.Allocations = .{}; + const device: mtl.Device = .{ .allocations = &allocations }; + const ids = tokens(); + var h: Harness = .{}; + h.init(); + defer h.deinit(); + h.yield_at = 128; + var yielded = try st.Cache.init(a, device, 400); + defer yielded.deinit(); + seed(&yielded); + try t.expectError(error.Yielded, h.pass(&yielded, ids[0..300], &.{})); + try t.expectEqual(@as(usize, 128), yielded.len); // one chunk ran, not the whole prompt + + // The completed prefix is kept before the pass steps aside, so the next pass resumes at it. + h.yield_at = null; + var resumed = try st.Cache.init(a, device, 410); + defer resumed.deinit(); + seed(&resumed); + try t.expectEqual(@as(u32, 128), try h.pass(&resumed, &ids, &.{})); +} + test "Qwen retained: a failed chunk never captures its incomplete state" { var allocations: mtl.Allocations = .{}; const device: mtl.Device = .{ .allocations = &allocations }; diff --git a/zig/src/server/chat.zig b/zig/src/server/chat.zig index 1c0076d1845..b02f226fc13 100644 --- a/zig/src/server/chat.zig +++ b/zig/src/server/chat.zig @@ -16,7 +16,6 @@ const wait = @import("wait_reason.zig"); const refusals = @import("refusals.zig"); const server_mod = @import("server.zig"); const Server = server_mod.Server; -const chunk_plan = @import("chunk_plan.zig"); const Mailbox = @import("mailbox.zig").Mailbox; const StopHook = @import("stop_hook.zig").StopHook; const engine_refusal = @import("engine_refusal.zig"); @@ -200,7 +199,7 @@ pub fn prepare(srv: *Server, cx: *Cx, input: Input, gone: anytype) Failure!Prepa .user_end = @intCast(rendered.user_end), .shared_prefixes = shared.items, // a cut before the conversation's own text: fresh sessions resume their whole harness - .chunks = try chunk_plan.withCut(a, try srv.chunks.starts(a, rendered.ids), if (srv.chunks.step > 0) @intCast(@max(system_len, 1) - 1) else 0, rendered.ids.len, srv.chunks.min_chunk), + .chunks = try srv.chunks.request(a, rendered.ids, system_len), // from the tokens alone, for every request: cached states are keyed by tokens .decode_spans = try prompt_mod.replySpans(srv, cx, rendered.ids), .tools_json = if (input.tools.len > 0) try json.stringify(a, .{ .array = @constCast(input.tools) }, .{ .ascii = false }) else "", diff --git a/zig/src/server/chat_generation.zig b/zig/src/server/chat_generation.zig index 137db952be5..0671a613b62 100644 --- a/zig/src/server/chat_generation.zig +++ b/zig/src/server/chat_generation.zig @@ -279,8 +279,13 @@ pub const Generation = struct { const native = if (g.srv.text.vtable.format == .kimi) try @import("chat_kimi.zig").read(g, content_tokens, true) else null; const raw_visible = g.stops.visible(raw, false); const visible = if (native) |n| n.content else try @import("tool_minimax.zig").dsml(a, raw_visible, g.tools); + const close_at: ?reply_text.Close = if (native == null and g.thinking) + try @import("tool_minimax.zig").closeAfterRewrite(a, raw_visible, g.tools, try reply_text.closeWhere(a, reply_text.decodeText, g.srv.text, content_tokens, g.srv.close_id)) + else + null; + const call_tail = answerTail(visible, g.srv.markers, close_at); // closed before the think split, so a call ending an unclosed think block is the answer - const close = if (native != null) "" else try g.closeCall(visible); + const close = if (native != null) "" else try g.closeCall(call_tail); const text = if (close.len > 0) try std.mem.concat(a, u8, &.{ visible, close }) else visible; var content: []const u8 = text; var reasoning: ?[]const u8 = null; @@ -288,9 +293,7 @@ pub const Generation = struct { const r = reply_text.pyStrip(n.reasoning); reasoning = if (r.len > 0) r else null; } else if (g.thinking) { - const original_close = try reply_text.closeWhere(a, reply_text.decodeText, g.srv.text, content_tokens, g.srv.close_id); - const close_at = try @import("tool_minimax.zig").closeAfterRewrite(a, raw_visible, g.tools, original_close); - const split = try reply_text.splitThinkingAt(a, text, true, g.srv.markers, close_at); + const split = try reply_text.splitThinkingAt(a, text, true, g.srv.markers, close_at.?); const r = reply_text.pyStrip(split.reasoning); reasoning = if (r.len > 0) r else null; content = split.answer; @@ -308,12 +311,17 @@ pub const Generation = struct { const sent = g.streamed.text.items; const rest = if (std.mem.startsWith(u8, shown, sent) and shown.len > sent.len) shown[sent.len..] else ""; if (rest.len > 0) try g.emit(sink, .{ .string = rest }); - if (g.calls) |*c| if (close.len > 0 or std.mem.eql(u8, reason, "length")) { + if (g.calls) |*c| { // the streamer reads the closers as markup the model wrote, so the call ends with the same deltas var out: std.ArrayList(Value) = .empty; - try c.finishCut(if (g.thinking) content else text, &out); // a cut value sends its held bytes + const final_text = if (g.thinking) content else text; + if (std.mem.eql(u8, reason, "length")) { + try c.finishCut(final_text, &out); + } else if (close.len > 0 or c.streamed) { + try c.finish(final_text, &out); + } for (out.items) |d| try g.emit(sink, d); - }; + } } const prefilled = m.prefilled_ns; const decode_s: f64 = if (prefilled) |p| @max(0, seconds(finished_ns - p)) else 0; @@ -401,3 +409,21 @@ pub const Generation = struct { return reply; } }; + +/// Answer suffix after a confirmed thinking close, so unclosed fences inside thinking do not block closeCall. +fn answerTail(visible: []const u8, m: reply_text.Markers, close_at: ?reply_text.Close) []const u8 { + const close = close_at orelse return visible; + if (m.open.len > 0 and reply_text.findTag(visible, 0, m.open) == null) return visible; + const at = switch (close) { + .token => |v| v, + .pending => return visible, + .spelled => blk: { + const start = if (m.open.len > 0) reply_text.findTag(visible, 0, m.open).? else 0; + break :blk reply_text.findTag(visible, start, m.close) orelse return visible; + }, + }; + if (at + m.close.len <= visible.len and std.mem.startsWith(u8, visible[at..], m.close)) { + return visible[at + m.close.len ..]; + } + return visible; +} diff --git a/zig/src/server/chunk_plan.zig b/zig/src/server/chunk_plan.zig index bf3fdf0672f..930fbb62db7 100644 --- a/zig/src/server/chunk_plan.zig +++ b/zig/src/server/chunk_plan.zig @@ -52,6 +52,11 @@ pub const Plan = struct { last = next; } } + + /// The starts of a request over `ids`: `starts` with the system prompt's cut, so a warm pass and a turn agree. + pub fn request(p: Plan, a: Allocator, ids: []const u32, system_len: usize) ![]const u32 { + return withCut(a, try p.starts(a, ids), if (p.step > 0) @intCast(@max(system_len, 1) - 1) else 0, ids.len, p.min_chunk); + } }; /// `starts` with `cut` too: a state kept just before a conversation's own text reads only shared tokens. @@ -154,6 +159,24 @@ test "a harness cut joins the starts, nearer ones go" { try std.testing.expectEqualSlices(u32, &.{ 600, 4096 }, try withCut(a, &.{4096}, 600, 4680, 256)); } +test "a warm pass and the next request cut the same starts below the warm end" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const p: Plan = .{ .step = 4096, .min_chunk = 1 }; + const next = try a.alloc(u32, 4700); // the next turn's prompt; a warm pass covered its first 4680 tokens + @memset(next, 0); + const warm = next[0..4680]; + const system_len: usize = 600; + const w = try p.request(a, warm, system_len); + const n = try p.request(a, next, system_len); + try std.testing.expect(std.mem.indexOfScalar(u32, w, 599) != null); // the warm pass cuts before the conversation's own text + var shared: usize = 0; + while (shared < n.len and n[shared] < warm.len) shared += 1; // the next turn's starts the warm pass could serve + try std.testing.expectEqualSlices(u32, w, n[0..shared]); + try std.testing.expect(std.mem.indexOfScalar(u32, try p.starts(a, warm), 599) == null); // starts alone keep no such cut +} + test "chunk starts match PrefillPlan.chunks" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); diff --git a/zig/src/server/logprob_parts.zig b/zig/src/server/logprob_parts.zig index 4aa8feaa3b7..3863113d9a8 100644 --- a/zig/src/server/logprob_parts.zig +++ b/zig/src/server/logprob_parts.zig @@ -256,10 +256,16 @@ fn toolRanges(a: A, answer: []const u8, tools: []const V, count: usize, offset_a try envelopes.appendSlice(a, try tp.envelopes(a, answer)); const lfm = rt.calls[3]; var pos: usize = 0; + var code: @import("reply_code.zig").Scanner = .{}; while (std.mem.indexOfPos(u8, answer, pos, lfm[0])) |at| { + if (code.check(answer, at, true) == .skip) { + pos = code.skip_end; + continue; + } const end = if (std.mem.indexOfPos(u8, answer, at + lfm[0].len, lfm[1])) |e| e + lfm[1].len else answer.len; try envelopes.append(a, .{ .start = at, .end = end, .payload = answer[at..end] }); pos = end; + code.jumpTo(pos); } if (tp.openCall(answer)) |at| try envelopes.append(a, .{ .start = at, .end = answer.len, .payload = answer[at..] }); std.mem.sort(tp.Envelope, envelopes.items, {}, struct { diff --git a/zig/src/server/reply_code.zig b/zig/src/server/reply_code.zig new file mode 100644 index 00000000000..8eb600921ea --- /dev/null +++ b/zig/src/server/reply_code.zig @@ -0,0 +1,315 @@ +//! Linear-time Markdown inline code-span and fenced code-block scanner so quoted call markup stays prose. +const std = @import("std"); + +pub const Status = union(enum) { + outside, + skip: usize, + pending, +}; + +const LineEnd = enum { yes, no, wait }; + +pub const Scanner = struct { + pos: usize = 0, + skip_end: usize = 0, + open_kind: enum { none, fence_line, fence_body, inline_span } = .none, + open_at: usize = 0, + open_ch: u8 = 0, + open_len: usize = 0, + open_scan: usize = 0, + once: u128 = 0, + twice: u128 = 0, + long_runs: usize = 0, + dead_until: usize = 0, + dead_runs: u128 = 0, + dead_long: bool = false, + + /// Advances past an already consumed envelope so markup inside tool arguments is not scanned as Markdown. + pub fn jumpTo(c: *Scanner, pos: usize) void { + if (c.pos < pos or c.open_kind != .none) c.* = .{ .pos = pos, .skip_end = pos }; + } + + /// Classifies `at` in `text` against preceding Markdown code spans and fences; monotone `at` stays O(N). + pub fn check(c: *Scanner, text: []const u8, at: usize, finished: bool) Status { + if (at >= text.len) return .outside; + if (at < c.skip_end) c.* = .{}; + if (c.open_kind == .none and at < c.pos) return .outside; + if (c.open_kind != .none and at < c.open_at) return .outside; + if (c.open_kind != .none) if (c.resumeOpen(text, at, finished)) |st| return st; + while (c.pos <= at) { + const i = std.mem.indexOfAnyPos(u8, text[0 .. at + 1], c.pos, "`~") orelse { + c.pos = at + 1; + return .outside; + }; + c.pos = i; + const ch = text[i]; + const e = runEnd(text, i, ch); + const n = e - i; + if (ch == '~') { + if (!atFenceStart(text, i)) { + c.pos = e; + continue; + } + if (e == text.len and !finished and n < 3) return .pending; + if (n < 3) { + c.pos = e; + continue; + } + c.open_kind = .fence_line; + } else { + if (e == text.len and !finished) return .pending; + if (e == text.len) { + c.pos = e; + continue; + } + if (n >= 3 and atFenceStart(text, i)) { + c.open_kind = .fence_line; + } else { + if (i < c.dead_until and c.isDead(n)) { + c.pos = e; + continue; + } + c.open_kind = .inline_span; + c.once = 0; + c.twice = 0; + c.long_runs = 0; + } + } + c.open_at = i; + c.open_ch = ch; + c.open_len = n; + c.open_scan = e; + if (c.resumeOpen(text, at, finished)) |st| return st; + } + return .outside; + } + + fn resumeOpen(c: *Scanner, text: []const u8, at: usize, finished: bool) ?Status { + if (c.open_kind == .fence_line) { + const needles: []const u8 = if (c.open_ch == '`') "\n`" else "\n"; + if (std.mem.indexOfAnyPos(u8, text, c.open_scan, needles)) |hit| { + if (text[hit] == '`') { + c.open_kind = .inline_span; + c.open_scan = hit; + c.once = 0; + c.twice = 0; + c.long_runs = 0; + } else { + c.open_kind = .fence_body; + c.open_scan = hit + 1; + } + } else { + if (finished) { + c.open_kind = .none; + c.pos = c.open_at + c.open_len; + return null; + } + c.open_scan = text.len; + return .pending; + } + } + if (c.open_kind == .fence_body) return c.resumeFenceBody(text, at, finished); + return c.resumeInline(text, at, finished); + } + + fn resumeFenceBody(c: *Scanner, text: []const u8, at: usize, finished: bool) ?Status { + var line = c.open_scan; + while (true) { + c.open_scan = line; + if (line == text.len) { + if (!finished) return .{ .skip = text.len }; + c.open_kind = .none; + c.pos = text.len; + c.skip_end = text.len; + return .{ .skip = text.len }; + } + var q = line; + var sp: usize = 0; + while (sp < 4 and q < text.len and text[q] == ' ') : ({ + q += 1; + sp += 1; + }) {} + if (sp <= 3 and q < text.len and text[q] == c.open_ch) { + const r = runEnd(text, q, c.open_ch); + if (r - q >= c.open_len) { + var k = r; + while (k < text.len and (text[k] == ' ' or text[k] == '\t' or text[k] == '\r')) k += 1; + if (k < text.len and text[k] == '\n') { + const end = k + 1; + c.open_kind = .none; + c.pos = end; + c.skip_end = end; + return if (at < end) .{ .skip = end } else null; + } + if (k == text.len) { + if (!finished) return .{ .skip = text.len }; + c.open_kind = .none; + c.pos = text.len; + c.skip_end = text.len; + return .{ .skip = text.len }; + } + } + } + if (std.mem.indexOfScalarPos(u8, text, line, '\n')) |nl| { + line = nl + 1; + continue; + } + if (!finished) return .{ .skip = text.len }; + c.open_kind = .none; + c.pos = text.len; + c.skip_end = text.len; + return .{ .skip = text.len }; + } + } + + fn resumeInline(c: *Scanner, text: []const u8, at: usize, finished: bool) ?Status { + var p = c.open_scan; + while (std.mem.indexOfAnyPos(u8, text, p, "\n`")) |hit| { + if (text[hit] == '\n') { + switch (nlEndsParagraph(text, hit, finished)) { + .yes => { + c.markDead(hit); + c.open_kind = .none; + c.pos = c.open_at + c.open_len; + return null; + }, + .wait => { + c.open_scan = hit; + return .pending; + }, + .no => { + p = hit + 1; + continue; + }, + } + } + const je = runEnd(text, hit, '`'); + if (!finished and je == text.len) { + c.open_scan = hit; + return .pending; + } + const m = je - hit; + if (m == c.open_len) { + c.open_kind = .none; + c.pos = je; + c.skip_end = je; + return if (at < je) .{ .skip = je } else null; + } + c.recordRun(m); + p = je; + } + if (finished) { + c.markDead(text.len); + c.open_kind = .none; + c.pos = c.open_at + c.open_len; + return null; + } + c.open_scan = text.len; + return .pending; + } + + fn recordRun(c: *Scanner, n: usize) void { + if (n < 128) { + const bit = @as(u128, 1) << @intCast(n); + if ((c.once & bit) != 0) c.twice |= bit; + c.once |= bit; + } else c.long_runs +|= 1; + } + + fn markDead(c: *Scanner, until: usize) void { + c.dead_until = until; + c.dead_runs = ~c.twice; + c.dead_long = c.long_runs < 2; + } + + fn isDead(c: *const Scanner, n: usize) bool { + if (n < 128) return (c.dead_runs & (@as(u128, 1) << @intCast(n))) != 0; + return c.dead_long; + } +}; + +fn runEnd(text: []const u8, from: usize, ch: u8) usize { + var i = from + 1; + while (i < text.len and text[i] == ch) i += 1; + return i; +} + +fn atFenceStart(text: []const u8, i: usize) bool { + var s: usize = 0; + while (s < 4 and i > s and text[i - 1 - s] == ' ') s += 1; + return s <= 3 and (i == s or text[i - 1 - s] == '\n'); +} + +fn nlEndsParagraph(text: []const u8, nl: usize, finished: bool) LineEnd { + var q = nl + 1; + while (q < text.len and (text[q] == ' ' or text[q] == '\t' or text[q] == '\r')) q += 1; + if (q == text.len) return if (finished) .no else .wait; + if (text[q] == '\n') return .yes; + var s = nl + 1; + var sp: usize = 0; + while (sp < 4 and s < text.len and text[s] == ' ') : ({ + s += 1; + sp += 1; + }) {} + if (sp <= 3 and s < text.len and (text[s] == '`' or text[s] == '~')) { + const ch = text[s]; + const e = runEnd(text, s, ch); + if (!finished and e == text.len and e - s < 3) return .wait; + if (e - s >= 3) { + var u = e; + while (u < text.len) : (u += 1) { + if (ch == '`' and text[u] == '`') return .no; + if (text[u] == '\n') return .yes; + } + return if (finished) .no else .wait; + } + } + return .no; +} + +test "reply code scanner agrees between one-pass finished and incremental streaming queries" { + var prng: std.Random.DefaultPrng = .init(0x5eedc0de); + const r = prng.random(); + const parts = [_][]const u8{ "`", "``", "```", "~~~", "<", "x", " ", "\n", "\n\n", "a buf.len) break; + @memcpy(buf[len..][0..p.len], p); + len += p.len; + } + const text = buf[0..len]; + var whole_sc: Scanner = .{}; + var stream_sc: Scanner = .{}; + for (0..text.len) |i| { + const ch = text[i]; + if (ch == '`' or ch == '~') continue; + var resolved = false; + var n = i + 1; + while (n <= text.len) : (n += 1) { + const st = stream_sc.check(text[0..n], i, false); + if (st != .pending) { + const whole = whole_sc.check(text, i, true); + switch (st) { + .outside => try std.testing.expectEqual(Status.outside, whole), + .skip => |s| switch (whole) { + .skip => |w| try std.testing.expect(s <= w), + else => return error.TestUnexpectedResult, + }, + .pending => unreachable, + } + resolved = true; + break; + } + } + if (!resolved) { + const st = stream_sc.check(text, i, true); + const whole = whole_sc.check(text, i, true); + try std.testing.expectEqual(whole, st); + } + } + } +} diff --git a/zig/src/server/reply_text.zig b/zig/src/server/reply_text.zig index 6f942d1e4a3..bba2c60a13e 100644 --- a/zig/src/server/reply_text.zig +++ b/zig/src/server/reply_text.zig @@ -201,14 +201,16 @@ pub fn hideToolCalls(a: Allocator, text: []const u8, finished: bool) Allocator.E pub fn hideInto(a: Allocator, out: *std.ArrayList(u8), text: []const u8, finished: bool, defer_closed: bool, o: Openers) Allocator.Error![]const u8 { out.clearRetainingCapacity(); var pos: usize = 0; - var next_buf: [mm_calls.len]?usize = undefined; // each opener at or after `pos`, searched again only once `pos` passes it + var search: usize = 0; + var code: @import("reply_code.zig").Scanner = .{}; + var next_buf: [mm_calls.len]?usize = undefined; // each opener at or after `search`, re-searched when passed const next = next_buf[0..o.calls.len]; for (o.calls, next) |c, *n| n.* = findTag(text, 0, c[0]); while (true) { var start: ?usize = null; var which: usize = 0; for (o.calls, next, 0..) |c, *n, i| { - if (n.* != null and n.*.? < pos) n.* = findTag(text, pos, c[0]); + if (n.* != null and n.*.? < search) n.* = findTag(text, search, c[0]); if (n.*) |at| if (start == null or at < start.?) { start = at; which = i; @@ -217,24 +219,33 @@ pub fn hideInto(a: Allocator, out: *std.ArrayList(u8), text: []const u8, finishe if (start == null) { const tail = text[pos..]; var held: usize = 0; - if (!finished) for (o.calls) |c| { - held = @max(held, partialTag(tail, c[0])); - }; + if (!finished) { + const scan = text[@min(text.len, @max(pos, search))..]; + for (o.calls) |c| held = @max(held, partialTag(scan, c[0])); + } if (pos == 0) return text[0 .. text.len - held]; try out.appendSlice(a, tail[0 .. tail.len - held]); return out.items; } - try out.appendSlice(a, text[pos..start.?]); + const st = code.check(text, start.?, finished); + if (st == .skip) { + search = st.skip; + continue; + } const after = start.? + o.calls[which][0].len; - switch (payloadOf(text[after..], o, which, finished)) { + switch (if (st == .pending) .wait else payloadOf(text[after..], o, which, finished)) { .call => {}, - .wait => return out.items, + .wait => { + if (pos == 0) return text[0..start.?]; + try out.appendSlice(a, text[pos..start.?]); + return out.items; + }, .prose => { - try out.appendSlice(a, text[start.?..after]); - pos = after; + search = after; continue; }, } + try out.appendSlice(a, text[pos..start.?]); const end = findTag(text, after, o.calls[which][1]) orelse { // a finished reply's envelope that never closed is text, as tool_parse.parse keeps it in the content if (finished) try out.appendSlice(a, text[start.?..]); @@ -243,6 +254,8 @@ pub fn hideInto(a: Allocator, out: *std.ArrayList(u8), text: []const u8, finishe // Final parsing may retain this envelope, so later prose must not overtake it. if (defer_closed) return out.items; pos = end + o.calls[which][1].len; + search = pos; + code.jumpTo(pos); } } diff --git a/zig/src/server/reply_tool_tail.zig b/zig/src/server/reply_tool_tail.zig index 8e36a9ee95d..6151e9230ab 100644 --- a/zig/src/server/reply_tool_tail.zig +++ b/zig/src/server/reply_tool_tail.zig @@ -1,9 +1,11 @@ //! The first byte of a suffix made only of whole call envelopes and whitespace. const reply = @import("reply_text.zig"); +const reply_code = @import("reply_code.zig"); pub fn start(text: []const u8, openers: reply.Openers) ?usize { var pos: usize = 0; var tail: ?usize = null; + var code: reply_code.Scanner = .{}; while (true) { var next: ?usize = null; var which: usize = 0; @@ -14,6 +16,11 @@ pub fn start(text: []const u8, openers: reply.Openers) ?usize { } }; const at = next orelse return if (reply.pyStrip(text[pos..]).len == 0) tail else null; + if (code.check(text, at, true) == .skip) { + tail = null; + pos = code.skip_end; + continue; + } const tags = openers.calls[which]; const payload = at + tags[0].len; if (reply.payloadOf(text[payload..], openers, which, true) != .call) { @@ -24,5 +31,6 @@ pub fn start(text: []const u8, openers: reply.Openers) ?usize { const end = reply.findTag(text, payload, tags[1]) orelse return null; if (tail == null or reply.pyStrip(text[pos..at]).len > 0) tail = at; pos = end + tags[1].len; + code.jumpTo(pos); } } diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index 7c53e262325..adbb6398ec6 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -57,6 +57,7 @@ test { _ = @import("json"); _ = @import("std_options.zig"); _ = @import("fields.zig"); + _ = @import("reply_code.zig"); _ = @import("reply_text.zig"); _ = @import("reply_incremental_test.zig"); _ = @import("tool_parse.zig"); @@ -158,6 +159,7 @@ test { _ = @import("thinking_reserve_test.zig"); _ = @import("loop_stop_test.zig"); _ = @import("late_system_test.zig"); + _ = @import("tool_prose_code_http_test.zig"); _ = @import("compact.zig"); _ = @import("compact_test.zig"); _ = @import("private_files_test.zig"); diff --git a/zig/src/server/tool_lfm2.zig b/zig/src/server/tool_lfm2.zig index 9ca68a902af..7e99ff068ea 100644 --- a/zig/src/server/tool_lfm2.zig +++ b/zig/src/server/tool_lfm2.zig @@ -21,7 +21,19 @@ pub fn dsml(a: Allocator, text: []const u8, tools: []const Value, finished: bool var pos: usize = 0; var end = text.len; var rewrote = false; + var code: @import("reply_code.zig").Scanner = .{}; while (true) { + switch (code.check(text, at, finished)) { + .skip => |to| { + at = reply_text.findTag(text, to, open) orelse break; + continue; + }, + .pending => { + end = at; + break; + }, + .outside => {}, + } const e = reply_text.findTag(text, at + open.len, close) orelse { if (!finished) { // the stream's parser resumes where it stopped: it must meet the calls so far as DSML end = at; @@ -42,6 +54,7 @@ pub fn dsml(a: Allocator, text: []const u8, tools: []const Value, finished: bool pos = e + close.len; rewrote = true; } + code.jumpTo(e + close.len); at = reply_text.findTag(text, e + close.len, open) orelse break; } if (!rewrote) return text[0..end]; diff --git a/zig/src/server/tool_parse.zig b/zig/src/server/tool_parse.zig index 6d1252dc61f..0ec7795e7fb 100644 --- a/zig/src/server/tool_parse.zig +++ b/zig/src/server/tool_parse.zig @@ -2,6 +2,7 @@ const std = @import("std"); const json = @import("json"); const ids = @import("ids.zig"); +const reply_code = @import("reply_code.zig"); const reply_text = @import("reply_text.zig"); const tool_closers = @import("tool_closers.zig"); const tool_dsml = @import("tool_dsml.zig"); @@ -53,55 +54,49 @@ fn allSpace(s: []const u8) bool { /// (start, end, payload) of each tool-call block in order; a block inside an earlier one is part of it. pub fn envelopes(a: Allocator, text: []const u8) Allocator.Error![]Envelope { - var found: std.ArrayList(Envelope) = .empty; + var kept: std.ArrayList(Envelope) = .empty; var pos: usize = 0; - var dsml = tool_dsml.findOpen(text, 0); // the DSML opener at or after `pos`, searched again only once `pos` passes it - while (findCI(text, "", pos)) |s| { - if (dsml != null and dsml.?.at < pos) dsml = tool_dsml.findOpen(text, pos); - if (dsml) |outer| if (outer.at < s) { - pos = tool_dsml.blockEnd(text, outer) orelse break; - continue; - }; - const e = findCI(text, "", s + 11) orelse break; - try found.append(a, .{ .start = s, .end = e + 12, .payload = strip(text[s + 11 .. e]) }); - pos = e + 12; - } - pos = 0; + var code: reply_code.Scanner = .{}; var closers: tool_closers.Closers = .{ .text = text }; + var no_tc = false; + var no_gemma = false; while (std.mem.indexOfScalarPos(u8, text, pos, '<')) |s| { - pos = s + 1; - var j = s + 1; - if (j >= text.len or !(std.ascii.isAlphabetic(text[j]) or text[j] == '_')) continue; - j += 1; - while (j < text.len and tool_closers.nameByte(text[j])) j += 1; - if (!std.ascii.startsWithIgnoreCase(text[j..], ":tool_call>")) continue; - const e = (try closers.next(a, text[s + 1 .. j], j + 11)) orelse continue; - const end = e + j - s + 12; // ```` - try found.append(a, .{ .start = s, .end = end, .payload = strip(text[j + 11 .. e]) }); - pos = end; - } - pos = 0; - while (find(text, "<|tool_call>", pos)) |s| { - const e = find(text, "", s + 12) orelse break; - try found.append(a, .{ .start = s, .end = e + 12, .payload = strip(text[s + 12 .. e]) }); - pos = e + 12; - } - pos = 0; - while (tool_dsml.findOpen(text, pos)) |o| { - const e = tool_dsml.blockEnd(text, o); - const end = e orelse text.len; - try found.append(a, .{ .start = o.at, .end = end, .payload = text[o.at..end], .complete = e != null }); - pos = end; - } - std.mem.sort(Envelope, found.items, {}, struct { - fn less(_: void, x: Envelope, y: Envelope) bool { - if (x.start != y.start) return x.start < y.start; - if (x.end != y.end) return x.end < y.end; - return std.mem.order(u8, x.payload, y.payload) == .lt; + if (code.check(text, s, true) == .skip) { + pos = code.skip_end; + continue; } - }.less); - var kept: std.ArrayList(Envelope) = .empty; - for (found.items) |env| if (kept.items.len == 0 or env.start >= kept.items[kept.items.len - 1].end) try kept.append(a, env); + const env: ?Envelope = blk: { + if (tool_dsml.openedBy(text[s..])) |sp| { + const e = tool_dsml.blockEnd(text, .{ .at = s, .spelling = sp }); + const end = e orelse text.len; + break :blk .{ .start = s, .end = end, .payload = text[s..end], .complete = e != null }; + } + if (!no_tc and std.ascii.startsWithIgnoreCase(text[s..], "")) { + if (findCI(text, "", s + 11)) |e| { + break :blk .{ .start = s, .end = e + 12, .payload = strip(text[s + 11 .. e]) }; + } + no_tc = true; + } + if (!no_gemma and std.mem.startsWith(u8, text[s..], "<|tool_call>")) { + if (find(text, "", s + 12)) |e| { + break :blk .{ .start = s, .end = e + 12, .payload = strip(text[s + 12 .. e]) }; + } + no_gemma = true; + } + var j = s + 1; + if (j >= text.len or !(std.ascii.isAlphabetic(text[j]) or text[j] == '_')) break :blk null; + j += 1; + while (j < text.len and tool_closers.nameByte(text[j])) j += 1; + if (!std.ascii.startsWithIgnoreCase(text[j..], ":tool_call>")) break :blk null; + const e = (try closers.next(a, text[s + 1 .. j], j + 11)) orelse break :blk null; + break :blk .{ .start = s, .end = e + j - s + 12, .payload = strip(text[j + 11 .. e]) }; + }; + if (env) |item| { + try kept.append(a, item); + pos = item.end; + code.jumpTo(pos); + } else pos = s + 1; + } return kept.items; } @@ -205,14 +200,25 @@ pub fn closeCall(a: Allocator, text: []const u8, tools: []const Value) Allocator /// Where the reply's open call starts: the opener ``envelopes`` leaves without a closer, so one appended pairs with it. pub fn openCall(text: []const u8) ?usize { var pos: usize = 0; + var code: reply_code.Scanner = .{}; var dsml = tool_dsml.findOpen(text, 0); // as in ``envelopes`` return while (findCI(text, "", pos)) |s| { if (dsml != null and dsml.?.at < pos) dsml = tool_dsml.findOpen(text, pos); if (dsml) |outer| if (outer.at < s) { + if (code.check(text, outer.at, true) == .skip) { + pos = code.skip_end; + continue; + } pos = tool_dsml.blockEnd(text, outer) orelse return null; + code.jumpTo(pos); continue; }; + if (code.check(text, s, true) == .skip) { + pos = code.skip_end; + continue; + } pos = (findCI(text, "", s + 11) orelse break s) + 12; + code.jumpTo(pos); } else null; } diff --git a/zig/src/server/tool_parse_visibility_test.zig b/zig/src/server/tool_parse_visibility_test.zig index 40e8da2c90e..b54fe08c275 100644 --- a/zig/src/server/tool_parse_visibility_test.zig +++ b/zig/src/server/tool_parse_visibility_test.zig @@ -1,7 +1,35 @@ //! Rejected tool envelopes stay visible without consuming the accepted-call limit. const std = @import("std"); const json = @import("json"); -const parse = @import("tool_parse.zig").parse; +const tp = @import("tool_parse.zig"); +const rc = @import("reply_code.zig"); +const rt = @import("reply_text.zig"); + +test { + _ = rc; +} +const tail_mod = @import("reply_tool_tail.zig"); +const lfm2 = @import("tool_lfm2.zig"); +const stream = @import("tool_stream.zig"); +const parse = tp.parse; + +fn testTools(a: std.mem.Allocator) ![]const json.Value { + return (try json.parse(a, "[{\"type\":\"function\",\"function\":{\"name\":\"lookup\"}}]")).ok.array; +} + +fn streamedArgs(a: std.mem.Allocator, tools: []const json.Value, text: []const u8, split: usize) !struct { headers: usize, args: []const u8 } { + var s = try stream.Streamer.init(a, tools); + var out: std.ArrayList(json.Value) = .empty; + try s.feed(text[0..split], &out); + try s.finishCut(text, &out); + var headers: usize = 0; + var args: std.ArrayList(u8) = .empty; + for (out.items) |delta| for (delta.get("tool_calls").?.array) |one| { + if (one.get("id") != null) headers += 1; + if (one.get("function").?.strField("arguments")) |part| try args.appendSlice(a, part); + }; + return .{ .headers = headers, .args = args.items }; +} test "tool visibility: a first unoffered call remains content in single-call mode" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); @@ -34,3 +62,122 @@ test "tool visibility: rejected text does not consume a valid call and the secon try std.testing.expectEqual(@as(usize, 1), result.calls.?.len); try std.testing.expectEqualStrings("execute", result.calls.?[0].get("function").?.get("name").?.string); } + +test "quoted openers in inline code or fenced blocks do not swallow a following call" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const tools = try testTools(a); + const call = "lookupqok"; + const cases = [_]struct { reply: []const u8, content: []const u8 }{ + .{ .reply = "Raw `` markup before call.\n" ++ call, .content = "Raw `` markup before call." }, + .{ .reply = "Doubled `` `` `` markup.\n" ++ call, .content = "Doubled `` `` `` markup." }, + .{ .reply = "Fenced:\n```xml\n\n```\n" ++ call, .content = "Fenced:\n```xml\n\n```" }, + .{ .reply = "Tilde:\n~~~\n<|tool_call>call:lookup{}\n~~~\n" ++ call, .content = "Tilde:\n~~~\n<|tool_call>call:lookup{}\n~~~" }, + .{ .reply = "Note `<|DSML|tool_calls><|DSML|invoke name=\"lookup\">` first.\n" ++ call, .content = "Note `<|DSML|tool_calls><|DSML|invoke name=\"lookup\">` first." }, + }; + for (cases) |c| { + const res = try parse(a, c.reply, tools, null); + try std.testing.expectEqual(@as(usize, 0), res.rejected_envelopes); + try std.testing.expectEqualStrings(c.content, res.content); + try std.testing.expectEqual(@as(usize, 1), res.calls.?.len); + try std.testing.expectEqualStrings("{\"q\":\"ok\"}", res.calls.?[0].get("function").?.get("arguments").?.string); + } + // An unclosed fence inside a real call's value stays part of that call and must not suppress the next call. + const nested = "lookupq```md\n\n\n" ++ call; + const nested_res = try parse(a, nested, tools, null); + try std.testing.expectEqual(@as(usize, 2), nested_res.calls.?.len); + try std.testing.expectEqualStrings("{\"q\":\"```md\\n\\n\"}", nested_res.calls.?[0].get("function").?.get("arguments").?.string); + try std.testing.expectEqualStrings("{\"q\":\"ok\"}", nested_res.calls.?[1].get("function").?.get("arguments").?.string); + const cut = "Raw `` and `<|DSML|tool_calls>` before:\nlookupqok"; + try std.testing.expectEqualStrings("", try tp.closeCall(a, cut, tools)); + const quoted_lfm = "Note `<|tool_call_start|>[lookup(q=\"x\")]<|tool_call_end|>` prose."; + try std.testing.expectEqualStrings(quoted_lfm, try lfm2.dsml(a, quoted_lfm, tools, true)); +} + +test "streamed quoted GLM opener naming an offered tool stays prose at every byte boundary" { + const text = "The tag `lookupbad` broke; running:\n" ++ + "lookupqok"; + const want_prose = "The tag `lookupbad` broke; running:\n"; + var outer = std.heap.ArenaAllocator.init(std.testing.allocator); + defer outer.deinit(); + const whole = try rt.hideToolCalls(outer.allocator(), text, true); + try std.testing.expectEqualStrings(want_prose, whole); + for (0..text.len + 1) |b| { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const tools = try testTools(a); + const partial = try rt.hideToolCalls(a, text[0..b], false); + try std.testing.expect(std.mem.startsWith(u8, whole, partial)); + const got = try streamedArgs(a, tools, text, b); + try std.testing.expectEqual(@as(usize, 1), got.headers); + try std.testing.expectEqualStrings("{\"q\":\"ok\"}", got.args); + } +} + +test "complete calls inside inline code or fenced blocks stay prose whole and streamed" { + const cases = [_][]const u8{ + "Use `lookupqx` here.", + "Example:\n```xml\nlookupqx\n```\nDone.", + "Example:\n~~~\n{\"name\":\"lookup\",\"arguments\":{\"q\":\"x\"}}\n~~~", + "Gemma form: `<|tool_call>call:lookup{q:<|\"|>x<|\"|>}`.", + "LFM form: `<|tool_call_start|>[lookup(q=\"x\")]<|tool_call_end|>`.", + }; + const single: stream.Policy = .{ .single = true }; + for (cases) |text| { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const tools = try testTools(a); + const res = try parse(a, text, tools, null); + try std.testing.expect(res.calls == null); + try std.testing.expectEqual(@as(usize, 0), res.rejected_envelopes); + try std.testing.expectEqualStrings(text, res.content); + try std.testing.expectEqualStrings(text, try rt.hideToolCalls(a, text, true)); + try std.testing.expectEqualStrings(text, try rt.finishedProse(a, text)); + try std.testing.expectEqualStrings(text, try single.parsedContent(a, text)); + for (0..text.len + 1) |b| { + const partial = try rt.hideToolCalls(a, text[0..b], false); + try std.testing.expect(std.mem.startsWith(u8, text, partial)); + } + } + const tail = "Thought.\n```xml\nlookupqx\n```"; + try std.testing.expect(tail_mod.start(tail, rt.shared_openers) == null); +} + +test "single-call TextFilter keeps unclosed quoted openers and stray backtick does not block later call" { + const prose = "Prose quotes `` and `` and `` and keeps going."; + var outer = std.heap.ArenaAllocator.init(std.testing.allocator); + defer outer.deinit(); + const oa = outer.allocator(); + var f: stream.TextFilter = .{}; + var joined: std.ArrayList(u8) = .empty; + for (0..prose.len) |i| try joined.appendSlice(oa, try f.feed(oa, prose[i .. i + 1])); + try joined.appendSlice(oa, f.finish()); + try std.testing.expectEqualStrings(prose, joined.items); + const single: stream.Policy = .{ .single = true }; + try std.testing.expectEqualStrings(prose, try single.parsedContent(oa, prose)); + const stray_cases = [_]struct { reply: []const u8, prose: []const u8 }{ + .{ .reply = "Format is `lookupqok", .prose = "Format is `" }, + .{ .reply = "Format is `\n\nlookupqok", .prose = "Format is `\n\n" }, + }; + for (stray_cases) |c| { + const tools = try testTools(oa); + const res = try parse(oa, c.reply, tools, null); + try std.testing.expectEqual(@as(usize, 1), res.calls.?.len); + try std.testing.expectEqualStrings(std.mem.trimEnd(u8, c.prose, "\n"), res.content); + try std.testing.expectEqualStrings(c.prose, try rt.hideToolCalls(oa, c.reply, true)); + for (0..c.reply.len + 1) |b| { + var run = std.heap.ArenaAllocator.init(std.testing.allocator); + defer run.deinit(); + const ra = run.allocator(); + const rtools = try testTools(ra); + const partial = try rt.hideToolCalls(ra, c.reply[0..b], false); + try std.testing.expect(std.mem.startsWith(u8, c.prose, partial)); + const got = try streamedArgs(ra, rtools, c.reply, b); + try std.testing.expectEqual(@as(usize, 1), got.headers); + try std.testing.expectEqualStrings("{\"q\":\"ok\"}", got.args); + } + } +} diff --git a/zig/src/server/tool_policy.zig b/zig/src/server/tool_policy.zig new file mode 100644 index 00000000000..774cbc2569a --- /dev/null +++ b/zig/src/server/tool_policy.zig @@ -0,0 +1,181 @@ +//! Single-call tool policy and streamed prose tag filter (parallel_tool_calls: false). +const std = @import("std"); +const reply_code = @import("reply_code.zig"); +const reply_text = @import("reply_text.zig"); +const Allocator = std.mem.Allocator; + +fn nameLike(s: []const u8) bool { + if (s.len == 0 or !(std.ascii.isAlphabetic(s[0]) or s[0] == '_')) return false; + for (s[1..]) |ch| if (!(std.ascii.isAlphanumeric(ch) or ch == '_' or ch == '.' or ch == '-' or ch >= 0x80)) return false; + return true; +} + +/// ``(?:NAME:)?tool_call``, any case. +pub fn callTag(name: []const u8) bool { + if (std.ascii.eqlIgnoreCase(name, "tool_call")) return true; + const colon = std.mem.indexOfScalar(u8, name, ':') orelse return false; + return nameLike(name[0..colon]) and std.ascii.eqlIgnoreCase(name[colon + 1 ..], "tool_call"); +} + +/// Hides tool envelopes from streamed prose, holding only a partial tag or open code span between deltas. +pub const TextFilter = struct { + buf: std.ArrayList(u8) = .empty, + sent: usize = 0, + scan: usize = 0, + hidden: ?[2]usize = null, + hidden_from: usize = 0, + deferred: bool = false, // a closed envelope was hidden: later prose waits for the reply's final content + code: reply_code.Scanner = .{}, + + pub fn feed(f: *TextFilter, a: Allocator, text: []const u8) Allocator.Error![]const u8 { + if (f.deferred) return ""; + try f.buf.appendSlice(a, text); + return f.step(false); + } + + pub fn finish(f: *TextFilter) []const u8 { + const tail = if (f.hidden != null or f.deferred) "" else f.step(true); + f.buf = .empty; + return tail; + } + + fn step(f: *TextFilter, finished: bool) []const u8 { + const b = f.buf.items; + const emit_start = f.sent; + if (f.hidden) |tag| { + f.matchCloser(b, tag); + return b[emit_start..f.sent]; + } + while (std.mem.indexOfScalarPos(u8, b, f.scan, '<')) |start| { + switch (f.code.check(b, start, finished)) { + .skip => |to| { + f.sent = @min(to, b.len); + f.scan = f.sent; + continue; + }, + .pending => { + f.sent = start; + f.scan = start; + return b[emit_start..f.sent]; + }, + .outside => {}, + } + const rest = b[start..]; + const end = std.mem.indexOfScalar(u8, rest, '>') orelse { + if (!finished) { + const name = rest[1..]; + const colon = std.mem.indexOfScalar(u8, name, ':'); + const possible = name.len == 0 or nameLike(name) or (colon != null and nameLike(name[0..colon.?]) and + std.ascii.startsWithIgnoreCase("tool_call", name[colon.? + 1 ..])); + if (possible) { + f.sent = start; + f.scan = start; + return b[emit_start..f.sent]; + } + } + f.sent = start + 1; + f.scan = start + 1; + continue; + }; + if (callTag(rest[1..end])) { + f.sent = start; + f.hidden = .{ start + 1, start + end }; + f.hidden_from = start + end + 1; + f.matchCloser(b, f.hidden.?); + return b[emit_start..f.sent]; + } + f.sent = start + 1; + f.scan = start + 1; + } + f.sent = b.len; + f.scan = b.len; + return b[emit_start..f.sent]; + } + + fn matchCloser(f: *TextFilter, b: []const u8, tag: [2]usize) void { + const name = b[tag[0]..tag[1]]; + var at = f.hidden_from; + while (std.mem.indexOfScalarPos(u8, b, at, '<')) |i| { + if (i + 3 + name.len > b.len) { + f.hidden_from = i; + return; + } + if (b[i + 1] == '/' and std.ascii.eqlIgnoreCase(b[i + 2 .. i + 2 + name.len], name) and b[i + 2 + name.len] == '>') { + f.hidden = null; + f.deferred = true; + return; + } + at = i + 1; + } + f.hidden_from = b.len; + } +}; + +/// ``parallel_tool_calls: false`` keeps one call and hides call markup from streamed prose. +pub const Policy = struct { + single: bool = false, + filter: TextFilter = .{}, + + pub fn maxCalls(p: *const Policy) ?usize { + return if (p.single) 1 else null; + } + + /// Filters a str delta's text (dict deltas lose tool_calls and filter content), or passes it through. + pub fn text(p: *Policy, a: Allocator, s: []const u8) Allocator.Error![]const u8 { + return if (p.single) p.filter.feed(a, s) else s; + } + + pub fn flush(p: *Policy) []const u8 { + return if (p.single) p.filter.finish() else ""; + } + + pub fn content(p: *const Policy, a: Allocator, s: []const u8) Allocator.Error![]const u8 { + if (!p.single) return s; + var f: TextFilter = .{}; + const head = try f.feed(a, s); + return std.mem.concat(a, u8, &.{ head, f.finish() }); + } + + /// parsed_content: parsed reply content; whole envelopes left as text kept, rest filtered; unclosed stays hidden. + pub fn parsedContent(p: *const Policy, a: Allocator, s: []const u8) Allocator.Error![]const u8 { + if (!p.single) return s; + var out: std.ArrayList(u8) = .empty; + var cursor: usize = 0; + var code: reply_code.Scanner = .{}; + while (try wholeEnvelope(a, s, cursor, &code)) |e| : (cursor = e.end) { + try out.appendSlice(a, try p.content(a, s[cursor..e.start])); + try out.appendSlice(a, s[e.start..e.end]); + } + try out.appendSlice(a, try p.content(a, s[cursor..])); + return out.items; + } + + /// Held-back malformed or unoffered call envelopes kept as reply text: ``final`` past the prose ``sent``. + pub fn kept(p: *const Policy, final: []const u8, sent: []const u8) ?[]const u8 { + // Replies without parsed calls retain their leading whitespace; parsed content may be stripped. + const shown = if (std.mem.startsWith(u8, final, sent)) sent else reply_text.pyLstrip(sent); + if (!std.mem.startsWith(u8, final, shown)) return null; + const rest = final[shown.len..]; + if (p.single) return if (rest.len > 0) rest else null; + return if (reply_text.pyStrip(rest).len > 0) rest else null; + } +}; + +/// The first whole envelope from ``from`` (``<((?:NAME:)?tool_call)>.*?``, any case). +fn wholeEnvelope(a: Allocator, s: []const u8, from: usize, code: *reply_code.Scanner) Allocator.Error!?struct { start: usize, end: usize } { + var at = from; + while (std.mem.indexOfScalarPos(u8, s, at, '<')) |start| { + if (code.check(s, start, true) == .skip) { + at = code.skip_end; + continue; + } + at = start + 1; + const close = std.mem.indexOfScalarPos(u8, s, start, '>') orelse return null; + if (!callTag(s[start + 1 .. close])) continue; + const closer = try std.mem.concat(a, u8, &.{ "" }); + const end = std.ascii.findIgnoreCasePos(s, close + 1, closer) orelse continue; + code.jumpTo(end + closer.len); + return .{ .start = start, .end = end + closer.len }; + } + return null; +} diff --git a/zig/src/server/tool_prose_code_http_test.zig b/zig/src/server/tool_prose_code_http_test.zig new file mode 100644 index 00000000000..d5331b29e17 --- /dev/null +++ b/zig/src/server/tool_prose_code_http_test.zig @@ -0,0 +1,233 @@ +//! Quoted tool markup in Markdown inline code spans and fenced code blocks stays prose over HTTP and SSE. +const std = @import("std"); +const api = @import("engine_api"); +const server = @import("root.zig"); +const json = server.json; +const openai = @import("openai.zig"); +const pre = @import("stream_preflight_test.zig"); +const Conn = @import("http_conn.zig").Conn; +const Allocator = std.mem.Allocator; + +const Got = struct { + opened: bool = false, + status: ?u16 = null, + calls: usize = 0, + has_kept: bool = false, + content: std.ArrayList(u8) = .empty, + arguments: std.ArrayList(u8) = .empty, + finish: [16]u8 = undefined, + finish_len: usize = 0, + + fn deinit(g: *Got) void { + g.content.deinit(std.testing.allocator); + g.arguments.deinit(std.testing.allocator); + } + + fn reason(g: *const Got) []const u8 { + return g.finish[0..g.finish_len]; + } + + fn keepFinish(g: *Got, choice: json.Value) void { + const f = choice.strField("finish_reason") orelse return; + g.finish_len = @min(f.len, g.finish.len); + @memcpy(g.finish[0..g.finish_len], f[0..g.finish_len]); + } + + fn keepCall(g: *Got, call: json.Value) error{Closed}!void { + const f = call.get("function") orelse return; + const args = f.strField("arguments") orelse return; + g.arguments.appendSlice(std.testing.allocator, args) catch return error.Closed; + } + + fn out(g: *Got) openai.Out { + return .{ .ctx = g, .vt = &.{ .open = open, .event = event, .reply = reply } }; + } + + fn open(ctx: *anyopaque, _: usize) error{Closed}!void { + const g: *Got = @ptrCast(@alignCast(ctx)); + g.opened = true; + } + + fn event(ctx: *anyopaque, payload: ?json.Value) error{Closed}!void { + const g: *Got = @ptrCast(@alignCast(ctx)); + const p = payload orelse return; + if (p.get("tensorfold")) |tf| if (tf.get("kept_tool_calls") != null) { + g.has_kept = true; + }; + const choices = p.get("choices") orelse return; + if (choices != .array or choices.array.len == 0) return; + const choice = choices.array[0]; + g.keepFinish(choice); + const delta = choice.get("delta") orelse return; + if (delta.get("content")) |t| if (t == .string) { + g.content.appendSlice(std.testing.allocator, t.string) catch return error.Closed; + }; + if (delta.get("tool_calls")) |t| if (t == .array) for (t.array) |call| { + if (call.get("id") != null) g.calls += 1; + try g.keepCall(call); + }; + } + + fn reply(ctx: *anyopaque, status: u16, payload: json.Value) void { + const g: *Got = @ptrCast(@alignCast(ctx)); + g.status = status; + if (payload.get("tensorfold")) |tf| if (tf.get("kept_tool_calls") != null) { + g.has_kept = true; + }; + const choices = payload.get("choices") orelse return; + if (choices != .array or choices.array.len == 0) return; + const choice = choices.array[0]; + g.keepFinish(choice); + const message = choice.get("message") orelse return; + if (message.get("content")) |t| if (t == .string) g.content.appendSlice(std.testing.allocator, t.string) catch {}; + if (message.get("tool_calls")) |t| if (t == .array) { + g.calls += t.array.len; + for (t.array) |call| g.keepCall(call) catch {}; + }; + } +}; + +fn send(engine: api.Engine, body: []const u8) !Got { + var text: pre.TestText = .{}; + var srv = try server.Server.init(std.testing.allocator, std.testing.io, engine, text.text(), .{ + .served_name = "test-model", + .model_ids = &.{"test-model"}, + .enable_thinking = false, + .use_drafts = false, + }, null); + defer srv.deinit(); + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const raw = (try json.parse(a, body)).ok; + var conn: Conn = .{ .fd = -1, .peer = "", .buf = &.{}, .gpa = a }; + var got: Got = .{}; + errdefer got.deinit(); + openai.run(srv, a, got.out(), .{ .conn = &conn }, true, raw); + return got; +} + +const head = "{\"model\":\"test-model\",\"messages\":[{\"role\":\"user\",\"content\":\"x\"}]," ++ + "\"tools\":[{\"type\":\"function\",\"function\":{\"name\":\"lookup\",\"parameters\":{\"type\":\"object\"," ++ + "\"properties\":{\"q\":{\"type\":\"string\"}}}}}]"; + +const Case = struct { + reply: []const u8, + cut: ?usize = null, + content: []const u8, + calls: usize = 0, + arguments: []const u8 = "", + finish: []const u8 = "stop", +}; + +fn expectAgreesSingle(a: Allocator, single: bool, c: Case) !void { + const tokens = try pre.TestText.encode(undefined, a, c.reply, false); + const body = try std.fmt.allocPrint(a, "{s}{s},\"max_tokens\":{d}", .{ head, if (single) ",\"parallel_tool_calls\":false" else "", c.cut orelse 2000 }); + for ([_]bool{ false, true }) |batched| { + var backend: pre.CallEngine = .{ .tokens = tokens, .batched = batched }; + var whole = try send(backend.engine(), try std.mem.concat(a, u8, &.{ body, ",\"stream\":false}" })); + defer whole.deinit(); + var streamed = try send(backend.engine(), try std.mem.concat(a, u8, &.{ body, ",\"stream\":true}" })); + defer streamed.deinit(); + try std.testing.expectEqual(@as(?u16, 200), whole.status); + try std.testing.expect(streamed.opened and streamed.status == null); + try std.testing.expect(!whole.has_kept); + try std.testing.expect(!streamed.has_kept); + try std.testing.expectEqualStrings(c.content, whole.content.items); + try std.testing.expectEqual(c.calls, whole.calls); + try std.testing.expectEqualStrings(c.arguments, whole.arguments.items); + try std.testing.expectEqualStrings(c.finish, whole.reason()); + try std.testing.expectEqualStrings(whole.content.items, streamed.content.items); + try std.testing.expectEqual(whole.calls, streamed.calls); + try std.testing.expectEqualStrings(whole.arguments.items, streamed.arguments.items); + try std.testing.expectEqualStrings(whole.reason(), streamed.reason()); + } +} + +fn expectAgrees(a: Allocator, c: Case) !void { + try expectAgreesSingle(a, false, c); + try expectAgreesSingle(a, true, c); +} + +test "tool visibility HTTP: backticked tool openers before a real GLM or XML call stream prose and emit only the real call" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const glm = "lookupqok"; + const xml = "\n\n\nok\n\n\n"; + try expectAgrees(a, .{ + .reply = "Raw `` XML leaking into output.\n" ++ glm, + .content = "Raw `` XML leaking into output.", + .calls = 1, + .arguments = "{\"q\":\"ok\"}", + .finish = "tool_calls", + }); + try expectAgrees(a, .{ + .reply = "The tag `lookupx` broke args.\n" ++ glm, + .content = "The tag `lookupx` broke args.", + .calls = 1, + .arguments = "{\"q\":\"ok\"}", + .finish = "tool_calls", + }); + try expectAgrees(a, .{ + .reply = "Quoting `` before:\n" ++ xml, + .content = "Quoting `` before:", + .calls = 1, + .arguments = "{\"q\":\"ok\"}", + .finish = "tool_calls", + }); +} + +test "tool visibility HTTP: complete tool calls inside inline code or fenced blocks stay prose with stop finish" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const quoted = "Use `lookupqx` here."; + try expectAgrees(a, .{ .reply = quoted, .content = quoted }); + const fenced = "Example:\n```xml\nlookupqx\n```\nDone."; + try expectAgrees(a, .{ .reply = fenced, .content = fenced }); + const real = "lookupqreal"; + try expectAgrees(a, .{ + .reply = fenced ++ "\n" ++ real, + .content = fenced, + .calls = 1, + .arguments = "{\"q\":\"real\"}", + .finish = "tool_calls", + }); +} + +test "tool visibility HTTP: an unmatched backtick before a real call agrees whole and streamed" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const glm = "lookupqok"; + try expectAgrees(a, .{ + .reply = "DeepSeek's format is `" ++ glm, + .content = "DeepSeek's format is `", + .calls = 1, + .arguments = "{\"q\":\"ok\"}", + .finish = "tool_calls", + }); + try expectAgrees(a, .{ + .reply = "DeepSeek's format is `\n\n" ++ glm, + .content = "DeepSeek's format is `", + .calls = 1, + .arguments = "{\"q\":\"ok\"}", + .finish = "tool_calls", + }); + const cut_reply = "Prose with `` then\nlookupqok"; + try expectAgreesSingle(a, false, .{ + .reply = cut_reply ++ " more", + .cut = cut_reply.len, + .content = "Prose with `` then", + .calls = 1, + .arguments = "{\"q\":\"ok", + .finish = "length", + }); + try expectAgreesSingle(a, true, .{ + .reply = cut_reply ++ " more", + .cut = cut_reply.len, + .content = "Prose with `` then\n", + .finish = "length", + }); +} diff --git a/zig/src/server/tool_stream.zig b/zig/src/server/tool_stream.zig index 76bad230b94..47b118c4dc2 100644 --- a/zig/src/server/tool_stream.zig +++ b/zig/src/server/tool_stream.zig @@ -1,7 +1,8 @@ -//! Tool calls while they are written: XML calls as argument deltas, and the one-call policy's text filter. +//! Tool calls while they are written: XML, GLM and DSML calls as argument deltas. const std = @import("std"); const json = @import("json"); const ids = @import("ids.zig"); +const reply_code = @import("reply_code.zig"); const reply_text = @import("reply_text.zig"); const tool_dsml = @import("tool_dsml.zig"); const tool_dsml_stream = @import("tool_dsml_stream.zig"); @@ -9,11 +10,15 @@ const tool_glm_cut = @import("tool_glm_cut.zig"); const tool_json_cut = @import("tool_json_cut.zig"); const tool_glm_stream = @import("tool_glm_stream.zig"); const tool_params = @import("tool_params.zig"); +const tool_policy = @import("tool_policy.zig"); const tool_specs = @import("tool_specs.zig"); const tool_parse = @import("tool_parse.zig"); const Value = json.Value; const Allocator = std.mem.Allocator; +pub const TextFilter = tool_policy.TextFilter; +pub const Policy = tool_policy.Policy; + const space = reply_text.isSpaceByte; /// ``\s*\n]+)>\n?`` at the start of ``rest``: the name and the bytes matched. @@ -64,6 +69,8 @@ pub const Streamer = struct { buffered_close: []const u8 = "", glm: tool_glm_stream.Glm = .{}, dsml: tool_dsml_stream.Dsml = .{}, + code: reply_code.Scanner = .{}, + finished: bool = false, pub fn init(a: Allocator, tools: []const Value) Allocator.Error!Streamer { var s: Streamer = .{ .a = a, .schemas = try tool_params.schemas(a, tools), .tools = tools }; @@ -148,10 +155,22 @@ pub const Streamer = struct { const parsed = try tool_parse.parse(s.a, text[start..s.pos], s.tools, null); if (parsed.calls) |calls| try s.emitCalls(calls, out); } + s.code.jumpTo(s.pos); if (text.len < s.searched) s.searched = s.pos; - const from = @min(text.len, @max(s.pos, s.searched -| (tool_dsml.open_max - 1))); + const from = @min(text.len, @max(@max(s.pos, s.code.skip_end), s.searched -| (tool_dsml.open_max - 1))); var at = from; while (std.mem.indexOfScalarPos(u8, text, at, '<')) |start| { + switch (s.code.check(text, start, s.finished)) { + .skip => |to| { + at = to; + continue; + }, + .pending => { + s.searched = start; + return; + }, + .outside => {}, + } if (tool_dsml.openedBy(text[start..])) |sp| { s.dsml_seen = true; s.pos = start + sp.open.len; @@ -182,7 +201,7 @@ pub const Streamer = struct { at = end; continue; } - if (callTag(text[start + 1 .. end])) { + if (tool_policy.callTag(text[start + 1 .. end])) { s.buffered_start = start; s.buffered_close = try std.mem.concat(s.a, u8, &.{ "" }); s.pos = end + 1; @@ -356,9 +375,15 @@ pub const Streamer = struct { } } + /// ``feed`` at the reply's end: resolves any open backtick ambiguity without cutting open values. + pub fn finish(s: *Streamer, text: []const u8, out: *std.ArrayList(Value)) Allocator.Error!void { + s.finished = true; + return s.feed(text, out); + } + /// ``feed`` of the reply's final text; a value it cuts sends the bytes held back for a closer that never came. pub fn finishCut(s: *Streamer, text: []const u8, out: *std.ArrayList(Value)) Allocator.Error!void { - try s.feed(text, out); + try s.finish(text, out); if (s.state == .glm) return tool_glm_stream.cut(s, text, out); // a GLM value's held bytes if (s.state == .dsml) return tool_dsml_stream.cut(s, text, out); // a DSML value's held bytes if (s.state != .value) return; @@ -424,150 +449,6 @@ fn typedSchema(a: Allocator, schema: tool_params.Schema) Allocator.Error!bool { const wrap = @import("tool_parse.zig").wrapCalls; -fn nameLike(s: []const u8) bool { - if (s.len == 0 or !(std.ascii.isAlphabetic(s[0]) or s[0] == '_')) return false; - for (s[1..]) |ch| if (!(std.ascii.isAlphanumeric(ch) or ch == '_' or ch == '.' or ch == '-' or ch >= 0x80)) return false; - return true; -} - -/// Hides tool envelopes from streamed prose, holding only a partial tag between deltas. -pub const TextFilter = struct { - pending: std.ArrayList(u8) = .empty, - hidden: ?[]const u8 = null, - deferred: bool = false, // a closed envelope was hidden: later prose waits for the reply's final content - - pub fn feed(f: *TextFilter, a: Allocator, text: []const u8) Allocator.Error![]const u8 { - if (f.deferred) return ""; - try f.pending.appendSlice(a, text); - var out: std.ArrayList(u8) = .empty; - while (f.pending.items.len > 0) { - const p = f.pending.items; - if (f.hidden) |name| { - const close = try std.mem.concat(a, u8, &.{ "" }); - if (std.ascii.findIgnoreCase(p, close) == null) { - const keep = reply_text.charCount(close) - 1; - const chars = reply_text.charCount(p); - const tail = if (chars > keep) reply_text.afterChars(p, chars - keep) else p; - try f.reset(a, tail); - break; - } - // The whole reply may keep this envelope as text, so what follows cannot overtake it. - f.hidden = null; - f.deferred = true; - f.pending.clearRetainingCapacity(); - break; - } - const start = std.mem.indexOfScalar(u8, p, '<') orelse { - try out.appendSlice(a, p); - f.pending.clearRetainingCapacity(); - break; - }; - try out.appendSlice(a, p[0..start]); - const rest = p[start..]; - const end = std.mem.indexOfScalar(u8, rest, '>') orelse { - const name = rest[1..]; - const colon = std.mem.indexOfScalar(u8, name, ':'); - const possible = name.len == 0 or nameLike(name) or (colon != null and nameLike(name[0..colon.?]) and - std.ascii.startsWithIgnoreCase("tool_call", name[colon.? + 1 ..])); - if (possible) { - try f.reset(a, rest); - break; - } - try out.append(a, '<'); - try f.reset(a, rest[1..]); - continue; - }; - const name = rest[1..end]; - if (callTag(name)) { - f.hidden = try std.ascii.allocLowerString(a, name); - } else try out.appendSlice(a, rest[0 .. end + 1]); - try f.reset(a, rest[end + 1 ..]); - } - return out.items; - } - - fn reset(f: *TextFilter, a: Allocator, rest: []const u8) Allocator.Error!void { - const copy = try a.dupe(u8, rest); - f.pending.clearRetainingCapacity(); - try f.pending.appendSlice(a, copy); - } - - pub fn finish(f: *TextFilter) []const u8 { - const tail = if (f.hidden != null or f.deferred) "" else f.pending.items; - f.pending = .empty; - return tail; - } -}; - -/// ``(?:NAME:)?tool_call``, any case. -fn callTag(name: []const u8) bool { - if (std.ascii.eqlIgnoreCase(name, "tool_call")) return true; - const colon = std.mem.indexOfScalar(u8, name, ':') orelse return false; - return nameLike(name[0..colon]) and std.ascii.eqlIgnoreCase(name[colon + 1 ..], "tool_call"); -} - -/// ``parallel_tool_calls: false`` keeps one call and hides call markup from streamed prose. -pub const Policy = struct { - single: bool = false, - filter: TextFilter = .{}, - - pub fn maxCalls(p: *const Policy) ?usize { - return if (p.single) 1 else null; - } - - /// Filters a str delta's text (dict deltas lose tool_calls and filter content), or passes it through. - pub fn text(p: *Policy, a: Allocator, s: []const u8) Allocator.Error![]const u8 { - return if (p.single) p.filter.feed(a, s) else s; - } - - pub fn flush(p: *Policy) []const u8 { - return if (p.single) p.filter.finish() else ""; - } - - pub fn content(p: *const Policy, a: Allocator, s: []const u8) Allocator.Error![]const u8 { - if (!p.single) return s; - var f: TextFilter = .{}; - const head = try f.feed(a, s); - return std.mem.concat(a, u8, &.{ head, f.finish() }); - } - - /// parsed_content: parsed reply content; whole envelopes left as text kept, rest filtered; unclosed stays hidden. - pub fn parsedContent(p: *const Policy, a: Allocator, s: []const u8) Allocator.Error![]const u8 { - if (!p.single) return s; - var out: std.ArrayList(u8) = .empty; - var cursor: usize = 0; - while (try wholeEnvelope(a, s, cursor)) |e| : (cursor = e.end) { - try out.appendSlice(a, try p.content(a, s[cursor..e.start])); - try out.appendSlice(a, s[e.start..e.end]); - } - try out.appendSlice(a, try p.content(a, s[cursor..])); - return out.items; - } - - /// Held-back malformed or unoffered call envelopes kept as reply text: ``final`` past the prose ``sent``. - pub fn kept(p: *const Policy, final: []const u8, sent: []const u8) ?[]const u8 { - // Replies without parsed calls retain their leading whitespace; parsed content may be stripped. - const shown = if (std.mem.startsWith(u8, final, sent)) sent else reply_text.pyLstrip(sent); - if (!std.mem.startsWith(u8, final, shown)) return null; - const rest = final[shown.len..]; - if (p.single) return if (rest.len > 0) rest else null; - return if (reply_text.pyStrip(rest).len > 0) rest else null; - } -}; - -/// The first whole envelope from ``from`` (``<((?:NAME:)?tool_call)>.*?``, any case). -fn wholeEnvelope(a: Allocator, s: []const u8, from: usize) Allocator.Error!?struct { start: usize, end: usize } { - var at = from; - while (std.mem.indexOfScalarPos(u8, s, at, '<')) |start| : (at = start + 1) { - const close = std.mem.indexOfScalarPos(u8, s, start, '>') orelse return null; - if (!callTag(s[start + 1 .. close])) continue; - const closer = try std.mem.concat(a, u8, &.{ "" }); - const end = std.ascii.findIgnoreCasePos(s, close + 1, closer) orelse continue; - return .{ .start = start, .end = end + closer.len }; - } - return null; -} - test { _ = @import("tool_stream_test.zig"); } diff --git a/zig/src/server/warm.zig b/zig/src/server/warm.zig index 6f63b9ae365..5b4629993e8 100644 --- a/zig/src/server/warm.zig +++ b/zig/src/server/warm.zig @@ -50,8 +50,9 @@ fn start(srv: *Server, input: chat.Input, message: Value, thinking: bool, effort const pictures = try images.expand(srv.info.vision, null, srv.text, &cx, .{ .array = warm_prompt.messages }, prompt, prompt.len); if (pictures) |x| prompt = x.ids; if (prompt.len == 0 or (srv.info.context_window > 0 and prompt.len >= srv.info.context_window)) return; + const system_len = prompt_mod.systemPrefixLen(srv, &cx, .{ .array = warm_prompt.messages }, input.tools, prompt, thinking, effort); // its states count as the reply's request's: they supersede none of that turn's own until a later turn does - p.request = .{ .prompt = prompt, .max_tokens = 0, .background = true, .born = @intCast(prompt_len), .history_len = @intCast(prompt.len), .rewind_len = if (pictures != null) 0 else @intCast(prompt_mod.rewindLen(srv, &cx, .{ .array = warm_prompt.messages }, input.messages.array.len, input.tools, prompt, thinking, effort)), .chunks = try srv.chunks.starts(a, prompt), .decode_spans = try prompt_mod.replySpans(srv, &cx, prompt) }; + p.request = .{ .prompt = prompt, .max_tokens = 0, .background = true, .born = @intCast(prompt_len), .history_len = @intCast(prompt.len), .rewind_len = if (pictures != null) 0 else @intCast(prompt_mod.rewindLen(srv, &cx, .{ .array = warm_prompt.messages }, input.messages.array.len, input.tools, prompt, thinking, effort)), .chunks = try srv.chunks.request(a, prompt, system_len), .decode_spans = try prompt_mod.replySpans(srv, &cx, prompt) }; if (pictures) |x| { p.request.images = x.images; p.request.cache_key = x.cache_key;