Skip to content

Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

serve: refuse an over-long prompt instead of silently truncating it (#401)

JustVuggb06affde7a49
diff --git a/c/colibri.c b/c/colibri.c
index 4a4b2e06..24e13af3 100644
--- a/c/colibri.c
+++ b/c/colibri.c
@@ -5092,9 +5092,25 @@ static int mux_submit(Model *m, Tok *T, ServeCtx *ctx, ServeReq *req, GrDraft *g
ServeCtx *sc=&ctx[sub.slot]; kv_bind(m,&sc->kv);
int *tmp=malloc(maxctx*sizeof(int));
if(!tmp){ fprintf(stderr,"OOM mux_submit tmp\n"); free(raw); free(line); exit(1); }
- int nt=tok_encode(T,raw,(int)sub.bytes,tmp,maxctx-2);
+ /* Encode with one token of headroom (maxctx-1, buffer is maxctx) purely to DETECT overflow:
+ * tok_encode stops dead at its cap and returns no signal that it ran out, so encoding at the
+ * real limit silently truncates an over-long prompt to its first maxctx-2 tokens. That is the
+ * #401 field failure: a coding client's system prompt alone exceeded CTX=4096, the tail --
+ * the tool instructions and the actual user turn -- was dropped, the model saw a prompt cut
+ * mid-markup and emitted a bare "<". Retries were identical because the surviving *head*
+ * never changes when a client appends to the end (hence "prefill 0" on every retry).
+ * Refuse loudly instead; the gateway turns this into a 400 context_length_exceeded. */
+ int nt=tok_encode(T,raw,(int)sub.bytes,tmp,maxctx-1);
free(raw); free(line);
if(nt<1){ free(tmp); printf("ERROR %llu EMPTY_PROMPT\n",sub.id); fflush(stdout); return 0; }
+ if(nt>maxctx-2){
+ free(tmp);
+ fprintf(stderr,"[API] prompt does not fit: >=%d token, context is %d (CTX=%d). "
+ "Raise it, e.g. CTX=32768 -- coding clients send large system prompts.\n",
+ nt,maxctx-2,maxctx);
+ printf("ERROR %llu CONTEXT_EXCEEDED %d %d\n",sub.id,nt,maxctx-2);
+ fflush(stdout); return 0;
+ }
int prefix=0; while(prefix<sc->len && prefix<nt && sc->hist[prefix]==tmp[prefix]) prefix++;
if(prefix<sc->len){ sc->len=prefix; if(m->has_mtp) m->kv_start[m->c.n_layers]=-1;
kv_disk_truncate(m,sc->len); }
diff --git a/c/openai_server.py b/c/openai_server.py
index ae1032c9..a0e56c06 100644
--- a/c/openai_server.py
+++ b/c/openai_server.py
@@ -59,6 +59,24 @@ def error_object(error):
"param": error.param, "code": error.code}}
+def _engine_error(fields, message):
+ """Turn an engine ERROR frame into the right exception type.
+
+ CONTEXT_EXCEEDED is a client mistake, not a server fault: the prompt is longer than the
+ engine's context. Report it the way every OpenAI-compatible server does, so clients that
+ know how to compact a conversation actually get the chance to (previously the engine
+ silently truncated the prompt instead, which is #401)."""
+ if fields and fields[0] == "CONTEXT_EXCEEDED":
+ limit = fields[2] if len(fields) > 2 else "the context"
+ used = fields[1] if len(fields) > 1 else "?"
+ return APIError(400,
+ f"This model's maximum context length is {limit} tokens, however your "
+ f"messages resulted in at least {used} tokens. Please shorten the "
+ f"conversation, or restart the server with a larger CTX.",
+ "messages", "context_length_exceeded")
+ return RuntimeError(message)
+
+
class GenerationScheduler:
"""Bounded FIFO admission for the engine's independent KV contexts."""
@@ -652,7 +670,7 @@ class Engine:
with self.pending_lock:
events = self.pending.pop(request_id, None)
if events is not None:
- events.put(("error", RuntimeError(message)))
+ events.put(("error", _engine_error(fields[2:], message)))
else:
raise RuntimeError(f"invalid engine response: {' '.join(fields)}")
except Exception as error:
diff --git a/c/tests/test_openai_server.py b/c/tests/test_openai_server.py
index 8000b400..7b0bb2bc 100644
--- a/c/tests/test_openai_server.py
+++ b/c/tests/test_openai_server.py
@@ -11,7 +11,7 @@ from urllib.request import Request, urlopen
from pathlib import Path
from openai_server import (APIError, APIHandler, APIServer, ClientCancelled, END, GenerationScheduler,
- READY, Engine, generation_options, parse_tool_calls,
+ READY, Engine, _engine_error, generation_options, parse_tool_calls,
read_engine_turn, render_chat, serve)
@@ -682,6 +682,32 @@ class ToolArgumentTypeTest(unittest.TestCase):
self.assertEqual(args["extra"], 7)
+class EngineErrorFrameTest(unittest.TestCase):
+ """#401: an over-long prompt used to be silently truncated to the first CTX-2 tokens, so the
+ model answered from a mutilated prompt and the client got HTTP 200 with junk. The engine now
+ refuses, and the refusal has to reach the client as a 400 it can act on -- not a 500."""
+
+ def test_context_exceeded_becomes_a_400_the_client_can_act_on(self):
+ err = _engine_error(["CONTEXT_EXCEEDED", "8321", "4094"], "CONTEXT_EXCEEDED 8321 4094")
+ self.assertIsInstance(err, APIError)
+ self.assertEqual(err.status, 400)
+ self.assertEqual(err.code, "context_length_exceeded")
+ self.assertEqual(err.param, "messages")
+ self.assertIn("4094", err.message)
+ self.assertIn("8321", err.message)
+
+ def test_other_engine_errors_stay_runtime_errors(self):
+ for frame in (["SLOT_BUSY"], ["BAD_REQUEST"], []):
+ err = _engine_error(frame, " ".join(frame) or "engine request failed")
+ self.assertIsInstance(err, RuntimeError)
+ self.assertNotIsInstance(err, APIError)
+
+ def test_malformed_context_frame_does_not_crash_the_dispatcher(self):
+ err = _engine_error(["CONTEXT_EXCEEDED"], "CONTEXT_EXCEEDED")
+ self.assertIsInstance(err, APIError)
+ self.assertEqual(err.status, 400)
+
+
class ToolChoiceTest(unittest.TestCase):
def test_none_does_not_offer_the_tools(self):
prompt = render_chat([{"role": "user", "content": "hi"}], tools=ORDER_TOOL,