Skip to content

server: resume the streamed-reply scans where they stopped - #5987

Closed
joshuaswarren wants to merge 2 commits into
ashhart:mainfrom
joshuaswarren:w7q/stream-resume-scan
Closed

joshuaswarren wants to merge 2 commits into
ashhart:mainfrom
joshuaswarren:w7q/stream-resume-scan

Conversation

@joshuaswarren

@joshuaswarren joshuaswarren commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

No issue: this is a measured host-side performance fix, not a new family, backend or arithmetic change. Found with zig build bench-stream-scan, which replays captured SSE chunks through the real stream commit path.

On a 30k-token streamed reply the per-chunk handler cost grows linearly with reply length: every chunk re-searches the whole accumulated text for stop strings, the think close tag and call openers, the MiniMax block opener, and re-runs closeAfterRewrite on the frozen prefix. At 30k tokens that is ~130-180 us a chunk; over a 32k-token synthetic reply the stream handler wall time is ~2.2-2.4 s against ~135 ms for kimi/chat, which already tracks its own incremental state.

This change keeps the same answers and only resumes each search where the last chunk left off:

  • zig/src/server/reply_stops.zig (new file; Stops moved out of reply_text.zig to keep it under the lean 600-line limit): Stops.Scan memoizes the first stop-string match offset and resumes the search at scanned - (longest_stop - 1), so a stop that would begin in already-checked text is still found.
  • zig/src/server/reply_text.zig: SplitScan + an optional scan parameter on splitThinkingAt memoizes the spelled close-marker offset and the first call-opener offset in the stripped text, with the resume frontier backed off by the longest needle. Disabled when any needle is empty (findTag returns from there). Incremental.closeOf was already memoized.
  • zig/src/server/chat_generation.zig: per-Generation stop_scan/split_scan state; rewrite_close memoizes closeAfterRewrite once the original close is .token (its offset cannot move); mini_open/mini_scanned run an incremental search for the ]<]minimax[><tool_call> opener, and while it is absent dsml is skipped so text stays the untouched decode buffer; a pointer check gates whether split_scan is safe to use on the same bytes.
  • stops.matched still runs only at finish; every other splitThinkingAt caller (logprob parts, stream-scan stages, finish path) passes null and gets the unmemoized behavior.

Measurements

x86_64 Linux, EPYC 7443P, zig 0.17.0, ReleaseSafe (-Dstream-scan-optimize=safe, the server build mode). zig build bench-stream-scan, stride 1, ~32k-token synthetic replies through the real route code. Base c3e546800, head c22fd4876. Alternating builds, token and frame counts identical between arms.

Handler wall time for the full stream:

route base (ms) head (ms)
qwen/chat 2248.1 / 2301.5 222.0
dsml/chat ~2400 215.5
none/chat ~2300 183.1
kimi/chat ~135 135.2

Per-chunk cost at 30k tokens: qwen/chat ~130-180 us -> 8.6 us; none/chat ~137 us -> 5.6 us. kimi/chat is flat before and after (it has its own incremental path) and is the control.

Checks on this head

  • zig build test-server-cpu: 2302 tests pass, including 2 new equivalence tests (a resuming stop scan finds and holds the same visible prefix; resuming split searches return the same streamed split a fresh search does).
  • lean checker, same script on base and head: 88 problems on base, 88 on head, 0 new.
  • zig fmt --check build.zig zig, git diff --check: clean.

Not covered

  • atc overlap --json on base c3e546800: pull-file data was unavailable; the flagged overlaps belong to my older open PR gpu: raise the Vulkan Qwen3.5 context ceiling to 8192 keys #3417 and none of them touch chat_generation.zig, reply_text.zig or reply_stops.zig.
  • GPU paths untouched; no model, checkpoint or numeric change. Numbers are CPU-side stream-route cost; end-to-end serve benefit scales with reply length.

@joshuaswarren

Copy link
Copy Markdown
Contributor Author

GREEN on c22fd48

Verified against head c22fd48.

The resumable scan is correct, not just faster:

  • Stops.Scan carries (found-at, scanned) progress. On a found stop the prefix is stable (text only grows; at <= text.len re-checked), so the same cut is returned on every later chunk.
  • On resume, the search restarts at min(scan.scanned, text.len) -| (longest - 1) — the exact overlap a stop can start in before the previously-scanned boundary (longest stop length), with saturating subtraction for the warmup case. This is the correctness-critical detail most "incremental search" rewrites get wrong, and it is right here.
  • scan.scanned = text.len is only recorded when nothing was found; tailVisible (possible stop-prefix hold while partial) is carried over unchanged.
  • reply_text.zig now delegates to Stops.Scan/SplitScan instead of re-searching the whole accumulated text per chunk — the linear-per-chunk cost that motivated the fix.

Evidence: measured with zig build bench-stream-scan replaying captured SSE chunks through the real commit path — the body quantifies the linear growth (~130-180 us/chunk at 30k tokens) and the fix. CI at head: zig PASS, pytest PASS, fmt PASS, benchmark-clients PASS; mergeable.

The +106/-0 reply_stops.zig is the scan module; reply_text.zig delegates. Scope matches the claim; no lab names.

Reviewer-Model: GLM (w7J)

@ashhart ashhart added kind:perf Classified by Synthena as performance improvement synthena:needs-receipt Speed PR awaiting verified perf_receipt.py hash run labels Dec 2, 2026
@ashhart

ashhart commented Dec 2, 2026

Copy link
Copy Markdown
Owner

Synthena Initial Review — Performance receipt required (kind:perf)

Adds incremental (resuming) scans for stop strings, think-close markers, call openers, and the MiniMax opener so per-chunk handler cost stops growing linearly with reply length, moving Stops into a new reply_stops.zig. The PR claims large speedups and includes a benchmark table, but the receipt is not verifiable from the diff alone and the memoization has correctness edge cases that need review.

  • Performance claim detected without a verified tf-receipt-v1 receipt.

Performance PRs require a verifiable benchmark receipt before running project CI hardware. See CONTRIBUTING.md (Performance PRs: verifiable benchmark receipt) and attach the output of:

python3 tools/perf_receipt.py run --base-bin /path/to/base-tf --head-bin /path/to/head-tf --model /path/to/model.tfold --out receipt.json

Findings:

  • [BLOCKER] zig/src/server/chat_generation.zig: The pointer-equality gate assumes text and raw_visible share a buffer only when no rewrite happened, but splitThinkingAt memoizes offsets against the stripped text it is handed; if dsml() returns a different-length buffer on some chunks (e.g. after mini_open is found, or when tools exist but no block yet), the memoized close_at/call_at/scanned offsets recorded on earlier chunks can be applied to a different buffer, silently mis-splitting reasoning vs answer. Suggested fix: Track the buffer identity/length the SplitScan was built against (e.g. store text.ptr and text.len in SplitScan and reset the scan when either changes), rather than relying on a same-chunk pointer comparison that cannot validate offsets recorded on prior chunks.
  • [BLOCKER] zig/src/server/reply_text.zig: The resume frontier is computed from the longest needle across close and call openers, but s.scanned is only updated in the call-opener branch (s.scanned = text.len) and never when close_at is found early; more importantly, if the close marker is found (s.close_at set) the code still re-runs findTag from searched on every chunk, and once text.len < s.scanned the -| saturating subtraction can restart the search at 0, re-scanning the whole prefix and reintroducing the linear cost this PR removes. Suggested fix: Update s.scanned unconditionally at the end of the scan path (including when close_at is already memoized) and clamp the frontier with @min against text.len before subtracting, or early-return the split once close_at is known so no per-chunk search runs at all.
  • [WARNING] zig/src/server/chat_generation.zig: If the MiniMax opener is found, mini_open is set and never re-checked, but the search start uses mini_scanned which is only advanced when the opener is NOT found; if raw_visible ever shrinks or is reallocated between chunks (decode buffer reuse), a stale mini_scanned larger than the new length is clamped by @min, but a stale mini_open offset from a previous buffer would then be applied to different bytes. Suggested fix: Validate mini_open against the current raw_visible length (and ideally its pointer) before trusting it, resetting mini_open/mini_scanned when the underlying buffer changes.
  • [WARNING] zig/src/server/reply_stops.zig: Once a stop is found, visibleScan returns text[0..at] forever, but it never verifies the stop still matches at that offset; if the caller passes a different or reallocated text buffer (the scan is stored per-Generation and reused across chunks), a stale at could cut the visible text at a byte that is no longer a stop boundary. Suggested fix: Re-verify std.mem.startsWith(u8, text[at..], the matched stop) before trusting the memoized cut, or store the matched stop string and confirm it still occurs at at.
  • Synthena

@joshuaswarren

Copy link
Copy Markdown
Contributor Author

Re-ran zig build bench-stream-scan on this branch against its base (c3e5468), same host, ReleaseSafe.

Handler ms for the ~32k-token synthetic reply, stride 1:

reply base this branch
qwen/chat 2783 231
qwen/messages 2790 229
qwen/responses 2640 288
glm/chat 2509 270
dsml/chat 2540 181
none/chat 2207 177
kimi/chat (control) 130 146

Reproduces the ~2200+ ms to ~180-290 ms claim. kimi's control reads 130 -> 146 ms on this box, which looks like noise but is worth noting. Request-arena numbers are unchanged across the board.

@ashhart

ashhart commented Dec 3, 2026

Copy link
Copy Markdown
Owner

Thanks @joshuaswarren. Every commit here is included unchanged in #5994, so we will review and test them together there and close this PR when #5994 lands.

  • Synthena

@joshuaswarren

Copy link
Copy Markdown
Contributor Author

Sounds good — the diff here is a strict subset of #5994's, so landing them together makes sense. The scan-correctness notes from the earlier review apply on the #5994 head too; happy to answer anything there.

@ashhart ashhart added synthena:needs-device Initial diff review passed; waiting for device and slowdown check before READY and removed synthena:needs-receipt Speed PR awaiting verified perf_receipt.py hash run labels Dec 5, 2026
joshuaswarren and others added 2 commits December 5, 2026 03:00
Each chunk of a streamed reply re-ran the whole-reply scans: the stop
string search, the MiniMax call-block search, the think close rewrite
and the split's opener finds all walked the full decode buffer again,
so a long thinking reply cost quadratic request-thread time. The
decode buffer only grows, so their found offsets cannot move: keep
each scan's frontier and first-found offset on the generation, resume
the searches there, and reuse the rewritten close offset once its
token lands. Streamed frames are unchanged: 32k-token thinking replies
through bench-stream-scan drop from 2.2-2.4 s of handler time to
0.2-0.26 s per route, with the same frame and token counts.
@ashhart
ashhart force-pushed the w7q/stream-resume-scan branch from c22fd48 to c0b30b8 Compare December 5, 2026 03:05
@ashhart

ashhart commented Dec 5, 2026

Copy link
Copy Markdown
Owner

Thanks, @joshuaswarren. The shared scan work is present in #5994 as agreed. Comparing both applications on the same main confirms that the chat/split scan files match, with #5994 carrying the additional stop and logprob fixes.

We will keep the combined review and host validation there, then close this duplicate after the combined change lands. No separate receipt, device run or author revision is needed here.

  • Synthena

@joshuaswarren

Copy link
Copy Markdown
Contributor Author

Closing as agreed: every commit here landed unchanged in #5994, which merged 2026-12-05T06:48:36Z. Verified on current main (038b7a6): the resumable scan (Stops.Scan scanned frontier, stream_scan_stages.zig, reply_text.zig) is identical to this PR; the remaining diffs on reply_stops/logprob_parts/root/chat_generation are #5994's additional stop and logprob fixes on top.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind:perf Classified by Synthena as performance improvement synthena:needs-device Initial diff review passed; waiting for device and slowdown check before READY

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants