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/recorder.py ADDED
@@ -0,0 +1,918 @@
1
+ """Monotonic-clock HTTP streaming recorder with strict RFC 9112 framing, SSE/NDJSON framers, and per-frame flush."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ import datetime
7
+ import http.client
8
+ import json
9
+ import math
10
+ import re
11
+ import secrets
12
+ import socket
13
+ import ssl
14
+ import time
15
+ import urllib.parse
16
+ from dataclasses import dataclass
17
+ from pathlib import Path
18
+ from typing import Any, Dict, Iterator, List, Mapping, Optional, Tuple, Union
19
+
20
+ from .dialects import detect_dialect, normalize_payload
21
+ from .probes.base import BackendProbe
22
+ from .redact import (
23
+ extract_header_secret_values,
24
+ has_control_chars,
25
+ redact_headers,
26
+ sanitize_url_for_error,
27
+ sanitize_url_for_export,
28
+ scrub_known_secrets,
29
+ )
30
+ from .schema import (
31
+ TraceDocument,
32
+ TraceFrame,
33
+ TraceHeader,
34
+ assemble_summary,
35
+ body_sha256,
36
+ canonical_json_bytes,
37
+ canonical_json_line,
38
+ empty_usage,
39
+ extract_effective_params,
40
+ frame_has_effective_payload,
41
+ has_lone_surrogate,
42
+ strict_json_loads,
43
+ )
44
+
45
+ # RFC 9110 HTTP field-name token characters
46
+ _HEADER_NAME_RE = re.compile(r"^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$")
47
+ _MANAGED_HEADERS = frozenset({"content-length", "transfer-encoding", "host"})
48
+ _MAX_CHUNK_LINE_BYTES = 16384
49
+ _MAX_TRAILER_BYTES = 65536
50
+
51
+
52
+ class RecorderError(RuntimeError):
53
+ """Raised on network connection refusal, invalid URL/headers, or non-200 HTTP error."""
54
+
55
+
56
+ def validate_url(url: str) -> urllib.parse.SplitResult:
57
+ """Validate an HTTP(S) target URL before connection (rejects control chars & embedded credentials)."""
58
+ if not isinstance(url, str) or not url or has_control_chars(url):
59
+ raise RecorderError("Invalid URL: empty or contains control characters.")
60
+ try:
61
+ parsed = urllib.parse.urlsplit(url)
62
+ except ValueError as exc:
63
+ raise RecorderError(f"Invalid URL syntax: {exc}") from exc
64
+ if parsed.scheme not in ("http", "https") or not parsed.hostname:
65
+ raise RecorderError(f"Unsupported or invalid URL scheme/host: {sanitize_url_for_error(url)}")
66
+ if parsed.username or parsed.password:
67
+ raise RecorderError("URL must not contain embedded credentials; use --header instead.")
68
+ try:
69
+ _ = parsed.port
70
+ except ValueError as exc:
71
+ raise RecorderError(f"Invalid URL port: {exc}") from exc
72
+ return parsed
73
+
74
+
75
+ def validate_and_merge_headers(
76
+ base: Mapping[str, str],
77
+ extra: Optional[Mapping[str, str]] = None,
78
+ ) -> Dict[str, str]:
79
+ """Validate RFC 9110 header names/values, merge case-insensitively, and reject framing overrides."""
80
+ merged: Dict[str, Tuple[str, str]] = {}
81
+ for k, v in base.items():
82
+ merged[k.lower()] = (k, v)
83
+
84
+ if extra:
85
+ for raw_k, raw_v in extra.items():
86
+ if not isinstance(raw_k, str) or not isinstance(raw_v, str):
87
+ raise RecorderError("HTTP headers must be string key/value pairs.")
88
+ k = raw_k.strip()
89
+ v = raw_v.strip()
90
+ if not k or not _HEADER_NAME_RE.match(k):
91
+ raise RecorderError(f"Invalid HTTP header name: {k!r}")
92
+ if has_control_chars(v):
93
+ raise RecorderError(f"Invalid control characters in HTTP header value for {k!r}.")
94
+ low = k.lower()
95
+ if low in _MANAGED_HEADERS:
96
+ raise RecorderError(f"Header {k!r} is managed internally by inferdiff and cannot be overridden.")
97
+ merged[low] = (k, v)
98
+
99
+ return {orig_k: val for orig_k, val in merged.values()}
100
+
101
+
102
+ def _decode_safe(data: bytes) -> Tuple[str, bool]:
103
+ """Decode UTF-8 bytes cleanly; fall back to surrogateescape on invalid byte sequences."""
104
+ try:
105
+ return data.decode("utf-8"), False
106
+ except UnicodeDecodeError:
107
+ return data.decode("utf-8", errors="surrogateescape"), True
108
+
109
+
110
+ @dataclass
111
+ class WireChunk:
112
+ """One framed raw wire record (either an SSE block or an NDJSON line)."""
113
+
114
+ t_mono_ns: int
115
+ sse_event: Optional[str]
116
+ payload_text: str
117
+ raw_wire: str
118
+ is_incomplete: bool = False
119
+ invalid_utf8: bool = False
120
+ framing_error: Optional[str] = None
121
+
122
+
123
+ class SSEFramer:
124
+ """Incremental WHATWG SSE byte framer resilient to split UTF-8, mixed CRLF/LF/CR, and sticky packets."""
125
+
126
+ def __init__(self) -> None:
127
+ self._bom_checked = False
128
+ self._bom_buf = bytearray()
129
+ self._line_buf = bytearray()
130
+ self._pending_cr = False
131
+ self._discard_next_lf = False
132
+ self._block_raw = bytearray()
133
+ self._event_name: Optional[str] = None
134
+ self._data_suffixes: List[bytes] = []
135
+ self._has_data = False
136
+ self._has_meaningful_field = False
137
+ self._pending_dispatch: Optional[Tuple[int, Optional[str], List[bytes], bytearray]] = None
138
+
139
+ def feed(self, chunk: bytes, t_mono_ns: int) -> List[WireChunk]:
140
+ if not chunk:
141
+ return []
142
+ events: List[WireChunk] = []
143
+ data = chunk
144
+
145
+ if not self._bom_checked:
146
+ self._bom_buf.extend(data)
147
+ if len(self._bom_buf) < 3:
148
+ if b"\xef\xbb\xbf".startswith(bytes(self._bom_buf)):
149
+ return events
150
+ data = bytes(self._bom_buf)
151
+ self._bom_buf.clear()
152
+ self._bom_checked = True
153
+ else:
154
+ if self._bom_buf[:3] == b"\xef\xbb\xbf":
155
+ del self._bom_buf[:3]
156
+ data = bytes(self._bom_buf)
157
+ self._bom_buf.clear()
158
+ self._bom_checked = True
159
+
160
+ i = 0
161
+ n = len(data)
162
+ while i < n:
163
+ b = data[i]
164
+ if self._pending_cr:
165
+ self._pending_cr = False
166
+ if b == 0x0A:
167
+ if self._pending_dispatch is not None:
168
+ ts, ev, sufs, raw = self._pending_dispatch
169
+ raw.append(0x0A)
170
+ self._pending_dispatch = None
171
+ events.append(self._emit(ts, ev, sufs, raw, incomplete=False))
172
+ elif self._discard_next_lf:
173
+ self._discard_next_lf = False
174
+ else:
175
+ self._block_raw.append(0x0A)
176
+ i += 1
177
+ continue
178
+ self._discard_next_lf = False
179
+ if self._pending_dispatch is not None:
180
+ ts, ev, sufs, raw = self._pending_dispatch
181
+ self._pending_dispatch = None
182
+ events.append(self._emit(ts, ev, sufs, raw, incomplete=False))
183
+
184
+ if b == 0x0D: # CR
185
+ line = bytes(self._line_buf)
186
+ self._line_buf.clear()
187
+ self._pending_cr = True
188
+ if not line:
189
+ self._block_raw.append(0x0D)
190
+ if self._has_data:
191
+ self._pending_dispatch = (t_mono_ns, self._event_name, self._data_suffixes, self._block_raw)
192
+ self._block_raw = bytearray()
193
+ self._event_name = None
194
+ self._data_suffixes = []
195
+ self._has_data = False
196
+ self._has_meaningful_field = False
197
+ else:
198
+ # Discard paired LF of this non-data/comment-only CRLF blank line
199
+ self._discard_next_lf = True
200
+ self._reset_block()
201
+ else:
202
+ self._block_raw.extend(line)
203
+ self._block_raw.append(0x0D)
204
+ self._handle_line(line)
205
+ i += 1
206
+ elif b == 0x0A: # LF
207
+ line = bytes(self._line_buf)
208
+ self._line_buf.clear()
209
+ if not line:
210
+ self._block_raw.append(0x0A)
211
+ if self._has_data:
212
+ events.append(self._emit(t_mono_ns, self._event_name, self._data_suffixes, self._block_raw, incomplete=False))
213
+ self._reset_block()
214
+ else:
215
+ self._block_raw.extend(line)
216
+ self._block_raw.append(0x0A)
217
+ self._handle_line(line)
218
+ i += 1
219
+ else:
220
+ self._line_buf.append(b)
221
+ i += 1
222
+ return events
223
+
224
+ def finish(self, t_end_ns: int) -> List[WireChunk]:
225
+ events: List[WireChunk] = []
226
+ if not self._bom_checked and self._bom_buf:
227
+ leftover = bytes(self._bom_buf)
228
+ self._bom_buf.clear()
229
+ self._bom_checked = True
230
+ events.extend(self.feed(leftover, t_end_ns))
231
+ if self._pending_dispatch is not None:
232
+ ts, ev, sufs, raw = self._pending_dispatch
233
+ self._pending_dispatch = None
234
+ self._pending_cr = False
235
+ events.append(self._emit(ts, ev, sufs, raw, incomplete=False))
236
+ if self._line_buf:
237
+ line = bytes(self._line_buf)
238
+ self._line_buf.clear()
239
+ self._block_raw.extend(line)
240
+ self._handle_line(line)
241
+ # Preserve both unterminated data: blocks AND unterminated event:/field tails as incomplete evidence
242
+ if self._has_data or self._has_meaningful_field:
243
+ events.append(self._emit(t_end_ns, self._event_name, self._data_suffixes, self._block_raw, incomplete=True))
244
+ self._reset_block()
245
+ self._pending_cr = False
246
+ self._discard_next_lf = False
247
+ return events
248
+
249
+ def _reset_block(self) -> None:
250
+ self._block_raw = bytearray()
251
+ self._event_name = None
252
+ self._data_suffixes = []
253
+ self._has_data = False
254
+ self._has_meaningful_field = False
255
+
256
+ def _handle_line(self, line: bytes) -> None:
257
+ if not line or line.startswith(b":"):
258
+ return
259
+ self._has_meaningful_field = True
260
+ colon = line.find(b":")
261
+ if colon == -1:
262
+ field, suffix = line, b""
263
+ else:
264
+ field, suffix = line[:colon], line[colon + 1 :]
265
+ if field == b"data":
266
+ self._has_data = True
267
+ self._data_suffixes.append(suffix)
268
+ elif field == b"event":
269
+ val = suffix[1:] if suffix.startswith(b" ") else suffix
270
+ dec, _ = _decode_safe(val)
271
+ self._event_name = dec if dec != "" else None
272
+
273
+ @staticmethod
274
+ def _emit(
275
+ t_mono_ns: int,
276
+ event: Optional[str],
277
+ suffixes: List[bytes],
278
+ raw_blk: bytearray,
279
+ *,
280
+ incomplete: bool,
281
+ ) -> WireChunk:
282
+ stripped_lines = [s[1:] if s.startswith(b" ") else s for s in suffixes]
283
+ payload_text, bad_p = _decode_safe(b"\n".join(stripped_lines))
284
+ raw_wire, bad_r = _decode_safe(bytes(raw_blk))
285
+ return WireChunk(
286
+ t_mono_ns=t_mono_ns,
287
+ sse_event=event,
288
+ payload_text=payload_text,
289
+ raw_wire=raw_wire,
290
+ is_incomplete=incomplete,
291
+ invalid_utf8=bad_p or bad_r,
292
+ )
293
+
294
+
295
+ class NDJSONFramer:
296
+ """Strict incremental line-delimited JSON byte framer for Ollama /api/chat and /api/generate."""
297
+
298
+ def __init__(self) -> None:
299
+ self._buf = bytearray()
300
+
301
+ def feed(self, chunk: bytes, t_mono_ns: int) -> List[WireChunk]:
302
+ if not chunk:
303
+ return []
304
+ self._buf.extend(chunk)
305
+ out: List[WireChunk] = []
306
+ while True:
307
+ nl = self._buf.find(b"\n")
308
+ if nl == -1:
309
+ break
310
+ raw_line = bytes(self._buf[: nl + 1])
311
+ del self._buf[: nl + 1]
312
+ # Consume exact single LF or CRLF delimiter; reject embedded bare CR (e.g. \r\r\n)
313
+ if raw_line.endswith(b"\r\n"):
314
+ content = raw_line[:-2]
315
+ else:
316
+ content = raw_line[:-1]
317
+ if not content.strip():
318
+ if b"\r" in content:
319
+ raw_wire, bad_r = _decode_safe(raw_line)
320
+ out.append(
321
+ WireChunk(
322
+ t_mono_ns=t_mono_ns,
323
+ sse_event=None,
324
+ payload_text="",
325
+ raw_wire=raw_wire,
326
+ is_incomplete=False,
327
+ invalid_utf8=bad_r,
328
+ framing_error="invalid_ndjson_cr",
329
+ )
330
+ )
331
+ continue
332
+ has_bare_cr = b"\r" in content
333
+ payload_text, bad_p = _decode_safe(content)
334
+ raw_wire, bad_r = _decode_safe(raw_line)
335
+ out.append(
336
+ WireChunk(
337
+ t_mono_ns=t_mono_ns,
338
+ sse_event=None,
339
+ payload_text=payload_text,
340
+ raw_wire=raw_wire,
341
+ is_incomplete=False,
342
+ invalid_utf8=bad_p or bad_r,
343
+ framing_error="invalid_ndjson_cr" if has_bare_cr else None,
344
+ )
345
+ )
346
+ return out
347
+
348
+ def finish(self, t_end_ns: int) -> List[WireChunk]:
349
+ if not self._buf:
350
+ return []
351
+ raw_line = bytes(self._buf)
352
+ self._buf.clear()
353
+ if not raw_line.strip():
354
+ return []
355
+ has_bare_cr = b"\r" in raw_line
356
+ payload_text, bad_p = _decode_safe(raw_line)
357
+ raw_wire, bad_r = _decode_safe(raw_line)
358
+ if has_bare_cr:
359
+ return [
360
+ WireChunk(
361
+ t_mono_ns=t_end_ns,
362
+ sse_event=None,
363
+ payload_text=payload_text,
364
+ raw_wire=raw_wire,
365
+ is_incomplete=False,
366
+ invalid_utf8=bad_p or bad_r,
367
+ framing_error="invalid_ndjson_cr",
368
+ )
369
+ ]
370
+ # Compatibility choice: accept a valid final JSON object without trailing LF (some Ollama proxies)
371
+ is_inc = False
372
+ try:
373
+ obj = strict_json_loads(payload_text)
374
+ if not isinstance(obj, dict):
375
+ is_inc = True
376
+ except Exception:
377
+ is_inc = True
378
+ return [
379
+ WireChunk(
380
+ t_mono_ns=t_end_ns,
381
+ sse_event=None,
382
+ payload_text=payload_text,
383
+ raw_wire=raw_wire,
384
+ is_incomplete=is_inc,
385
+ invalid_utf8=bad_p or bad_r,
386
+ )
387
+ ]
388
+
389
+
390
+ def _parse_content_length_headers(resp: http.client.HTTPResponse) -> Tuple[Optional[int], bool]:
391
+ """Normalize Content-Length headers per RFC 9112. Returns (expected_len, framing_valid)."""
392
+ raw_headers = resp.headers.get_all("Content-Length") or []
393
+ if not raw_headers:
394
+ return None, True
395
+ values: List[int] = []
396
+ for hdr in raw_headers:
397
+ for part in hdr.split(","):
398
+ tok = part.strip()
399
+ # Reject non-digits or absurdly long integers before int() conversion
400
+ if not tok or not tok.isdigit() or len(tok) > 20:
401
+ return None, False
402
+ try:
403
+ values.append(int(tok))
404
+ except ValueError:
405
+ return None, False
406
+ if not values:
407
+ return None, False
408
+ if len(set(values)) > 1:
409
+ return None, False
410
+ return values[0], True
411
+
412
+
413
+ def _iter_chunked_body_strict(fp: Any, read_size: int = 8192) -> Iterator[Tuple[bytes, bool]]:
414
+ """Strict RFC 9112 §7.1 incremental chunked decoder reading via read1().
415
+
416
+ Yields (confirmed_body_bytes, True) incrementally, and yields a final sentinel (b"", clean_eof)
417
+ where clean_eof is True ONLY when 0-chunk AND terminating CRLF after trailers are explicitly observed.
418
+ Never passes HTTP chunk delimiters to the application framer and never raises uncaught LineTooLong.
419
+ """
420
+ buf = bytearray()
421
+ state = "CHUNK_SIZE"
422
+ chunk_rem = 0
423
+ trailer_bytes = 0
424
+
425
+ def _fill() -> bool:
426
+ try:
427
+ data = fp.read1(read_size) if hasattr(fp, "read1") else fp.read(read_size)
428
+ except (socket.timeout, TimeoutError, OSError, http.client.HTTPException):
429
+ return False
430
+ if not data:
431
+ return False
432
+ buf.extend(data)
433
+ return True
434
+
435
+ while True:
436
+ if state == "CHUNK_SIZE":
437
+ idx = buf.find(b"\r\n")
438
+ if idx == -1:
439
+ if len(buf) > _MAX_CHUNK_LINE_BYTES:
440
+ yield b"", False
441
+ return
442
+ if not _fill():
443
+ yield b"", False
444
+ return
445
+ continue
446
+ size_line = bytes(buf[:idx])
447
+ del buf[: idx + 2]
448
+ semi = size_line.find(b";")
449
+ size_part = (size_line[:semi] if semi != -1 else size_line).strip()
450
+ if not size_part or any(c not in b"0123456789abcdefABCDEF" for c in size_part):
451
+ yield b"", False
452
+ return
453
+ chunk_size = int(size_part, 16)
454
+ if chunk_size == 0:
455
+ state = "TRAILER"
456
+ else:
457
+ chunk_rem = chunk_size
458
+ state = "CHUNK_DATA"
459
+
460
+ elif state == "CHUNK_DATA":
461
+ if not buf:
462
+ if not _fill():
463
+ yield b"", False
464
+ return
465
+ take = min(chunk_rem, len(buf))
466
+ if take > 0:
467
+ out = bytes(buf[:take])
468
+ del buf[:take]
469
+ chunk_rem -= take
470
+ yield out, True
471
+ if chunk_rem == 0:
472
+ state = "CHUNK_CRLF"
473
+
474
+ elif state == "CHUNK_CRLF":
475
+ while len(buf) < 2:
476
+ if not _fill():
477
+ yield b"", False
478
+ return
479
+ if buf[:2] != b"\r\n":
480
+ yield b"", False
481
+ return
482
+ del buf[:2]
483
+ state = "CHUNK_SIZE"
484
+
485
+ elif state == "TRAILER":
486
+ idx = buf.find(b"\r\n")
487
+ if idx == -1:
488
+ if trailer_bytes + len(buf) > _MAX_TRAILER_BYTES:
489
+ yield b"", False
490
+ return
491
+ if not _fill():
492
+ # Missing terminating CRLF after 0\r\n (or truncated trailer)
493
+ yield b"", False
494
+ return
495
+ continue
496
+ trailer_line = bytes(buf[:idx])
497
+ del buf[: idx + 2]
498
+ trailer_bytes += len(trailer_line) + 2
499
+ if trailer_bytes > _MAX_TRAILER_BYTES:
500
+ yield b"", False
501
+ return
502
+ if len(trailer_line) == 0:
503
+ # Explicitly observed final empty CRLF terminating chunked body!
504
+ yield b"", True
505
+ return
506
+
507
+
508
+ def build_frame_from_chunk(
509
+ chunk: WireChunk,
510
+ *,
511
+ seq: int,
512
+ dialect: str,
513
+ prev_rel_ms: float,
514
+ t0_ns: int,
515
+ sglang_prev_text: str,
516
+ ) -> Tuple[TraceFrame, str]:
517
+ """Convert one framed WireChunk into a TraceFrame + updated sglang cumulative text."""
518
+ t_rel_ms = round(max(0, chunk.t_mono_ns - t0_ns) / 1_000_000.0, 3)
519
+ dt_ms = round(max(0.0, t_rel_ms - prev_rel_ms), 3) if seq > 0 else t_rel_ms
520
+
521
+ empty_norm = dataclasses.asdict(normalize_payload("openai-chat", {}, sse_event=None))
522
+ empty_norm["phase"] = "UNKNOWN"
523
+ empty_norm["usage"] = empty_usage()
524
+
525
+ if chunk.framing_error:
526
+ return (
527
+ TraceFrame(
528
+ seq=seq,
529
+ t_rel_ms=t_rel_ms,
530
+ dt_ms=dt_ms,
531
+ sse_event=chunk.sse_event,
532
+ raw_wire=chunk.raw_wire,
533
+ is_done_sentinel=False,
534
+ parse_error=chunk.framing_error,
535
+ norm=empty_norm,
536
+ ),
537
+ sglang_prev_text,
538
+ )
539
+
540
+ if chunk.is_incomplete:
541
+ return (
542
+ TraceFrame(
543
+ seq=seq,
544
+ t_rel_ms=t_rel_ms,
545
+ dt_ms=dt_ms,
546
+ sse_event=chunk.sse_event,
547
+ raw_wire=chunk.raw_wire,
548
+ is_done_sentinel=False,
549
+ parse_error="incomplete_event",
550
+ norm=empty_norm,
551
+ ),
552
+ sglang_prev_text,
553
+ )
554
+
555
+ if chunk.invalid_utf8:
556
+ return (
557
+ TraceFrame(
558
+ seq=seq,
559
+ t_rel_ms=t_rel_ms,
560
+ dt_ms=dt_ms,
561
+ sse_event=chunk.sse_event,
562
+ raw_wire=chunk.raw_wire,
563
+ is_done_sentinel=False,
564
+ parse_error="invalid_utf8",
565
+ norm=empty_norm,
566
+ ),
567
+ sglang_prev_text,
568
+ )
569
+
570
+ if dialect != "ollama-ndjson" and chunk.payload_text == "[DONE]":
571
+ done_norm = dict(empty_norm)
572
+ done_norm["phase"] = "TERMINAL"
573
+ done_norm["closed_events"] = ["[DONE]"]
574
+ done_norm["is_done_sentinel"] = True
575
+ return (
576
+ TraceFrame(
577
+ seq=seq,
578
+ t_rel_ms=t_rel_ms,
579
+ dt_ms=dt_ms,
580
+ sse_event=chunk.sse_event,
581
+ raw_wire=chunk.raw_wire,
582
+ is_done_sentinel=True,
583
+ parse_error=None,
584
+ norm=done_norm,
585
+ ),
586
+ sglang_prev_text,
587
+ )
588
+
589
+ try:
590
+ payload_obj = strict_json_loads(chunk.payload_text)
591
+ except (json.JSONDecodeError, ValueError, RecursionError) as exc:
592
+ msg = exc.msg if isinstance(exc, json.JSONDecodeError) else str(exc)
593
+ return (
594
+ TraceFrame(
595
+ seq=seq,
596
+ t_rel_ms=t_rel_ms,
597
+ dt_ms=dt_ms,
598
+ sse_event=chunk.sse_event,
599
+ raw_wire=chunk.raw_wire,
600
+ is_done_sentinel=False,
601
+ parse_error=f"invalid_json: {msg}",
602
+ norm=empty_norm,
603
+ ),
604
+ sglang_prev_text,
605
+ )
606
+
607
+ if not isinstance(payload_obj, dict):
608
+ return (
609
+ TraceFrame(
610
+ seq=seq,
611
+ t_rel_ms=t_rel_ms,
612
+ dt_ms=dt_ms,
613
+ sse_event=chunk.sse_event,
614
+ raw_wire=chunk.raw_wire,
615
+ is_done_sentinel=False,
616
+ parse_error="json_not_object",
617
+ norm=empty_norm,
618
+ ),
619
+ sglang_prev_text,
620
+ )
621
+
622
+ if has_lone_surrogate(payload_obj):
623
+ return (
624
+ TraceFrame(
625
+ seq=seq,
626
+ t_rel_ms=t_rel_ms,
627
+ dt_ms=dt_ms,
628
+ sse_event=chunk.sse_event,
629
+ raw_wire=chunk.raw_wire,
630
+ is_done_sentinel=False,
631
+ parse_error="invalid_unicode_surrogate",
632
+ norm=empty_norm,
633
+ ),
634
+ sglang_prev_text,
635
+ )
636
+
637
+ try:
638
+ norm_obj = normalize_payload(
639
+ dialect,
640
+ payload_obj,
641
+ sse_event=chunk.sse_event,
642
+ prev_text=sglang_prev_text,
643
+ )
644
+ except (ValueError, TypeError, OverflowError, RecursionError) as exc:
645
+ return (
646
+ TraceFrame(
647
+ seq=seq,
648
+ t_rel_ms=t_rel_ms,
649
+ dt_ms=dt_ms,
650
+ sse_event=chunk.sse_event,
651
+ raw_wire=chunk.raw_wire,
652
+ is_done_sentinel=False,
653
+ parse_error=f"normalize_error: {type(exc).__name__}",
654
+ norm=empty_norm,
655
+ ),
656
+ sglang_prev_text,
657
+ )
658
+ new_prev = sglang_prev_text
659
+ if dialect == "sglang-native" and isinstance(payload_obj.get("text"), str) and payload_obj["text"] != "":
660
+ new_prev = payload_obj["text"]
661
+
662
+ norm_dict = dataclasses.asdict(norm_obj)
663
+ return (
664
+ TraceFrame(
665
+ seq=seq,
666
+ t_rel_ms=t_rel_ms,
667
+ dt_ms=dt_ms,
668
+ sse_event=chunk.sse_event,
669
+ raw_wire=chunk.raw_wire,
670
+ is_done_sentinel=norm_obj.is_done_sentinel,
671
+ parse_error=norm_obj.protocol_error,
672
+ norm=norm_dict,
673
+ ),
674
+ new_prev,
675
+ )
676
+
677
+
678
+ def record_stream(
679
+ *,
680
+ url: str,
681
+ request_body: Dict[str, Any],
682
+ out_path: Optional[Union[str, Path]] = None,
683
+ headers: Optional[Mapping[str, str]] = None,
684
+ dialect: str = "auto",
685
+ label: str = "",
686
+ timeout: float = 120.0,
687
+ probe: Optional[BackendProbe] = None,
688
+ ) -> TraceDocument:
689
+ """Send one streaming POST via stdlib http.client and record per-frame flushed .trace.jsonl."""
690
+ parsed = validate_url(url)
691
+ if not (isinstance(timeout, (int, float)) and not isinstance(timeout, bool) and math.isfinite(timeout) and timeout > 0):
692
+ raise RecorderError("Timeout must be a positive finite number.")
693
+
694
+ if not isinstance(request_body, dict):
695
+ raise RecorderError("Request body must be a JSON object.")
696
+
697
+ body = dict(request_body)
698
+ if "stream" not in body:
699
+ body["stream"] = True
700
+ elif body["stream"] is not True:
701
+ raise RecorderError("Request body must have stream=true for streaming capture.")
702
+
703
+ body_bytes = canonical_json_bytes(body)
704
+ req_path = parsed.path or "/"
705
+ if parsed.query:
706
+ req_path = f"{req_path}?{parsed.query}"
707
+
708
+ default_headers: Dict[str, str] = {
709
+ "Content-Type": "application/json",
710
+ "Accept": "text/event-stream, application/x-ndjson",
711
+ "Accept-Encoding": "identity",
712
+ }
713
+ send_headers = validate_and_merge_headers(default_headers, headers)
714
+
715
+ conn: http.client.HTTPConnection
716
+ if parsed.scheme == "https":
717
+ conn = http.client.HTTPSConnection(
718
+ parsed.hostname,
719
+ parsed.port or 443,
720
+ timeout=timeout,
721
+ context=ssl.create_default_context(),
722
+ )
723
+ else:
724
+ conn = http.client.HTTPConnection(
725
+ parsed.hostname,
726
+ parsed.port or 80,
727
+ timeout=timeout,
728
+ )
729
+
730
+ now_utc = datetime.datetime.now(datetime.timezone.utc)
731
+ trace_id = f"tr_{now_utc.strftime('%Y%m%dT%H%M%SZ')}_{secrets.token_hex(3)}"
732
+ recorded_at = now_utc.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
733
+
734
+ probe_topology = probe.describe_topology() if probe is not None else None
735
+ if probe is not None:
736
+ probe.sample_pre()
737
+
738
+ try:
739
+ conn.connect()
740
+ t0_ns = time.monotonic_ns()
741
+ conn.request("POST", req_path, body=body_bytes, headers=send_headers)
742
+ resp = conn.getresponse()
743
+ t_headers_ns = time.monotonic_ns()
744
+ except (OSError, http.client.HTTPException) as exc:
745
+ conn.close()
746
+ raise RecorderError(
747
+ f"HTTP connection/request failed for {sanitize_url_for_error(url)} ({type(exc).__name__})"
748
+ ) from exc
749
+
750
+ status_code = resp.status
751
+ content_type = resp.getheader("Content-Type") or ""
752
+ resolved_dialect = detect_dialect(parsed.path, content_type) if dialect == "auto" else dialect
753
+ t_headers_ms = round((t_headers_ns - t0_ns) / 1_000_000.0, 3)
754
+
755
+ # Streaming capture strictly requires HTTP 200; never expose raw query or response body in errors
756
+ if status_code != 200:
757
+ conn.close()
758
+ raise RecorderError(
759
+ f"HTTP {status_code} from {sanitize_url_for_error(url)} (expected HTTP 200 for streaming capture)"
760
+ )
761
+
762
+ redacted_req_headers = redact_headers(send_headers)
763
+ outgoing_secrets = extract_header_secret_values(send_headers)
764
+ # Also capture any non-allowlisted query param values as secrets to scrub if reflected
765
+ if parsed.query:
766
+ for qk, qv in urllib.parse.parse_qsl(parsed.query, keep_blank_values=True):
767
+ if len(qv) >= 6 and qk.lower() not in ("api-version", "version", "alt", "stream"):
768
+ outgoing_secrets.append(qv)
769
+ outgoing_secrets = sorted(set(outgoing_secrets), key=len, reverse=True)
770
+
771
+ safe_stored_url = sanitize_url_for_export(url)
772
+ header = TraceHeader(
773
+ trace_id=trace_id,
774
+ label=label,
775
+ recorded_at_utc=recorded_at,
776
+ dialect=resolved_dialect,
777
+ request={
778
+ "method": "POST",
779
+ "url": safe_stored_url,
780
+ "headers_redacted": redacted_req_headers,
781
+ "body_sha256": body_sha256(body),
782
+ "body": body,
783
+ "effective_params": extract_effective_params(body, resolved_dialect),
784
+ },
785
+ response_meta={
786
+ "status_code": status_code,
787
+ "content_type": content_type,
788
+ "t_headers_ms": t_headers_ms,
789
+ },
790
+ backend_probe=probe_topology,
791
+ )
792
+
793
+ framer: Union[SSEFramer, NDJSONFramer] = (
794
+ NDJSONFramer() if resolved_dialect == "ollama-ndjson" else SSEFramer()
795
+ )
796
+
797
+ expected_len: Optional[int] = None
798
+ cl_valid = True
799
+
800
+ fh = None
801
+ frames: List[TraceFrame] = []
802
+ prev_rel_ms = 0.0
803
+ sglang_prev = ""
804
+ bytes_read = 0
805
+ socket_eof_clean = True
806
+ probe_ttft_sampled = False
807
+ summary = None
808
+ interrupted_exc: Optional[BaseException] = None
809
+
810
+ def _emit_chunk(wc: WireChunk) -> None:
811
+ nonlocal prev_rel_ms, sglang_prev, probe_ttft_sampled
812
+ # Scrub any reflected outgoing credential (e.g. echoed API key) BEFORE normalization or persistence
813
+ if outgoing_secrets:
814
+ wc = WireChunk(
815
+ t_mono_ns=wc.t_mono_ns,
816
+ sse_event=scrub_known_secrets(wc.sse_event, outgoing_secrets) if wc.sse_event else None,
817
+ payload_text=scrub_known_secrets(wc.payload_text, outgoing_secrets),
818
+ raw_wire=scrub_known_secrets(wc.raw_wire, outgoing_secrets),
819
+ is_incomplete=wc.is_incomplete,
820
+ invalid_utf8=wc.invalid_utf8,
821
+ framing_error=wc.framing_error,
822
+ )
823
+ tf, sglang_prev = build_frame_from_chunk(
824
+ wc,
825
+ seq=len(frames),
826
+ dialect=resolved_dialect,
827
+ prev_rel_ms=prev_rel_ms,
828
+ t0_ns=t0_ns,
829
+ sglang_prev_text=sglang_prev,
830
+ )
831
+ if probe is not None and not probe_ttft_sampled and frame_has_effective_payload(tf.norm):
832
+ probe.sample_ttft()
833
+ probe_ttft_sampled = True
834
+ prev_rel_ms = tf.t_rel_ms
835
+ frames.append(tf)
836
+ if fh is not None:
837
+ fh.write(canonical_json_line(tf.to_dict()) + "\n")
838
+ fh.flush()
839
+
840
+ try:
841
+ if not resp.chunked:
842
+ expected_len, cl_valid = _parse_content_length_headers(resp)
843
+ socket_eof_clean = cl_valid
844
+ if out_path is not None:
845
+ out_p = Path(out_path)
846
+ out_p.parent.mkdir(parents=True, exist_ok=True)
847
+ fh = out_p.open("w", encoding="utf-8", newline="\n")
848
+ fh.write(canonical_json_line(header.to_dict()) + "\n")
849
+ fh.flush()
850
+
851
+ try:
852
+ if resp.chunked:
853
+ for body_chunk, ok in _iter_chunked_body_strict(resp.fp, 8192):
854
+ if not body_chunk:
855
+ if not ok:
856
+ socket_eof_clean = False
857
+ break
858
+ t_now = time.monotonic_ns()
859
+ bytes_read += len(body_chunk)
860
+ for wc in framer.feed(body_chunk, t_now):
861
+ _emit_chunk(wc)
862
+ else:
863
+ while True:
864
+ to_read = 8192
865
+ if expected_len is not None:
866
+ rem = expected_len - bytes_read
867
+ if rem <= 0:
868
+ break
869
+ to_read = min(8192, rem)
870
+ try:
871
+ raw = resp.fp.read1(to_read) if hasattr(resp.fp, "read1") else resp.read1(to_read)
872
+ except (http.client.HTTPException, socket.timeout, TimeoutError, OSError):
873
+ socket_eof_clean = False
874
+ break
875
+ if not raw:
876
+ break
877
+ t_now = time.monotonic_ns()
878
+ bytes_read += len(raw)
879
+ for wc in framer.feed(raw, t_now):
880
+ _emit_chunk(wc)
881
+
882
+ if expected_len is not None and bytes_read != expected_len:
883
+ socket_eof_clean = False
884
+ except BaseException as exc:
885
+ socket_eof_clean = False
886
+ interrupted_exc = exc
887
+
888
+ # Always finalize trailing partial frames and summary so flushed evidence is never stranded
889
+ t_end_ns = time.monotonic_ns()
890
+ for wc in framer.finish(t_end_ns):
891
+ _emit_chunk(wc)
892
+
893
+ probe_summary = probe.sample_eof() if probe is not None else None
894
+ total_ms = round((t_end_ns - t0_ns) / 1_000_000.0, 3)
895
+ summary = assemble_summary(
896
+ header,
897
+ frames,
898
+ total_ms=total_ms,
899
+ socket_eof_clean=socket_eof_clean,
900
+ backend_probe_summary=probe_summary,
901
+ )
902
+ if fh is not None:
903
+ fh.write(canonical_json_line(summary.to_dict()) + "\n")
904
+ fh.flush()
905
+ finally:
906
+ if fh is not None:
907
+ fh.close()
908
+ try:
909
+ resp.close()
910
+ except Exception:
911
+ pass
912
+ conn.close()
913
+
914
+ if interrupted_exc is not None:
915
+ raise interrupted_exc
916
+
917
+ assert summary is not None
918
+ return TraceDocument(header=header, frames=frames, summary=summary)