Coverage for app / util / safe_json.py: 92%

129 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1"""JSON that never fails to serialise. 

2 

3Every frame svc-ai streams goes through ``dumps``. A value the standard 

4encoder refuses — a datetime, UUID, Decimal, set, pydantic model, LangChain 

5message, a tuple dict key, a cycle, NaN — used to raise in the middle of a 

6stream, and the engine replaced the whole turn with "An internal error has 

7occurred." Here such a value is converted instead. 

8 

9The fast path is the standard encoder with a ``default`` for the common 

10types, so a well-formed frame (every token) costs what it did. Only a 

11payload that encoder still rejects is walked and made JSON-safe: non-finite 

12floats become ``null`` (``JSON.parse`` rejects a bare ``NaN``), keys become 

13strings, a cycle is cut, and anything unknown becomes its ``str``. 

14 

15Separators stay at ``json.dumps``'s defaults: ``rules.audit_done_frame`` 

16finds the done frame by its exact ``"type": "done"`` substring. 

17""" 

18 

19from __future__ import annotations 

20 

21import dataclasses 

22import json 

23import math 

24from datetime import date, datetime, time 

25from decimal import Decimal 

26from enum import Enum 

27from typing import Any 

28from uuid import UUID 

29 

30from app.util.time import utc_isoformat 

31 

32#: Nesting beyond this is cut — a payload that deep is a bug, not data. 

33_MAX_DEPTH = 64 

34_CYCLE = "<cycle>" 

35_TOO_DEEP = "<too deep>" 

36 

37 

38def _convert(value: Any) -> Any: 

39 """One step towards JSON for a value the encoder does not take natively. 

40 

41 Returns something the encoder (or the walk) can take further: never 

42 raises, because the last resort is ``str``. 

43 """ 

44 if hasattr(value, "model_dump"): # pydantic models, LangChain messages 

45 # Python mode, so the values come back through here: a naive 

46 # datetime then goes out with its UTC offset (json mode drops it). 

47 try: 

48 return value.model_dump() 

49 except Exception: # noqa: BLE001 — a field pydantic cannot dump 

50 return str(value) 

51 if isinstance(value, datetime): 

52 return utc_isoformat(value) 

53 if isinstance(value, (date, time)): 

54 return value.isoformat() 

55 if isinstance(value, Enum): 

56 return value.value 

57 if isinstance(value, (UUID, Decimal)): 

58 return str(value) 

59 if isinstance(value, (set, frozenset, tuple)): 

60 return list(value) 

61 if isinstance(value, (bytes, bytearray)): 

62 return bytes(value).decode("utf-8", errors="replace") 

63 if dataclasses.is_dataclass(value) and not isinstance(value, type): 

64 try: 

65 return dataclasses.asdict(value) 

66 except Exception: # noqa: BLE001 

67 return str(value) 

68 if isinstance(value, BaseException): 

69 return f"{type(value).__name__}: {value}" 

70 return str(value) 

71 

72 

73def _key(key: Any) -> str | int | bool | None: 

74 if key is None or isinstance(key, (str, bool, int)): 

75 return key 

76 if isinstance(key, float): 

77 return key if math.isfinite(key) else str(key) 

78 converted = _convert(key) 

79 return converted if isinstance(converted, str) else str(converted) 

80 

81 

82def to_jsonable(value: Any, _stack: frozenset[int] = frozenset()) -> Any: 

83 """``value`` as plain JSON data: dicts, lists, str, finite numbers, bool, None.""" 

84 if value is None or isinstance(value, (str, bool, int)): 

85 return value 

86 if isinstance(value, float): 

87 return value if math.isfinite(value) else None 

88 if len(_stack) >= _MAX_DEPTH: 

89 return _TOO_DEEP 

90 marker = id(value) 

91 if marker in _stack: 

92 return _CYCLE 

93 inner = _stack | {marker} 

94 if isinstance(value, dict): 

95 return {_key(k): to_jsonable(v, inner) for k, v in value.items()} 

96 if isinstance(value, list): 

97 return [to_jsonable(v, inner) for v in value] 

98 converted = _convert(value) 

99 if isinstance(converted, str): 

100 return converted 

101 return to_jsonable(converted, inner) 

102 

103 

104def _default(value: Any) -> Any: 

105 return _convert(value) 

106 

107 

108def dumps(value: Any, **kwargs: Any) -> str: 

109 """``json.dumps`` that cannot raise. ``kwargs`` pass through (``indent``, 

110 ``ensure_ascii``); ``default`` and ``allow_nan`` are this module's.""" 

111 try: 

112 return json.dumps(value, default=_default, allow_nan=False, **kwargs) 

113 except (TypeError, ValueError, RecursionError): 

114 return json.dumps(to_jsonable(value), allow_nan=False, **kwargs) 

115 

116 

117# ── Reading JSON out of model text ──────────────────────────────────────────── 

118 

119_FENCE = "```" 

120 

121 

122def _balanced_spans(text: str) -> list[str]: 

123 """Outermost brace- or bracket-balanced spans, in order, string-aware.""" 

124 spans: list[str] = [] 

125 i = 0 

126 while i < len(text): 

127 opener = text[i] 

128 if opener not in "{[": 

129 i += 1 

130 continue 

131 closer = "}" if opener == "{" else "]" 

132 depth, in_str, esc = 0, False, False 

133 for j in range(i, len(text)): 

134 ch = text[j] 

135 if in_str: 

136 if esc: 

137 esc = False 

138 elif ch == "\\": 

139 esc = True 

140 elif ch == '"': 

141 in_str = False 

142 continue 

143 if ch == '"': 

144 in_str = True 

145 elif ch == opener: 

146 depth += 1 

147 elif ch == closer: 

148 depth -= 1 

149 if depth == 0: 

150 spans.append(text[i : j + 1]) 

151 i = j 

152 break 

153 i += 1 

154 return spans 

155 

156 

157def _fenced_blocks(text: str) -> list[str]: 

158 blocks: list[str] = [] 

159 parts = text.split(_FENCE) 

160 # Odd-indexed parts are fence bodies; drop a language tag on line one. 

161 for body in parts[1::2]: 

162 first, _, rest = body.partition("\n") 

163 blocks.append(rest if first.strip().isalpha() or not first.strip() else body) 

164 return blocks 

165 

166 

167def loads_lenient(text: str) -> Any: 

168 """The JSON value a model meant, from text that may wrap it. 

169 

170 Tries, in order: the whole text, each fenced block, then each outermost 

171 balanced ``{…}`` / ``[…]`` span. Models told to "reply with JSON" add a 

172 ```json fence or a sentence before it often enough that a bare 

173 ``json.loads`` is the wrong reader for model text. Raises ``ValueError`` 

174 when nothing parses. 

175 """ 

176 stripped = text.strip() 

177 candidates = [stripped, *_fenced_blocks(stripped), *_balanced_spans(stripped)] 

178 for candidate in candidates: 

179 candidate = candidate.strip() 

180 if not candidate: 

181 continue 

182 try: 

183 return json.loads(candidate) 

184 except ValueError: 

185 continue 

186 raise ValueError("no JSON value found in the text") 

187 

188 

189def loads_exact(text: str) -> Any: 

190 """The JSON value the whole of ``text`` is — no fence, no prose, no span. 

191 

192 For a reply that may have been cut off at the output token limit: 

193 ``loads_lenient`` finds a balanced span *inside* a truncated value — one 

194 complete item of a cut-off list — and reads it as the answer. A cut-off 

195 reply that still parses whole was complete; anything else was not. 

196 Surrounding whitespace is ignored. Raises ``ValueError`` otherwise. 

197 """ 

198 stripped = (text or "").strip() 

199 if not stripped: 

200 raise ValueError("no JSON value found in the text") 

201 return json.loads(stripped)