diff --git a/server/app.py b/server/app.py index 6c49dc67e..6050f53e8 100644 --- a/server/app.py +++ b/server/app.py @@ -10116,10 +10116,15 @@ def _complete(self, body: dict, chat: bool) -> None: if rec.finish_reason is None and rec.status in (429, 503): rec.finish_reason = "refused" rec.end() - if rec.regen is not None and STATE.get("regenerate") is not None and \ - regenerate_mod.answered_ok(rec.status, rec.finish_reason, - rec.completion_tokens): - STATE["regenerate"].answered(rec.regen, rec.request_id) # SRV-241 + if rec.regen is not None and STATE.get("regenerate") is not None: + if regenerate_mod.answered_ok(rec.status, rec.finish_reason, + rec.completion_tokens): + STATE["regenerate"].answered(rec.regen, rec.request_id) # SRV-241 + if (rec.status or 0) < 400 and regenerate_mod.degenerate_completion( + rec.finish_reason, rec.tool_calls, rec.reasoning_tokens, + rec.completion_tokens): + # reasoning-only: the agent's byte-identical retry must sample, not replay + STATE["regenerate"].degenerate(rec.regen, rec.request_id) live_registry().finish(rec) if rec.sup is not None: EXT.ask("turn_ended", rec.sup) # the watch's idle time starts here diff --git a/server/regenerate.py b/server/regenerate.py index c329ba3a5..556bdeea1 100644 --- a/server/regenerate.py +++ b/server/regenerate.py @@ -53,6 +53,17 @@ OTHER CLIENTS. `X-Tandem-Regenerate: 1` asks for a regenerate outright; `X-Tandem-Regenerate: 0` turns the detection off for that request (a client that re-sends one prompt on purpose and wants the greedy answer each time). Off for the server: `--regenerate off` (`QWEN38_REGENERATE=off`). + +DEGENERATE RETRIES (2026-11-21). An agent client that gets a reasoning-only answer (finish=stop, +no visible content, no tool call) retries by re-sending the SAME conversation, whose tail is a +tool result — `signature` cannot match it (the rule above needs a user tail), and greedy replay +returns the identical degenerate continuation forever (observed: three byte-identical retries, +request chatcmpl-6d21296b94bb48f5b802af7d). So a completion that wrote reasoning and nothing +else is remembered by the conversation's retry signature (a user OR tool tail), and the next +request with that signature samples like a regenerate. The signature is anchored at the last +tool result (or the prompt behind a run of user rows), so a client that appends a nudge to the +retry tail still matches. A request that answers clears the mark: a deliberate re-send after a +good answer stays greedy, and `X-Tandem-Regenerate: 0` never matches it either. """ from __future__ import annotations @@ -100,6 +111,48 @@ def signature(messages) -> str | None: return hashlib.sha256(raw.encode("utf-8", "surrogatepass")).hexdigest() +def retry_signature(messages) -> str | None: + """The fingerprint for the degenerate-retry match: the canonical hash of the conversation + up to its UNANSWERED ANCHOR — the last tool result if the conversation carries one, else + the first user row of a trailing run of user rows. The tail may be the user's OR a tool + result (an agent loop retries on its tool round), and a client that appends a nudge on + retry — a user row after a tool result, or a second user row after its prompt — still + signs the same conversation. None when there are no messages or the tail is an assistant + row (a Continue is not a retry).""" + if not isinstance(messages, list): + return None + conv = [_norm(m) for m in messages if isinstance(m, dict) and m.get("role") not in + ("system", "developer")] + if not conv or conv[-1].get("role") not in ("user", "tool"): + return None + cut = len(conv) + for i in range(len(conv) - 1, -1, -1): + if conv[i].get("role") == "tool": + cut = i + 1 + break + else: + # no tool row: a lone user tail IS the prompt; a run of user rows is the prompt plus + # nudges appended on retry — sign the prompt, not what was appended + if len(conv) >= 2 and conv[-1].get("role") == "user" and conv[-2].get("role") == "user": + i = len(conv) - 1 + while i > 0 and conv[i - 1].get("role") == "user": + i -= 1 + cut = i + 1 + raw = json.dumps(conv[:cut], sort_keys=True, ensure_ascii=False, separators=(",", ":")) + return hashlib.sha256(raw.encode("utf-8", "surrogatepass")).hexdigest() + + +def degenerate_completion(finish_reason, tool_calls, reasoning_tokens, + completion_tokens) -> bool: + """A completion that thought and wrote nothing the client can use: stop, no tool call, + reasoning tokens but no visible content (the closing/EOS token beside the block is not + content). This is what a greedy replay of the same conversation returns forever, so the + next identical request must sample instead.""" + return (finish_reason == "stop" and not tool_calls + and int(reasoning_tokens or 0) > 0 + and int(completion_tokens or 0) - int(reasoning_tokens or 0) <= 2) + + def head_key(messages) -> str: """The fallback session key: the conversation up to and including its first user message.""" head = [] @@ -137,10 +190,11 @@ def client_sampling(body: dict) -> bool: class Decision: - __slots__ = ("key", "sig", "how", "of", "client") + __slots__ = ("key", "sig", "rsig", "how", "of", "client") - def __init__(self, key, sig, how=None, of=None, client=False): - self.key, self.sig, self.how, self.of, self.client = key, sig, how, of, client + def __init__(self, key, sig, how=None, of=None, client=False, rsig=None): + self.key, self.sig, self.rsig = key, sig, rsig + self.how, self.of, self.client = how, of, client @property def sample(self) -> bool: @@ -165,8 +219,12 @@ def __init__(self, mode: str = "sample", temperature: float = 0.7, top_p: float self.temperature, self.top_p, self.top_k = float(temperature), float(top_p), int(top_k) self.sessions_max, self.per, self.ttl_s, self.clock = sessions, per, ttl_s, clock self._s: collections.OrderedDict = collections.OrderedDict() + # per session: conversations whose last completion was reasoning-only, waiting for the + # client's identical re-send to sample instead of replaying the degenerate continuation + self._d: collections.OrderedDict = collections.OrderedDict() self._lock = threading.Lock() - self.counts = {"detected": 0, "header": 0, "client_params": 0, "answered": 0} + self.counts = {"detected": 0, "header": 0, "client_params": 0, "answered": 0, + "degenerate": 0} def report(self) -> dict: with self._lock: @@ -181,30 +239,50 @@ def decide(self, body: dict, headers) -> Decision | None: msgs = body.get("messages") sig = signature(msgs) key = session_of(body, headers) - d = Decision(key, sig, client=client_sampling(body)) + d = Decision(key, sig, client=client_sampling(body), rsig=retry_signature(msgs)) if hv in ("0", "false", "off", "no"): d.sig = None # not detected, and not remembered either + d.rsig = None # ... nor as a degenerate retry return d if hv in ("1", "true", "on", "yes"): d.how = "header" - elif sig is not None: + elif sig is not None or d.rsig is not None: now = self.clock() with self._lock: sess = self._s.get(key) - hit = sess.get(sig) if sess is not None else None + hit = sess.get(sig) if (sess is not None and sig is not None) else None if hit is not None and now - hit[0] <= self.ttl_s: d.how, d.of = "detected", hit[1] + elif d.rsig is not None: + # the same conversation the last request degenerated on: sample, or greedy + # replays the identical reasoning-only continuation (the retry is byte- + # identical by construction -- an agent re-sends its tool round verbatim) + dsess = self._d.get(key) + dhit = dsess.get(d.rsig) if dsess is not None else None + if dhit is not None and now - dhit[0] <= self.ttl_s: + d.how, d.of = "degenerate", dhit[1] if d.how is not None: with self._lock: self.counts["client_params" if d.client else d.how] += 1 return d def answered(self, d: Decision | None, request_id: str) -> None: - """The request produced an answer: its conversation counts as answered from now on.""" - if d is None or d.sig is None: + """The request produced an answer: its conversation counts as answered from now on, and + any degenerate-retry mark on the same conversation is cleared — a deliberate re-send + after a good answer is greedy again, only a re-send after a reasoning-only answer + samples.""" + if d is None or (d.sig is None and d.rsig is None): return now = self.clock() with self._lock: + if d.rsig is not None: + dsess = self._d.get(d.key) + if dsess is not None: + dsess.pop(d.rsig, None) + if not dsess: + del self._d[d.key] + if d.sig is None: + return sess = self._s.pop(d.key, None) or collections.OrderedDict() sess.pop(d.sig, None) sess[d.sig] = (now, request_id) @@ -215,6 +293,21 @@ def answered(self, d: Decision | None, request_id: str) -> None: self._s.popitem(last=False) self.counts["answered"] += 1 + def degenerate(self, d: Decision | None, request_id: str) -> None: + """The request wrote reasoning and nothing usable: remember its retry signature so the + client's identical re-send samples instead of replaying the degenerate continuation.""" + if d is None or d.rsig is None: + return + now = self.clock() + with self._lock: + sess = self._d.pop(d.key, None) or collections.OrderedDict() + sess[d.rsig] = (now, request_id) + while len(sess) > self.per: + sess.popitem(last=False) + self._d[d.key] = sess + while len(self._d) > self.sessions_max: + self._d.popitem(last=False) + def sampling(self) -> dict: """The regenerate's sampling parameters, a fresh seed each call.""" return {"temperature": self.temperature, "top_p": self.top_p, "top_k": self.top_k, diff --git a/tests/test_regenerate_degenerate.py b/tests/test_regenerate_degenerate.py new file mode 100644 index 000000000..9a911ad0e --- /dev/null +++ b/tests/test_regenerate_degenerate.py @@ -0,0 +1,172 @@ +"""A reasoning-only answer makes the next identical request sample (degenerate retries). + +An agent client retries by re-sending the byte-identical conversation whose tail is a tool +result. `signature` cannot match it (a regenerate needs a user tail), so greedy replay returns +the identical reasoning-only continuation forever. The fix: a completion that wrote reasoning +and nothing usable is remembered by its retry signature, and the next request with that +signature samples like a regenerate. A good answer clears the mark; the header off switch +never matches; a client that names sampling decides as ever. + +Run: python tests/test_regenerate_degenerate.py +""" + +from __future__ import annotations + +import os +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) + +from server import regenerate as rg # noqa: E402 + +SYS = {"role": "system", "content": "You are helpful."} +U1 = {"role": "user", "content": "Read the file and tell me what changed."} +AS = {"role": "assistant", "content": "", "tool_calls": [{"id": "1", "type": "function", + "function": {"name": "read", "arguments": "{}"}}]} +TR = {"role": "tool", "tool_call_id": "1", "content": "the file contents"} +H = {"x-session-id": "sess-1"} + + +def _r(**kw): + return rg.Regenerates(**kw) + + +def test_retry_signature(): + msgs = [SYS, U1, AS, TR] + s = rg.retry_signature(msgs) + assert s is not None and s == rg.retry_signature([dict(m) for m in msgs]) + assert rg.signature(msgs) is None # tool tail: not a classic regenerate + assert rg.retry_signature([SYS, U1, AS]) is None # assistant tail (Continue): not a retry + assert rg.retry_signature([SYS]) is None # no conversation + assert rg.retry_signature(None) is None + # reasoning fields are presentation: the same turn hashes the same + assert rg.retry_signature([SYS, U1, dict(AS, reasoning_content="hmm"), TR]) == s + print("ok: retry_signature") + + +def test_degenerate_completion(): + assert rg.degenerate_completion("stop", 0, 449, 451) # thought, wrote nothing + assert not rg.degenerate_completion("stop", 0, 449, 900) # visible content after + assert not rg.degenerate_completion("stop", 2, 449, 451) # a tool call is an answer + assert not rg.degenerate_completion("stop", 0, 0, 40) # no thinking at all + assert not rg.degenerate_completion("length", 0, 449, 451) # cut, not degenerate + assert not rg.degenerate_completion("tool_calls", 1, 449, 451) + print("ok: degenerate_completion") + + +def test_degenerate_retry_samples(): + r = _r() + body = {"messages": [SYS, U1, AS, TR]} + d1 = r.decide(body, H) + assert d1.how is None and not d1.sample and d1.rsig is not None + r.degenerate(d1, "req-1") # the degenerate completion + d2 = r.decide(body, H) # the agent's identical retry + assert d2.how == "degenerate" and d2.sample and d2.of == "req-1" + assert r.sampling()["temperature"] == 0.7 and "seed" in r.sampling() + assert r.counts["degenerate"] == 1 + print("ok: degenerate retry samples") + + +def test_good_answer_clears_the_mark(): + r = _r() + body = {"messages": [SYS, U1, AS, TR]} + d1 = r.decide(body, H) + r.degenerate(d1, "req-1") + d2 = r.decide(body, H) + assert d2.how == "degenerate" + r.answered(d2, "req-2") # the retry answered + d3 = r.decide(body, H) # a deliberate re-send + assert d3.how is None and not d3.sample # greedy again, as asked + print("ok: good answer clears the mark") + + +def test_off_header_and_client_params(): + r = _r() + body = {"messages": [SYS, U1, AS, TR]} + d1 = r.decide(body, H) + r.degenerate(d1, "req-1") + d2 = r.decide(body, {**H, rg.HEADER: "0"}) + assert d2.how is None and d2.rsig is None and not d2.sample # off means off + d3 = r.decide(dict(body, temperature=0.3), H) + assert d3.how == "degenerate" and not d3.sample # the client decides + assert r.counts["client_params"] == 1 + print("ok: off header and client params") + + +def test_bounds_and_ttl(): + clock = [1000.0] + r = _r(sessions=2, per=2, ttl_s=10.0, clock=lambda: clock[0]) + body = {"messages": [SYS, U1, AS, TR]} + d1 = r.decide(body, H) + r.degenerate(d1, "req-1") + clock[0] += 11.0 # past the ttl + assert r.decide(body, H).how is None + clock[0] -= 11.0 + r.degenerate(r.decide(body, H), "req-2") + for i in range(3): # more sessions than the cap + r.degenerate(r.decide({"messages": [SYS, dict(U1, content=f"q{i}"), AS, TR]}, + {"x-session-id": f"s{i}"}), f"r{i}") + assert len(r._d) <= 2 + print("ok: bounds and ttl") + + +def test_tool_tail_answered_keeps_retry_memory_of_user_tail(): + # a user-tail conversation keeps BOTH memories working: the classic regenerate still + # samples after a good answer, and a degenerate one samples through the new path too + r = _r() + body = {"messages": [SYS, U1]} + d1 = r.decide(body, H) + r.answered(d1, "req-1") + assert r.decide(body, H).how == "detected" # classic path untouched + print("ok: classic regenerate path untouched") + + +def test_nudge_after_tool_tail_still_matches(): + # a client that appends a nudge user row after the tool result on retry still signs the + # same conversation (anchored at the last tool result), so the retry samples + r = _r() + body = {"messages": [SYS, U1, AS, TR]} + d1 = r.decide(body, H) + r.degenerate(d1, "req-1") + nudged = {"messages": [SYS, U1, AS, TR, {"role": "user", "content": "Please answer now."}]} + d2 = r.decide(nudged, H) + assert d2.sample and d2.how == "degenerate" + print("ok: nudge after a tool tail still matches") + + +def test_nudge_after_user_tail_still_matches(): + # a second user row after the prompt is the prompt plus an appended nudge: the signature + # is anchored at the first user row of the run, so the marked prompt and the nudged retry + # sign the same conversation + r = _r() + body = {"messages": [SYS, U1]} + d1 = r.decide(body, H) + r.degenerate(d1, "req-1") + nudged = {"messages": [SYS, U1, {"role": "user", "content": "Say something useful."}]} + d2 = r.decide(nudged, H) + assert d2.sample and d2.how == "degenerate" + # and a genuinely different prompt in a fresh session is not swept in by the anchor + r2 = _r() + d3 = r2.decide({"messages": [SYS, {"role": "user", "content": "Totally new question."}]}, + {"x-session-id": "sess-2"}) + assert not d3.sample + print("ok: nudge after a user tail still matches, a new prompt does not") + + +def run(): + test_retry_signature() + test_degenerate_completion() + test_degenerate_retry_samples() + test_good_answer_clears_the_mark() + test_off_header_and_client_params() + test_bounds_and_ttl() + test_tool_tail_answered_keeps_retry_memory_of_user_tail() + test_nudge_after_tool_tail_still_matches() + test_nudge_after_user_tail_still_matches() + print("regenerate degenerate-retry: all ok") + + +if __name__ == "__main__": + run() + sys.exit(0) \ No newline at end of file