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: STRATA_ADMIT_SHORT_FIRST=<tokens> admits short prompts before long ones (opt-in)

havok2-htwoed4fa42a8014
diff --git a/serve/server.py b/serve/server.py
index 5ca7f4e4d..2cb99bb66 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -254,6 +254,15 @@ def _timeout_env(name: str, default: float) -> float | None:
# still working is never ended by this, only reported once (the recommendation: engine_silence_s, or this variable).
# STRATA_ENGINE_STALL_S overrides it (0 = off). Needs psutil (setup installs it); without it nothing is ended.
ENGINE_STALL_S = _timeout_env("STRATA_ENGINE_STALL_S", 90.0)
+# --batch: new requests take the control lines (one prompt read at a time) short prompts first: a prompt of at most
+# STRATA_ADMIT_SHORT_FIRST tokens goes before longer ones (opt-in; unset or 0: whoever gets the lock first), and a
+# longer one that waited STRATA_ADMIT_MAX_WAIT_S (default 30) counts as short. A chat question then waits for the one
+# read in progress, not for every agent read that came before it.
+try:
+ ADMIT_SHORT_FIRST = max(0, int(os.environ.get("STRATA_ADMIT_SHORT_FIRST") or 0))
+except ValueError:
+ ADMIT_SHORT_FIRST = 0
+ADMIT_MAX_WAIT_S = _timeout_env("STRATA_ADMIT_MAX_WAIT_S", 30.0) or 0.0
STALL_CPU_EPS_S = 0.5 # CPU seconds the engine may use in the whole stall window and still count as frozen
STALL_IO_EPS_B = 1 << 20 # bytes read or written in that window
@@ -1416,10 +1425,11 @@ class StrataEngine:
YIELDS_MAX = 2 # #656: how often one request's prompt read gives way to a shorter waiting one
- def _take_control(self, cancel, plen: int, after_epoch: int | None = None):
+ def _take_control(self, cancel, plen: int, after_epoch: int | None = None, new: bool = False):
"""Waits for the control lines (one prompt read at a time), yielding None heartbeats; False when cancelled.
- `after_epoch`: a request whose read gave way lets the requests waiting then go first."""
- entry = [plen]
+ `after_epoch`: a request whose read gave way lets the requests waiting then go first.
+ `new`: the request's first admission (STRATA_ADMIT_SHORT_FIRST orders only these)."""
+ entry = [plen, time.monotonic(), new] # (length, arrival, ordered: STRATA_ADMIT_SHORT_FIRST)
with self.slot_cv:
self.waiting += 1
self.wait_lens.append(entry)
@@ -1433,7 +1443,17 @@ class StrataEngine:
raise EngineDied("the engine stopped while this request waited; it was not sent")
with self.slot_cv:
turn = after_epoch is None or self.ctl_epoch > after_epoch or self.waiting <= 1
+ if turn and new and ADMIT_SHORT_FIRST > 0:
+ turn = self._admit_next() is entry
if turn and self.ctl.acquire(timeout=0.5):
+ if new and ADMIT_SHORT_FIRST > 0:
+ with self.slot_cv: # a shorter one came while this one waited in acquire()
+ first = self._admit_next() is entry
+ if not first:
+ self.ctl.release()
+ with self.slot_cv:
+ self.slot_cv.notify_all()
+ continue
if self.alive():
break
self.ctl.release() # it died (or is being restarted) while this one was getting
@@ -1456,6 +1476,18 @@ class StrataEngine:
self.slot_cv.notify_all()
return True
+ def _admit_next(self):
+ """STRATA_ADMIT_SHORT_FIRST=<tokens> (the caller holds slot_cv): the new request that takes the control lines
+ next - one whose prompt is at most that long (it reads little) before a longer one, in arrival order within
+ each; a longer one that has waited STRATA_ADMIT_MAX_WAIT_S counts as short (it is never held back for good).
+ Off (unset or 0): whoever gets the lock first, as before. Only the order changes, never what is read."""
+ now = time.monotonic()
+ ordered = [e for e in self.wait_lens if len(e) > 2 and e[2]]
+ if not ordered:
+ return None
+ return min(ordered, key=lambda e: (0 if e[0] <= ADMIT_SHORT_FIRST or now - e[1] >= ADMIT_MAX_WAIT_S else 1,
+ e[1]))
+
SOLO_AGAIN_MAX = 2 # how often a request left alone in a slot goes back to the solo path
SOLO_AGAIN_MIN_LEFT = 32 # ... only with at least this many tokens still allowed (max_tokens)
@@ -1493,7 +1525,7 @@ class StrataEngine:
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
carry = {} # #1869: the figures of the legs that ended in a hand-back to the solo path (the final DONE adds to them)
- ok = yield from self._take_control(cancel, len(prompt))
+ ok = yield from self._take_control(cancel, len(prompt), new=True)
if not ok:
return
holding, born = True, self.gen # (the engine it now has the control lines of)
diff --git a/serve/test_admit_order.py b/serve/test_admit_order.py
new file mode 100644
index 000000000..67766e557
--- /dev/null
+++ b/serve/test_admit_order.py
@@ -0,0 +1,119 @@
+"""serve/test_admit_order.py - STRATA_ADMIT_SHORT_FIRST: new requests take the control lines short prompts first
+(StrataEngine._take_control / _admit_next; no process, no GPU).
+
+ python -m unittest serve.test_admit_order -v
+"""
+from __future__ import annotations
+
+import sys
+import threading
+import time
+import unittest
+from pathlib import Path
+from unittest import mock
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+import serve.server as server # noqa: E402
+from serve.server import StrataEngine # noqa: E402
+
+
+def engine_without_process(n=2):
+ """A StrataEngine with the admission state of a started one and no process: alive() is `e.up`."""
+ e = StrataEngine("missing-executable", [], lazy=True)
+ e.batch = n
+ e.slot_busy = [False] * n
+ e.slot_claims, e.slot_releasing, e._orphan_seen = set(), set(), {}
+ e.slot_cv = threading.Condition()
+ e.waiting, e.admitting, e.wait_lens, e.ctl_epoch = 0, 0, [], 0
+ e.ctl = threading.Lock()
+ e.gen = 1
+ e.up = True
+ e.alive = lambda: e.up
+ return e
+
+
+class AdmitOrderTest(unittest.TestCase):
+ def setUp(self):
+ self.e = engine_without_process(16)
+ self.order, self.cancels = [], []
+ self.order_lock = threading.Lock()
+
+ def tearDown(self):
+ for c in self.cancels:
+ c.set()
+
+ def take(self, name, plen, **kw):
+ """A request waiting for the control lines; once it has them it notes its name and gives them back."""
+ c = threading.Event()
+ self.cancels.append(c)
+
+ def go():
+ gen = self.e._take_control(c, plen, **kw)
+ try:
+ while True:
+ next(gen)
+ except StopIteration as s:
+ if s.value:
+ with self.order_lock:
+ self.order.append(name)
+ time.sleep(0.05) # its read
+ self.e.ctl.release()
+ threading.Thread(target=go, daemon=True).start()
+
+ def until(self, cond, s=5.0):
+ end = time.time() + s
+ while time.time() < end and not cond():
+ time.sleep(0.01)
+ self.assertTrue(cond())
+
+ def queue(self, *reqs):
+ """While a long read holds the control lines, the requests arrive in this order; then the read ends."""
+ self.assertTrue(self.e.ctl.acquire(timeout=1))
+ for name, plen in reqs:
+ self.take(name, plen, new=True)
+ self.until(lambda n=len(self.order) + sum(1 for _ in self.e.wait_lens): self.e.waiting >= 1)
+ time.sleep(0.02) # (distinct arrival times)
+ self.until(lambda: self.e.waiting == len(reqs))
+ self.e.ctl.release()
+ self.until(lambda: len(self.order) == len(reqs), s=15.0)
+ return self.order
+
+ def test_short_first_puts_the_chat_before_the_agent_reads(self):
+ with mock.patch.object(server, "ADMIT_SHORT_FIRST", 8192), mock.patch.object(server, "ADMIT_MAX_WAIT_S", 60.0):
+ order = self.queue(("agent1", 120000), ("agent2", 190000), ("chat", 500), ("agent3", 150000))
+ self.assertEqual(order[0], "chat")
+ self.assertEqual(order[1:], ["agent1", "agent2", "agent3"]) # arrival order among the long ones
+
+ def test_a_long_request_that_waited_too_long_goes_first(self):
+ with mock.patch.object(server, "ADMIT_SHORT_FIRST", 8192), mock.patch.object(server, "ADMIT_MAX_WAIT_S", 0.2):
+ self.assertTrue(self.e.ctl.acquire(timeout=1))
+ self.take("agent", 120000, new=True)
+ self.until(lambda: self.e.waiting == 1)
+ time.sleep(0.4) # past STRATA_ADMIT_MAX_WAIT_S
+ self.take("chat", 500, new=True)
+ self.until(lambda: self.e.waiting == 2)
+ self.e.ctl.release()
+ self.until(lambda: len(self.order) == 2, s=15.0)
+ self.assertEqual(self.order, ["agent", "chat"])
+
+ def test_off_by_default(self):
+ self.assertEqual(server.ADMIT_SHORT_FIRST if "STRATA_ADMIT_SHORT_FIRST" not in __import__("os").environ
+ else 0, 0)
+ with mock.patch.object(server, "ADMIT_SHORT_FIRST", 0):
+ order = self.queue(("agent1", 120000), ("chat", 500))
+ self.assertEqual(sorted(order), ["agent1", "chat"]) # both get their turn, in any order
+
+ def test_a_continuation_is_not_held_back(self):
+ """A request already admitted once (new=False: promoted from the solo path) is not part of the order."""
+ with mock.patch.object(server, "ADMIT_SHORT_FIRST", 8192), mock.patch.object(server, "ADMIT_MAX_WAIT_S", 60.0):
+ self.assertTrue(self.e.ctl.acquire(timeout=1))
+ self.take("chat", 500, new=True)
+ self.take("continuation", 190000)
+ self.until(lambda: self.e.waiting == 2)
+ self.e.ctl.release()
+ self.until(lambda: len(self.order) == 2, s=15.0)
+ self.assertEqual(sorted(self.order), ["chat", "continuation"])
+
+
+if __name__ == "__main__":
+ unittest.main()