Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
feat(serve): measure first output and engine call durations
ZacharyZcR6567e76bcb64
diff --git a/c/openai_server.py b/c/openai_server.pyindex 57888ac7..2128f9da 100644--- a/c/openai_server.py+++ b/c/openai_server.py@@ -134,7 +134,8 @@ class GenerationScheduler:self.timed_out = 0self.cancelled = 0self.timings = {name: {"sum": 0.0, "buckets": [0] * len(self._buckets)}- for name in ("queue_wait_seconds", "slot_duration_seconds")}+ for name in ("queue_wait_seconds", "slot_duration_seconds",+ "first_output_seconds", "engine_call_seconds")}@contextlib.contextmanagerdef admit(self, cancelled=None, slot=None):@@ -227,6 +228,10 @@ class GenerationScheduler:if seconds <= bound:timing["buckets"][i] += 1+ def observe_timing(self, name, seconds):+ with self.condition:+ self._observe(name, seconds)+def prometheus(self):"""One consistent, bounded snapshot; no prompt or request-ID labels."""gauges = {"active": "Currently admitted requests.",@@ -249,7 +254,9 @@ class GenerationScheduler:f"{name} {value}"))for field, help_text in (("queue_wait_seconds", "Queue wait of admitted requests only."),- ("slot_duration_seconds", "Slot occupancy of finished admitted requests, including errors and cancellation.")):+ ("slot_duration_seconds", "Slot occupancy of finished admitted requests, including errors and cancellation."),+ ("first_output_seconds", "Engine-call start to first nonempty text or tool callback, excluding queue wait."),+ ("engine_call_seconds", "Duration of finished engine generation calls, including errors and cancellation.")):name = "colibri_scheduler_" + fieldtiming = self.timings[field]lines.extend((f"# HELP {name} {help_text}", f"# TYPE {name} histogram"))@@ -3589,6 +3596,27 @@ class APIServer(ThreadingHTTPServer):self._conn_by_ip = {}self._conn_owner = {}+ def generate(self, prompt, max_tokens, temperature, top_p, on_text, *args, **kwargs):+ started = time.monotonic()+ first_output = False++ def measured(callback):+ def feed(text):+ nonlocal first_output+ if text and not first_output:+ first_output = True+ self.scheduler.observe_timing("first_output_seconds", time.monotonic() - started)+ return callback(text)+ return feed++ if kwargs.get("on_tool") is not None:+ kwargs["on_tool"] = measured(kwargs["on_tool"])+ try:+ return self.engine.generate(prompt, max_tokens, temperature, top_p,+ measured(on_text), *args, **kwargs)+ finally:+ self.scheduler.observe_timing("engine_call_seconds", time.monotonic() - started)+def process_request(self, request, client_address):"""Refuse past the caps instead of spawning an unbounded thread."""peer = client_address[0] if client_address else "?"@@ -4199,7 +4227,7 @@ class APIHandler(BaseHTTPRequestHandler):def on_accept(value):accepted.update(value)- self.server.engine.generate(+ self.server.generate(text, 0, 0.0, 1.0, lambda _chunk: None, cache_slot,self.client_disconnected, logprobs=1, pin=pin,on_echo=echoes.append, on_accept=on_accept)@@ -4513,7 +4541,7 @@ class APIHandler(BaseHTTPRequestHandler):def generation_stopped():return stop_filter.stopped() or sideband.stopped()- stats = self.server.engine.generate(+ stats = self.server.generate(prompt, maximum, temperature, top_p, stop_filter.feed, cache_slot,self.client_disconnected, grammar=grammar, stopped=generation_stopped,**({"on_tool": sideband.feed} if sideband.enabled else {}),@@ -4695,7 +4723,7 @@ class APIHandler(BaseHTTPRequestHandler):def generation_stopped():return stop_filter.stopped() or sideband.stopped()- stats = self.server.engine.generate(+ stats = self.server.generate(prompt, maximum, temperature, top_p, stop_filter.feed, cache_slot,self.client_disconnected, grammar=grammar, stopped=generation_stopped,**({"on_tool": sideband.feed} if sideband.enabled else {}),@@ -4728,7 +4756,7 @@ class APIHandler(BaseHTTPRequestHandler):sys.stderr.write(chunk); sys.stderr.flush()(content_split.feed if content_split else emit)(chunk)stop_filter = StopFilter(stop_sequences, emit_plain, ignore_leading_stop)- stats = self.server.engine.generate(+ stats = self.server.generate(prompt, maximum, temperature, top_p, stop_filter.feed, cache_slot,self.client_disconnected, grammar=grammar, stopped=stop_filter.stopped,on_accept=start_stream, **({"audio": audio} if audio else {}),@@ -4946,7 +4974,7 @@ class APIHandler(BaseHTTPRequestHandler):def generation_stopped():return stop_filter.stopped() or sideband.stopped()- stats = self.server.engine.generate(+ stats = self.server.generate(prompt, maximum, temperature, top_p, stop_filter.feed, cache_slot,self.client_disconnected, grammar=grammar, stopped=generation_stopped,**({"on_tool": sideband.feed} if sideband.enabled else {}))@@ -5087,7 +5115,7 @@ class APIHandler(BaseHTTPRequestHandler):def generation_stopped():return stop_filter.stopped() or sideband.stopped()- stats = self.server.engine.generate(+ stats = self.server.generate(prompt, maximum, temperature, top_p, stop_filter.feed, cache_slot,lambda: not connected[0], grammar=grammar, stopped=generation_stopped,**({"on_tool": sideband.feed} if sideband.enabled else {}))diff --git a/c/tests/test_openai_server.py b/c/tests/test_openai_server.pyindex 581b5443..4d7065ff 100644--- a/c/tests/test_openai_server.py+++ b/c/tests/test_openai_server.py@@ -532,6 +532,64 @@ class ProtocolTest(unittest.TestCase):listener.close()+class GenerationMetricsTest(unittest.TestCase):+ def setUp(self):+ self.server = APIServer(("127.0.0.1", 0), FakeEngine(), "test")+ self.addCleanup(self.server.server_close)++ def test_records_first_output_once_and_preserves_text_and_stats(self):+ output = []+ with patch("openai_server.time.monotonic", side_effect=[10, 10.5, 13]):+ stats = self.server.generate("prompt", 4, 0, 1, output.append)+ self.assertEqual(output, ["Hé", "llo"])+ self.assertEqual(stats["completion_tokens"], 2)+ metrics = self.server.scheduler.prometheus()+ self.assertIn("colibri_scheduler_first_output_seconds_sum 0.5\n", metrics)+ self.assertIn("colibri_scheduler_first_output_seconds_count 1\n", metrics)+ self.assertIn("colibri_scheduler_engine_call_seconds_sum 3.0\n", metrics)+ self.assertIn("colibri_scheduler_engine_call_seconds_count 1\n", metrics)++ def test_empty_output_does_not_count_but_tool_output_does(self):+ text, tools = [], []+ def generate(prompt, maximum, temperature, top_p, on_text, **kwargs):+ on_text("")+ kwargs["on_tool"]("")+ kwargs["on_tool"]("tool payload")+ on_text("tail")+ return {"completion_tokens": 2}+ with patch.object(self.server.engine, "generate", side_effect=generate), \+ patch("openai_server.time.monotonic", side_effect=[10, 12, 15]):+ self.server.generate("prompt", 4, 0, 1, text.append, on_tool=tools.append)+ self.assertEqual(text, ["", "tail"])+ self.assertEqual(tools, ["", "tool payload"])+ metrics = self.server.scheduler.prometheus()+ self.assertIn("colibri_scheduler_first_output_seconds_sum 2.0\n", metrics)+ self.assertIn("colibri_scheduler_first_output_seconds_count 1\n", metrics)++ def test_error_and_cancellation_before_output_do_not_invent_first_output(self):+ for error in (RuntimeError("failed"), ClientCancelled()):+ with patch.object(self.server.engine, "generate", side_effect=error), \+ patch("openai_server.time.monotonic", side_effect=[10, 14]):+ with self.assertRaises(type(error)):+ self.server.generate("prompt", 4, 0, 1, lambda text: None)+ metrics = self.server.scheduler.prometheus()+ self.assertIn("colibri_scheduler_first_output_seconds_count 0\n", metrics)+ self.assertIn("colibri_scheduler_engine_call_seconds_sum 8.0\n", metrics)+ self.assertIn("colibri_scheduler_engine_call_seconds_count 2\n", metrics)++ def test_failure_after_output_keeps_both_observations(self):+ def generate(prompt, maximum, temperature, top_p, on_text):+ on_text("partial")+ raise RuntimeError("failed after output")+ with patch.object(self.server.engine, "generate", side_effect=generate), \+ patch("openai_server.time.monotonic", side_effect=[10, 11, 12]):+ with self.assertRaises(RuntimeError):+ self.server.generate("prompt", 4, 0, 1, lambda text: None)+ metrics = self.server.scheduler.prometheus()+ self.assertIn("colibri_scheduler_first_output_seconds_count 1\n", metrics)+ self.assertIn("colibri_scheduler_engine_call_seconds_count 1\n", metrics)++class SchedulerTest(unittest.TestCase):def test_engine_failure_is_not_a_completed_request(self):scheduler = GenerationScheduler()diff --git a/docs/api.md b/docs/api.mdindex b2cbaa4b..e4cdfced 100644--- a/docs/api.md+++ b/docs/api.md@@ -119,6 +119,8 @@ All names start with `colibri_scheduler_`:| `cancelled_total` | counter | Cancellations while queued or admitted || `queue_wait_seconds` | histogram | Wait until admission, for admitted requests only || `slot_duration_seconds` | histogram | Slot occupancy until completion, failure, or cancellation |+| `first_output_seconds` | histogram | Engine-call start to first nonempty text or tool-output callback |+| `engine_call_seconds` | histogram | Duration of each finished engine generation call, including failure/cancellation |Histogram buckets are 0.001, 0.01, 0.05, 0.1, 0.5, 1, 5, 10, 30, 60, 300 seconds,and `+Inf`; each histogram exposes `_bucket`, `_sum`, and `_count`.@@ -126,9 +128,19 @@ Counters reset when the gateway restarts. Collection does not call the engineor consume a generation slot. `failed` is also included in `/health`'sauthenticated scheduler snapshot; failures no longer increment `completed`.-These are admission/slot metrics, not TTFT, per-token latency, or GPU kernel-measurements. Slot occupancy includes any response handling while the slot is-held. Validation/authentication failures before admission are not counted.+The engine-call histograms exclude admission queue wait and prompt rendering.+First output is observed before the gateway's stop filtering, reasoning split,+or HTTP serialization: it can be reasoning or tool data, not necessarily+user-visible answer text. Empty callbacks, ACCEPT frames, and SSE keepalives do+not count. Calls that finish or fail without output add no first-output sample;+a failure after output retains that sample. Engine-call duration includes callback+processing and response writes during generation. One request can invoke the+engine multiple times (for example Brio scoring), so these histogram counts are+engine calls, not HTTP request counts.++These are gateway observations, not end-to-end client TTFT, per-token latency,+or GPU kernel measurements. Output callbacks need not correspond one-to-one to+tokens. Slot occupancy includes any response handling while the slot is held. Validation/authentication failures before admission are not counted.`completed` means the admitted handler returned normally, not that the clientreceived every response byte. Request exceptions can include client input ortransport errors as well as engine failures.