inferdiff 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- inferdiff/__init__.py +64 -0
- inferdiff/__main__.py +10 -0
- inferdiff/canary.py +1431 -0
- inferdiff/cli.py +490 -0
- inferdiff/detectors.py +423 -0
- inferdiff/dialects/__init__.py +41 -0
- inferdiff/dialects/ollama_ndjson.py +94 -0
- inferdiff/dialects/openai_chat.py +113 -0
- inferdiff/dialects/openai_responses.py +180 -0
- inferdiff/dialects/sglang_native.py +68 -0
- inferdiff/differ.py +649 -0
- inferdiff/exporter.py +482 -0
- inferdiff/probes/__init__.py +5 -0
- inferdiff/probes/base.py +52 -0
- inferdiff/recorder.py +918 -0
- inferdiff/redact.py +355 -0
- inferdiff/schema.py +955 -0
- inferdiff/waterfall.py +771 -0
- inferdiff-0.1.0.dist-info/METADATA +165 -0
- inferdiff-0.1.0.dist-info/RECORD +24 -0
- inferdiff-0.1.0.dist-info/WHEEL +5 -0
- inferdiff-0.1.0.dist-info/entry_points.txt +2 -0
- inferdiff-0.1.0.dist-info/licenses/LICENSE +21 -0
- inferdiff-0.1.0.dist-info/top_level.txt +1 -0
inferdiff/canary.py
ADDED
|
@@ -0,0 +1,1431 @@
|
|
|
1
|
+
"""inferdiff doctor: zero-setup C1..C8 canary probe suite for local engines & API relays."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import datetime
|
|
6
|
+
import http.client
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import secrets
|
|
10
|
+
import ssl
|
|
11
|
+
import time
|
|
12
|
+
import urllib.parse
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple
|
|
16
|
+
|
|
17
|
+
from . import __version__
|
|
18
|
+
from .detectors import D1, D2, D3, D4, Finding, audit_trace
|
|
19
|
+
from .recorder import RecorderError, record_stream, validate_and_merge_headers, validate_url
|
|
20
|
+
from .redact import (
|
|
21
|
+
extract_header_secret_values,
|
|
22
|
+
sanitize_url_for_error,
|
|
23
|
+
sanitize_url_for_export,
|
|
24
|
+
scrub_known_secrets,
|
|
25
|
+
)
|
|
26
|
+
from .schema import (
|
|
27
|
+
EXIT_OK,
|
|
28
|
+
EXIT_SEMANTIC_REGRESSION,
|
|
29
|
+
EXIT_SILENT_PROTOCOL_BREACH,
|
|
30
|
+
EXIT_USAGE_OR_IO_ERROR,
|
|
31
|
+
TraceDocument,
|
|
32
|
+
is_strict_int,
|
|
33
|
+
strict_json_loads,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
PROFILE_PROBES: Dict[str, Tuple[str, ...]] = {
|
|
37
|
+
"quick": ("C1", "C4", "C5", "C6", "C7"),
|
|
38
|
+
"full": ("C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8"),
|
|
39
|
+
"relay": ("C1", "C2", "C4", "C5", "C6", "C7", "C8"),
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
PROBE_CATALOG: Dict[str, Tuple[str, str, str]] = {
|
|
43
|
+
"C1": ("TOOL_CALL_BUDGET_CLIP", "P0", "https://github.com/ggml-org/llama.cpp/issues/30773"),
|
|
44
|
+
"C2": ("REASONING_STARVATION_GUARD", "P0", "https://github.com/ollama/ollama/issues/17274"),
|
|
45
|
+
"C3": ("FIXED_BUDGET_HONOR", "P1", "https://github.com/sgl-project/sglang/pull/53119"),
|
|
46
|
+
"C4": ("STREAM_INCLUDE_USAGE_CONTRACT", "P1", "https://github.com/BerriAI/litellm/issues/16112"),
|
|
47
|
+
"C5": ("INITIAL_ROLE_AND_TOOL_INDEX", "P1", "https://github.com/BerriAI/litellm/issues/24221"),
|
|
48
|
+
"C6": ("UTF8_MULTIBYTE_INTEGRITY", "P0", "https://github.com/vllm-project/vllm/issues/68324"),
|
|
49
|
+
"C7": ("FAKE_STREAMING_BUFFER", "P1", "https://github.com/BerriAI/litellm/issues/5803"),
|
|
50
|
+
"C8": ("SEED_AND_RELAY_DRIFT", "P2", "https://docs.vllm.ai/en/stable/benchmarking/cli/"),
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
C6_TARGET_TEXT = "ๅๅ้ฮ=99.8% [๐ฅ๐๐งช๐]"
|
|
54
|
+
C6_TRAILING_EMOJI = "๐"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _clean_display(text: Any, secrets_list: Sequence[str] = (), max_chars: int = 180) -> str:
|
|
58
|
+
"""Strip terminal control characters and scrub known/pattern secrets before display or JSON export."""
|
|
59
|
+
scrubbed = scrub_known_secrets(str(text), secrets_list)
|
|
60
|
+
out: List[str] = []
|
|
61
|
+
for ch in scrubbed:
|
|
62
|
+
code = ord(ch)
|
|
63
|
+
if ch in ("\r", "\n", "\u0085", "\u2028", "\u2029"):
|
|
64
|
+
out.append(" ")
|
|
65
|
+
elif code < 32 or code == 127:
|
|
66
|
+
out.append(f"\\x{code:02x}")
|
|
67
|
+
else:
|
|
68
|
+
out.append(ch)
|
|
69
|
+
s = "".join(out).strip()
|
|
70
|
+
if len(s) > max_chars:
|
|
71
|
+
return s[: max_chars - 3] + "..."
|
|
72
|
+
return s
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass
|
|
76
|
+
class ProbeResult:
|
|
77
|
+
probe_id: str
|
|
78
|
+
code: str
|
|
79
|
+
severity: str # "P0" | "P1" | "P2"
|
|
80
|
+
status: str # "PASS" | "WARN" | "FAIL" | "SKIP" | "ERROR"
|
|
81
|
+
summary: str
|
|
82
|
+
duration_ms: float
|
|
83
|
+
total_frames: int
|
|
84
|
+
tokens_used: Optional[int]
|
|
85
|
+
reference_url: str
|
|
86
|
+
trace_paths: List[str] = field(default_factory=list)
|
|
87
|
+
findings: List[Finding] = field(default_factory=list)
|
|
88
|
+
traces: List[TraceDocument] = field(default_factory=list)
|
|
89
|
+
details: Dict[str, Any] = field(default_factory=dict)
|
|
90
|
+
|
|
91
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
92
|
+
return {
|
|
93
|
+
"probe_id": self.probe_id,
|
|
94
|
+
"code": self.code,
|
|
95
|
+
"severity": self.severity,
|
|
96
|
+
"status": self.status,
|
|
97
|
+
"summary": self.summary,
|
|
98
|
+
"duration_ms": round(self.duration_ms, 1),
|
|
99
|
+
"total_frames": self.total_frames,
|
|
100
|
+
"tokens_used": self.tokens_used if self.tokens_used is not None else "unknown",
|
|
101
|
+
"reference_url": self.reference_url,
|
|
102
|
+
"trace_paths": self.trace_paths,
|
|
103
|
+
"findings": [
|
|
104
|
+
{
|
|
105
|
+
"detector_id": f.detector_id,
|
|
106
|
+
"code": f.code,
|
|
107
|
+
"severity": f.severity,
|
|
108
|
+
"frame_seq": f.frame_seq,
|
|
109
|
+
"message": _clean_display(f.message, max_chars=240),
|
|
110
|
+
}
|
|
111
|
+
for f in self.findings
|
|
112
|
+
],
|
|
113
|
+
"details": self.details,
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@dataclass
|
|
118
|
+
class DoctorReport:
|
|
119
|
+
target_url: str
|
|
120
|
+
chat_url: str
|
|
121
|
+
dialect: str
|
|
122
|
+
model: str
|
|
123
|
+
profile: str
|
|
124
|
+
grade: str # "A+" | "A" | "B" | "C" | "F"
|
|
125
|
+
exit_code: int
|
|
126
|
+
p0_count: int
|
|
127
|
+
warning_count: int
|
|
128
|
+
error_count: int
|
|
129
|
+
total_tokens: Optional[int]
|
|
130
|
+
save_dir: Optional[str]
|
|
131
|
+
results: List[ProbeResult] = field(default_factory=list)
|
|
132
|
+
|
|
133
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
134
|
+
return {
|
|
135
|
+
"version": __version__,
|
|
136
|
+
"target_url": sanitize_url_for_export(self.target_url) if self.target_url else "",
|
|
137
|
+
"dialect": self.dialect,
|
|
138
|
+
"model": self.model,
|
|
139
|
+
"profile": self.profile,
|
|
140
|
+
"grade": self.grade,
|
|
141
|
+
"exit_code": self.exit_code,
|
|
142
|
+
"p0_count": self.p0_count,
|
|
143
|
+
"warning_count": self.warning_count,
|
|
144
|
+
"error_count": self.error_count,
|
|
145
|
+
"total_tokens": self.total_tokens if self.total_tokens is not None else "unknown",
|
|
146
|
+
"save_dir": self.save_dir,
|
|
147
|
+
"results": [r.to_dict() for r in self.results],
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def resolve_api_key(raw_key: Optional[str]) -> Optional[str]:
|
|
152
|
+
"""Resolve explicit --api-key (rejecting empty values) or return None for caller fallback."""
|
|
153
|
+
if raw_key is None:
|
|
154
|
+
return None
|
|
155
|
+
cand = raw_key.strip()
|
|
156
|
+
if not cand:
|
|
157
|
+
raise ValueError("Explicit --api-key cannot be empty.")
|
|
158
|
+
if cand.startswith("$"):
|
|
159
|
+
env_name = cand[1:]
|
|
160
|
+
if not env_name:
|
|
161
|
+
raise ValueError("Invalid --api-key environment variable reference '$'.")
|
|
162
|
+
val = (os.environ.get(env_name) or "").strip()
|
|
163
|
+
if not val:
|
|
164
|
+
raise ValueError(f"Environment variable {env_name!r} specified in --api-key is empty or not set.")
|
|
165
|
+
return val
|
|
166
|
+
if cand in os.environ and cand.isupper() and "_" in cand:
|
|
167
|
+
val = (os.environ.get(cand) or "").strip()
|
|
168
|
+
if not val:
|
|
169
|
+
raise ValueError(f"Environment variable {cand!r} specified in --api-key is empty.")
|
|
170
|
+
return val
|
|
171
|
+
return cand
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _format_origin(parsed: urllib.parse.SplitResult) -> str:
|
|
175
|
+
host = parsed.hostname or ""
|
|
176
|
+
if ":" in host and not host.startswith("["):
|
|
177
|
+
host = f"[{host}]"
|
|
178
|
+
return f"{parsed.scheme}://{host}" + (f":{parsed.port}" if parsed.port is not None else "")
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _build_url(parsed: urllib.parse.SplitResult, new_path: str) -> str:
|
|
182
|
+
"""Rebuild URL safely from parsed components (preserving IPv6 brackets and query cleanly)."""
|
|
183
|
+
origin = _format_origin(parsed)
|
|
184
|
+
norm_path = "/" + new_path.lstrip("/")
|
|
185
|
+
if parsed.query:
|
|
186
|
+
return f"{origin}{norm_path}?{parsed.query}"
|
|
187
|
+
return f"{origin}{norm_path}"
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _http_get_json(url: str, headers: Mapping[str, str], timeout: float) -> Tuple[int, Optional[Dict[str, Any]]]:
|
|
191
|
+
parsed = validate_url(url)
|
|
192
|
+
path = parsed.path or "/"
|
|
193
|
+
if parsed.query:
|
|
194
|
+
path = f"{path}?{parsed.query}"
|
|
195
|
+
conn: http.client.HTTPConnection
|
|
196
|
+
if parsed.scheme == "https":
|
|
197
|
+
conn = http.client.HTTPSConnection(
|
|
198
|
+
parsed.hostname,
|
|
199
|
+
parsed.port or 443,
|
|
200
|
+
timeout=timeout,
|
|
201
|
+
context=ssl.create_default_context(),
|
|
202
|
+
)
|
|
203
|
+
else:
|
|
204
|
+
conn = http.client.HTTPConnection(parsed.hostname, parsed.port or 80, timeout=timeout)
|
|
205
|
+
try:
|
|
206
|
+
conn.request("GET", path, headers=dict(headers))
|
|
207
|
+
resp = conn.getresponse()
|
|
208
|
+
status = resp.status
|
|
209
|
+
raw = resp.read(262144)
|
|
210
|
+
if status != 200:
|
|
211
|
+
return status, None
|
|
212
|
+
obj = strict_json_loads(raw.decode("utf-8", errors="replace"))
|
|
213
|
+
return status, obj if isinstance(obj, dict) else None
|
|
214
|
+
except (OSError, http.client.HTTPException, ValueError, json.JSONDecodeError):
|
|
215
|
+
return 0, None
|
|
216
|
+
finally:
|
|
217
|
+
conn.close()
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _pick_preferred_model(ids: List[str]) -> Optional[str]:
|
|
221
|
+
if not ids:
|
|
222
|
+
return None
|
|
223
|
+
skip_words = ("embed", "embedding", "whisper", "tts-", "dall-e", "moderation", "rerank")
|
|
224
|
+
for mid in ids:
|
|
225
|
+
low = mid.lower()
|
|
226
|
+
if not any(w in low for w in skip_words):
|
|
227
|
+
return mid
|
|
228
|
+
return ids[0]
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def resolve_endpoints_and_model(
|
|
232
|
+
base_url: str,
|
|
233
|
+
*,
|
|
234
|
+
model: Optional[str],
|
|
235
|
+
headers: Mapping[str, str],
|
|
236
|
+
timeout: float,
|
|
237
|
+
known_secrets: Sequence[str] = (),
|
|
238
|
+
) -> Tuple[str, Optional[str], str, str]:
|
|
239
|
+
"""Return (chat_url, responses_url, dialect, resolved_model) using safe parsed URL components."""
|
|
240
|
+
parsed = validate_url(base_url)
|
|
241
|
+
base_path = (parsed.path or "").rstrip("/")
|
|
242
|
+
path_low = base_path.lower()
|
|
243
|
+
|
|
244
|
+
is_ollama_hint = (
|
|
245
|
+
path_low.endswith("/api/chat")
|
|
246
|
+
or path_low.endswith("/api")
|
|
247
|
+
or (parsed.port == 11434 and not path_low.endswith("/v1") and not path_low.endswith("/chat/completions"))
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
if path_low.endswith("/chat/completions"):
|
|
251
|
+
prefix = base_path[: -len("/chat/completions")]
|
|
252
|
+
chat_url = _build_url(parsed, base_path)
|
|
253
|
+
responses_url: Optional[str] = _build_url(parsed, f"{prefix}/responses")
|
|
254
|
+
models_url = _build_url(parsed, f"{prefix}/models")
|
|
255
|
+
tags_url = _build_url(parsed, f"{prefix[:-3] if prefix.lower().endswith('/v1') else prefix}/api/tags")
|
|
256
|
+
dialect = "openai-chat"
|
|
257
|
+
elif path_low.endswith("/api/chat"):
|
|
258
|
+
prefix = base_path[: -len("/api/chat")]
|
|
259
|
+
chat_url = _build_url(parsed, base_path)
|
|
260
|
+
responses_url = None
|
|
261
|
+
models_url = _build_url(parsed, f"{prefix}/v1/models")
|
|
262
|
+
tags_url = _build_url(parsed, f"{prefix}/api/tags")
|
|
263
|
+
dialect = "ollama-ndjson"
|
|
264
|
+
elif is_ollama_hint:
|
|
265
|
+
prefix = base_path[: -len("/api")] if path_low.endswith("/api") else base_path
|
|
266
|
+
chat_url = _build_url(parsed, f"{prefix}/api/chat")
|
|
267
|
+
responses_url = None
|
|
268
|
+
models_url = _build_url(parsed, f"{prefix}/v1/models")
|
|
269
|
+
tags_url = _build_url(parsed, f"{prefix}/api/tags")
|
|
270
|
+
dialect = "ollama-ndjson"
|
|
271
|
+
elif path_low.endswith("/v1"):
|
|
272
|
+
prefix = base_path[: -len("/v1")]
|
|
273
|
+
chat_url = _build_url(parsed, f"{base_path}/chat/completions")
|
|
274
|
+
responses_url = _build_url(parsed, f"{base_path}/responses")
|
|
275
|
+
models_url = _build_url(parsed, f"{base_path}/models")
|
|
276
|
+
tags_url = _build_url(parsed, f"{prefix}/api/tags")
|
|
277
|
+
dialect = "openai-chat"
|
|
278
|
+
else:
|
|
279
|
+
chat_url = _build_url(parsed, f"{base_path}/v1/chat/completions")
|
|
280
|
+
responses_url = _build_url(parsed, f"{base_path}/v1/responses")
|
|
281
|
+
models_url = _build_url(parsed, f"{base_path}/v1/models")
|
|
282
|
+
tags_url = _build_url(parsed, f"{base_path}/api/tags")
|
|
283
|
+
dialect = "openai-chat"
|
|
284
|
+
|
|
285
|
+
if model and model.strip():
|
|
286
|
+
return chat_url, responses_url, dialect, _clean_display(model.strip(), known_secrets, 128)
|
|
287
|
+
|
|
288
|
+
st_models = 0
|
|
289
|
+
st_tags = 0
|
|
290
|
+
|
|
291
|
+
if dialect != "ollama-ndjson":
|
|
292
|
+
st_models, obj = _http_get_json(models_url, headers, min(timeout, 15.0))
|
|
293
|
+
if st_models == 200 and isinstance(obj, dict) and isinstance(obj.get("data"), list):
|
|
294
|
+
ids = [str(item["id"]) for item in obj["data"] if isinstance(item, dict) and isinstance(item.get("id"), str) and item["id"]]
|
|
295
|
+
picked = _pick_preferred_model(ids)
|
|
296
|
+
if picked:
|
|
297
|
+
return chat_url, responses_url, dialect, _clean_display(picked, known_secrets, 128)
|
|
298
|
+
|
|
299
|
+
st_tags, obj_ol = _http_get_json(tags_url, headers, min(timeout, 15.0))
|
|
300
|
+
if st_tags == 200 and isinstance(obj_ol, dict) and isinstance(obj_ol.get("models"), list):
|
|
301
|
+
ids = [str(item["name"]) for item in obj_ol["models"] if isinstance(item, dict) and isinstance(item.get("name"), str) and item["name"]]
|
|
302
|
+
picked = _pick_preferred_model(ids)
|
|
303
|
+
if picked:
|
|
304
|
+
ol_prefix = base_path[: -len("/api")] if path_low.endswith("/api") else (base_path[: -len("/v1")] if path_low.endswith("/v1") else base_path)
|
|
305
|
+
return _build_url(parsed, f"{ol_prefix}/api/chat"), None, "ollama-ndjson", _clean_display(picked, known_secrets, 128)
|
|
306
|
+
|
|
307
|
+
auth_hint = " and --api-key <KEY>" if (st_models in (401, 403) or st_tags in (401, 403)) else ""
|
|
308
|
+
raise RecorderError(
|
|
309
|
+
f"Could not auto-discover model from {sanitize_url_for_error(models_url)} (HTTP {st_models}) "
|
|
310
|
+
f"or {sanitize_url_for_error(tags_url)} (HTTP {st_tags}); specify --model <MODEL_ID>{auth_hint}."
|
|
311
|
+
)
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _doc_tokens(doc: TraceDocument) -> Optional[int]:
|
|
315
|
+
u = doc.summary.assembled.get("reported_usage") or {}
|
|
316
|
+
pt = u.get("prompt_tokens")
|
|
317
|
+
ct = u.get("completion_tokens")
|
|
318
|
+
if is_strict_int(pt) and is_strict_int(ct):
|
|
319
|
+
return pt + ct
|
|
320
|
+
if is_strict_int(ct):
|
|
321
|
+
return ct
|
|
322
|
+
return None
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _has_inband_error(doc: TraceDocument) -> bool:
|
|
326
|
+
return any((f.norm or {}).get("phase") == "ERROR" or (f.norm or {}).get("inband_error") for f in doc.frames)
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def _build_chat_body(
|
|
330
|
+
dialect: str,
|
|
331
|
+
model: str,
|
|
332
|
+
messages: List[Dict[str, Any]],
|
|
333
|
+
*,
|
|
334
|
+
max_tokens: int,
|
|
335
|
+
temperature: float = 0.0,
|
|
336
|
+
seed: Optional[int] = None,
|
|
337
|
+
tools: Optional[List[Dict[str, Any]]] = None,
|
|
338
|
+
tool_choice: Any = None,
|
|
339
|
+
parallel_tool_calls: Optional[bool] = None,
|
|
340
|
+
include_usage: bool = False,
|
|
341
|
+
ignore_eos: Optional[bool] = None,
|
|
342
|
+
stop: Optional[List[str]] = None,
|
|
343
|
+
) -> Dict[str, Any]:
|
|
344
|
+
if dialect == "ollama-ndjson":
|
|
345
|
+
opts: Dict[str, Any] = {"temperature": temperature, "num_predict": max_tokens}
|
|
346
|
+
if seed is not None:
|
|
347
|
+
opts["seed"] = seed
|
|
348
|
+
if ignore_eos is not None:
|
|
349
|
+
opts["ignore_eos"] = ignore_eos
|
|
350
|
+
if stop is not None:
|
|
351
|
+
opts["stop"] = stop
|
|
352
|
+
body: Dict[str, Any] = {"model": model, "stream": True, "messages": messages, "options": opts}
|
|
353
|
+
if tools is not None:
|
|
354
|
+
body["tools"] = tools
|
|
355
|
+
return body
|
|
356
|
+
|
|
357
|
+
body = {
|
|
358
|
+
"model": model,
|
|
359
|
+
"stream": True,
|
|
360
|
+
"messages": messages,
|
|
361
|
+
"max_tokens": max_tokens,
|
|
362
|
+
"temperature": temperature,
|
|
363
|
+
}
|
|
364
|
+
if seed is not None:
|
|
365
|
+
body["seed"] = seed
|
|
366
|
+
if tools is not None:
|
|
367
|
+
body["tools"] = tools
|
|
368
|
+
if tool_choice is not None:
|
|
369
|
+
body["tool_choice"] = tool_choice
|
|
370
|
+
if parallel_tool_calls is not None:
|
|
371
|
+
body["parallel_tool_calls"] = parallel_tool_calls
|
|
372
|
+
if include_usage:
|
|
373
|
+
body["stream_options"] = {"include_usage": True}
|
|
374
|
+
if ignore_eos is not None:
|
|
375
|
+
body["ignore_eos"] = ignore_eos
|
|
376
|
+
if stop is not None:
|
|
377
|
+
body["stop"] = stop
|
|
378
|
+
return body
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def _c4_large_tool_schema() -> List[Dict[str, Any]]:
|
|
382
|
+
"""Standard multi-field function schema (~450-550 tokens) to detect tool-token omission in C4."""
|
|
383
|
+
props: Dict[str, Any] = {}
|
|
384
|
+
for idx in range(1, 13):
|
|
385
|
+
props[f"cluster_storage_policy_field_{idx:02d}"] = {
|
|
386
|
+
"type": "string",
|
|
387
|
+
"description": (
|
|
388
|
+
f"Deterministic configuration selector #{idx:02d} controlling tiered KV-cache placement, "
|
|
389
|
+
"alignment granularity, eviction watermark threshold, and synchronous flush verification."
|
|
390
|
+
),
|
|
391
|
+
}
|
|
392
|
+
return [
|
|
393
|
+
{
|
|
394
|
+
"type": "function",
|
|
395
|
+
"function": {
|
|
396
|
+
"name": "configure_tiered_kv_storage_cluster",
|
|
397
|
+
"description": (
|
|
398
|
+
"Validate and configure distributed KV-cache offloading policy across DRAM L1, "
|
|
399
|
+
"local NVMe O_DIRECT L2, and shared storage tiers with strict quota telemetry."
|
|
400
|
+
),
|
|
401
|
+
"parameters": {
|
|
402
|
+
"type": "object",
|
|
403
|
+
"properties": props,
|
|
404
|
+
"required": ["cluster_storage_policy_field_01"],
|
|
405
|
+
},
|
|
406
|
+
},
|
|
407
|
+
}
|
|
408
|
+
]
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def _iter_frame_json_objects(doc: TraceDocument) -> List[Dict[str, Any]]:
|
|
412
|
+
objs: List[Dict[str, Any]] = []
|
|
413
|
+
for f in doc.frames:
|
|
414
|
+
for line in f.raw_wire.splitlines():
|
|
415
|
+
s = line.strip()
|
|
416
|
+
if s.startswith("data:"):
|
|
417
|
+
s = s[5:].strip()
|
|
418
|
+
if not s or s == "[DONE]" or not s.startswith("{"):
|
|
419
|
+
continue
|
|
420
|
+
try:
|
|
421
|
+
obj = strict_json_loads(s)
|
|
422
|
+
except Exception:
|
|
423
|
+
continue
|
|
424
|
+
if isinstance(obj, dict):
|
|
425
|
+
objs.append(obj)
|
|
426
|
+
return objs
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def _extract_wire_metadata(doc: TraceDocument) -> Tuple[Optional[str], Optional[str], Optional[int], bool]:
|
|
430
|
+
"""Return (model, system_fingerprint, total_tokens, has_empty_choices_usage_tail)."""
|
|
431
|
+
rep_model: Optional[str] = None
|
|
432
|
+
rep_fp: Optional[str] = None
|
|
433
|
+
rep_total: Optional[int] = None
|
|
434
|
+
has_empty_choices_usage = False
|
|
435
|
+
for obj in _iter_frame_json_objects(doc):
|
|
436
|
+
if isinstance(obj.get("model"), str) and obj["model"]:
|
|
437
|
+
rep_model = obj["model"]
|
|
438
|
+
if isinstance(obj.get("system_fingerprint"), str) and obj["system_fingerprint"]:
|
|
439
|
+
rep_fp = obj["system_fingerprint"]
|
|
440
|
+
u = obj.get("usage")
|
|
441
|
+
if isinstance(u, dict):
|
|
442
|
+
if is_strict_int(u.get("total_tokens")):
|
|
443
|
+
rep_total = u["total_tokens"]
|
|
444
|
+
choices = obj.get("choices")
|
|
445
|
+
if isinstance(choices, list) and len(choices) == 0:
|
|
446
|
+
if is_strict_int(u.get("prompt_tokens")) and is_strict_int(u.get("completion_tokens")):
|
|
447
|
+
has_empty_choices_usage = True
|
|
448
|
+
return rep_model, rep_fp, rep_total, has_empty_choices_usage
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def _inspect_raw_c5_wire(doc: TraceDocument) -> Tuple[bool, List[Any], bool]:
|
|
452
|
+
"""Inspect raw wire frames BEFORE dialect fallback normalization.
|
|
453
|
+
|
|
454
|
+
Returns (has_initial_role, raw_explicit_indices_seen, any_omitted_index).
|
|
455
|
+
"""
|
|
456
|
+
has_role = doc.header.dialect == "ollama-ndjson"
|
|
457
|
+
saw_first_choice = False
|
|
458
|
+
raw_indices: List[Any] = []
|
|
459
|
+
any_omitted = False
|
|
460
|
+
|
|
461
|
+
for obj in _iter_frame_json_objects(doc):
|
|
462
|
+
choices = obj.get("choices")
|
|
463
|
+
if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):
|
|
464
|
+
continue
|
|
465
|
+
delta = choices[0].get("delta")
|
|
466
|
+
if not isinstance(delta, dict):
|
|
467
|
+
continue
|
|
468
|
+
if not saw_first_choice:
|
|
469
|
+
if delta.get("role") == "assistant":
|
|
470
|
+
has_role = True
|
|
471
|
+
saw_first_choice = True
|
|
472
|
+
elif delta.get("content") or delta.get("tool_calls") or delta.get("reasoning_content"):
|
|
473
|
+
saw_first_choice = True
|
|
474
|
+
tcalls = delta.get("tool_calls")
|
|
475
|
+
if isinstance(tcalls, list):
|
|
476
|
+
for tc in tcalls:
|
|
477
|
+
if not isinstance(tc, dict):
|
|
478
|
+
continue
|
|
479
|
+
if "index" not in tc or tc["index"] is None:
|
|
480
|
+
any_omitted = True
|
|
481
|
+
else:
|
|
482
|
+
raw_indices.append(tc["index"])
|
|
483
|
+
return has_role, raw_indices, any_omitted
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def _save_path(save_dir: Optional[Path], name: str) -> Optional[Path]:
|
|
487
|
+
return (save_dir / name) if save_dir is not None else None
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def _run_c1(
|
|
491
|
+
chat_url: str,
|
|
492
|
+
responses_url: Optional[str],
|
|
493
|
+
dialect: str,
|
|
494
|
+
model: str,
|
|
495
|
+
headers: Dict[str, str],
|
|
496
|
+
timeout: float,
|
|
497
|
+
save_dir: Optional[Path],
|
|
498
|
+
profile: str,
|
|
499
|
+
secrets_list: Sequence[str],
|
|
500
|
+
) -> ProbeResult:
|
|
501
|
+
code, sev, ref = PROBE_CATALOG["C1"]
|
|
502
|
+
tools = [
|
|
503
|
+
{
|
|
504
|
+
"type": "function",
|
|
505
|
+
"function": {
|
|
506
|
+
"name": "write_config",
|
|
507
|
+
"description": "Write detailed service configuration JSON.",
|
|
508
|
+
"parameters": {
|
|
509
|
+
"type": "object",
|
|
510
|
+
"properties": {
|
|
511
|
+
"service_name": {"type": "string"},
|
|
512
|
+
"description": {"type": "string"},
|
|
513
|
+
"endpoints": {"type": "array", "items": {"type": "string"}},
|
|
514
|
+
},
|
|
515
|
+
"required": ["service_name", "description", "endpoints"],
|
|
516
|
+
},
|
|
517
|
+
},
|
|
518
|
+
}
|
|
519
|
+
]
|
|
520
|
+
msgs = [
|
|
521
|
+
{
|
|
522
|
+
"role": "user",
|
|
523
|
+
"content": "Call write_config with a 150-character description and 4 endpoint URLs.",
|
|
524
|
+
}
|
|
525
|
+
]
|
|
526
|
+
body = _build_chat_body(
|
|
527
|
+
dialect,
|
|
528
|
+
model,
|
|
529
|
+
msgs,
|
|
530
|
+
max_tokens=28,
|
|
531
|
+
temperature=0.0,
|
|
532
|
+
seed=42,
|
|
533
|
+
tools=tools,
|
|
534
|
+
tool_choice={"type": "function", "function": {"name": "write_config"}} if dialect != "ollama-ndjson" else None,
|
|
535
|
+
)
|
|
536
|
+
out_p = _save_path(save_dir, "c1_tool_call_budget_clip.trace.jsonl")
|
|
537
|
+
t0 = time.monotonic()
|
|
538
|
+
try:
|
|
539
|
+
doc = record_stream(url=chat_url, request_body=body, out_path=out_p, headers=headers, dialect=dialect, label="doctor-C1", timeout=timeout)
|
|
540
|
+
except RecorderError as exc:
|
|
541
|
+
if "HTTP 400" in str(exc) or "HTTP 422" in str(exc):
|
|
542
|
+
body["tool_choice"] = "auto"
|
|
543
|
+
if dialect == "ollama-ndjson":
|
|
544
|
+
body.pop("tool_choice", None)
|
|
545
|
+
try:
|
|
546
|
+
doc = record_stream(url=chat_url, request_body=body, out_path=out_p, headers=headers, dialect=dialect, label="doctor-C1", timeout=timeout)
|
|
547
|
+
except RecorderError as exc2:
|
|
548
|
+
return ProbeResult("C1", code, sev, "SKIP", _clean_display(f"tool calling rejected by endpoint ({exc2})", secrets_list), (time.monotonic() - t0) * 1000, 0, None, ref)
|
|
549
|
+
else:
|
|
550
|
+
return ProbeResult("C1", code, sev, "ERROR", _clean_display(f"transport/HTTP error: {exc}", secrets_list), (time.monotonic() - t0) * 1000, 0, None, ref)
|
|
551
|
+
|
|
552
|
+
dur = doc.summary.timing.get("total_ms") or ((time.monotonic() - t0) * 1000)
|
|
553
|
+
findings = audit_trace(doc)
|
|
554
|
+
d_ids = {f.detector_id for f in findings}
|
|
555
|
+
asm = doc.summary.assembled
|
|
556
|
+
tpaths = [str(out_p)] if out_p else []
|
|
557
|
+
docs = [doc]
|
|
558
|
+
total_frames = doc.summary.total_frames
|
|
559
|
+
tot_tok = _doc_tokens(doc)
|
|
560
|
+
|
|
561
|
+
if _has_inband_error(doc):
|
|
562
|
+
return ProbeResult("C1", code, "P0", "FAIL", "HTTP 200 returned an in-band error event", dur, total_frames, tot_tok, ref, tpaths, findings, docs)
|
|
563
|
+
|
|
564
|
+
if D1 in d_ids or D4 in d_ids:
|
|
565
|
+
return ProbeResult("C1", code, "P0", "FAIL", _clean_display(findings[0].message, secrets_list), dur, total_frames, tot_tok, ref, tpaths, findings, docs)
|
|
566
|
+
|
|
567
|
+
# Optional /v1/responses cross-check in `full` profile (non-fatal if 404/405/501)
|
|
568
|
+
if profile == "full" and responses_url and dialect == "openai-chat":
|
|
569
|
+
resp_body = {
|
|
570
|
+
"model": model,
|
|
571
|
+
"stream": True,
|
|
572
|
+
"temperature": 0.0,
|
|
573
|
+
"seed": 42,
|
|
574
|
+
"max_output_tokens": 28,
|
|
575
|
+
"tools": [
|
|
576
|
+
{
|
|
577
|
+
"type": "function",
|
|
578
|
+
"name": "write_config",
|
|
579
|
+
"description": "Write detailed service configuration JSON.",
|
|
580
|
+
"parameters": tools[0]["function"]["parameters"],
|
|
581
|
+
}
|
|
582
|
+
],
|
|
583
|
+
"input": msgs[0]["content"],
|
|
584
|
+
}
|
|
585
|
+
out_r = _save_path(save_dir, "c1_responses_tool_clip.trace.jsonl")
|
|
586
|
+
try:
|
|
587
|
+
doc_r = record_stream(url=responses_url, request_body=resp_body, out_path=out_r, headers=headers, dialect="openai-responses", label="doctor-C1-responses", timeout=timeout)
|
|
588
|
+
docs.append(doc_r)
|
|
589
|
+
if out_r:
|
|
590
|
+
tpaths.append(str(out_r))
|
|
591
|
+
dur += doc_r.summary.timing.get("total_ms") or 0.0
|
|
592
|
+
total_frames += doc_r.summary.total_frames
|
|
593
|
+
rt = _doc_tokens(doc_r)
|
|
594
|
+
if rt is not None:
|
|
595
|
+
tot_tok = (tot_tok or 0) + rt
|
|
596
|
+
r_findings = audit_trace(doc_r)
|
|
597
|
+
findings.extend(r_findings)
|
|
598
|
+
r_ids = {f.detector_id for f in r_findings}
|
|
599
|
+
if _has_inband_error(doc_r) or D1 in r_ids or D4 in r_ids:
|
|
600
|
+
msg = r_findings[0].message if r_findings else "HTTP 200 /v1/responses returned in-band error"
|
|
601
|
+
return ProbeResult("C1", code, "P0", "FAIL", _clean_display(f"/v1/responses breach: {msg}", secrets_list), dur, total_frames, tot_tok, ref, tpaths, findings, docs)
|
|
602
|
+
except RecorderError:
|
|
603
|
+
pass # 404/405/501 or unsupported /v1/responses is expected on Chat-only servers
|
|
604
|
+
|
|
605
|
+
tcalls = asm.get("tool_calls") or []
|
|
606
|
+
if not tcalls:
|
|
607
|
+
return ProbeResult(
|
|
608
|
+
"C1",
|
|
609
|
+
code,
|
|
610
|
+
sev,
|
|
611
|
+
"SKIP",
|
|
612
|
+
"inconclusive: model returned plain text with 0 tool calls",
|
|
613
|
+
dur,
|
|
614
|
+
total_frames,
|
|
615
|
+
tot_tok,
|
|
616
|
+
ref,
|
|
617
|
+
tpaths,
|
|
618
|
+
findings,
|
|
619
|
+
docs,
|
|
620
|
+
)
|
|
621
|
+
|
|
622
|
+
fr = asm.get("finish_reason", "unknown")
|
|
623
|
+
st = asm.get("terminal_status", "unknown")
|
|
624
|
+
if fr == "length" or st == "incomplete":
|
|
625
|
+
return ProbeResult("C1", code, sev, "PASS", f'finish_reason="{fr}" honored on 28-tok tool cutoff (status={st})', dur, total_frames, tot_tok, ref, tpaths, findings, docs)
|
|
626
|
+
if all(tc.get("json_valid") is True for tc in tcalls):
|
|
627
|
+
return ProbeResult("C1", code, sev, "PASS", f'valid complete tool JSON within 28-tok cap (finish_reason="{fr}")', dur, total_frames, tot_tok, ref, tpaths, findings, docs)
|
|
628
|
+
return ProbeResult("C1", code, "P0", "FAIL", f'incomplete tool JSON with unexpected terminal "{fr}/{st}"', dur, total_frames, tot_tok, ref, tpaths, findings, docs)
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
def _run_c2(
|
|
632
|
+
chat_url: str,
|
|
633
|
+
responses_url: Optional[str],
|
|
634
|
+
dialect: str,
|
|
635
|
+
model: str,
|
|
636
|
+
headers: Dict[str, str],
|
|
637
|
+
timeout: float,
|
|
638
|
+
save_dir: Optional[Path],
|
|
639
|
+
profile: str,
|
|
640
|
+
secrets_list: Sequence[str],
|
|
641
|
+
) -> ProbeResult:
|
|
642
|
+
code, sev, ref = PROBE_CATALOG["C2"]
|
|
643
|
+
body = _build_chat_body(
|
|
644
|
+
dialect,
|
|
645
|
+
model,
|
|
646
|
+
[{"role": "user", "content": "Reply with digits 42 only."}],
|
|
647
|
+
max_tokens=32,
|
|
648
|
+
temperature=0.0,
|
|
649
|
+
seed=42,
|
|
650
|
+
include_usage=(dialect != "ollama-ndjson"),
|
|
651
|
+
)
|
|
652
|
+
out_p = _save_path(save_dir, "c2_reasoning_starvation.trace.jsonl")
|
|
653
|
+
t0 = time.monotonic()
|
|
654
|
+
try:
|
|
655
|
+
doc = record_stream(url=chat_url, request_body=body, out_path=out_p, headers=headers, dialect=dialect, label="doctor-C2", timeout=timeout)
|
|
656
|
+
except RecorderError as exc:
|
|
657
|
+
if ("HTTP 400" in str(exc) or "HTTP 422" in str(exc)) and "stream_options" in body:
|
|
658
|
+
body.pop("stream_options", None)
|
|
659
|
+
try:
|
|
660
|
+
doc = record_stream(url=chat_url, request_body=body, out_path=out_p, headers=headers, dialect=dialect, label="doctor-C2", timeout=timeout)
|
|
661
|
+
except RecorderError as exc2:
|
|
662
|
+
return ProbeResult("C2", code, sev, "ERROR", _clean_display(f"transport/HTTP error: {exc2}", secrets_list), (time.monotonic() - t0) * 1000, 0, None, ref)
|
|
663
|
+
else:
|
|
664
|
+
return ProbeResult("C2", code, sev, "ERROR", _clean_display(f"transport/HTTP error: {exc}", secrets_list), (time.monotonic() - t0) * 1000, 0, None, ref)
|
|
665
|
+
|
|
666
|
+
dur = doc.summary.timing.get("total_ms") or ((time.monotonic() - t0) * 1000)
|
|
667
|
+
findings = audit_trace(doc)
|
|
668
|
+
d_ids = {f.detector_id for f in findings}
|
|
669
|
+
asm = doc.summary.assembled
|
|
670
|
+
tpaths = [str(out_p)] if out_p else []
|
|
671
|
+
|
|
672
|
+
if _has_inband_error(doc):
|
|
673
|
+
return ProbeResult("C2", code, "P0", "FAIL", "HTTP 200 returned an in-band error event", dur, doc.summary.total_frames, _doc_tokens(doc), ref, tpaths, findings, [doc])
|
|
674
|
+
|
|
675
|
+
if D4 in d_ids:
|
|
676
|
+
return ProbeResult("C2", code, "P0", "FAIL", _clean_display(findings[0].message, secrets_list), dur, doc.summary.total_frames, _doc_tokens(doc), ref, tpaths, findings, [doc])
|
|
677
|
+
|
|
678
|
+
content = (asm.get("content_text") or "").strip()
|
|
679
|
+
reas = asm.get("reasoning_text") or ""
|
|
680
|
+
comp = (asm.get("reported_usage") or {}).get("completion_tokens")
|
|
681
|
+
fr = asm.get("finish_reason", "unknown")
|
|
682
|
+
|
|
683
|
+
if D2 in d_ids:
|
|
684
|
+
# Honest finish_reason="length" is PASS only when credible reasoning/token cap exhaustion occurred
|
|
685
|
+
credible_length = fr == "length" and (bool(reas) or bool(asm.get("has_unclosed_think")) or (is_strict_int(comp) and comp >= 16))
|
|
686
|
+
if credible_length:
|
|
687
|
+
return ProbeResult("C2", code, sev, "PASS", 'reasoning hit 32-tok cap honestly (finish_reason="length")', dur, doc.summary.total_frames, _doc_tokens(doc), ref, tpaths, findings, [doc])
|
|
688
|
+
return ProbeResult("C2", code, "P0", "FAIL", _clean_display(findings[0].message, secrets_list), dur, doc.summary.total_frames, _doc_tokens(doc), ref, tpaths, findings, [doc])
|
|
689
|
+
|
|
690
|
+
if not content:
|
|
691
|
+
return ProbeResult("C2", code, "P1", "WARN", f'empty content without credible length cutoff (finish_reason="{fr}")', dur, doc.summary.total_frames, _doc_tokens(doc), ref, tpaths, findings, [doc])
|
|
692
|
+
|
|
693
|
+
return ProbeResult(
|
|
694
|
+
"C2",
|
|
695
|
+
code,
|
|
696
|
+
sev,
|
|
697
|
+
"PASS",
|
|
698
|
+
f'non-empty content ({len(content)} chars), no ghost budget leak',
|
|
699
|
+
dur,
|
|
700
|
+
doc.summary.total_frames,
|
|
701
|
+
_doc_tokens(doc),
|
|
702
|
+
ref,
|
|
703
|
+
tpaths,
|
|
704
|
+
findings,
|
|
705
|
+
[doc],
|
|
706
|
+
)
|
|
707
|
+
|
|
708
|
+
|
|
709
|
+
def _run_c3(
|
|
710
|
+
chat_url: str,
|
|
711
|
+
responses_url: Optional[str],
|
|
712
|
+
dialect: str,
|
|
713
|
+
model: str,
|
|
714
|
+
headers: Dict[str, str],
|
|
715
|
+
timeout: float,
|
|
716
|
+
save_dir: Optional[Path],
|
|
717
|
+
profile: str,
|
|
718
|
+
secrets_list: Sequence[str],
|
|
719
|
+
) -> ProbeResult:
|
|
720
|
+
code, sev, ref = PROBE_CATALOG["C3"]
|
|
721
|
+
body = _build_chat_body(
|
|
722
|
+
dialect,
|
|
723
|
+
model,
|
|
724
|
+
[{"role": "user", "content": "Count upwards from 1 separated by spaces."}],
|
|
725
|
+
max_tokens=96,
|
|
726
|
+
temperature=0.0,
|
|
727
|
+
seed=42,
|
|
728
|
+
ignore_eos=True,
|
|
729
|
+
stop=[],
|
|
730
|
+
include_usage=(dialect != "ollama-ndjson"),
|
|
731
|
+
)
|
|
732
|
+
out_p = _save_path(save_dir, "c3_fixed_budget_honor.trace.jsonl")
|
|
733
|
+
t0 = time.monotonic()
|
|
734
|
+
try:
|
|
735
|
+
doc = record_stream(url=chat_url, request_body=body, out_path=out_p, headers=headers, dialect=dialect, label="doctor-C3", timeout=timeout)
|
|
736
|
+
except RecorderError as exc:
|
|
737
|
+
if "HTTP 400" in str(exc) or "HTTP 422" in str(exc):
|
|
738
|
+
return ProbeResult("C3", code, sev, "SKIP", "endpoint rejected ignore_eos (HTTP 400/422)", (time.monotonic() - t0) * 1000, 0, None, ref)
|
|
739
|
+
return ProbeResult("C3", code, sev, "ERROR", _clean_display(f"transport/HTTP error: {exc}", secrets_list), (time.monotonic() - t0) * 1000, 0, None, ref)
|
|
740
|
+
|
|
741
|
+
dur = doc.summary.timing.get("total_ms") or ((time.monotonic() - t0) * 1000)
|
|
742
|
+
findings = audit_trace(doc)
|
|
743
|
+
d_ids = {f.detector_id for f in findings}
|
|
744
|
+
tpaths = [str(out_p)] if out_p else []
|
|
745
|
+
|
|
746
|
+
if _has_inband_error(doc) or D4 in d_ids:
|
|
747
|
+
msg = findings[0].message if findings else "HTTP 200 returned an in-band error event"
|
|
748
|
+
return ProbeResult("C3", code, "P0", "FAIL", _clean_display(msg, secrets_list), dur, doc.summary.total_frames, _doc_tokens(doc), ref, tpaths, findings, [doc])
|
|
749
|
+
|
|
750
|
+
comp = (doc.summary.assembled.get("reported_usage") or {}).get("completion_tokens")
|
|
751
|
+
if not is_strict_int(comp):
|
|
752
|
+
return ProbeResult("C3", code, "P1", "WARN", "server omitted completion_tokens on fixed-budget stream (evidence missing)", dur, doc.summary.total_frames, _doc_tokens(doc), ref, tpaths, findings, [doc])
|
|
753
|
+
if D3 in d_ids or comp < 96:
|
|
754
|
+
return ProbeResult("C3", code, "P1", "WARN", f"ignore_eos=true clipped to {comp}/96 tokens (D3)", dur, doc.summary.total_frames, _doc_tokens(doc), ref, tpaths, findings, [doc])
|
|
755
|
+
if comp > 96:
|
|
756
|
+
return ProbeResult("C3", code, "P1", "WARN", f"fixed budget exceeded ({comp}/96 completion_tokens)", dur, doc.summary.total_frames, _doc_tokens(doc), ref, tpaths, findings, [doc])
|
|
757
|
+
return ProbeResult("C3", code, sev, "PASS", "fixed budget honored (96/96 completion_tokens)", dur, doc.summary.total_frames, _doc_tokens(doc), ref, tpaths, findings, [doc])
|
|
758
|
+
|
|
759
|
+
|
|
760
|
+
def _run_c4(
|
|
761
|
+
chat_url: str,
|
|
762
|
+
responses_url: Optional[str],
|
|
763
|
+
dialect: str,
|
|
764
|
+
model: str,
|
|
765
|
+
headers: Dict[str, str],
|
|
766
|
+
timeout: float,
|
|
767
|
+
save_dir: Optional[Path],
|
|
768
|
+
profile: str,
|
|
769
|
+
secrets_list: Sequence[str],
|
|
770
|
+
) -> ProbeResult:
|
|
771
|
+
code, sev, ref = PROBE_CATALOG["C4"]
|
|
772
|
+
msgs = [{"role": "user", "content": "Reply OK."}]
|
|
773
|
+
body_a = _build_chat_body(dialect, model, msgs, max_tokens=16, temperature=0.0, include_usage=(dialect != "ollama-ndjson"))
|
|
774
|
+
body_b = _build_chat_body(dialect, model, msgs, max_tokens=16, temperature=0.0, tools=_c4_large_tool_schema(), include_usage=(dialect != "ollama-ndjson"))
|
|
775
|
+
|
|
776
|
+
out_a = _save_path(save_dir, "c4a_usage_no_tools.trace.jsonl")
|
|
777
|
+
out_b = _save_path(save_dir, "c4b_usage_with_tools.trace.jsonl")
|
|
778
|
+
t0 = time.monotonic()
|
|
779
|
+
try:
|
|
780
|
+
doc_a = record_stream(url=chat_url, request_body=body_a, out_path=out_a, headers=headers, dialect=dialect, label="doctor-C4a", timeout=timeout)
|
|
781
|
+
doc_b = record_stream(url=chat_url, request_body=body_b, out_path=out_b, headers=headers, dialect=dialect, label="doctor-C4b", timeout=timeout)
|
|
782
|
+
except RecorderError as exc:
|
|
783
|
+
if "HTTP 400" in str(exc) or "HTTP 422" in str(exc):
|
|
784
|
+
return ProbeResult("C4", code, "P1", "WARN", _clean_display(f"stream_options.include_usage or tools rejected ({exc})", secrets_list), (time.monotonic() - t0) * 1000, 0, None, ref)
|
|
785
|
+
return ProbeResult("C4", code, sev, "ERROR", _clean_display(f"transport/HTTP error: {exc}", secrets_list), (time.monotonic() - t0) * 1000, 0, None, ref)
|
|
786
|
+
|
|
787
|
+
dur = (doc_a.summary.timing.get("total_ms") or 0) + (doc_b.summary.timing.get("total_ms") or 0)
|
|
788
|
+
frames = doc_a.summary.total_frames + doc_b.summary.total_frames
|
|
789
|
+
tpaths = [str(p) for p in (out_a, out_b) if p]
|
|
790
|
+
findings = audit_trace(doc_a) + audit_trace(doc_b)
|
|
791
|
+
tok_a, tok_b = _doc_tokens(doc_a), _doc_tokens(doc_b)
|
|
792
|
+
tot_tok = (tok_a or 0) + (tok_b or 0) if (tok_a is not None or tok_b is not None) else None
|
|
793
|
+
|
|
794
|
+
if _has_inband_error(doc_a) or _has_inband_error(doc_b) or any(f.detector_id == D4 for f in findings):
|
|
795
|
+
msg = findings[0].message if findings else "HTTP 200 returned an in-band error event"
|
|
796
|
+
return ProbeResult("C4", code, "P0", "FAIL", _clean_display(msg, secrets_list), dur, frames, tot_tok, ref, tpaths, findings, [doc_a, doc_b])
|
|
797
|
+
|
|
798
|
+
ua = doc_a.summary.assembled.get("reported_usage") or {}
|
|
799
|
+
ub = doc_b.summary.assembled.get("reported_usage") or {}
|
|
800
|
+
pa, ca = ua.get("prompt_tokens"), ua.get("completion_tokens")
|
|
801
|
+
pb, cb = ub.get("prompt_tokens"), ub.get("completion_tokens")
|
|
802
|
+
_, _, raw_tot_a, empty_tail_a = _extract_wire_metadata(doc_a)
|
|
803
|
+
_, _, raw_tot_b, empty_tail_b = _extract_wire_metadata(doc_b)
|
|
804
|
+
|
|
805
|
+
issues: List[str] = []
|
|
806
|
+
if not (is_strict_int(pa) and is_strict_int(ca)):
|
|
807
|
+
issues.append("trailing usage missing (no tools)")
|
|
808
|
+
else:
|
|
809
|
+
if dialect == "openai-chat" and not empty_tail_a:
|
|
810
|
+
issues.append("usage not on trailing empty-choices chunk (no tools)")
|
|
811
|
+
if raw_tot_a is not None and raw_tot_a != pa + ca:
|
|
812
|
+
issues.append(f"total_tokens mismatch on Run A ({raw_tot_a} != {pa}+{ca})")
|
|
813
|
+
|
|
814
|
+
if not (is_strict_int(pb) and is_strict_int(cb)):
|
|
815
|
+
issues.append("trailing usage missing when tools present")
|
|
816
|
+
else:
|
|
817
|
+
if dialect == "openai-chat" and not empty_tail_b:
|
|
818
|
+
issues.append("usage not on trailing empty-choices chunk (with tools)")
|
|
819
|
+
if raw_tot_b is not None and raw_tot_b != pb + cb:
|
|
820
|
+
issues.append(f"total_tokens mismatch on Run B ({raw_tot_b} != {pb}+{cb})")
|
|
821
|
+
|
|
822
|
+
if is_strict_int(pa) and is_strict_int(pb):
|
|
823
|
+
delta_p = pb - pa
|
|
824
|
+
if delta_p < 250:
|
|
825
|
+
issues.append(f"tool schema tokens under-counted (prompt_tokens +{delta_p}, expected >=250)")
|
|
826
|
+
|
|
827
|
+
if issues:
|
|
828
|
+
return ProbeResult("C4", code, "P1", "WARN", "; ".join(issues), dur, frames, tot_tok, ref, tpaths, findings, [doc_a, doc_b])
|
|
829
|
+
return ProbeResult(
|
|
830
|
+
"C4",
|
|
831
|
+
code,
|
|
832
|
+
sev,
|
|
833
|
+
"PASS",
|
|
834
|
+
f"include_usage trailing empty-choices intact (prompt_tokens {pa} -> {pb}, +{pb - pa})",
|
|
835
|
+
dur,
|
|
836
|
+
frames,
|
|
837
|
+
tot_tok,
|
|
838
|
+
ref,
|
|
839
|
+
tpaths,
|
|
840
|
+
findings,
|
|
841
|
+
[doc_a, doc_b],
|
|
842
|
+
)
|
|
843
|
+
|
|
844
|
+
|
|
845
|
+
def _run_c5(
|
|
846
|
+
chat_url: str,
|
|
847
|
+
responses_url: Optional[str],
|
|
848
|
+
dialect: str,
|
|
849
|
+
model: str,
|
|
850
|
+
headers: Dict[str, str],
|
|
851
|
+
timeout: float,
|
|
852
|
+
save_dir: Optional[Path],
|
|
853
|
+
profile: str,
|
|
854
|
+
secrets_list: Sequence[str],
|
|
855
|
+
) -> ProbeResult:
|
|
856
|
+
code, sev, ref = PROBE_CATALOG["C5"]
|
|
857
|
+
tools = [
|
|
858
|
+
{
|
|
859
|
+
"type": "function",
|
|
860
|
+
"function": {
|
|
861
|
+
"name": "get_node_status",
|
|
862
|
+
"description": "Fetch live health metrics for a single cluster node.",
|
|
863
|
+
"parameters": {
|
|
864
|
+
"type": "object",
|
|
865
|
+
"properties": {"node": {"type": "string"}},
|
|
866
|
+
"required": ["node"],
|
|
867
|
+
},
|
|
868
|
+
},
|
|
869
|
+
}
|
|
870
|
+
]
|
|
871
|
+
body = _build_chat_body(
|
|
872
|
+
dialect,
|
|
873
|
+
model,
|
|
874
|
+
[{"role": "user", "content": "Call get_node_status in parallel for both 'node-a' and 'node-b' in a single turn."}],
|
|
875
|
+
max_tokens=128,
|
|
876
|
+
temperature=0.0,
|
|
877
|
+
seed=42,
|
|
878
|
+
tools=tools,
|
|
879
|
+
parallel_tool_calls=True if dialect != "ollama-ndjson" else None,
|
|
880
|
+
include_usage=(dialect != "ollama-ndjson"),
|
|
881
|
+
)
|
|
882
|
+
out_p = _save_path(save_dir, "c5_role_and_parallel_tools.trace.jsonl")
|
|
883
|
+
t0 = time.monotonic()
|
|
884
|
+
try:
|
|
885
|
+
doc = record_stream(url=chat_url, request_body=body, out_path=out_p, headers=headers, dialect=dialect, label="doctor-C5", timeout=timeout)
|
|
886
|
+
except RecorderError as exc:
|
|
887
|
+
if "HTTP 400" in str(exc) or "HTTP 422" in str(exc):
|
|
888
|
+
return ProbeResult("C5", code, sev, "SKIP", _clean_display(f"parallel tool calling unsupported ({exc})", secrets_list), (time.monotonic() - t0) * 1000, 0, None, ref)
|
|
889
|
+
return ProbeResult("C5", code, sev, "ERROR", _clean_display(f"transport/HTTP error: {exc}", secrets_list), (time.monotonic() - t0) * 1000, 0, None, ref)
|
|
890
|
+
|
|
891
|
+
dur = doc.summary.timing.get("total_ms") or ((time.monotonic() - t0) * 1000)
|
|
892
|
+
findings = audit_trace(doc)
|
|
893
|
+
d_ids = {f.detector_id for f in findings}
|
|
894
|
+
tpaths = [str(out_p)] if out_p else []
|
|
895
|
+
|
|
896
|
+
if _has_inband_error(doc):
|
|
897
|
+
return ProbeResult("C5", code, "P0", "FAIL", "HTTP 200 returned an in-band error event", dur, doc.summary.total_frames, _doc_tokens(doc), ref, tpaths, findings, [doc])
|
|
898
|
+
|
|
899
|
+
role_ok, raw_indices, any_omitted_idx = _inspect_raw_c5_wire(doc)
|
|
900
|
+
tcalls = doc.summary.assembled.get("tool_calls") or []
|
|
901
|
+
merged_bad_json = any(
|
|
902
|
+
(tc.get("json_valid") is False) and ("}{" in (tc.get("raw_arguments") or "").replace(" ", ""))
|
|
903
|
+
for tc in tcalls
|
|
904
|
+
)
|
|
905
|
+
|
|
906
|
+
if D1 in d_ids or D4 in d_ids or merged_bad_json:
|
|
907
|
+
parts = []
|
|
908
|
+
if not role_ok:
|
|
909
|
+
parts.append("delta.role stripped")
|
|
910
|
+
if merged_bad_json:
|
|
911
|
+
parts.append("parallel tools merged onto colliding idx=0")
|
|
912
|
+
elif findings:
|
|
913
|
+
parts.append(_clean_display(findings[0].message, secrets_list))
|
|
914
|
+
return ProbeResult("C5", code, "P0", "FAIL", " + ".join(parts), dur, doc.summary.total_frames, _doc_tokens(doc), ref, tpaths, findings, [doc])
|
|
915
|
+
|
|
916
|
+
# Validate raw indices strictly BEFORE dialect fallback normalization
|
|
917
|
+
invalid_raw_idx = any((not is_strict_int(ix)) or ix < 0 for ix in raw_indices)
|
|
918
|
+
distinct_raw = sorted({ix for ix in raw_indices if is_strict_int(ix)})
|
|
919
|
+
expected_seq = list(range(len(distinct_raw)))
|
|
920
|
+
|
|
921
|
+
warns: List[str] = []
|
|
922
|
+
if not role_ok:
|
|
923
|
+
warns.append("initial delta.role='assistant' stripped")
|
|
924
|
+
if dialect == "openai-chat" and tcalls:
|
|
925
|
+
if any_omitted_idx:
|
|
926
|
+
warns.append("tool_calls delta omitted raw index field")
|
|
927
|
+
if invalid_raw_idx or (distinct_raw and distinct_raw != expected_seq):
|
|
928
|
+
warns.append(f"non-contiguous/invalid raw tool indices {raw_indices}")
|
|
929
|
+
|
|
930
|
+
if warns:
|
|
931
|
+
return ProbeResult("C5", code, "P1", "WARN", "; ".join(warns), dur, doc.summary.total_frames, _doc_tokens(doc), ref, tpaths, findings, [doc])
|
|
932
|
+
|
|
933
|
+
if len(tcalls) < 2:
|
|
934
|
+
return ProbeResult(
|
|
935
|
+
"C5",
|
|
936
|
+
code,
|
|
937
|
+
sev,
|
|
938
|
+
"SKIP",
|
|
939
|
+
f"inconclusive: model emitted only {len(tcalls)} tool call(s) (expected 2 parallel calls)",
|
|
940
|
+
dur,
|
|
941
|
+
doc.summary.total_frames,
|
|
942
|
+
_doc_tokens(doc),
|
|
943
|
+
ref,
|
|
944
|
+
tpaths,
|
|
945
|
+
findings,
|
|
946
|
+
[doc],
|
|
947
|
+
)
|
|
948
|
+
|
|
949
|
+
return ProbeResult(
|
|
950
|
+
"C5",
|
|
951
|
+
code,
|
|
952
|
+
sev,
|
|
953
|
+
"PASS",
|
|
954
|
+
f"initial role present, {len(tcalls)} parallel calls with contiguous raw indices {distinct_raw}",
|
|
955
|
+
dur,
|
|
956
|
+
doc.summary.total_frames,
|
|
957
|
+
_doc_tokens(doc),
|
|
958
|
+
ref,
|
|
959
|
+
tpaths,
|
|
960
|
+
findings,
|
|
961
|
+
[doc],
|
|
962
|
+
)
|
|
963
|
+
|
|
964
|
+
|
|
965
|
+
def _run_c6(
|
|
966
|
+
chat_url: str,
|
|
967
|
+
responses_url: Optional[str],
|
|
968
|
+
dialect: str,
|
|
969
|
+
model: str,
|
|
970
|
+
headers: Dict[str, str],
|
|
971
|
+
timeout: float,
|
|
972
|
+
save_dir: Optional[Path],
|
|
973
|
+
profile: str,
|
|
974
|
+
secrets_list: Sequence[str],
|
|
975
|
+
) -> ProbeResult:
|
|
976
|
+
code, sev, ref = PROBE_CATALOG["C6"]
|
|
977
|
+
body = _build_chat_body(
|
|
978
|
+
dialect,
|
|
979
|
+
model,
|
|
980
|
+
[{"role": "user", "content": f"ๅๆ ท้ๅญๅค่ฟฐ๏ผไธ่ฆ่งฃ้๏ผ{C6_TARGET_TEXT}"}],
|
|
981
|
+
max_tokens=48,
|
|
982
|
+
temperature=0.0,
|
|
983
|
+
seed=42,
|
|
984
|
+
)
|
|
985
|
+
out_p = _save_path(save_dir, "c6_utf8_multibyte_integrity.trace.jsonl")
|
|
986
|
+
t0 = time.monotonic()
|
|
987
|
+
try:
|
|
988
|
+
doc = record_stream(url=chat_url, request_body=body, out_path=out_p, headers=headers, dialect=dialect, label="doctor-C6", timeout=timeout)
|
|
989
|
+
except RecorderError as exc:
|
|
990
|
+
return ProbeResult("C6", code, sev, "ERROR", _clean_display(f"transport/HTTP error: {exc}", secrets_list), (time.monotonic() - t0) * 1000, 0, None, ref)
|
|
991
|
+
|
|
992
|
+
dur = doc.summary.timing.get("total_ms") or ((time.monotonic() - t0) * 1000)
|
|
993
|
+
findings = audit_trace(doc)
|
|
994
|
+
d_ids = {f.detector_id for f in findings}
|
|
995
|
+
tpaths = [str(out_p)] if out_p else []
|
|
996
|
+
|
|
997
|
+
if _has_inband_error(doc):
|
|
998
|
+
return ProbeResult("C6", code, "P0", "FAIL", "HTTP 200 returned an in-band error event", dur, doc.summary.total_frames, _doc_tokens(doc), ref, tpaths, findings, [doc])
|
|
999
|
+
|
|
1000
|
+
content = doc.summary.assembled.get("content_text") or ""
|
|
1001
|
+
has_fffd_frame = any("\ufffd" in ((f.norm or {}).get("text_delta") or "") for f in doc.frames)
|
|
1002
|
+
has_bad_utf8 = any(f.parse_error == "invalid_utf8" for f in doc.frames)
|
|
1003
|
+
has_fffd_text = "\ufffd" in content
|
|
1004
|
+
swallowed_tail = (
|
|
1005
|
+
("๐ฅ" in content or "๐" in content)
|
|
1006
|
+
and (C6_TRAILING_EMOJI not in content)
|
|
1007
|
+
and (doc.summary.assembled.get("finish_reason") == "stop")
|
|
1008
|
+
)
|
|
1009
|
+
|
|
1010
|
+
if D4 in d_ids or has_fffd_frame or has_fffd_text or has_bad_utf8 or swallowed_tail:
|
|
1011
|
+
reasons = []
|
|
1012
|
+
if has_fffd_frame or has_fffd_text:
|
|
1013
|
+
reasons.append("U+FFFD replacement char detected in UTF-8 stream")
|
|
1014
|
+
if has_bad_utf8:
|
|
1015
|
+
reasons.append("invalid UTF-8 wire bytes")
|
|
1016
|
+
if swallowed_tail:
|
|
1017
|
+
reasons.append("trailing 4-byte emoji swallowed before finish_reason=stop")
|
|
1018
|
+
if D4 in d_ids and not reasons:
|
|
1019
|
+
reasons.append(_clean_display(findings[0].message, secrets_list))
|
|
1020
|
+
return ProbeResult("C6", code, "P0", "FAIL", "; ".join(reasons), dur, doc.summary.total_frames, _doc_tokens(doc), ref, tpaths, findings, [doc])
|
|
1021
|
+
|
|
1022
|
+
# Require actual multilingual + 4-byte emoji echo to claim PASS (ASCII-only output is inconclusive)
|
|
1023
|
+
has_multibyte = ("ๅๅ้" in content or "ฮ" in content) and (C6_TRAILING_EMOJI in content)
|
|
1024
|
+
if not has_multibyte:
|
|
1025
|
+
return ProbeResult(
|
|
1026
|
+
"C6",
|
|
1027
|
+
code,
|
|
1028
|
+
sev,
|
|
1029
|
+
"SKIP",
|
|
1030
|
+
"inconclusive: output did not echo CJK + trailing 4-byte emoji target",
|
|
1031
|
+
dur,
|
|
1032
|
+
doc.summary.total_frames,
|
|
1033
|
+
_doc_tokens(doc),
|
|
1034
|
+
ref,
|
|
1035
|
+
tpaths,
|
|
1036
|
+
findings,
|
|
1037
|
+
[doc],
|
|
1038
|
+
)
|
|
1039
|
+
|
|
1040
|
+
return ProbeResult(
|
|
1041
|
+
"C6",
|
|
1042
|
+
code,
|
|
1043
|
+
sev,
|
|
1044
|
+
"PASS",
|
|
1045
|
+
f"0 U+FFFD across {doc.summary.total_frames} frames, CJK & trailing 4-byte emoji intact",
|
|
1046
|
+
dur,
|
|
1047
|
+
doc.summary.total_frames,
|
|
1048
|
+
_doc_tokens(doc),
|
|
1049
|
+
ref,
|
|
1050
|
+
tpaths,
|
|
1051
|
+
findings,
|
|
1052
|
+
[doc],
|
|
1053
|
+
)
|
|
1054
|
+
|
|
1055
|
+
|
|
1056
|
+
def _run_c7(
|
|
1057
|
+
chat_url: str,
|
|
1058
|
+
responses_url: Optional[str],
|
|
1059
|
+
dialect: str,
|
|
1060
|
+
model: str,
|
|
1061
|
+
headers: Dict[str, str],
|
|
1062
|
+
timeout: float,
|
|
1063
|
+
save_dir: Optional[Path],
|
|
1064
|
+
profile: str,
|
|
1065
|
+
secrets_list: Sequence[str],
|
|
1066
|
+
) -> ProbeResult:
|
|
1067
|
+
code, sev, ref = PROBE_CATALOG["C7"]
|
|
1068
|
+
body = _build_chat_body(
|
|
1069
|
+
dialect,
|
|
1070
|
+
model,
|
|
1071
|
+
[{"role": "user", "content": "Output integers 01 through 25 separated by commas on one line, nothing else."}],
|
|
1072
|
+
max_tokens=90,
|
|
1073
|
+
temperature=0.0,
|
|
1074
|
+
seed=42,
|
|
1075
|
+
)
|
|
1076
|
+
out_p = _save_path(save_dir, "c7_fake_streaming_buffer.trace.jsonl")
|
|
1077
|
+
t0 = time.monotonic()
|
|
1078
|
+
try:
|
|
1079
|
+
doc = record_stream(url=chat_url, request_body=body, out_path=out_p, headers=headers, dialect=dialect, label="doctor-C7", timeout=timeout)
|
|
1080
|
+
except RecorderError as exc:
|
|
1081
|
+
return ProbeResult("C7", code, sev, "ERROR", _clean_display(f"transport/HTTP error: {exc}", secrets_list), (time.monotonic() - t0) * 1000, 0, None, ref)
|
|
1082
|
+
|
|
1083
|
+
dur = doc.summary.timing.get("total_ms") or ((time.monotonic() - t0) * 1000)
|
|
1084
|
+
findings = audit_trace(doc)
|
|
1085
|
+
d_ids = {f.detector_id for f in findings}
|
|
1086
|
+
tpaths = [str(out_p)] if out_p else []
|
|
1087
|
+
|
|
1088
|
+
if _has_inband_error(doc) or D4 in d_ids:
|
|
1089
|
+
msg = findings[0].message if findings else "HTTP 200 returned an in-band error event"
|
|
1090
|
+
return ProbeResult("C7", code, "P0", "FAIL", _clean_display(msg, secrets_list), dur, doc.summary.total_frames, _doc_tokens(doc), ref, tpaths, findings, [doc])
|
|
1091
|
+
|
|
1092
|
+
ttft_eff = doc.summary.timing.get("ttft_effective_ms") or 0.0
|
|
1093
|
+
total_ms = doc.summary.timing.get("total_ms") or 0.0
|
|
1094
|
+
eff_frames = [f for f in doc.frames if (f.norm or {}).get("text_delta")]
|
|
1095
|
+
eff_count = len(eff_frames)
|
|
1096
|
+
content_bytes = doc.summary.assembled.get("content_utf8_bytes") or 0
|
|
1097
|
+
|
|
1098
|
+
ratio = (ttft_eff / total_ms) if total_ms > 0 else 0.0
|
|
1099
|
+
content_span_ms = (eff_frames[-1].t_rel_ms - eff_frames[0].t_rel_ms) if eff_count >= 2 else 0.0
|
|
1100
|
+
|
|
1101
|
+
# Buffered fake streaming: >=40B payload, >=250ms total latency, >96% spent waiting for first content,
|
|
1102
|
+
# AND all content delivered in a single burst (<5ms arrival span).
|
|
1103
|
+
is_buffered = (
|
|
1104
|
+
content_bytes >= 40
|
|
1105
|
+
and total_ms >= 250.0
|
|
1106
|
+
and ratio > 0.96
|
|
1107
|
+
and content_span_ms < 5.0
|
|
1108
|
+
)
|
|
1109
|
+
if is_buffered:
|
|
1110
|
+
return ProbeResult(
|
|
1111
|
+
"C7",
|
|
1112
|
+
code,
|
|
1113
|
+
"P1",
|
|
1114
|
+
"WARN",
|
|
1115
|
+
f"{ratio * 100:.1f}% latency in TTFT ({ttft_eff:.0f}/{total_ms:.0f} ms), {eff_count}-frame burst ({content_span_ms:.1f} ms span)",
|
|
1116
|
+
dur,
|
|
1117
|
+
doc.summary.total_frames,
|
|
1118
|
+
_doc_tokens(doc),
|
|
1119
|
+
ref,
|
|
1120
|
+
tpaths,
|
|
1121
|
+
findings,
|
|
1122
|
+
[doc],
|
|
1123
|
+
)
|
|
1124
|
+
|
|
1125
|
+
# Insufficient frames on a fast stream: mark inconclusive instead of claiming incremental delivery
|
|
1126
|
+
if eff_count < 4:
|
|
1127
|
+
return ProbeResult(
|
|
1128
|
+
"C7",
|
|
1129
|
+
code,
|
|
1130
|
+
sev,
|
|
1131
|
+
"SKIP",
|
|
1132
|
+
f"inconclusive: only {eff_count} content frame(s) over {total_ms:.1f} ms (span {content_span_ms:.1f} ms)",
|
|
1133
|
+
dur,
|
|
1134
|
+
doc.summary.total_frames,
|
|
1135
|
+
_doc_tokens(doc),
|
|
1136
|
+
ref,
|
|
1137
|
+
tpaths,
|
|
1138
|
+
findings,
|
|
1139
|
+
[doc],
|
|
1140
|
+
)
|
|
1141
|
+
|
|
1142
|
+
return ProbeResult(
|
|
1143
|
+
"C7",
|
|
1144
|
+
code,
|
|
1145
|
+
sev,
|
|
1146
|
+
"PASS",
|
|
1147
|
+
f"incremental stream ({eff_count} content frames, content span {content_span_ms:.1f} ms)",
|
|
1148
|
+
dur,
|
|
1149
|
+
doc.summary.total_frames,
|
|
1150
|
+
_doc_tokens(doc),
|
|
1151
|
+
ref,
|
|
1152
|
+
tpaths,
|
|
1153
|
+
findings,
|
|
1154
|
+
[doc],
|
|
1155
|
+
)
|
|
1156
|
+
|
|
1157
|
+
|
|
1158
|
+
def _run_c8(
|
|
1159
|
+
chat_url: str,
|
|
1160
|
+
responses_url: Optional[str],
|
|
1161
|
+
dialect: str,
|
|
1162
|
+
model: str,
|
|
1163
|
+
headers: Dict[str, str],
|
|
1164
|
+
timeout: float,
|
|
1165
|
+
save_dir: Optional[Path],
|
|
1166
|
+
profile: str,
|
|
1167
|
+
secrets_list: Sequence[str],
|
|
1168
|
+
) -> ProbeResult:
|
|
1169
|
+
code, sev, ref = PROBE_CATALOG["C8"]
|
|
1170
|
+
n1 = secrets.token_hex(4)
|
|
1171
|
+
n2 = secrets.token_hex(4)
|
|
1172
|
+
body_1 = _build_chat_body(
|
|
1173
|
+
dialect,
|
|
1174
|
+
model,
|
|
1175
|
+
[{"role": "user", "content": f"[nonce:{n1}] Reply with the single word READY."}],
|
|
1176
|
+
max_tokens=32,
|
|
1177
|
+
temperature=0.0,
|
|
1178
|
+
seed=42,
|
|
1179
|
+
include_usage=(dialect != "ollama-ndjson"),
|
|
1180
|
+
)
|
|
1181
|
+
body_2 = _build_chat_body(
|
|
1182
|
+
dialect,
|
|
1183
|
+
model,
|
|
1184
|
+
[{"role": "user", "content": f"[nonce:{n2}] Reply with the single word READY."}],
|
|
1185
|
+
max_tokens=32,
|
|
1186
|
+
temperature=0.0,
|
|
1187
|
+
seed=42,
|
|
1188
|
+
include_usage=(dialect != "ollama-ndjson"),
|
|
1189
|
+
)
|
|
1190
|
+
out_1 = _save_path(save_dir, "c8a_relay_drift_1.trace.jsonl")
|
|
1191
|
+
out_2 = _save_path(save_dir, "c8b_relay_drift_2.trace.jsonl")
|
|
1192
|
+
t0 = time.monotonic()
|
|
1193
|
+
try:
|
|
1194
|
+
d1 = record_stream(url=chat_url, request_body=body_1, out_path=out_1, headers=headers, dialect=dialect, label="doctor-C8a", timeout=timeout)
|
|
1195
|
+
d2 = record_stream(url=chat_url, request_body=body_2, out_path=out_2, headers=headers, dialect=dialect, label="doctor-C8b", timeout=timeout)
|
|
1196
|
+
except RecorderError as exc:
|
|
1197
|
+
return ProbeResult("C8", code, sev, "ERROR", _clean_display(f"transport/HTTP error: {exc}", secrets_list), (time.monotonic() - t0) * 1000, 0, None, ref)
|
|
1198
|
+
|
|
1199
|
+
dur = (d1.summary.timing.get("total_ms") or 0) + (d2.summary.timing.get("total_ms") or 0)
|
|
1200
|
+
frames = d1.summary.total_frames + d2.summary.total_frames
|
|
1201
|
+
tpaths = [str(p) for p in (out_1, out_2) if p]
|
|
1202
|
+
findings = audit_trace(d1) + audit_trace(d2)
|
|
1203
|
+
t1, t2 = _doc_tokens(d1), _doc_tokens(d2)
|
|
1204
|
+
tot_tok = (t1 or 0) + (t2 or 0) if (t1 is not None or t2 is not None) else None
|
|
1205
|
+
|
|
1206
|
+
if _has_inband_error(d1) or _has_inband_error(d2) or any(f.detector_id == D4 for f in findings):
|
|
1207
|
+
msg = findings[0].message if findings else "HTTP 200 returned an in-band error event"
|
|
1208
|
+
return ProbeResult("C8", code, "P0", "FAIL", _clean_display(msg, secrets_list), dur, frames, tot_tok, ref, tpaths, findings, [d1, d2])
|
|
1209
|
+
|
|
1210
|
+
m1, fp1, _, _ = _extract_wire_metadata(d1)
|
|
1211
|
+
m2, fp2, _, _ = _extract_wire_metadata(d2)
|
|
1212
|
+
p1 = (d1.summary.assembled.get("reported_usage") or {}).get("prompt_tokens")
|
|
1213
|
+
p2 = (d2.summary.assembled.get("reported_usage") or {}).get("prompt_tokens")
|
|
1214
|
+
txt1 = (d1.summary.assembled.get("content_text") or "").strip()
|
|
1215
|
+
txt2 = (d2.summary.assembled.get("content_text") or "").strip()
|
|
1216
|
+
tail1 = (d1.summary.assembled.get("saw_textless_usage_frame"), d1.summary.assembled.get("finish_reason"))
|
|
1217
|
+
tail2 = (d2.summary.assembled.get("saw_textless_usage_frame"), d2.summary.assembled.get("finish_reason"))
|
|
1218
|
+
|
|
1219
|
+
drifts: List[str] = []
|
|
1220
|
+
if m1 and m2 and m1 != m2:
|
|
1221
|
+
drifts.append(f"model drifted ({_clean_display(m1, secrets_list, 48)} -> {_clean_display(m2, secrets_list, 48)})")
|
|
1222
|
+
if fp1 and fp2 and fp1 != fp2:
|
|
1223
|
+
drifts.append(f"system_fingerprint drifted ({_clean_display(fp1, secrets_list, 32)} -> {_clean_display(fp2, secrets_list, 32)})")
|
|
1224
|
+
if is_strict_int(p1) and is_strict_int(p2) and abs(p1 - p2) >= 3:
|
|
1225
|
+
drifts.append(f"prompt_tokens shifted ({p1} -> {p2}) on identical template")
|
|
1226
|
+
if tail1 != tail2:
|
|
1227
|
+
drifts.append(f"protocol tail mutated ({tail1} -> {tail2})")
|
|
1228
|
+
if txt1 != txt2:
|
|
1229
|
+
drifts.append("output text drifted across seed=42 runs")
|
|
1230
|
+
|
|
1231
|
+
if drifts:
|
|
1232
|
+
return ProbeResult("C8", code, "P2", "WARN", "; ".join(drifts), dur, frames, tot_tok, ref, tpaths, findings, [d1, d2])
|
|
1233
|
+
|
|
1234
|
+
# Require reported telemetry (usage or fingerprint/model) to claim full backend consistency
|
|
1235
|
+
has_telemetry = (is_strict_int(p1) and is_strict_int(p2)) or bool(fp1 and fp2)
|
|
1236
|
+
if not has_telemetry:
|
|
1237
|
+
return ProbeResult(
|
|
1238
|
+
"C8",
|
|
1239
|
+
code,
|
|
1240
|
+
sev,
|
|
1241
|
+
"SKIP",
|
|
1242
|
+
"inconclusive: output matched, but server omitted prompt_tokens and system_fingerprint",
|
|
1243
|
+
dur,
|
|
1244
|
+
frames,
|
|
1245
|
+
tot_tok,
|
|
1246
|
+
ref,
|
|
1247
|
+
tpaths,
|
|
1248
|
+
findings,
|
|
1249
|
+
[d1, d2],
|
|
1250
|
+
)
|
|
1251
|
+
|
|
1252
|
+
return ProbeResult(
|
|
1253
|
+
"C8",
|
|
1254
|
+
code,
|
|
1255
|
+
sev,
|
|
1256
|
+
"PASS",
|
|
1257
|
+
f"consistent backend identity, tokenization (prompt_tokens={p1}/{p2}), and output",
|
|
1258
|
+
dur,
|
|
1259
|
+
frames,
|
|
1260
|
+
tot_tok,
|
|
1261
|
+
ref,
|
|
1262
|
+
tpaths,
|
|
1263
|
+
findings,
|
|
1264
|
+
[d1, d2],
|
|
1265
|
+
)
|
|
1266
|
+
|
|
1267
|
+
|
|
1268
|
+
_PROBE_RUNNERS = {
|
|
1269
|
+
"C1": _run_c1,
|
|
1270
|
+
"C2": _run_c2,
|
|
1271
|
+
"C3": _run_c3,
|
|
1272
|
+
"C4": _run_c4,
|
|
1273
|
+
"C5": _run_c5,
|
|
1274
|
+
"C6": _run_c6,
|
|
1275
|
+
"C7": _run_c7,
|
|
1276
|
+
"C8": _run_c8,
|
|
1277
|
+
}
|
|
1278
|
+
|
|
1279
|
+
|
|
1280
|
+
def compute_wire_grade(results: List[ProbeResult], *, strict: bool = False) -> Tuple[str, int, int, int, int]:
|
|
1281
|
+
"""Return (grade, exit_code, p0_count, warning_count, error_count)."""
|
|
1282
|
+
p0_fails = [r for r in results if r.status == "FAIL"]
|
|
1283
|
+
errors = [r for r in results if r.status == "ERROR"]
|
|
1284
|
+
p1_warns = [r for r in results if r.status == "WARN" and r.severity == "P1"]
|
|
1285
|
+
p2_warns = [r for r in results if r.status == "WARN" and r.severity == "P2"]
|
|
1286
|
+
skips = [r for r in results if r.status == "SKIP"]
|
|
1287
|
+
warn_total = len(p1_warns) + len(p2_warns)
|
|
1288
|
+
|
|
1289
|
+
if p0_fails:
|
|
1290
|
+
return "F", EXIT_SILENT_PROTOCOL_BREACH, len(p0_fails), warn_total, len(errors)
|
|
1291
|
+
if errors:
|
|
1292
|
+
return "F", EXIT_USAGE_OR_IO_ERROR, 0, warn_total, len(errors)
|
|
1293
|
+
if len(p1_warns) >= 2:
|
|
1294
|
+
grade = "C"
|
|
1295
|
+
elif len(p1_warns) == 1:
|
|
1296
|
+
grade = "B"
|
|
1297
|
+
elif len(p2_warns) >= 1 or len(skips) >= 1:
|
|
1298
|
+
# Inconclusive/skipped checks or P2 advisory warnings cannot earn A+
|
|
1299
|
+
grade = "A"
|
|
1300
|
+
else:
|
|
1301
|
+
grade = "A+"
|
|
1302
|
+
|
|
1303
|
+
rc = EXIT_SEMANTIC_REGRESSION if (strict and len(p1_warns) >= 1) else EXIT_OK
|
|
1304
|
+
return grade, rc, 0, warn_total, 0
|
|
1305
|
+
|
|
1306
|
+
|
|
1307
|
+
def run_doctor(
|
|
1308
|
+
*,
|
|
1309
|
+
base_url: str,
|
|
1310
|
+
model: Optional[str] = None,
|
|
1311
|
+
api_key: Optional[str] = None,
|
|
1312
|
+
headers: Optional[Mapping[str, str]] = None,
|
|
1313
|
+
profile: str = "quick",
|
|
1314
|
+
timeout: float = 60.0,
|
|
1315
|
+
save_dir: Optional[str] = None,
|
|
1316
|
+
strict: bool = False,
|
|
1317
|
+
) -> DoctorReport:
|
|
1318
|
+
"""Execute the C1..C8 canary suite against a live LLM endpoint or relay."""
|
|
1319
|
+
if profile not in PROFILE_PROBES:
|
|
1320
|
+
raise ValueError(f"Unknown doctor profile: {profile!r} (valid: quick, full, relay)")
|
|
1321
|
+
|
|
1322
|
+
# Auth precedence: explicit --api-key -> -H Authorization:... -> OPENAI_API_KEY -> none
|
|
1323
|
+
req_headers: Dict[str, str] = validate_and_merge_headers({}, headers) if headers else {}
|
|
1324
|
+
has_hdr_auth = any(k.lower() == "authorization" for k in req_headers)
|
|
1325
|
+
if api_key is not None:
|
|
1326
|
+
resolved_key = resolve_api_key(api_key)
|
|
1327
|
+
if resolved_key:
|
|
1328
|
+
req_headers = validate_and_merge_headers(req_headers, {"Authorization": f"Bearer {resolved_key}"})
|
|
1329
|
+
elif not has_hdr_auth:
|
|
1330
|
+
env_key = (os.environ.get("OPENAI_API_KEY") or "").strip()
|
|
1331
|
+
if env_key:
|
|
1332
|
+
req_headers = validate_and_merge_headers(req_headers, {"Authorization": f"Bearer {env_key}"})
|
|
1333
|
+
|
|
1334
|
+
known_secrets = extract_header_secret_values(req_headers)
|
|
1335
|
+
|
|
1336
|
+
chat_url, responses_url, dialect, resolved_model = resolve_endpoints_and_model(
|
|
1337
|
+
base_url,
|
|
1338
|
+
model=model,
|
|
1339
|
+
headers=req_headers,
|
|
1340
|
+
timeout=timeout,
|
|
1341
|
+
known_secrets=known_secrets,
|
|
1342
|
+
)
|
|
1343
|
+
|
|
1344
|
+
if save_dir == "":
|
|
1345
|
+
ts = datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
|
1346
|
+
out_dir: Optional[Path] = Path(".inferdiff-doctor") / ts
|
|
1347
|
+
elif save_dir is None:
|
|
1348
|
+
out_dir = None
|
|
1349
|
+
else:
|
|
1350
|
+
out_dir = Path(save_dir)
|
|
1351
|
+
|
|
1352
|
+
if out_dir is not None:
|
|
1353
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
1354
|
+
|
|
1355
|
+
results: List[ProbeResult] = []
|
|
1356
|
+
for pid in PROFILE_PROBES[profile]:
|
|
1357
|
+
runner = _PROBE_RUNNERS[pid]
|
|
1358
|
+
res = runner(chat_url, responses_url, dialect, resolved_model, req_headers, timeout, out_dir, profile, known_secrets)
|
|
1359
|
+
results.append(res)
|
|
1360
|
+
|
|
1361
|
+
grade, rc, p0_count, warn_count, err_count = compute_wire_grade(results, strict=strict)
|
|
1362
|
+
known_toks = [r.tokens_used for r in results if r.tokens_used is not None]
|
|
1363
|
+
total_tokens = sum(known_toks) if known_toks else None
|
|
1364
|
+
|
|
1365
|
+
report = DoctorReport(
|
|
1366
|
+
target_url=sanitize_url_for_export(base_url),
|
|
1367
|
+
chat_url=sanitize_url_for_export(chat_url),
|
|
1368
|
+
dialect=dialect,
|
|
1369
|
+
model=_clean_display(resolved_model, known_secrets, 128),
|
|
1370
|
+
profile=profile,
|
|
1371
|
+
grade=grade,
|
|
1372
|
+
exit_code=rc,
|
|
1373
|
+
p0_count=p0_count,
|
|
1374
|
+
warning_count=warn_count,
|
|
1375
|
+
error_count=err_count,
|
|
1376
|
+
total_tokens=total_tokens,
|
|
1377
|
+
save_dir=str(out_dir) if out_dir is not None else None,
|
|
1378
|
+
results=results,
|
|
1379
|
+
)
|
|
1380
|
+
if out_dir is not None:
|
|
1381
|
+
(out_dir / "doctor_summary.json").write_text(
|
|
1382
|
+
json.dumps(report.to_dict(), ensure_ascii=True, indent=2) + "\n",
|
|
1383
|
+
encoding="utf-8",
|
|
1384
|
+
newline="\n",
|
|
1385
|
+
)
|
|
1386
|
+
return report
|
|
1387
|
+
|
|
1388
|
+
|
|
1389
|
+
def render_doctor_terminal(report: DoctorReport, *, no_color: bool = False) -> str:
|
|
1390
|
+
"""Render the compact terminal Wire Health Scorecard."""
|
|
1391
|
+
import sys
|
|
1392
|
+
|
|
1393
|
+
use_color = False
|
|
1394
|
+
if not no_color:
|
|
1395
|
+
try:
|
|
1396
|
+
use_color = sys.stdout.isatty()
|
|
1397
|
+
except Exception:
|
|
1398
|
+
use_color = False
|
|
1399
|
+
|
|
1400
|
+
def _c(txt: str, code: str) -> str:
|
|
1401
|
+
return f"\033[{code}m{txt}\033[0m" if use_color else txt
|
|
1402
|
+
|
|
1403
|
+
sep = "-" * 102
|
|
1404
|
+
lines = [
|
|
1405
|
+
_c(
|
|
1406
|
+
f"inferdiff doctor v{__version__} | target: {_clean_display(report.target_url)} | model: {_clean_display(report.model)} | profile: {report.profile}",
|
|
1407
|
+
"1",
|
|
1408
|
+
),
|
|
1409
|
+
sep,
|
|
1410
|
+
]
|
|
1411
|
+
badge_color = {"PASS": "32", "WARN": "33", "FAIL": "31", "ERROR": "31", "SKIP": "36"}
|
|
1412
|
+
for r in report.results:
|
|
1413
|
+
b = _c(f"[{r.status}]", badge_color.get(r.status, "0"))
|
|
1414
|
+
label = f"{r.probe_id} {r.code}".ljust(34)
|
|
1415
|
+
lines.append(f"{b} {label} {_clean_display(r.summary)} ({r.duration_ms:.0f} ms)")
|
|
1416
|
+
lines.append(sep)
|
|
1417
|
+
|
|
1418
|
+
tok_str = f"{report.total_tokens:,} tokens" if report.total_tokens is not None else "unknown tokens"
|
|
1419
|
+
grade_col = "31" if report.grade == "F" else ("33" if report.warning_count > 0 else "32")
|
|
1420
|
+
lines.append(
|
|
1421
|
+
_c(
|
|
1422
|
+
f"Wire Health Grade: {report.grade} ({report.p0_count} P0 Breaches, {report.error_count} Errors, {report.warning_count} P1/P2 Warnings) | Cost: {tok_str} | Exit: {report.exit_code}",
|
|
1423
|
+
grade_col,
|
|
1424
|
+
)
|
|
1425
|
+
)
|
|
1426
|
+
if report.save_dir:
|
|
1427
|
+
saved_count = sum(len(r.trace_paths) for r in report.results)
|
|
1428
|
+
lines.append(
|
|
1429
|
+
f"Saved {saved_count} sanitized traces to {report.save_dir} (run `inferdiff export <trace>` for <=25-line Issue)"
|
|
1430
|
+
)
|
|
1431
|
+
return "\n".join(lines) + "\n"
|