diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 56f676ad98..5a91cfcbdb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1728,7 +1728,12 @@ jobs: SNAP=./glm_tiny TF=1 COLI_TEMP=0 ORACLE_STRICT=1 ORACLE_TF_MAX_MISMATCHES=2 ./colibri 64 16 16 SNAP=./glm_tiny COLI_TEMP=0 ORACLE_STRICT=1 ./colibri 64 16 16 - name: Oracle allowance and failure regressions - run: cd c && python3 tests/test_glm_oracle.py + run: | + cd c + python3 tests/test_glm_oracle.py + # Reuse the generated fixture: discovery without this variable skips + # every serving context-refusal regression. + COLI_ORACLE_FIXTURE="$PWD/glm_tiny" python3 -m unittest -v tests.test_run_serve_context_exceeded - name: The MTP head under the draft gate (docs/speculative.md) # Greedy stays exact whatever the gate picks (a draft is only ever verified), # with the gate deciding from measured times and with every draft carried. diff --git a/c/coli b/c/coli index 483c34fc77..5ce8413df6 100755 --- a/c/coli +++ b/c/coli @@ -1294,6 +1294,18 @@ def stream_turn(p, sentinel, on_bytes): line=p.stdout.readline().decode("utf-8","replace").strip() # STAT tok tps hit rss m=re.match(r"STAT (\S+) (\S+) (\S+) (\S+)", line) st={"tok":int(m.group(1)),"tps":float(m.group(2)),"hit":float(m.group(3)),"rss":float(m.group(4))} if m else {} + fields=line.split() + # STAT tok tps hit rss prompt_tokens 0 CONTEXT_EXCEEDED [cause]: + # the token sits at fields[7] (the PR's "7th token" counts past + # the STAT keyword). + if len(fields)>=8 and fields[7]=="CONTEXT_EXCEEDED": + # #2097: the legacy protocol has no ERROR frame; the engine + # refuses an over-context turn with an empty answer plus this + # token (and the cause as the next field: PROMPT_TOO_LONG, + # HISTORY_FULL, or RENDER_CLIPPED). The chat loop turns it + # into the message the user actually sees; older engines send + # no cause, hence True as the fallback. + st["context_exceeded"]=fields[8] if len(fields)>=9 else True if interrupted: st["interrupted"]=True return st if len(pend)>len(sentinel): @@ -3066,6 +3078,23 @@ def cmd_chat(a): if not raw: md.close() sp2.stop() if st is None: engine_diag(p, errlog); break + if st.get("context_exceeded"): + # #2097: the turn was refused, not answered. An empty answer + # here used to read as the model going silent, with the reason + # only in the engine's stderr, which this client drains to a + # temporary log and never shows. Say why, and what fixes it. + cause=st["context_exceeded"] + if cause=="HISTORY_FULL": + why="the conversation history no longer fits the context" + hint="type :reset to clear it and continue" + elif cause=="RENDER_CLIPPED": + why="the prompt text exceeded the 64KB render buffer and was clipped" + hint="paste it in shorter chunks" + else: # PROMPT_TOO_LONG, or an older engine with no cause token + why="this turn does not fit the context" + hint="shorten the prompt or raise CTX (:reset only clears history)" + print(f" {C.yel}[context is full: {why}; {hint}]{C.r}\n") + continue el=time.time()-t0 if st.get("tok") and chat_stats_mode(a) == "off": if st.get("interrupted"): print(f" {C.yel}⏹ interrupted; type :more to continue the response{C.r}") diff --git a/c/colibri.c b/c/colibri.c index 4df19d2565..bc963f0555 100644 --- a/c/colibri.c +++ b/c/colibri.c @@ -11431,7 +11431,28 @@ static void run_serve(Model *m, const char *snap){ const char *tk = getenv("THINK")&&atoi(getenv("THINK"))? "" : ""; if(raw_mode){ int *tmp=malloc(maxctx*sizeof(int)); if(!tmp){fprintf(stderr,"OOM raw tokens\n");exit(1);} - prompt_tokens=tok_encode(&T,input,input_n,tmp,maxctx-8-g_draft); + /* #2097: encode with one token of headroom (maxctx-1, buffer is + * maxctx) purely to DETECT overflow -- tok_encode stops dead at its + * cap with no signal, so the old cap (maxctx-8-g_draft) silently + * truncated an over-long prompt and the engine answered from the + * cut text. A full buffer means the prompt does not fit: refuse + * like mux_submit instead of generating from a truncated prompt. */ + prompt_tokens=tok_encode(&T,input,input_n,tmp,maxctx-1); + if(prompt_tokens>maxctx-2){ + /* The legacy protocol has no ERROR frame: this is an empty + * answer plus a STAT line carrying CONTEXT_EXCEEDED as a 7th + * token and the cause (PROMPT_TOO_LONG here) as an 8th + * ('coli' matches the first fields and ignores the rest), + * plus a stderr line the operator can act on. */ + free(tmp); free(raw); g_temp=base_temp; g_nuc=base_nuc; + fprintf(stderr,"[API] prompt does not fit: >=%d tokens, context is %d " + "(CTX=%d). Raise CTX or shorten the prompt.\n", + prompt_tokens,maxctx-2,maxctx); + printf("\x01\x01" "END" "\x01\x01\n"); + printf("STAT 0 0.00 0.0 %.2f %d 0 CONTEXT_EXCEEDED PROMPT_TOO_LONG\n", + rss_gb(),prompt_tokens); + fflush(stdout); continue; + } int old_len=len, prefix=0; while(prefix"); - bl+=snprintf(buf+bl,(1<<16)-bl,"<|user|>%s<|assistant|>%s",input,tk); } - else bl+=snprintf(buf+bl,(1<<16)-bl,"%s",input); - k=tok_encode(&T,buf,bl,hist+len,maxctx-len); prompt_tokens=k; - if(len+k+8+g_draft>=maxctx){ len=0; first=1; kv_disk_reset(m); - bl=0; if(templ){ bl+=snprintf(buf+bl,(1<<16)-bl,"[gMASK]<|user|>%s<|assistant|>%s",input,tk); } - else bl+=snprintf(buf+bl,(1<<16)-bl,"%s",input); - k=tok_encode(&T,buf,bl,hist,maxctx); if(k>maxctx-8-g_draft) k=maxctx-8-g_draft; - prompt_tokens=k; + /* Render the turn into the 64KB buf first, watching for a clipped + * render (snprintf returns what it *would* have written), then + * encode with one token of headroom to DETECT overflow. The old + * code reset the conversation (len=0) and clamped k to + * maxctx-8-g_draft, silently dropping history and the tail of the + * prompt; refuse loudly in every case instead. */ + int clipped=0, w; + if(templ){ + if(first){ w=snprintf(buf+bl,(1<<16)-bl,"[gMASK]"); + if(w<0||w>=(1<<16)-bl) clipped=1; else bl+=w; } + w=snprintf(buf+bl,(1<<16)-bl,"<|user|>%s<|assistant|>%s",input,tk); + if(w<0||w>=(1<<16)-bl) clipped=1; else bl+=w; + } else { + w=snprintf(buf+bl,(1<<16)-bl,"%s",input); + if(w<0||w>=(1<<16)-bl) clipped=1; else bl+=w; + } + int *tmp=malloc(maxctx*sizeof(int)); if(!tmp){fprintf(stderr,"OOM turn tokens\n");exit(1);} + k=tok_encode(&T,buf,bl,tmp,maxctx-1); prompt_tokens=k; + if(clipped || k>maxctx-2 || len+k+8+g_draft>=maxctx){ + /* Same refusal contract as the API arm above, with the cause + * as the 8th STAT token so 'coli chat' can print the right + * hint: HISTORY_FULL wants :reset, PROMPT_TOO_LONG wants a + * shorter prompt or a bigger CTX, RENDER_CLIPPED wants the + * prompt pasted in smaller chunks. */ + free(tmp); g_temp=base_temp; g_nuc=base_nuc; + const char *cause; + if(clipped){ + cause="RENDER_CLIPPED"; + fprintf(stderr,"[chat] prompt text exceeded the 64KB render buffer and was " + "clipped; refusing rather than answering from clipped text. " + "Paste shorter chunks.\n"); + } else if(k>maxctx-2){ + cause="PROMPT_TOO_LONG"; + fprintf(stderr,"[chat] turn does not fit: >=%d tokens, context is %d " + "(CTX=%d). Raise CTX or shorten the prompt.\n", + k,maxctx-2,maxctx); + } else { + cause="HISTORY_FULL"; + fprintf(stderr,"[chat] conversation history no longer fits the context " + "(CTX=%d); clear it (\\x02RESET) to continue.\n",maxctx); + } + printf("\n\x01\x01" "END" "\x01\x01\n"); + printf("STAT 0 0.00 0.0 %.2f %d 0 CONTEXT_EXCEEDED %s\n", + rss_gb(),prompt_tokens,cause); + fflush(stdout); continue; } + if(k>0) memcpy(hist+len,tmp,k*sizeof(int)); + free(tmp); } if(prompt_tokens<1){ free(raw); g_temp=base_temp; g_nuc=base_nuc; printf("\x01\x01" "END" "\x01\x01\n"); printf("STAT 0 0.00 0.0 %.2f 0 0\n", rss_gb()); fflush(stdout); continue; } diff --git a/c/tests/test_chat_context_exceeded.py b/c/tests/test_chat_context_exceeded.py new file mode 100644 index 0000000000..e743ca0db5 --- /dev/null +++ b/c/tests/test_chat_context_exceeded.py @@ -0,0 +1,137 @@ +"""`coli chat` surfaces the engine's CONTEXT_EXCEEDED refusal instead of an empty answer. + +The legacy run_serve protocol has no ERROR frame: on an over-context turn the +engine emits an empty answer plus `STAT ... CONTEXT_EXCEEDED ` (#2097). +The reason used to go only to the engine's stderr, which `coli chat` drains +into a temporary log and never shows, so the user saw empty answers until they +typed `:reset`, without being told to. The chat loop now reads the token on +the STAT line and prints the reason with the hint that actually fixes it. + +The test runs the real cmd_chat in a child Python against a fake engine that +speaks the chat byte protocol and refuses every turn with a chosen cause +spelling, and asserts the user sees the reason plus the right hint. +""" +import json +import os +import subprocess +import sys +import tempfile +import textwrap +import unittest +from pathlib import Path + +CLI = Path(__file__).resolve().parent.parent / "coli" + +ENGINE = textwrap.dedent("""\ + import sys + cause = sys.argv[1] + err, out = sys.stderr.buffer, sys.stdout.buffer + out.write(b"\\x01\\x01READY\\x01\\x01\\n"); out.flush() + out.write(b"STAT 0 0.00 0.0 1.00\\n"); out.flush() + out.write(b"TIERS 0 0 0 0 0\\n"); out.flush() + for line in sys.stdin.buffer: + if line.strip() == b"\\x02RESET": + out.write(b"\\x01\\x01END\\x01\\x01\\n"); out.flush() + out.write(b"STAT 0 0.00 0.0 1.00\\n"); out.flush() + continue + # An over-context turn: empty answer, STAT refusal, no stderr reason + # (the real engine's reason lives in the temp log the chat never shows). + stat = b"STAT 0 0.00 0.0 1.00 99 0 CONTEXT_EXCEEDED" + if cause: + stat += b" " + cause.encode() + out.write(b"\\n\\x01\\x01END\\x01\\x01\\n"); out.flush() + out.write(stat + b"\\n"); out.flush() +""") + +DRIVER = textwrap.dedent("""\ + import importlib.util, io, json, os, subprocess, sys, tempfile + from importlib.machinery import SourceFileLoader + from pathlib import Path + from unittest import mock + + cli, engine, cause = sys.argv[1], sys.argv[2], sys.argv[3] + loader = SourceFileLoader("coli_chat_ctx", cli) + spec = importlib.util.spec_from_loader(loader.name, loader) + coli = importlib.util.module_from_spec(spec) + loader.exec_module(coli) + + model = tempfile.mkdtemp() + Path(model, "config.json").write_text('{"model_type": "glm_moe_dsa"}') + real_popen = subprocess.Popen + + class Spinner: + def __init__(self, label, tick=None): pass + def start(self): pass + def stop(self): pass + + prompts = iter(["first question", "second question"]) + sent = [] + def fake_input(*_): + try: + sent.append(next(prompts)); return sent[-1] + except StopIteration: + raise EOFError + + args = coli.argparse.Namespace(model=model, cap=None, ngen=16, ram=0, topp=0, topk=0, + no_attach=True, attach=None, api_key=None, stats="off", + temp=None, think=None, effort=None, ctx=0) + out = io.StringIO() + with mock.patch.object(coli, "need_model"), \\ + mock.patch.object(coli, "banner"), \\ + mock.patch.object(coli, "env_for", return_value=dict(os.environ)), \\ + mock.patch.object(coli, "TTY", False), \\ + mock.patch.object(coli, "Spinner", Spinner), \\ + mock.patch.object(coli.subprocess, "Popen", + lambda cmd, **kw: real_popen([sys.executable, engine, cause], **kw)), \\ + mock.patch("builtins.input", fake_input), \\ + mock.patch.object(sys, "stdout", out): + try: + coli.cmd_chat(args) + except SystemExit: + pass + print(json.dumps({"output": out.getvalue(), "turns": len(sent)}, ensure_ascii=True)) +""") + + +def chat(cause): + with tempfile.TemporaryDirectory() as scratch: + engine = Path(scratch, "engine.py") + engine.write_text(ENGINE, encoding="utf-8") + driver = Path(scratch, "driver.py") + driver.write_text(DRIVER, encoding="utf-8") + try: + result = subprocess.run([sys.executable, str(driver), str(CLI), str(engine), cause], + capture_output=True, timeout=90) + except subprocess.TimeoutExpired: + raise AssertionError("`coli chat` hung talking to the refusing engine") + if result.returncode: + raise AssertionError(result.stderr.decode("utf-8", "replace")[-3000:]) + report = json.loads(result.stdout.decode("utf-8").strip().splitlines()[-1]) + return report + + +class ChatContextExceededTest(unittest.TestCase): + def test_history_full_names_the_reset_hint(self): + report = chat("HISTORY_FULL") + self.assertEqual(report["turns"], 2) + self.assertIn("the conversation history no longer fits the context", report["output"]) + self.assertIn("type :reset to clear it and continue", report["output"]) + + def test_prompt_too_long_says_shorten_or_raise_ctx(self): + report = chat("PROMPT_TOO_LONG") + self.assertIn("this turn does not fit the context", report["output"]) + self.assertIn("shorten the prompt or raise CTX", report["output"]) + + def test_render_clipped_says_paste_shorter_chunks(self): + report = chat("RENDER_CLIPPED") + self.assertIn("exceeded the 64KB render buffer", report["output"]) + self.assertIn("paste it in shorter chunks", report["output"]) + + def test_older_engine_without_a_cause_token_still_explains(self): + report = chat("") + self.assertIn("[context is full:", report["output"]) + self.assertIn("shorten the prompt or raise CTX", report["output"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/c/tests/test_run_serve_context_exceeded.py b/c/tests/test_run_serve_context_exceeded.py new file mode 100644 index 0000000000..236fe0483b --- /dev/null +++ b/c/tests/test_run_serve_context_exceeded.py @@ -0,0 +1,154 @@ +"""Legacy run_serve refuses over-context prompts in both arms, never silently truncating. + +The legacy protocol (what `coli chat` speaks, and the pre-mux `\\x02PROMPT` API +mode) has no ERROR frame: on an over-context turn the engine emits an empty +answer plus `STAT ... CONTEXT_EXCEEDED ` (#2097). This drives the real +`colibri` binary with SERVE=1 against the tiny GLM oracle model +(`c/tools/make_glm_oracle.py`) with a small CTX and asserts the refusal in +both modes, the cause token for a filled history, and that a prompt that fits +is still answered. + +Needs a built `colibri` and COLI_ORACLE_FIXTURE pointing at a directory with +the oracle's model.safetensors + config.json. The byte-level tokenizer.json is +written into a scratch copy: the oracle ships none, and one token per byte +keeps the token math exact. +""" +import json +import os +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent.parent +BINARY = next((path for path in (HERE / "colibri.exe", HERE / "colibri") if path.exists()), None) +FIXTURE = Path(os.environ.get("COLI_ORACLE_FIXTURE", "")) +CTX = 64 +NGEN = 4 +OVER_LONG = b"abc" * 40 # 120 bytes -> 120 tokens, far past CTX + + +def byte_tokenizer(): + """One token per byte; byte 0 is skipped (the C JSON parser rejects NUL keys).""" + return {"version": "1.0", + "model": {"type": "BPE", + "vocab": {chr(b): b for b in range(1, 256)}, + "merges": []}, + "added_tokens": []} + + +class ServeSession: + """One SERVE=1 engine process speaking the legacy byte protocol.""" + + def __init__(self, snap): + keep = {"PATH", "SYSTEMROOT", "WINDIR", "TEMP", "TMP", "HOME", "USERPROFILE", + "LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH"} + env = {k: v for k, v in os.environ.items() if k in keep} + env.update(SNAP=str(snap), SERVE="1", CTX=str(CTX), NGEN=str(NGEN), + COLI_TEMP="0", OMP_NUM_THREADS="2", COLI_NO_OMP_TUNE="1") + self.process = subprocess.Popen([str(BINARY), "0"], env=env, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, bufsize=0) + while b"READY" not in self.readline(): + pass + self.readline() # startup STAT + self.readline() # TIERS + + def readline(self): + line = self.process.stdout.readline() + if not line: + raise AssertionError("the engine closed the stream mid-turn") + return line + + def turn(self, payload): + """Send one interactive line; return (answer bytes, STAT fields).""" + self.process.stdin.write(payload + b"\n") + self.process.stdin.flush() + return self._read_turn() + + def api_turn(self, prompt): + """Send one \\x02PROMPT frame (the pre-mux API mode).""" + self.process.stdin.write(f"\x02PROMPT {len(prompt)} {NGEN} 0.0 1.0\n".encode() + + prompt + b"\n") + self.process.stdin.flush() + return self._read_turn() + + def _read_turn(self): + answer = b"" + for _ in range(400): + line = self.readline() + if b"\x01\x01END\x01\x01" in line: + break + answer += line + else: + raise AssertionError("no END sentinel within 400 lines") + stat = self.readline().decode("utf-8", "replace").strip().split() + assert stat[0] == "STAT", stat + return answer, stat + + def close(self): + self.process.stdin.close() + try: + self.process.wait(60) + except subprocess.TimeoutExpired: + self.process.kill() + self.process.wait() + self.process.stdout.close() + + +@unittest.skipUnless(BINARY, "colibri engine is not built") +@unittest.skipUnless(FIXTURE.name and (FIXTURE / "model.safetensors").is_file() + and (FIXTURE / "config.json").is_file(), + "COLI_ORACLE_FIXTURE not set to a make_glm_oracle.py output dir") +class RunServeContextExceededTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.scratch = tempfile.TemporaryDirectory(prefix="colibri-ctx-") + snap = Path(cls.scratch.name) + shutil.copy2(FIXTURE / "model.safetensors", snap / "model.safetensors") + shutil.copy2(FIXTURE / "config.json", snap / "config.json") + (snap / "tokenizer.json").write_text(json.dumps(byte_tokenizer(), ensure_ascii=True), + encoding="utf-8") + cls.snap = snap + + @classmethod + def tearDownClass(cls): + cls.scratch.cleanup() + + def session(self): + session = ServeSession(self.snap) + self.addCleanup(session.close) + return session + + def test_interactive_over_long_prompt_is_refused(self): + answer, stat = self.session().turn(OVER_LONG) + self.assertFalse(answer.strip(), "an over-context turn must have no answer") + self.assertEqual(stat[7], "CONTEXT_EXCEEDED", stat) + self.assertEqual(stat[8], "PROMPT_TOO_LONG", stat) + + def test_api_mode_over_long_prompt_is_refused(self): + answer, stat = self.session().api_turn(OVER_LONG) + self.assertFalse(answer.strip(), "an over-context turn must have no answer") + self.assertEqual(stat[7], "CONTEXT_EXCEEDED", stat) + self.assertEqual(stat[8], "PROMPT_TOO_LONG", stat) + + def test_a_filled_history_is_refused_with_the_reset_cause(self): + session = self.session() + answer, stat = session.turn(b"hi") + self.assertTrue(answer.strip(), "a fitting turn must be answered") + self.assertNotIn("CONTEXT_EXCEEDED", stat) + # The second identical turn no longer fits CTX: refuse, do not wipe history. + answer, stat = session.turn(b"hi") + self.assertFalse(answer.strip(), "an over-context turn must have no answer") + self.assertEqual(stat[7], "CONTEXT_EXCEEDED", stat) + self.assertEqual(stat[8], "HISTORY_FULL", stat) + + def test_a_prompt_that_fits_is_still_answered(self): + answer, stat = self.session().turn(b"hi") + self.assertTrue(answer.strip(), "a fitting turn must be answered") + self.assertNotIn("CONTEXT_EXCEEDED", stat) + + +if __name__ == "__main__": + unittest.main() diff --git a/docs/serve_protocol.md b/docs/serve_protocol.md index beff9ec5fb..e51c01a489 100644 --- a/docs/serve_protocol.md +++ b/docs/serve_protocol.md @@ -195,3 +195,13 @@ Interactive lines are prompts; control frames: `\x02RESET` (clear history), `\x02PROMPT [kv_slot]\n\n` (the pre-mux API mode). Responses are raw text terminated by `\x01\x01END\x01\x01` plus a `STAT` line. New integrations should use the mux protocol. + +Over-context prompts are refused, never silently truncated (#2097): the engine +emits an empty answer, a `STAT` line with a seventh `CONTEXT_EXCEEDED` token, +and a stderr line naming the cause (prompt too long for the context, a +conversation history that no longer fits, or text clipped by the 64 KB render +buffer). The cause rides the `STAT` line as an eighth token (`PROMPT_TOO_LONG`, +`HISTORY_FULL`, or `RENDER_CLIPPED`) so `coli chat` can print it with the +right hint instead of an empty answer: `:reset` clears a full history, a +shorter prompt (or a larger `CTX`) fits an over-long turn. Raise `CTX` or +shorten the prompt; in chat, `\x02RESET` clears a full history.