Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
29 changes: 29 additions & 0 deletions c/coli
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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}")
Expand Down
79 changes: 69 additions & 10 deletions c/colibri.c
Original file line number Diff line number Diff line change
Expand Up @@ -11431,7 +11431,28 @@ static void run_serve(Model *m, const char *snap){
const char *tk = getenv("THINK")&&atoi(getenv("THINK"))? "<think>" : "<think></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<old_len && prefix<prompt_tokens && hist[prefix]==tmp[prefix]) prefix++;
if(prefix<old_len){
Expand All @@ -11445,16 +11466,54 @@ static void run_serve(Model *m, const char *snap){
active,len,prompt_tokens,k);
free(tmp);
} else {
if(templ){ if(first) bl+=snprintf(buf+bl,(1<<16)-bl,"[gMASK]<sop>");
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]<sop><|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]<sop>");
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; }
Expand Down
137 changes: 137 additions & 0 deletions c/tests/test_chat_context_exceeded.py
Original file line number Diff line number Diff line change
@@ -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 <cause>` (#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()
Loading
Loading