Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
studiobench: a window's stream-cost integrity is about one response (#9609)
Daniel Hanb7f86988ae18
diff --git a/tests/studio/studiobench/instruments/selftest/test_studiobench_streamcost_integrity.py b/tests/studio/studiobench/instruments/selftest/test_studiobench_streamcost_integrity.pyindex 02556f6e297..0db00ed4bb5 100644--- a/tests/studio/studiobench/instruments/selftest/test_studiobench_streamcost_integrity.py+++ b/tests/studio/studiobench/instruments/selftest/test_studiobench_streamcost_integrity.py@@ -124,6 +124,10 @@ def test_a_clean_stream_is_scoreable_and_counts_every_character(page):"failures": 0,"pending_chars": 0,"carried_flushes": got["carried_flushes"],+ # Not pinned to a value, on the same footing as `carried_flushes` beside it: the+ # id is which decoder the two numbers above are about, and the exact integer+ # depends on how many decoders the page has built before this assertion.+ "decoder_id": got["decoder_id"],}, got@@ -232,6 +236,10 @@ def test_the_counter_survives_a_split_inside_the_data_prefix(page):"failures": 0,"pending_chars": 0,"carried_flushes": got["carried_flushes"],+ # Not pinned to a value, on the same footing as `carried_flushes` beside it: the+ # id is which decoder the two numbers above are about, and the exact integer+ # depends on how many decoders the page has built before this assertion.+ "decoder_id": got["decoder_id"],}, got@@ -269,6 +277,10 @@ def test_unrelated_text_ending_in_a_marker_letter_does_not_corrupt_the_next_fram"failures": 0,"pending_chars": 0,"carried_flushes": got["carried_flushes"],+ # Not pinned to a value, on the same footing as `carried_flushes` beside it: the+ # id is which decoder the two numbers above are about, and the exact integer+ # depends on how many decoders the page has built before this assertion.+ "decoder_id": got["decoder_id"],}, got@@ -363,6 +375,41 @@ def test_a_window_that_opens_on_an_empty_buffer_is_still_scoreable(page):assert out["reply_chars_delta"] == len("during"), out+def test_a_marker_fragment_held_at_the_open_does_not_cost_the_window_its_reading(page):+ """THE BOUNDARY OF THE REFUSAL, and it is a boundary rather than a hole.++ A decoder whose first chunk is "dat" is holding a marker fragment, so `wireIntegrity` reports+ it as buffered -- deliberately, and the reason is above `markerHold`. But that decoder is NOT+ `active` yet, so `decoder_id` names whoever was, and when the fragment's frame completes+ inside the window the carried flush lands on the new decoder and the delta stays zero. The+ window is scoreable.++ That is correct, and the quantity is why. `markerTail` is at most four characters of the+ literal `data:` and is only ever set while `pending` is empty, so a held fragment carries+ ZERO denominator characters: every character `reply_chars_delta` counts here was delivered+ inside the window. The refusal exists for a buffer whose characters were delivered before the+ window and counted inside it, which is the half-frame case above, and that one still names+ the decoder holding it and still fires.+ """+ page.evaluate("() => window.__sb.streamcost.reset()")+ _feed(page, _frame("earlier"))+ _end_response(page)+ # The next response begins with a chunk that is only part of the marker.+ _feed(page, "dat")+ inst = _instrument(page)+ inst.open(_Window())+ assert inst._integrity_open["pending_chars"] == 3, inst._integrity_open++ _feed(page, 'a: {"choices":[{"delta":{"content":"hello"}}]}\n\n')+ out = inst.close(_Window())+ assert out["wire_pending_chars_at_open"] == 3, out+ assert out["wire_pending_chars_at_close"] == 0, out+ assert out["wire_parse_failures_in_window"] == 0, out+ # Every counted character arrived inside the window: the fragment held none of them.+ assert out["reply_chars_delta"] == len("hello"), out+ assert out["reply_chars_scoreable"] is True, out++# ── an aborted response must not poison the next one ──────────────────────────@@ -391,6 +438,10 @@ def test_an_aborted_frame_does_not_follow_the_stream_that_replaces_it(page):"failures": 0,"pending_chars": 0,"carried_flushes": got["carried_flushes"],+ # Not pinned to a value, on the same footing as `carried_flushes` beside it: the+ # id is which decoder the two numbers above are about, and the exact integer+ # depends on how many decoders the page has built before this assertion.+ "decoder_id": got["decoder_id"],}, got@@ -458,6 +509,92 @@ def test_a_window_opening_after_an_abort_keeps_the_next_response_scoreable(page)assert out["reply_chars_scoreable"] is True, out+def test_an_abort_does_not_cost_the_next_response_its_reading_when_that_one_is_split(page):+ """THE RESIDUAL ON THAT FIX, and it survived because the two halves of the refusal were read at+ two different scopes. `pending_at_open` belongs to ONE decoder; `carriedFlushes` was a counter+ on `S` that any decoder could move. So the abort's orphaned half frame was paired with a+ carried flush produced by the NEW response's own split, and the window was refused for a buffer+ that never flushed -- the same false refusal, surviving in the fragmented case.++ It is the fragmented case that matters most. Reads go ragged when the renderer is jammed, which+ is exactly the window worth measuring, so the loss is biased against the expensive windows.+ Measured before this change: this window delivered all 13 of its characters and was refused,+ while the same traffic with no abort in front of it was accepted."""+ page.evaluate("() => window.__sb.streamcost.reset()")+ _feed(page, 'data: {"choices":[{"delta":{"content":"half a re')+ _end_response(page)++ inst = _instrument(page)+ inst.open(_Window())+ assert inst._integrity_open["pending_chars"] > 0, inst._integrity_open # noqa: SLF001+ frame = _frame("a clean reply")+ head, tail = _halves(frame, frame.index("a clean") + 4)+ assert "\n\n" not in head, head+ _feed(page, head)+ _feed(page, tail)+ out = inst.close(_Window())+ assert out["reply_chars_delta"] == len("a clean reply"), out+ # The new response DID carry a frame across a decode boundary, so the counter really moved:+ # this window is accepted despite that, not because nothing was counted.+ assert out["wire_carried_frames_counted_in_window"] == 0, out+ assert out["reply_chars_scoreable"] is True, out+++def test_the_carried_counter_still_moves_for_the_decoder_that_owns_the_split(page):+ """THE CONTROL FOR THE ONE ABOVE. Without it that test passes just as well against an+ instrument that has stopped counting carried flushes altogether, which would take the genuine+ straddle refusal down with it. Same fragmentation, no abort in front of it.++ ASKED OF THE DECODER THAT OWNS THE SPLIT, which is the whole point of the change. The window's+ own `wire_carried_frames_counted_in_window` reads 0 here and that is correct rather than+ convenient: nothing was pending when it opened, so the decoder it names is not the one that+ went on to carry a frame, and its count is the honest answer to the question the refusal asks.+ The counter itself has to be shown to have moved, and only the decoder holding it can say so."""+ page.evaluate("() => window.__sb.streamcost.reset()")+ inst = _instrument(page)+ inst.open(_Window())+ assert inst._integrity_open["pending_chars"] == 0, inst._integrity_open # noqa: SLF001+ # Read BEFORE the close, which clears the open sample.+ opened_on = inst._integrity_open["decoder_id"] # noqa: SLF001+ frame = _frame("a clean reply")+ head, tail = _halves(frame, frame.index("a clean") + 4)+ _feed(page, head)+ _feed(page, tail)+ out = inst.close(_Window())+ live = page.evaluate("() => window.__sb.streamcost.wireIntegrity()")+ assert live["carried_flushes"] == 1, live+ assert live["decoder_id"] != opened_on, (live, opened_on)+ assert out["wire_carried_frames_counted_in_window"] == 0, out+ assert out["reply_chars_delta"] == len("a clean reply"), out+ assert out["reply_chars_scoreable"] is True, out+++def test_a_frame_that_really_did_straddle_the_open_still_refuses_its_window(page):+ """THE REFUSAL THIS MUST NOT REMOVE, in the shape that separates the two candidate fixes.++ The decoder that was pending at the open completes its carried frame INSIDE the window, so part+ of the delta really was delivered before the window opened -- and then another decoder becomes+ the active one before the close. A fix that compared the open's decoder id with the close's+ would see two different ids, discard the carry it is looking for, and accept a window whose+ denominator is wrong. Asking `wireIntegrity` about the NAMED decoder answers regardless of who+ is active now."""+ page.evaluate("() => window.__sb.streamcost.reset()")+ frame = _frame("straddles the open")+ head, tail = _halves(frame, 30)+ assert "\n\n" not in head, head+ _feed(page, head)++ inst = _instrument(page)+ inst.open(_Window())+ assert inst._integrity_open["pending_chars"] > 0, inst._integrity_open # noqa: SLF001+ _feed(page, tail)+ # Some other decoder takes over as active before the close.+ _feed_other(page, "unrelated page traffic")+ out = inst.close(_Window())+ assert out["wire_carried_frames_counted_in_window"] == 1, out+ assert out["reply_chars_scoreable"] is False, out++# ── the tail of a split frame is stream traffic on the numerator too ─────────## `noteSse` was gated on the marker while the character counter was gated on `looksSse ||diff --git a/tests/studio/studiobench/instruments/streamcost.js b/tests/studio/studiobench/instruments/streamcost.jsindex 8ab85a61226..408db129bd5 100644--- a/tests/studio/studiobench/instruments/streamcost.js+++ b/tests/studio/studiobench/instruments/streamcost.js@@ -125,13 +125,6 @@wireChars: 0,wireFrames: 0,wireParseFailures: 0,- // How many times a frame that was ALREADY BUFFERED when this call began was completed and- // counted. Cumulative and never reset, for the same reason `wireChars` is not: a window wants- // the growth across it. This is what turns "a buffer was pending when the window opened" into- // "characters that arrived before this window were counted inside it", which is the thing that- // actually makes the denominator wrong. A buffer left behind by an ABORTED response never- // completes, so it never increments this and never costs the next response its reading.- carriedFlushes: 0,};// The incremental SSE buffer. A decode() call is a slice of the socket, not an SSE frame: one// call can carry three frames and half of a fourth. Whatever is left after the last blank line@@ -152,10 +145,55 @@// retained. Within one response the same decoder is reused for every `decode(chunk, {stream:// true})` call, so a genuine split still reassembles exactly as before.const DECODER_STATE = new WeakMap();+ //: How many times a frame that was ALREADY BUFFERED when a decode call began was completed and+ //: counted. Cumulative and never reset, for the same reason `wireChars` is not: a window wants+ //: the growth across it. This is what turns "a buffer was pending when the window opened" into+ //: "characters that arrived before this window were counted inside it", which is the thing that+ //: actually makes the denominator wrong. A buffer left behind by an ABORTED response never+ //: completes, so it never increments this and never costs the next response its reading.+ //:+ //: PER DECODER, alongside `pending`, and it was page-global on `S` until it was not. `close`+ //: pairs the buffer pending AT THE OPEN with the flushes carried ACROSS the window, and those+ //: were read at two scopes: the buffer belonged to one decoder, the counter to all of them.+ //: `stop_generation` leaves the old decoder holding half a frame and `send_turn` follows it in+ //: all three shipped schedules, so if that NEW response was itself split -- ordinary, and+ //: likeliest exactly when the renderer is jammed -- its own split moved the shared counter and+ //: the window was refused for a stale buffer that never flushed. Measured before this change: a+ //: two-chunk reply after an abort delivered all 13 of its characters inside the window and was+ //: refused, while the same traffic without the abort was accepted. The loss is biased against+ //: the most expensive windows, in the flattering direction.+ const CARRIED_BY_ID = new Map();+ //: A bounded history, on the same discipline as `MAX_PENDING_CHARS`. `close` asks about the+ //: decoder pending when the window OPENED, which by then may be neither active nor alive, so+ //: the count cannot live only in the `WeakMap`. Keyed by an integer and holding no reference to+ //: any `TextDecoder`, so it cannot defeat the weak scoping above, and trimmed so a long film+ //: cannot grow it without limit.+ const MAX_DECODER_HISTORY = 64;+ let DECODER_SEQ = 0;+ const noteCarried = (st) => {+ st.carriedFlushes += 1;+ CARRIED_BY_ID.set(st.id, st.carriedFlushes);+ while (CARRIED_BY_ID.size > MAX_DECODER_HISTORY) {+ CARRIED_BY_ID.delete(CARRIED_BY_ID.keys().next().value);+ }+ };+ //: The carried count of a NAMED decoder, or of whichever one is active when no name is given.+ //: A decoder that never carried a frame is absent from the map and answers 0, which is the same+ //: answer it would have given had it still been alive.+ const carriedFor = (id) => {+ if (typeof id !== "number") return active.carriedFlushes;+ return CARRIED_BY_ID.get(id) || 0;+ };+ const newState = () => ({+ pending: "",+ markerTail: "",+ carriedFlushes: 0,+ id: (DECODER_SEQ += 1),+ });const stateFor = (decoder) => {let st = DECODER_STATE.get(decoder);if (!st) {- st = { pending: "", markerTail: "" };+ st = newState();DECODER_STATE.set(decoder, st);}return st;@@ -164,7 +202,10 @@//: `wireIntegrity` reports THIS buffer: half a frame of the response being measured is a short//: denominator and must refuse the window, while half a frame of a response that was aborted//: three slots ago says nothing about it.- let active = { pending: "", markerTail: "" };+ //: Built by `newState()` rather than by hand: a sentinel missing any field a real decoder state+ //: carries reads `undefined` on a window that opens before the first stream, and `undefined` is+ //: not zero. Its id comes from the same sequence, so `carriedFor` answers about it like any other.+ let active = newState();//: The decoder holding a speculative marker fragment, if any, and there is only ever one worth//: holding. A fragment is at most four characters and lives on the decoder that produced it, but//: it has to be REPORTED whoever holds it: a decoder whose first chunk is "dat" has not been@@ -298,7 +339,7 @@st.pending = parts.pop();// Something that was in the buffer before this call just became a counted frame. A window// whose OPEN saw a non-empty buffer is only wrong if this happens inside it.- if (carried && parts.length > 0) S.carriedFlushes += 1;+ if (carried && parts.length > 0) noteCarried(st);for (const part of parts) {const line = part.trim();if (!line.startsWith("data:")) continue;@@ -543,7 +584,14 @@// ever go up.// The two things that can make `wireChars` short by an unknown amount, read at the same O(1)// cost as the counter itself so a window boundary can capture both ends.- wireIntegrity() {+ // `forId` names the decoder to answer about, which `close` passes back from what `open`+ // sampled. WHOSE BUFFER AND WHOSE FLUSH HAVE TO BE THE SAME DECODER, and reading the active+ // one at both ends does not make them so: the decoder pending at the open can complete its+ // carried frame inside the window and be replaced as active before the close, and comparing+ // the two ends' ids would call that a mismatch and discard the very carry it looks for.+ // Naming the decoder answers regardless of who is active now, so a window that really did+ // count characters delivered before it opened is still refused.+ wireIntegrity(forId) {// The marker fragment counts as buffered, because it is: the frame it begins has not been// counted yet, so a window closing on it has a denominator that is short by that frame. The// cost of being honest here is that a stray one to four characters of unrelated traffic can@@ -552,9 +600,11 @@return {failures: S.wireParseFailures,pending_chars: active.pending.length + heldMarkerChars(),+ // WHICH decoder the two numbers above are about, so the close can ask about the same one.+ decoder_id: active.id,// Read as a DELTA across the window by `StreamCostInstrument.close`, so a buffer that was- // pending at the open refuses the window only when its frame was completed inside it.- carried_flushes: S.carriedFlushes,+ // pending at the open refuses the window only when ITS OWN frame was completed inside it.+ carried_flushes: carriedFor(forId),};},replyChars() {diff --git a/tests/studio/studiobench/instruments/streamcost.py b/tests/studio/studiobench/instruments/streamcost.pyindex 3ed83ff1f27..09518632a65 100644--- a/tests/studio/studiobench/instruments/streamcost.py+++ b/tests/studio/studiobench/instruments/streamcost.py@@ -122,7 +122,20 @@ class StreamCostInstrument(_PageInstrument):# different quantities -- the growth of the last mounted message against the characters# delivered to the page -- and nothing else in the row would tell them so.out["reply_chars_source"] = "sse_wire"- integrity = self._eval("() => window.__sb.streamcost.wireIntegrity()") or {}+ # ABOUT THE DECODER THAT WAS PENDING AT THE OPEN, named rather than assumed. The refusal+ # below pairs a buffer with a flush, and the two were read at different scopes: the buffer+ # belonged to one decoder, the flush counter was page-wide. Since `send_turn` follows+ # `stop_generation` in every shipped schedule, an abort's orphaned half frame was routinely+ # paired with a carried flush produced by the NEW response's own split, refusing a window+ # that had delivered every one of its characters. Naming the open's decoder makes the pair+ # a statement about one response.+ integrity = (+ self._eval(+ "(id) => window.__sb.streamcost.wireIntegrity(id)",+ self._integrity_open.get("decoder_id"),+ )+ or {}+ )failures = (integrity.get("failures") or 0) - (self._integrity_open.get("failures") or 0)residual = integrity.get("pending_chars") or 0# AND THE OTHER END OF THE SAME SPLIT. `pending` is not cleared by `reset()` -- it cannot