Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

serve: a batch request continued in another leg reports its own prompt's reuse, and input_tokens is never 0 (#1013)

CurtisTheb9fdc1cdcee9
diff --git a/serve/server.py b/serve/server.py
index 7b89f858a..48909d5ee 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -1089,6 +1089,7 @@ class StrataEngine:
out: list[int] = []
pending: list[int] = []
prompt, left = list(ids), int(max_new)
+ reused0 = None # the first read's reused tokens: a continued leg's count includes this request's own output
ok = yield from self._take_control(cancel, len(prompt))
if not ok:
return
@@ -1148,6 +1149,8 @@ class StrataEngine:
left = int(max_new) - len(out)
if cancel.is_set() or left <= 0 or finish in ("stop", "length") or (out and out[-1] in EOS_IDS):
return
+ if reused0 is None:
+ reused0 = (self.last or {}).get("reused")
prompt = list(ids) + out # promoted: it continues in a batch slot from here
while True:
if slot is None:
@@ -1257,6 +1260,8 @@ class StrataEngine:
self.slot_busy[slot] = False
self.slot_cv.notify_all()
slot, gen0 = None, None
+ if reused0 is None:
+ reused0 = (self.last or {}).get("reused")
prompt, left = list(ids) + out, int(max_new) - len(out)
solo_again += 1
btrace("back to the solo path")
@@ -1279,6 +1284,8 @@ class StrataEngine:
phase = "slot"
except EngineDied:
pass
+ if reused0 is not None and isinstance(self.last, dict):
+ self.last = {**self.last, "reused": reused0}
if holding:
self.ctl.release()
if reserved is not None:
@@ -3557,8 +3564,10 @@ def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, can
"tool_use" if used_tool and streamed <= finished and x["finish"] == "stop" else \
{"stop": "end_turn", "length": "max_tokens", "cancel": "end_turn"}[x["finish"]]
# the final counts, Anthropic's way: input_tokens leaves out what the conversation cache already held,
- # which is cache_read_input_tokens (message_start could only say the whole prompt)
- reused = min(x.get("reused") or 0, len(ids))
+ # which is cache_read_input_tokens (message_start could only say the whole prompt). At least the last
+ # prompt token is always read, and Claude Code takes an input_tokens of 0 as "not given" and keeps
+ # message_start's whole prompt beside cache_read_input_tokens: the prompt counted twice (#1013)
+ reused = max(0, min(x.get("reused") or 0, len(ids) - 1))
yield "message_delta", {"type": "message_delta", "delta": {"stop_reason": stop,
"stop_sequence": x.get("stop_sequence")},
"usage": {"input_tokens": len(ids) - reused, "cache_read_input_tokens": reused,
diff --git a/serve/test_parallel.py b/serve/test_parallel.py
index 52b0909b7..962ffbf28 100644
--- a/serve/test_parallel.py
+++ b/serve/test_parallel.py
@@ -42,11 +42,13 @@ print("INFO engine=0.1.39" + (f" batch_slots={fit}" if fit >= 2 else "") +
(" slot_cache=1" if "--slotcache" in args else ""), flush=True)
print("READY 4096 stop", flush=True)
LONG = list(b"LONGREPLY")
-def reply(ids): # the rest of the reply after what the prompt already ends with (a request continued)
+def continued(ids): # (the whole reply, how much of it the prompt already ends with: a request continued)
ids = [int(x) for x in ids]
long_one = any(ids[i:i + len(LONG)] == LONG for i in range(len(ids)))
R = list(b"ok, " + b"la " * 15 + b"done." if long_one else b"ok, done.") + [257]
- k = max(k for k in range(len(R)) if k == 0 or ids[-k:] == R[:k])
+ return R, max(k for k in range(len(R)) if k == 0 or ids[-k:] == R[:k])
+def reply(ids): # the rest of the reply after what the prompt already ends with
+ R, k = continued(ids)
return R[k:]
active = {} # slot -> [tokens left, max_new, produced]
stopped = set() # BSTOPped slots: they end "cancel"
@@ -67,6 +69,9 @@ def window(): # one batch window: every active slot one token
else:
active[b] = [left, max_new, produced]
log = open(args[args.index("--log") + 1], "a") if "--log" in args else None
+REUSE = "--reuse" in args # DONE's reused field as the engine gives it: a continued prompt is all held but its last
+def reused(ids): # token (the request's own output included), a fresh one the first 3 tokens
+ return 0 if not REUSE else len(ids) - 1 if continued(ids)[1] else 3
while True:
try:
line = lines.get(timeout=STEP if active else None)
@@ -121,7 +126,7 @@ while True:
if log:
log.write(f"YIELD {given[0]} {given[1]}\n"); log.flush()
print(f"YIELDED {given[0]} {given[1]}", flush=True)
- print(f"DONE 0 {len(ids)} 5.0 0.0 cancel 0 0 0", flush=True)
+ print(f"DONE 0 {len(ids)} 5.0 0.0 cancel 0 0 {reused(ids)}", flush=True)
if slot is not None:
print(f"BADM {slot} 0", flush=True)
continue
@@ -134,7 +139,7 @@ while True:
out += 1
time.sleep(STEP)
fin = "stop" if out and toks[out - 1] == 257 else ("cancel" if stop.is_set() else "length")
- print(f"DONE {out} {len(ids)} 5.0 {out * STEP * 1000:.1f} {fin} 0 0 0", flush=True)
+ print(f"DONE {out} {len(ids)} 5.0 {out * STEP * 1000:.1f} {fin} 0 0 {reused(ids)}", flush=True)
if slot is not None:
cont = fin == "length" and max_new > 1
if cont:
@@ -224,7 +229,7 @@ class PickSlot(unittest.TestCase):
class ParallelService(unittest.TestCase):
"""The real StrataEngine and Service over HTTP, the fake engine behind them."""
- def start(self, slots, fit=None, slot_cache=False, fail=False):
+ def start(self, slots, fit=None, slot_cache=False, fail=False, reuse=False):
import serve.server as server
self.tmp = tempfile.TemporaryDirectory()
script = Path(self.tmp.name) / "fake_strata.py"
@@ -234,6 +239,7 @@ class ParallelService(unittest.TestCase):
extra = ["--batch", str(slots)] + (["--fit", str(fit)] if fit is not None else []) + ["--log", str(self.log)]
extra += ["--slotcache"] if slot_cache else []
extra += ["--fail-window"] if fail else []
+ extra += ["--reuse"] if reuse else []
with mock.patch.object(server.subprocess, "Popen",
lambda cmd, **kw: real([sys.executable, str(script), *cmd[1:]], **kw)):
self.engine = StrataEngine("strata", extra)
@@ -258,6 +264,13 @@ class ParallelService(unittest.TestCase):
with urllib.request.urlopen(req, timeout=60) as r:
return json.loads(r.read().decode())
+ def message(self, text, max_tokens=64):
+ body = {"model": "m", "messages": [{"role": "user", "content": text}], "max_tokens": max_tokens}
+ req = urllib.request.Request(self.base + "/v1/messages", data=json.dumps(body).encode(),
+ headers={"Content-Type": "application/json", "anthropic-version": "2023-06-01"})
+ with urllib.request.urlopen(req, timeout=60) as r:
+ return json.loads(r.read().decode())
+
def get(self, path):
with urllib.request.urlopen(self.base + path, timeout=10) as r:
return json.loads(r.read().decode())
@@ -445,6 +458,28 @@ class ParallelService(unittest.TestCase):
self.assertIn("exited (code 1)", note)
self.assertIn("verify batch: layer 34 never rang (graph finished)", note)
+ def test_a_continued_request_reports_its_own_prompt_reuse(self):
+ """A request STOPped on the solo path and continued in a slot (or back on the solo path) is sent again as its
+ prompt + what it generated, and the engine holds all of that: the usage must still split the request's OWN
+ prompt (input_tokens + cache_read_input_tokens = the prompt, input_tokens >= 1). input_tokens 0 makes Claude
+ Code count the prompt twice (message_start's input_tokens + cache_read_input_tokens): "Prompt is too long"
+ at half the context."""
+ self.start(2, slot_cache=True, reuse=True)
+ res = {}
+ long = threading.Thread(target=lambda: res.setdefault("long", self.message("LONGREPLY please", 200)))
+ long.start()
+ time.sleep(0.05)
+ self.message("short", 200)
+ long.join(30)
+ kinds = [x.split()[0] for x in self.log.read_text().splitlines()]
+ self.assertIn("BGEN", kinds) # it was continued: the case under test
+ u = res["long"]["usage"]
+ prompt = self.svc.history[[h["output_tokens"] for h in self.svc.history].index(
+ max(h["output_tokens"] for h in self.svc.history))]["prompt_total"]
+ self.assertGreaterEqual(u["input_tokens"], 1, u)
+ self.assertEqual(u["input_tokens"] + u["cache_read_input_tokens"], prompt, u)
+ self.assertEqual(u["cache_read_input_tokens"], 3, u) # the first read's reuse, not the continuation's
+
if __name__ == "__main__":
unittest.main()