Coverage for app / services / cut_replies.py: 96%
137 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""What a structured reply cut off at its token cap was doing when it stopped.
3Triage ran to its 4,096-token cap on 6 of 31 turns of two scenario runs
4(Qwen3 235B on Bedrock, decoding natively), 30–39 s each, and fell back.
5A healthy profile is 120–990 tokens. Nothing said why: the reply is read
6whole or not at all, and the one log line said only that it was cut off.
8``shape_of`` reads the cut-off text without keeping any of it: how long it
9is, the schema field it stopped in (a path of the schema's own keys, read
10from the partial JSON), whether it stopped inside a string, and what its
11tail is — whitespace (constrained decoding's known runaway), one item
12repeated, or running text. Counts and the schema's keys only, never words:
13it is logged and carried to the trace.
14"""
16from __future__ import annotations
18from collections import Counter
19from dataclasses import asdict, dataclass
20from typing import Literal
22Tail = Literal["empty", "whitespace", "repeating", "text", "json"]
23#: What a whitespace tail is made of, to decide whether a stop sequence
24#: would end it: newlines, spaces, tabs, or a mix.
25Blank = Literal["newlines", "spaces", "tabs", "mixed", ""]
27#: How much of the end is read for the tail.
28TAIL_CHARS = 1200
29#: The share of the tail that is whitespace to call it a whitespace run.
30WHITESPACE_SHARE = 0.6
31#: An item seen this often in the tail, as this share of its items, repeats.
32MIN_REPEATS = 8
33REPEAT_SHARE = 0.4
36@dataclass(frozen=True)
37class CutShape:
38 chars: int
39 #: The schema field it stopped in or had just written, e.g.
40 #: ``relevant_tools[]`` or ``clarifying_questions[].options[].label``;
41 #: "" when none was open.
42 open_field: str
43 in_string: bool
44 tail: Tail
45 #: How often the repeated item came round in the last ``TAIL_CHARS``,
46 #: for a ``repeating`` tail.
47 repeats: int = 0
48 #: What a ``whitespace`` tail is made of.
49 blank: Blank = ""
50 #: Whether the open field's value had begun: run 6's runaways stopped in
51 #: ``worth_remembering``, and nothing said whether ``false`` was written.
52 value_written: bool = False
54 def wire(self) -> dict[str, object]:
55 return asdict(self)
57 def describe(self) -> str:
58 """One line for the log: counts and the schema's keys only."""
59 where = f"in {self.open_field}" if self.open_field else "outside any field"
60 tail = (
61 f"{self.tail} ×{self.repeats}"
62 if self.tail == "repeating"
63 else f"whitespace ({self.blank})"
64 if self.tail == "whitespace" and self.blank
65 else self.tail
66 )
67 return f"{self.chars} characters, stopped {where}, tail {tail}"
70class _Frame:
71 __slots__ = ("kind", "key", "awaiting_key", "key_start")
73 def __init__(self, kind: str) -> None:
74 self.kind = kind
75 self.key = ""
76 self.awaiting_key = kind == "object"
77 #: Where the current key's opening quote is in the text; -1 for none.
78 self.key_start = -1
81def _scan(text: str) -> tuple[list[_Frame], bool]:
82 """The containers open where ``text`` stops, outermost first, and
83 whether it stopped inside a string. A tolerant scan of partial JSON:
84 anything before the first brace (a model's preamble) is skipped."""
85 start = text.find("{")
86 if start < 0:
87 return [], False
88 stack: list[_Frame] = []
89 in_string = escaped = False
90 reading_key = False
91 buffer: list[str] = []
92 for at, char in enumerate(text[start:], start):
93 if in_string:
94 if escaped:
95 escaped = False
96 elif char == "\\":
97 escaped = True
98 elif char == '"':
99 in_string = False
100 if reading_key and stack:
101 stack[-1].key = "".join(buffer)
102 reading_key = False
103 elif reading_key:
104 buffer.append(char)
105 continue
106 if char == '"':
107 in_string = True
108 reading_key = bool(
109 stack and stack[-1].kind == "object" and stack[-1].awaiting_key
110 )
111 if reading_key:
112 stack[-1].key_start = at
113 buffer = []
114 elif char in "{[":
115 stack.append(_Frame("object" if char == "{" else "array"))
116 elif char in "}]":
117 if stack:
118 stack.pop()
119 elif char == ":" and stack and stack[-1].kind == "object":
120 stack[-1].awaiting_key = False
121 elif char == "," and stack and stack[-1].kind == "object":
122 stack[-1].awaiting_key = True
123 stack[-1].key = ""
124 stack[-1].key_start = -1
125 return stack, in_string
128def _dangling_key_start(body: str, stack: list[_Frame]) -> int:
129 """Where a key the reply never gave a value starts — written with its
130 colon or without — else -1."""
131 top = stack[-1] if stack else None
132 if top is None or top.kind != "object" or top.key_start < 0:
133 return -1
134 no_value = body.endswith(":") and not top.awaiting_key
135 no_colon = top.awaiting_key and bool(top.key) and body.endswith('"')
136 return top.key_start if no_value or no_colon else -1
139def _open_path(text: str) -> tuple[str, bool]:
140 """The path of keys open where ``text`` stops, and whether it stopped
141 inside a string (``_scan``)."""
142 stack, in_string = _scan(text)
143 parts: list[str] = []
144 for frame in stack:
145 if frame.kind == "array":
146 if parts:
147 parts[-1] += "[]"
148 elif frame.key and not frame.awaiting_key:
149 parts.append(frame.key)
150 return ".".join(parts), in_string
153def _repeats(tail: str) -> int:
154 """How often the tail's most common item came round, when it dominates."""
155 items = [
156 item.strip(" \t\r\n\"'")
157 for chunk in tail.splitlines()
158 for item in chunk.split(",")
159 ]
160 items = [item for item in items if len(item) >= 2]
161 if not items:
162 return 0
163 _, count = Counter(items).most_common(1)[0]
164 return count if count >= MIN_REPEATS and count >= REPEAT_SHARE * len(items) else 0
167def _blank(tail: str) -> Blank:
168 kinds = {
169 "newlines" if c in "\r\n" else "tabs" if c == "\t" else "spaces"
170 for c in tail
171 if c.isspace()
172 }
173 if not kinds:
174 return ""
175 return next(iter(kinds)) if len(kinds) == 1 else "mixed" # type: ignore[return-value]
178#: What a value can end with, or a container just opened: a closer, a
179#: string's quote, a number, a literal's last letter.
180_ENDS = frozenset('}]"0123456789el[{')
183def closed(text: str | None) -> str | None:
184 """``text`` with its open containers closed, when it ran on in whitespace
185 outside a string, else None.
187 Qwen3 235B on Bedrock writes whitespace to the cap rather than a value
188 or a closer. Closing what it left open gives exactly what it wrote. A
189 key it never gave a value (``"worth_remembering":`` and whitespace) is
190 dropped, never given one, so a defaulted field takes its default.
191 Nothing inside a string is completed, and the caller reads the result
192 whole (``loads_exact``) and validates it, so a decision left out, or
193 anything else that does not parse, is refused. Run 6 showed every
194 runaway stopping at the schema's first field, before anything was
195 written, so the triage schemas now ask for their decisions first
196 (``graph.TriageProfile``) and a runaway at the end is read here."""
197 text = text or ""
198 if not text.strip() or not text[-1:].isspace():
199 return None
200 body = text.rstrip()
201 stack, in_string = _scan(body)
202 if in_string or not stack:
203 return None
204 if (cut := _dangling_key_start(body, stack)) >= 0:
205 body = body[:cut].rstrip()
206 if body.endswith(","):
207 body = body[:-1].rstrip()
208 stack, in_string = _scan(body)
209 if not body or not stack or body[-1] not in _ENDS:
210 return None
211 return body + "".join("}" if f.kind == "object" else "]" for f in reversed(stack))
214def shape_of(text: str | None) -> CutShape:
215 """What a cut-off reply was doing when it stopped (module docstring)."""
216 text = text or ""
217 if not text.strip():
218 return CutShape(
219 len(text),
220 "",
221 False,
222 "whitespace" if text else "empty",
223 blank=_blank(text),
224 )
225 open_field, in_string = _open_path(text)
226 body = text.rstrip()
227 stack, _ = _scan(body)
228 value_written = bool(open_field) and _dangling_key_start(body, stack) < 0
229 tail = text[-TAIL_CHARS:]
230 spaces = sum(char.isspace() for char in tail)
231 blank: Blank = ""
232 if spaces >= WHITESPACE_SHARE * len(tail):
233 kind: Tail = "whitespace"
234 repeats = 0
235 blank = _blank(tail)
236 elif repeats := _repeats(tail):
237 kind = "repeating"
238 else:
239 kind = "text" if in_string else "json"
240 return CutShape(
241 len(text), open_field, in_string, kind, repeats, blank, value_written
242 )