Coverage for src/hypra/serialization.py: 96.47%

181 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-26 22:12 +0000

1"""Strict data-only JSON AST transport between SymPy and Wolfram. 

2 

3Never uses eval, sympify on strings, parse_expr, or executable source text. 

4Numeric atoms are decimal strings to avoid JSON integer-range/float loss. 

5Truncation orders and analytic assumptions belong to the request/result 

6protocol; ``Order`` and unevaluated integrals/derivatives are not accepted. 

7""" 

8 

9from __future__ import annotations 

10 

11import re 

12from collections.abc import Mapping 

13from collections.abc import Set as AbstractSet 

14from typing import Any 

15 

16import sympy as sp 

17from sympy.core.assumptions import _assume_defined 

18from sympy.core.relational import Relational 

19from sympy.logic.boolalg import Boolean 

20 

21from .hpl.notation import HPLPM, _pm_indices 

22from .nielsen import NielsenPolylog 

23from .symbolic import HPL, MZV, EulerSum 

24 

25 

26class SerializationError(ValueError): 

27 """An expression or AST cannot be transported exactly and safely.""" 

28 

29 

30MAX_DEPTH = 128 

31MAX_NODES = 100000 

32MAX_DIGITS = 10000 

33_NAME = re.compile(r"[A-Za-z][A-Za-z0-9_]{0,255}\Z") 

34_INTEGER = re.compile(r"(?:0|-[1-9][0-9]*|[1-9][0-9]*)\Z") 

35_CONSTANTS = { 

36 sp.pi: "Pi", 

37 sp.E: "E", 

38 sp.I: "ImaginaryUnit", 

39 sp.EulerGamma: "EulerGamma", 

40 sp.Catalan: "Catalan", 

41 sp.true: "True", 

42 sp.false: "False", 

43} 

44_CONSTANTS_BY_HEAD = {head: value for value, head in _CONSTANTS.items()} 

45_FUNCTIONS = { 

46 NielsenPolylog: "NielsenPolylog", 

47 sp.Add: "Add", 

48 sp.Mul: "Mul", 

49 sp.Pow: "Pow", 

50 sp.gamma: "Gamma", 

51 sp.log: "Log", 

52 sp.polylog: "PolyLog", 

53 sp.zeta: "Zeta", 

54 sp.exp: "Exp", 

55 sp.polygamma: "PolyGamma", 

56 sp.And: "And", 

57 sp.Or: "Or", 

58 sp.Not: "Not", 

59 sp.Eq: "Equal", 

60 sp.Ne: "Unequal", 

61 sp.Lt: "Less", 

62 sp.Le: "LessEqual", 

63 sp.Gt: "Greater", 

64 sp.Ge: "GreaterEqual", 

65} 

66_FUNCTIONS_BY_HEAD = {head: fn for fn, head in _FUNCTIONS.items()} 

67_ARITY = { 

68 "NielsenPolylog": (3,), 

69 "Pow": (2,), 

70 "Gamma": (1,), 

71 "Log": (1, 2), 

72 "PolyLog": (2,), 

73 "Zeta": (1, 2), 

74 "Exp": (1,), 

75 "PolyGamma": (2,), 

76 "Not": (1,), 

77 "Equal": (2,), 

78 "Unequal": (2,), 

79 "Less": (2,), 

80 "LessEqual": (2,), 

81 "Greater": (2,), 

82 "GreaterEqual": (2,), 

83 "HypergeometricPFQ": (3,), 

84 "HPL": (2,), 

85 "HPLPM": (2,), 

86 "MZV": (1,), 

87 "EulerSum": (2,), 

88} 

89_RELATIONS = {"Equal", "Unequal", "Less", "LessEqual", "Greater", "GreaterEqual"} 

90_LOGIC = {"And", "Or", "Not"} 

91 

92 

93def _name(name: object) -> str: 

94 if not isinstance(name, str) or not _NAME.fullmatch(name): 

95 raise SerializationError("Symbol names must be ASCII letters followed by letters/digits/_") 

96 return name 

97 

98 

99def _assumptions(facts: object) -> dict[str, bool]: 

100 if not isinstance(facts, dict): 100 ↛ 101line 100 didn't jump to line 101 because the condition on line 100 was never true

101 raise SerializationError("Symbol assumptions must be a dictionary") 

102 if any(key not in _assume_defined or type(value) is not bool for key, value in facts.items()): 

103 raise SerializationError("Symbol assumptions must contain known Boolean SymPy facts") 

104 return facts 

105 

106 

107def _number(value: object) -> int: 

108 if not isinstance(value, str) or len(value) > MAX_DIGITS or not _INTEGER.fullmatch(value): 

109 raise SerializationError("Exact integer must be a canonical decimal string") 

110 try: 

111 return int(value) 

112 except ValueError as exc: 

113 raise SerializationError( 

114 "Exact integer exceeds this Python runtime's supported size" 

115 ) from exc 

116 

117 

118def encode_expr(expression: sp.Basic | int | bool) -> dict[str, Any]: 

119 """Encode a supported exact SymPy expression or Boolean condition. 

120 

121 Python integers and booleans are accepted. Strings, floats, integrals, 

122 derivatives, unevaluated orders and all unknown function heads are rejected. 

123 Symbol names deliberately exclude Wolfram contexts and source syntax. 

124 

125 Args: 

126 expression: Exact expression, symbolic condition, or supported scalar. 

127 

128 Returns: 

129 A JSON-compatible symbolic AST. 

130 

131 Raises: 

132 SerializationError: The expression uses an unsupported head or field. 

133 """ 

134 budget = [MAX_NODES] 

135 

136 def encode(expr, depth): 

137 budget[0] -= 1 

138 if depth > MAX_DEPTH or budget[0] < 0: 138 ↛ 139line 138 didn't jump to line 139 because the condition on line 138 was never true

139 raise SerializationError("Expression exceeds AST size/depth limit") 

140 if type(expr) is bool: 140 ↛ 141line 140 didn't jump to line 141 because the condition on line 140 was never true

141 expr = sp.true if expr else sp.false 

142 elif type(expr) is int: 

143 expr = sp.Integer(expr) 

144 if not isinstance(expr, sp.Basic): 

145 raise SerializationError(f"Unsupported input type: {type(expr).__name__}") 

146 if isinstance(expr, sp.Float): 

147 raise SerializationError("Floating-point input is forbidden; use exact Rational values") 

148 if isinstance(expr, sp.Integer): 

149 return {"head": "Integer", "value": str(expr)} 

150 if isinstance(expr, sp.Rational): 

151 return {"head": "Rational", "numerator": str(expr.p), "denominator": str(expr.q)} 

152 if isinstance(expr, sp.Symbol): 

153 if type(expr) is not sp.Symbol or expr.is_commutative is False: 

154 raise SerializationError("Only ordinary commutative Symbols are supported") 

155 # Use original (not inferred) assumptions so reconstruction is reproducible. 

156 facts = {k: v for k, v in expr._assumptions_orig.items() if v is not None} 

157 return {"head": "Symbol", "name": _name(expr.name), "assumptions": _assumptions(facts)} 

158 if expr in _CONSTANTS: 

159 return {"head": _CONSTANTS[expr]} 

160 if isinstance(expr, HPLPM) and expr.func == HPLPM: 

161 # The distinct head makes integer codes unambiguous: 1 denotes 

162 # plus, -1 minus, and 0 the zero kernel. No string AST head or 

163 # executable symbolic-name parsing is needed for discrete words. 

164 _scalar(expr.argument) 

165 return { 

166 "head": "HPLPM", 

167 "args": [ 

168 encode(sp.Tuple(*_pm_indices(expr.word)), depth + 1), 

169 encode(expr.argument, depth + 1), 

170 ], 

171 } 

172 if isinstance(expr, sp.Tuple): 

173 head = "List" 

174 elif expr.func == sp.hyper: 

175 head = "HypergeometricPFQ" 

176 elif expr.func == HPL: 

177 head = "HPL" 

178 elif expr.func == EulerSum: 

179 head = "EulerSum" 

180 elif expr.func == MZV: 

181 head = "MZV" 

182 else: 

183 head = _FUNCTIONS.get(expr.func) 

184 if head is None: 

185 raise SerializationError(f"Unsupported symbolic head: {expr.func.__name__}") 

186 return {"head": head, "args": [encode(arg, depth + 1) for arg in expr.args]} 

187 

188 return encode(expression, 0) 

189 

190 

191def decode_expr(payload: object) -> sp.Basic: 

192 """Reconstruct a whitelisted data-only AST, rejecting malformed fields. 

193 

194 This API accepts already parsed JSON values. JSON parsers should also reject 

195 duplicate object keys before calling it. 

196 

197 Args: 

198 payload: Parsed JSON object representing a supported symbolic AST. 

199 

200 Returns: 

201 The reconstructed SymPy object. 

202 

203 Raises: 

204 SerializationError: The AST is malformed or outside the supported protocol. 

205 """ 

206 budget = [MAX_NODES] 

207 

208 def decode(node, depth): 

209 budget[0] -= 1 

210 if depth > MAX_DEPTH or budget[0] < 0: 

211 raise SerializationError("AST exceeds size/depth limit") 

212 if not isinstance(node, Mapping) or not isinstance(node.get("head"), str): 

213 raise SerializationError("Every AST node must be an object with a string head") 

214 head = node["head"] 

215 if head == "Integer": 

216 _keys(node, {"head", "value"}) 

217 return sp.Integer(_number(node["value"])) 

218 if head == "Rational": 

219 _keys(node, {"head", "numerator", "denominator"}) 

220 numerator, denominator = _number(node["numerator"]), _number(node["denominator"]) 

221 if denominator <= 0: 

222 raise SerializationError("Rational denominator must be strictly positive") 

223 return sp.Rational(numerator, denominator) 

224 if head == "Symbol": 

225 _keys(node, {"head", "name"}, {"assumptions"}) 

226 try: 

227 facts = _assumptions(node.get("assumptions", {})) 

228 if facts.get("commutative") is False: 

229 raise SerializationError("Noncommutative Symbols are not supported") 

230 return sp.Symbol(_name(node["name"]), **facts) 

231 except (TypeError, ValueError) as exc: 

232 raise SerializationError("Invalid or inconsistent symbol assumptions") from exc 

233 if head in _CONSTANTS_BY_HEAD: 

234 _keys(node, {"head"}) 

235 return _CONSTANTS_BY_HEAD[head] 

236 if head not in _FUNCTIONS_BY_HEAD and head not in { 

237 "List", 

238 "HypergeometricPFQ", 

239 "HPL", 

240 "HPLPM", 

241 "MZV", 

242 "EulerSum", 

243 }: 

244 raise SerializationError(f"Unsupported AST head: {head}") 

245 _keys(node, {"head", "args"}) 

246 if not isinstance(node["args"], list): 

247 raise SerializationError("AST args must be a JSON array") 

248 if head in _ARITY and len(node["args"]) not in _ARITY[head]: 

249 raise SerializationError(f"Wrong argument count for {head}") 

250 args = [decode(arg, depth + 1) for arg in node["args"]] 

251 if head == "List": 

252 return sp.Tuple(*args) 

253 if head == "HypergeometricPFQ": 

254 if not isinstance(args[0], sp.Tuple) or not isinstance(args[1], sp.Tuple): 

255 raise SerializationError("Hypergeometric upper/lower parameters must be Lists") 

256 _scalar(args[2]) 

257 for arg in (*args[0], *args[1]): 

258 _scalar(arg) 

259 return sp.hyper(args[0], args[1], args[2], evaluate=False) 

260 if head == "HPL": 

261 if not isinstance(args[0], sp.Tuple): 261 ↛ 262line 261 didn't jump to line 262 because the condition on line 261 was never true

262 raise SerializationError("HPL word must be a List") 

263 _scalar(args[1]) 

264 try: 

265 return HPL(args[0], args[1]) 

266 except (TypeError, ValueError) as exc: 

267 raise SerializationError( 

268 "HPL word must contain expanded letters -1, 0, or 1" 

269 ) from exc 

270 if head == "HPLPM": 

271 if not isinstance(args[0], sp.Tuple): 

272 raise SerializationError("HPLPM word must be a List of integer codes -1, 0, or 1") 

273 indices = [] 

274 for letter in args[0]: 

275 if not isinstance(letter, sp.Integer) or letter not in (-1, 0, 1): 

276 raise SerializationError( 

277 "HPLPM word must be a List of integer codes -1, 0, or 1" 

278 ) 

279 indices.append(int(letter)) 

280 _scalar(args[1]) 

281 return HPLPM.from_indices(tuple(indices), args[1]) 

282 if head == "EulerSum": 

283 try: 

284 return EulerSum(*args) 

285 except (TypeError, ValueError) as exc: 

286 raise SerializationError("Invalid or divergent EulerSum") from exc 

287 if head == "MZV": 

288 if not isinstance(args[0], sp.Tuple): 

289 raise SerializationError("MZV indices must be a List") 

290 try: 

291 return MZV(args[0]) 

292 except (TypeError, ValueError) as exc: 

293 raise SerializationError( 

294 "MZV requires positive indices with first index >= 2" 

295 ) from exc 

296 if head in _LOGIC: 

297 if any(not isinstance(arg, Boolean) for arg in args): 

298 raise SerializationError("Logical operators require Boolean arguments") 

299 else: 

300 for arg in args: 

301 _scalar(arg) 

302 try: 

303 # Unevaluated relations avoid dropping assumptions during transport. 

304 result = ( 

305 _FUNCTIONS_BY_HEAD[head](*args, evaluate=False) 

306 if head in _RELATIONS 

307 else (_FUNCTIONS_BY_HEAD[head](*args)) 

308 ) 

309 except (TypeError, ValueError, AttributeError) as exc: 

310 raise SerializationError(f"Invalid arguments to {head}") from exc 

311 if result.has(sp.oo, -sp.oo, sp.zoo, sp.nan): 

312 raise SerializationError("AST evaluates to a non-finite or undefined expression") 

313 return result 

314 

315 return decode(payload, 0) 

316 

317 

318def _keys( 

319 node: Mapping[str, object], 

320 required: AbstractSet[str], 

321 optional: AbstractSet[str] = frozenset(), 

322) -> None: 

323 if not required <= node.keys() or node.keys() - required - optional: 

324 raise SerializationError("Unexpected or missing AST fields") 

325 

326 

327def _scalar(expr): 

328 if not isinstance(expr, sp.Expr) or isinstance(expr, Relational): 

329 raise SerializationError("Expected a scalar symbolic expression")