Coverage for src/hypra/backend.py: 82.49%
187 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-26 22:12 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-26 22:12 +0000
1"""Fail-closed JSON/file subprocess transport for external Wolfram packages.
3No shell, eval, arbitrary expression strings, or Mathematica source generated
4from user expressions is used. The bundled bridge interprets a finite AST.
5"""
7from __future__ import annotations
9import hashlib
10import json
11import os
12import signal
13import subprocess
14import tempfile
15from dataclasses import asdict, dataclass
16from pathlib import Path
17from typing import Any
19from ._json import strict_json_loads
20from .config import BackendConfig
22PROTOCOL_VERSION = 1
23MAX_RESPONSE_BYTES = 16 * 1024 * 1024
26class BackendError(RuntimeError):
27 """A backend failure; no partial mathematical result is accepted."""
30class BackendUnavailableError(BackendError):
31 """The external licensed backend or one of its packages is unavailable."""
34class BackendTimeoutError(BackendError):
35 """The backend exceeded its configured wall-clock limit."""
38class BackendProtocolError(BackendError):
39 """The backend did not return a complete, valid protocol response."""
42@dataclass(frozen=True)
43class BackendInfo:
44 available: bool
45 executable: str | None
46 wolfram_version: str | None = None
47 system_id: str | None = None
48 hypexp_version: str | None = None
49 hpl_version: str | None = None
50 hypexp_path: str | None = None
51 hpl_path: str | None = None
52 fingerprint: str | None = None
53 hypexp_sha256: str | None = None
54 hpl_sha256: str | None = None
55 error: str | None = None
56 bridge_version: int = PROTOCOL_VERSION
58 def as_dict(self) -> dict[str, Any]:
59 return asdict(self)
62def _canonical(value: Any) -> bytes:
63 return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()
66def _file_hash(path: Path) -> str:
67 return hashlib.sha256(path.read_bytes()).hexdigest()
70def _package_fingerprint(path: str | None) -> str | None:
71 """Hash Wolfram sources and reduction tables used by the package."""
72 if not path: 72 ↛ 73line 72 didn't jump to line 73 because the condition on line 72 was never true
73 return None
74 root = Path(path).expanduser()
75 if not root.exists(): 75 ↛ 76line 75 didn't jump to line 76 because the condition on line 75 was never true
76 return None
77 if root.is_file(): 77 ↛ 81line 77 didn't jump to line 81 because the condition on line 77 was always true
78 root = root.parent
79 if root.name == "Kernel":
80 root = root.parent
81 digest = hashlib.sha256()
82 # HPL loads endpoint tables from .mat files. HypExp also loads its
83 # argument and integral reduction rules from .out and .out2 files.
84 package_suffixes = {".m", ".mat", ".mx", ".out", ".out2", ".wl", ".wls"}
85 files = sorted(p for p in root.rglob("*") if p.is_file() and p.suffix in package_suffixes)
86 for file in files:
87 digest.update(str(file.relative_to(root)).encode())
88 digest.update(bytes.fromhex(_file_hash(file)))
89 return digest.hexdigest()
92class WolframBackend:
93 """One-shot kernel execution; cache keys include full requests and versions."""
95 def __init__(self, config: BackendConfig | None = None):
96 self.config = config or BackendConfig.from_env()
97 self.bridge_path = Path(__file__).with_name("wolfram_bridge.wls")
99 def _run(self, request: dict[str, Any]) -> dict[str, Any]:
100 executable = self.config.resolved_executable()
101 if not executable: 101 ↛ 102line 101 didn't jump to line 102 because the condition on line 101 was never true
102 raise BackendUnavailableError(
103 "Wolfram executable not found. Install/license Wolfram and configure "
104 "HYPRA_WOLFRAM_EXECUTABLE; HypExp and HPL are separate external dependencies."
105 )
106 if not self.bridge_path.is_file(): 106 ↛ 107line 106 didn't jump to line 107 because the condition on line 106 was never true
107 raise BackendUnavailableError("Bundled Wolfram JSON bridge is missing")
108 payload = dict(request)
109 payload["protocol"] = PROTOCOL_VERSION
110 payload["packages"] = {
111 "hypexp": self.config.hypexp_path,
112 "hpl": self.config.hpl_path,
113 }
114 with tempfile.TemporaryDirectory(prefix="hypra-") as tmp:
115 request_path, response_path = Path(tmp) / "request.json", Path(tmp) / "response.json"
116 request_path.write_bytes(_canonical(payload))
117 request_path.chmod(0o600)
118 mode = "-file" if "wolframscript" in Path(executable).name.lower() else "-script"
119 command = [
120 executable,
121 mode,
122 str(self.bridge_path),
123 str(request_path),
124 str(response_path),
125 ]
126 try:
127 process = subprocess.Popen(
128 command,
129 stdout=subprocess.PIPE,
130 stderr=subprocess.PIPE,
131 text=True,
132 shell=False,
133 start_new_session=(os.name == "posix"),
134 )
135 except OSError as exc:
136 raise BackendUnavailableError(f"Cannot execute Wolfram backend: {exc}") from exc
137 try:
138 process.communicate(timeout=self.config.timeout)
139 except subprocess.TimeoutExpired as exc:
140 if os.name == "posix": 140 ↛ 146line 140 didn't jump to line 146 because the condition on line 140 was always true
141 try:
142 os.killpg(process.pid, signal.SIGKILL)
143 except ProcessLookupError:
144 pass
145 else:
146 process.kill()
147 process.communicate()
148 raise BackendTimeoutError(
149 f"Wolfram backend exceeded {self.config.timeout:g} seconds; no result accepted"
150 ) from exc
151 if process.returncode:
152 raise BackendError(
153 f"Wolfram exited with status {process.returncode}; no result accepted"
154 )
155 if not response_path.is_file() or response_path.stat().st_size > MAX_RESPONSE_BYTES:
156 raise BackendProtocolError("Missing or oversized Wolfram response")
157 try:
158 response = strict_json_loads(response_path.read_text())
159 except (OSError, UnicodeError, ValueError) as exc:
160 raise BackendProtocolError("Wolfram response is not valid JSON") from exc
161 if (
162 not isinstance(response, dict)
163 or type(response.get("protocol")) is not int
164 or response.get("protocol") != PROTOCOL_VERSION
165 ):
166 raise BackendProtocolError("Unexpected Wolfram protocol")
167 if response.get("status") != "ok":
168 detail = response.get("error", "unspecified backend error")
169 raise BackendError(f"Wolfram rejected the request: {detail}")
170 return response
172 def info(self) -> BackendInfo:
173 executable = self.config.resolved_executable()
174 if executable is None:
175 return BackendInfo(False, None, error="Wolfram executable not found")
176 try:
177 response = self._run({"operation": "info"})
178 meta = response.get("backend")
179 if not isinstance(meta, dict) or not isinstance(meta.get("wolfram_version"), str): 179 ↛ 180line 179 didn't jump to line 180 because the condition on line 179 was never true
180 raise BackendProtocolError("Backend version metadata missing")
181 for key in ("hypexp_path", "hpl_path", "hypexp_sha256", "hpl_sha256"):
182 if not isinstance(meta.get(key), str) or not meta[key]: 182 ↛ 183line 182 didn't jump to line 183 because the condition on line 182 was never true
183 raise BackendProtocolError(f"Backend fingerprint metadata missing: {key}")
184 fingerprint_inputs = {
185 "reported": meta,
186 "bridge_sha256": _file_hash(self.bridge_path),
187 "executable": executable,
188 "executable_sha256": _file_hash(Path(executable)),
189 "hypexp_tree": _package_fingerprint(meta["hypexp_path"]),
190 "hpl_tree": _package_fingerprint(meta["hpl_path"]),
191 }
192 return BackendInfo(
193 True,
194 executable,
195 wolfram_version=meta["wolfram_version"],
196 system_id=meta.get("system_id"),
197 hypexp_version=meta.get("hypexp_version"),
198 hpl_version=meta.get("hpl_version"),
199 hypexp_path=meta["hypexp_path"],
200 hpl_path=meta["hpl_path"],
201 fingerprint=hashlib.sha256(_canonical(fingerprint_inputs)).hexdigest(),
202 hypexp_sha256=meta["hypexp_sha256"],
203 hpl_sha256=meta["hpl_sha256"],
204 )
205 except (BackendError, OSError, ValueError) as exc:
206 return BackendInfo(False, executable, error=str(exc))
208 @staticmethod
209 def _validate_expansion(response: dict[str, Any], request: dict[str, Any]) -> None:
210 through = request["through"]
211 if ( 211 ↛ 217line 211 didn't jump to line 217 because the condition on line 211 was never true
212 not isinstance(response, dict)
213 or type(response.get("protocol")) is not int
214 or response.get("protocol") != PROTOCOL_VERSION
215 or response.get("status") != "ok"
216 ):
217 raise BackendProtocolError("Invalid expansion envelope")
218 if response.get("complete") is not True:
219 raise BackendProtocolError("Backend expansion is incomplete")
220 if (
221 type(response.get("achieved_through")) is not int
222 or type(response.get("remainder_order")) is not int
223 or response.get("achieved_through") != through
224 or response.get("remainder_order") != through + 1
225 ):
226 raise BackendProtocolError("Backend truncation order does not match request")
227 if not isinstance(response.get("result"), dict): 227 ↛ 228line 227 didn't jump to line 228 because the condition on line 227 was never true
228 raise BackendProtocolError("Backend result AST is missing")
229 if response.get("order_basis") != "hypra-pole-bound-plus-hypexp-series": 229 ↛ 230line 229 didn't jump to line 230 because the condition on line 229 was never true
230 raise BackendProtocolError("Backend omitted order provenance")
232 def expand(self, request: dict[str, Any]) -> dict[str, Any]:
233 """Expand an AST request; caller validates expression family and pole bound.
235 ``internal_order`` must cover all series depth required by prefactors.
236 The bridge's order annotation records the algorithm's truncation contract,
237 not an independent proof of HypExp's correctness or endpoint integrability.
238 """
239 for key in ("through", "internal_order"):
240 if isinstance(request.get(key), bool) or not isinstance(request.get(key), int): 240 ↛ 241line 240 didn't jump to line 241 because the condition on line 240 was never true
241 raise TypeError(f"{key} must be an integer")
242 if request["internal_order"] < max(0, request["through"]): 242 ↛ 243line 242 didn't jump to line 243 because the condition on line 242 was never true
243 raise ValueError("internal_order must cover nonnegative requested expansion order")
244 info = self.info()
245 if not info.available:
246 raise BackendUnavailableError(info.error or "External backend unavailable")
247 payload = dict(request, operation="expand")
248 digest = hashlib.sha256(
249 _canonical(
250 {
251 "request": payload,
252 "backend": info.as_dict(),
253 "protocol": PROTOCOL_VERSION,
254 }
255 )
256 ).hexdigest()
257 cache_path = self.config.resolved_cache_dir() / f"{digest}.json"
258 if self.config.use_cache and cache_path.is_file():
259 try:
260 if cache_path.stat().st_size > MAX_RESPONSE_BYTES: 260 ↛ 261line 260 didn't jump to line 261 because the condition on line 260 was never true
261 raise ValueError("oversized cache")
262 envelope = strict_json_loads(cache_path.read_text())
263 if not isinstance(envelope, dict): 263 ↛ 264line 263 didn't jump to line 264 because the condition on line 263 was never true
264 raise TypeError("invalid cache envelope")
265 if envelope.get("key") != digest: 265 ↛ 266line 265 didn't jump to line 266 because the condition on line 265 was never true
266 raise ValueError("cache identity mismatch")
267 response = envelope["response"]
268 if (
269 envelope.get("response_sha256")
270 != hashlib.sha256(_canonical(response)).hexdigest()
271 ):
272 raise ValueError("cache checksum mismatch")
273 self._validate_expansion(response, payload)
274 response["cache_hit"] = True
275 response["provenance"] = info.as_dict()
276 return response
277 except (ValueError, KeyError, TypeError, OSError, BackendError):
278 # A corrupt entry is never used as a mathematical result.
279 pass
280 response = self._run(payload)
281 self._validate_expansion(response, payload)
282 reported = response.get("backend", {})
283 if not isinstance(reported, dict): 283 ↛ 284line 283 didn't jump to line 284 because the condition on line 283 was never true
284 raise BackendProtocolError("Backend identity metadata missing")
285 for key in (
286 "wolfram_version",
287 "system_id",
288 "hypexp_path",
289 "hpl_path",
290 "hypexp_sha256",
291 "hpl_sha256",
292 ):
293 if reported.get(key) != getattr(info, key):
294 raise BackendProtocolError(f"Backend identity changed during expansion: {key}")
295 response["provenance"] = info.as_dict()
296 response["cache_hit"] = False
297 if self.config.use_cache: 297 ↛ 317line 297 didn't jump to line 317 because the condition on line 297 was always true
298 # Cache write failure does not invalidate an otherwise verified transport result.
299 temporary: Path | None = None
300 try:
301 cache_path.parent.mkdir(parents=True, exist_ok=True)
302 with tempfile.NamedTemporaryFile("wb", dir=cache_path.parent, delete=False) as file:
303 temporary = Path(file.name)
304 file.write(
305 _canonical(
306 {
307 "key": digest,
308 "response": response,
309 "response_sha256": hashlib.sha256(_canonical(response)).hexdigest(),
310 }
311 )
312 )
313 os.replace(temporary, cache_path)
314 except OSError:
315 if temporary is not None:
316 temporary.unlink(missing_ok=True)
317 return response
320def backend_info(config: BackendConfig | None = None) -> dict[str, Any]:
321 """Return a serializable health/version record, including unavailable states."""
322 return WolframBackend(config).info().as_dict()