f3d2solidcraft 0.3.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.
Files changed (74) hide show
  1. f3d2solidcraft/__init__.py +3 -0
  2. f3d2solidcraft/__main__.py +3 -0
  3. f3d2solidcraft/_vendor/__init__.py +0 -0
  4. f3d2solidcraft/_vendor/ezf3d/LICENSE +21 -0
  5. f3d2solidcraft/_vendor/ezf3d/__init__.py +1 -0
  6. f3d2solidcraft/_vendor/ezf3d/container/__init__.py +1 -0
  7. f3d2solidcraft/_vendor/ezf3d/container/archive.py +204 -0
  8. f3d2solidcraft/_vendor/ezf3d/model/__init__.py +1 -0
  9. f3d2solidcraft/_vendor/ezf3d/model/parameters.py +365 -0
  10. f3d2solidcraft/_vendor/ezf3d/model/sketch.py +645 -0
  11. f3d2solidcraft/_vendor/ezf3d/model/timeline.py +493 -0
  12. f3d2solidcraft/_vendor/ezf3d/streams/__init__.py +1 -0
  13. f3d2solidcraft/_vendor/ezf3d/streams/manifest.py +262 -0
  14. f3d2solidcraft/_vendor/ezf3d/streams/primitives.py +191 -0
  15. f3d2solidcraft/_vendor/ezf3d/streams/segment.py +521 -0
  16. f3d2solidcraft/cli.py +574 -0
  17. f3d2solidcraft/engine.py +458 -0
  18. f3d2solidcraft/fallback.py +250 -0
  19. f3d2solidcraft/geometry.py +397 -0
  20. f3d2solidcraft/mappers/__init__.py +141 -0
  21. f3d2solidcraft/mappers/bodies.py +99 -0
  22. f3d2solidcraft/mappers/combine.py +73 -0
  23. f3d2solidcraft/mappers/components.py +542 -0
  24. f3d2solidcraft/mappers/edges.py +449 -0
  25. f3d2solidcraft/mappers/extrude.py +1501 -0
  26. f3d2solidcraft/mappers/faces.py +50 -0
  27. f3d2solidcraft/mappers/loft.py +149 -0
  28. f3d2solidcraft/mappers/outputs.py +73 -0
  29. f3d2solidcraft/mappers/params.py +134 -0
  30. f3d2solidcraft/mappers/pattern.py +68 -0
  31. f3d2solidcraft/mappers/planes.py +222 -0
  32. f3d2solidcraft/mappers/primitives.py +144 -0
  33. f3d2solidcraft/mappers/records.py +51 -0
  34. f3d2solidcraft/mappers/revolve.py +134 -0
  35. f3d2solidcraft/mappers/sheet.py +95 -0
  36. f3d2solidcraft/mappers/shell.py +180 -0
  37. f3d2solidcraft/mappers/sketch.py +455 -0
  38. f3d2solidcraft/mcp.py +218 -0
  39. f3d2solidcraft/model.py +503 -0
  40. f3d2solidcraft/oracle.py +905 -0
  41. f3d2solidcraft/pairing.py +105 -0
  42. f3d2solidcraft/reader/__init__.py +77 -0
  43. f3d2solidcraft/reader/cadir.py +832 -0
  44. f3d2solidcraft/reader/fusion.py +218 -0
  45. f3d2solidcraft/reader/locale.py +115 -0
  46. f3d2solidcraft/replay.py +322 -0
  47. f3d2solidcraft/report.py +107 -0
  48. f3d2solidcraft/tools.py +219 -0
  49. f3d2solidcraft/verify.py +186 -0
  50. f3d2solidcraft/visibility.py +95 -0
  51. f3d2solidcraft-0.3.0.dist-info/METADATA +189 -0
  52. f3d2solidcraft-0.3.0.dist-info/RECORD +74 -0
  53. f3d2solidcraft-0.3.0.dist-info/WHEEL +4 -0
  54. f3d2solidcraft-0.3.0.dist-info/entry_points.txt +5 -0
  55. f3d2solidcraft-0.3.0.dist-info/licenses/LICENSE +21 -0
  56. f3d2solidcraft-0.3.0.dist-info/licenses/src/f3d2solidcraft/_vendor/ezf3d/LICENSE +21 -0
  57. f3d2solidcraft_app/__init__.py +5 -0
  58. f3d2solidcraft_app/__main__.py +40 -0
  59. f3d2solidcraft_app/engines.py +158 -0
  60. f3d2solidcraft_app/events.py +35 -0
  61. f3d2solidcraft_app/opener.py +22 -0
  62. f3d2solidcraft_app/outcome.py +54 -0
  63. f3d2solidcraft_app/resources/icon-128.png +0 -0
  64. f3d2solidcraft_app/resources/icon-16.png +0 -0
  65. f3d2solidcraft_app/resources/icon-256.png +0 -0
  66. f3d2solidcraft_app/resources/icon-32.png +0 -0
  67. f3d2solidcraft_app/resources/icon-512.png +0 -0
  68. f3d2solidcraft_app/resources/icon-64.png +0 -0
  69. f3d2solidcraft_app/resources/icon.icns +0 -0
  70. f3d2solidcraft_app/resources/icon.ico +0 -0
  71. f3d2solidcraft_app/resources/icon.svg +26 -0
  72. f3d2solidcraft_app/runner.py +91 -0
  73. f3d2solidcraft_app/texts.py +98 -0
  74. f3d2solidcraft_app/window.py +677 -0
@@ -0,0 +1,458 @@
1
+ """A persistent SolidCraft modelling session over MCP stdio."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import queue
8
+ import re
9
+ import subprocess
10
+ import sys
11
+ import threading
12
+ import time
13
+ from collections import Counter
14
+ from collections.abc import Iterator
15
+ from contextlib import contextmanager
16
+ from pathlib import Path
17
+ from typing import Any, Self
18
+
19
+ from f3d2solidcraft.tools import long_path
20
+
21
+
22
+ class EngineError(RuntimeError):
23
+ """The engine died, hung, or answered with a protocol error."""
24
+
25
+
26
+ # How long one body's measurement gets. A body that goes over it is not a slow design but a
27
+ # pathological one: measured on `Hypercube Evo+.f3z`, 56 of its original's 74 bodies answer in 0.05
28
+ # to 6 s each while `NEMA17_Stepper_Motor+Readscrew_F01 (3)` does not answer in 610 s, and its two
29
+ # siblings of the same definition answer in seconds (spec section 98).
30
+ BODY_TIMEOUT_SECONDS = 45.0
31
+
32
+
33
+ class BodyUnmeasurable(EngineError):
34
+ """One body did not answer in time. The engine is gone with it, and the body is named."""
35
+
36
+ def __init__(self, body: str, said: str) -> None:
37
+ super().__init__(said)
38
+ self.body = body
39
+
40
+
41
+ class CommandRefused(EngineError):
42
+ """The engine refused a command; the design is unchanged."""
43
+
44
+ def __init__(self, command: str, message: str) -> None:
45
+ super().__init__(f"{command}: {message}")
46
+ self.command = command
47
+ self.message = message
48
+
49
+
50
+ # Advice SolidCraft appends to a tool result's text, after the JSON. 0.22.1 adds one to every
51
+ # single result ("this is a headless session because the SolidCraft app was not found…"), which is
52
+ # fair enough for a person reading it and fatal for `json.loads`. The answers themselves are
53
+ # unchanged from 0.16.2 — same tools, same keys, same shapes — so the whole 0.16.2-to-0.22.1 break
54
+ # was this trailing sentence making every parse fail and `call` hand back the raw string instead.
55
+ _ADVICE = re.compile(r"\s*Note: [^\n]*?\bheadless session\b.*\Z", re.DOTALL)
56
+
57
+
58
+ def _without_advice(text: str) -> str:
59
+ return _ADVICE.sub("", text).strip()
60
+
61
+
62
+ def _answer(text: str) -> Any:
63
+ """A tool's answer: its JSON, ignoring any prose the engine appends after it.
64
+
65
+ Parsed with `raw_decode` rather than `loads` so it does not matter what follows the JSON or
66
+ which version wrote it — the first value is the answer. Text that is not JSON at all comes back
67
+ as text, as it always did, with the advice taken off.
68
+ """
69
+ stripped = text.lstrip()
70
+ try:
71
+ value, end = json.JSONDecoder().raw_decode(stripped)
72
+ except ValueError:
73
+ return _without_advice(text) or text
74
+ # Only the advice may follow the answer. Without this, prose that merely starts like JSON comes
75
+ # back as a truncated value: raw_decode reads "12 bodies removed" as the number 12 and drops the
76
+ # rest, where `loads` used to fail and hand back the sentence.
77
+ if _without_advice(stripped[end:]):
78
+ return _without_advice(text) or text
79
+ return value
80
+
81
+
82
+ # How long one engine call may take before the session is given up as out of step. 120 s was the
83
+ # value until a real design of the user's measured past it: importing the 38.6 MB STEP of
84
+ # `Hypercube Evo+.f3z`'s original — 104 B-rep bodies — takes **195 s** on this machine, and the
85
+ # conversion died on a call that was working. The point of the limit is to notice an engine that
86
+ # will never answer, not to cap a call that is simply big, so it is ten minutes now: still far
87
+ # under the 1800 s an all-bodies `measure` of that design failed to finish in, and far over any
88
+ # call the corpus takes (spec section 98).
89
+ CALL_TIMEOUT_SECONDS = 600.0
90
+
91
+
92
+ _TRACE = bool(os.environ.get("F3D2SC_TRACE"))
93
+
94
+
95
+ class Engine:
96
+ def __init__(
97
+ self, cli: Path, allow_paths: list[Path] | None = None, timeout: float = CALL_TIMEOUT_SECONDS
98
+ ) -> None:
99
+ self.cli = Path(cli)
100
+ # Spelt out in full: the engine refuses a Windows 8.3 short name in an allowed path too.
101
+ self.allow_paths = [long_path(p) for p in (allow_paths or [])]
102
+ self.timeout = timeout
103
+ # Whether a whole-design reading must enumerate placements rather than definitions. False
104
+ # until `cli` proves otherwise: it is the strict reading, and on a design the engine cannot
105
+ # measure in one call it is not available at all (spec section 98).
106
+ self.read_placements = False
107
+ # Bodies this engine has already been proved unable to measure, so no reading asks again.
108
+ # `cli` accumulates them across its retries and the report names every one (section 98).
109
+ self.unmeasurable: set[str] = set()
110
+ self.mutations = 0 # successful commands run, not undo steps (see undo_depth)
111
+ self._proc: subprocess.Popen[str] | None = None
112
+ self._lines: queue.Queue[str | None] = queue.Queue()
113
+ self._next_id = 0
114
+
115
+ def __enter__(self) -> Self:
116
+ self.start()
117
+ return self
118
+
119
+ def __exit__(self, *exc: object) -> None:
120
+ self.close()
121
+
122
+ def start(self) -> None:
123
+ args = [str(self.cli), "mcp"]
124
+ for path in self.allow_paths:
125
+ args += ["--allow-path", str(path)]
126
+ self._proc = subprocess.Popen(
127
+ args,
128
+ stdin=subprocess.PIPE,
129
+ stdout=subprocess.PIPE,
130
+ stderr=subprocess.DEVNULL,
131
+ text=True,
132
+ # The engine speaks UTF-8; Windows would read the pipe in its ANSI code page, which
133
+ # garbles an accented body name or stops the reader on a byte that code page lacks.
134
+ encoding="utf-8",
135
+ bufsize=1,
136
+ )
137
+ self._lines = queue.Queue()
138
+ threading.Thread(target=self._pump, args=(self._proc.stdout, self._lines), daemon=True).start()
139
+ try:
140
+ self._rpc(
141
+ "initialize",
142
+ {
143
+ "protocolVersion": "2025-06-18",
144
+ "capabilities": {},
145
+ "clientInfo": {"name": "f3d2solidcraft", "version": "0"},
146
+ },
147
+ )
148
+ self._send({"jsonrpc": "2.0", "method": "notifications/initialized"})
149
+ except BaseException:
150
+ self.close()
151
+ raise
152
+
153
+ @staticmethod
154
+ def _pump(stdout: Any, lines: queue.Queue[str | None]) -> None:
155
+ try:
156
+ for line in stdout:
157
+ lines.put(line)
158
+ except (OSError, ValueError):
159
+ pass
160
+ lines.put(None)
161
+
162
+ def _send(self, message: dict) -> None:
163
+ if self._proc is None or self._proc.stdin is None:
164
+ raise EngineError("engine is not running")
165
+ try:
166
+ self._proc.stdin.write(json.dumps(message) + "\n")
167
+ self._proc.stdin.flush()
168
+ except OSError:
169
+ self.close()
170
+ raise EngineError("solidcraft-cli mcp exited") from None
171
+
172
+ def _rpc(self, method: str, params: dict, timeout: float | None = None) -> dict:
173
+ self._next_id += 1
174
+ rid = self._next_id
175
+ self._send({"jsonrpc": "2.0", "id": rid, "method": method, "params": params})
176
+ limit = self.timeout if timeout is None else timeout
177
+ deadline = time.monotonic() + limit
178
+ while True:
179
+ remaining = deadline - time.monotonic()
180
+ try:
181
+ if remaining <= 0:
182
+ raise queue.Empty
183
+ line = self._lines.get(timeout=remaining)
184
+ except queue.Empty:
185
+ # The session is now out of step with the engine: never reuse it.
186
+ self.close()
187
+ raise EngineError(f"{method}: no answer within {limit:.0f} s") from None
188
+ if line is None:
189
+ self.close()
190
+ raise EngineError("solidcraft-cli mcp exited")
191
+ line = line.strip()
192
+ if not line:
193
+ continue
194
+ try:
195
+ message = json.loads(line)
196
+ except json.JSONDecodeError:
197
+ self.close()
198
+ raise EngineError(f"{method}: engine wrote non-JSON output: {line[:200]!r}") from None
199
+ if message.get("id") != rid:
200
+ continue
201
+ if "error" in message:
202
+ raise EngineError(f"{method}: {message['error']}")
203
+ return message["result"]
204
+
205
+ def call(self, tool: str, args: dict | None = None, timeout: float | None = None) -> Any:
206
+ # `F3D2SC_TRACE=1` prints one line per engine call with what it cost. Added for the
207
+ # question section 98 could not answer any other way — which call of a 554-feature design
208
+ # was the one taking minutes — and kept because that question recurs: the engine is the only
209
+ # part of a conversion whose cost is not ours to read off the code.
210
+ if _TRACE:
211
+ started = time.monotonic()
212
+ try:
213
+ return self._answer(tool, args, timeout)
214
+ finally:
215
+ print(f"[engine] {time.monotonic() - started:8.2f} s {tool}", file=sys.stderr, flush=True)
216
+ return self._answer(tool, args, timeout)
217
+
218
+ def _answer(self, tool: str, args: dict | None = None, timeout: float | None = None) -> Any:
219
+ result = self._rpc("tools/call", {"name": tool, "arguments": args or {}}, timeout)
220
+ text = "".join(c.get("text", "") for c in result.get("content", []) if c.get("type") == "text")
221
+ if result.get("isError"):
222
+ raise CommandRefused(tool, _without_advice(text))
223
+ return _answer(text)
224
+
225
+ def execute(self, command: str, params: dict | None = None) -> Any:
226
+ """Run a modelling command. Each success is one undo step."""
227
+ try:
228
+ out = self.call("execute", {"command": command, "params": params or {}})
229
+ except CommandRefused as exc:
230
+ raise CommandRefused(command, exc.message) from None
231
+ self.mutations += 1
232
+ return out
233
+
234
+ def batch(self, commands: list[dict]) -> list[Any]:
235
+ """Run several commands in one round trip; all or nothing."""
236
+ try:
237
+ out = self.call("batch", {"commands": commands, "rollback": True})
238
+ except CommandRefused as exc:
239
+ try:
240
+ failed = json.loads(exc.message)["failed"]
241
+ except (json.JSONDecodeError, KeyError, TypeError):
242
+ raise exc from None
243
+ raise CommandRefused(failed["command"], failed["error"]) from None
244
+ self.mutations += len(commands)
245
+ return out["results"]
246
+
247
+ def measure(self) -> dict:
248
+ return self.call("measure", {})
249
+
250
+ def body_names(self) -> list[str]:
251
+ """Which bodies the design has, without measuring them.
252
+
253
+ `measure` recomputes volume, area, faces, edges, vertices and centre of mass for every
254
+ body, and the engine only caches that until the geometry changes. Measured on the corpus's
255
+ heaviest file, one such recomputation costs 24 s while this answers in 2 ms, so a caller
256
+ that only needs to know *which* bodies are there asks this instead.
257
+ """
258
+ design = self.call("inspect_design", {"measure": False, "sketches": False})
259
+ return [str(b.get("name")) for b in design.get("bodies") or []]
260
+
261
+ def topology_of(self, body: str) -> dict:
262
+ """One body's faces, edges and vertices, bounded the same way a measurement is.
263
+
264
+ The same pathological geometry that will not be measured will not be inspected either:
265
+ measured on `Hypercube Evo+.f3z`, `body_topology` on
266
+ `NEMA17_Stepper_Motor+Readscrew_F01 (3)` does not answer in **610 s**, which killed a
267
+ conversion that had already walked 336 calls. A body in `unmeasurable` is refused outright
268
+ rather than asked again, and a body that goes over the limit joins that set through the
269
+ caller's retry (spec section 98).
270
+ """
271
+ try:
272
+ return self.call("body_topology", {"body": body}, timeout=BODY_TIMEOUT_SECONDS)
273
+ except BodyUnmeasurable:
274
+ raise
275
+ except EngineError as exc:
276
+ raise BodyUnmeasurable(body, f"the topology of {body!r} could not be read: {exc}") from None
277
+
278
+ def placement_count(self) -> int:
279
+ """How many body **placements** the design holds, read off the component graph.
280
+
281
+ `inspect_design` lists one body per definition and an all-bodies `measure` one per
282
+ placement, and the two differ wherever a component is placed more than once. This counts
283
+ the second from the first: every component's bodies, once per path that reaches it.
284
+
285
+ It is **free** and it is exact. Measured against the ground truth on the corpus's largest
286
+ package, `corpus-09.f3z`: the graph gives 494 in 0.00 s and the all-bodies measure
287
+ gives 494 in 1.74 s, against 462 definitions. On `Hypercube Evo+.f3z` it gives 177 against
288
+ 74 definitions (spec section 98).
289
+ """
290
+ return sum(self.placements_by_body().values())
291
+
292
+ def placements_by_body(self) -> Counter[str]:
293
+ """How many times each body is placed, by name, from one `component.list`.
294
+
295
+ The same walk as `placement_count`, kept per body so that a count which drops can say
296
+ **which** bodies lost placements. It is what lets the conversion check the design it saves
297
+ against the one it measured without measuring it again: a component placed N times whose
298
+ bodies are moved into a component placed once leaves the same names and N - 1 fewer
299
+ placements of each, and only the component graph shows that.
300
+ """
301
+ components = {c["id"]: c for c in self.execute("component.list", {})["components"]}
302
+ placed: dict[int, int] = {}
303
+
304
+ def walk(cid: int, times: int) -> None:
305
+ placed[cid] = placed.get(cid, 0) + times
306
+ for child in components[cid].get("children") or []:
307
+ walk(child["component"], times)
308
+
309
+ children = {ch["component"] for c in components.values() for ch in (c.get("children") or [])}
310
+ for root in (cid for cid in components if cid not in children):
311
+ walk(root, 1)
312
+ bodies: Counter[str] = Counter()
313
+ for cid, component in components.items():
314
+ for body in component.get("bodies") or []:
315
+ bodies[str(body)] += placed.get(cid, 0)
316
+ return bodies
317
+
318
+ def body_readings(self, names: list[str] | None = None) -> list[dict]:
319
+ """Every body's measurement, assembled one body at a time.
320
+
321
+ `measure` with no body asks the engine for all of them at once, and that call does not
322
+ scale. Measured on `Hypercube Evo+.f3z`, a real design of the user's whose original holds 74
323
+ imported B-rep bodies: it does **not answer in 1800 s**, while the same bodies measured one
324
+ at a time cost about 0.1 s each — nine seconds in all, a factor of over two hundred. On the
325
+ corpus's largest package, `corpus-09.f3z`, 462 bodies one at a time also beat the
326
+ single call (under a second against 1.7 s). So this is the cheaper path everywhere and the
327
+ only possible one on a big assembly (spec section 98).
328
+
329
+ What it does **not** do is expand placements: `measure` with no body lists one body per
330
+ placement — 494 on that package against the 462 definitions `inspect_design` lists — and a
331
+ per-body call answers only for the definition it names. Section 90's defect was not the
332
+ enumeration but the **mismatch**: a reference list of 462 against a design reading of 494
333
+ left 32 bodies unpaired and told a correct conversion it had 32 extra. Both sides of a
334
+ comparison therefore read through this, and the comparison is per definition.
335
+ """
336
+ if self.read_placements and names is None:
337
+ # The design places a body more than once somewhere, and only this call enumerates
338
+ # those placements. It is the strict reading, and `cli` has already proved in a
339
+ # throwaway session that this engine can answer it (spec section 98).
340
+ return list(self.call("measure", {}).get("bodies") or [])
341
+ wanted = self.body_names() if names is None else names
342
+ readings: list[dict] = []
343
+ for name in wanted:
344
+ if name in self.unmeasurable:
345
+ continue # already proved it does not answer; the report says so
346
+ try:
347
+ answered = self.call("measure", {"body": name}, timeout=BODY_TIMEOUT_SECONDS)
348
+ except EngineError as exc:
349
+ raise BodyUnmeasurable(name, f"the body {name!r} could not be measured: {exc}") from None
350
+ readings.extend(answered.get("bodies") or [])
351
+ return readings
352
+
353
+ def total_volume(self, readings: list[dict] | None = None) -> float:
354
+ """The volume `measure`'s own total carries, summed from the bodies instead.
355
+
356
+ An open body has no volume and contributes nothing, which is what the engine's total does
357
+ with it too.
358
+ """
359
+ rows = self.body_readings() if readings is None else readings
360
+ return sum(float(b["volume_mm3"]) for b in rows if b.get("volume_mm3") is not None)
361
+
362
+ def timeline_ids(self) -> list[int]:
363
+ """The ids of the features in the timeline, in order.
364
+
365
+ The witness `undo_depth` cannot be: **the engine's undo stack caps at 200 steps** (measured:
366
+ 259 boxes in one design leave `undo_depth` reading 200 for the last 59), so past that an
367
+ undo-depth target is reached without undoing anything. The timeline says what is actually
368
+ there.
369
+ """
370
+ design = self.call("inspect_design", {"measure": False, "sketches": False})
371
+ return [int(f["id"]) for f in design.get("timeline") or [] if f.get("id") is not None]
372
+
373
+ def undo(self) -> None:
374
+ self.call("undo", {})
375
+
376
+ def undo_depth(self) -> int:
377
+ """Steps on the engine's undo stack (not every command pushes one, e.g. sketch.finish)."""
378
+ return self.call("inspect_design", {"measure": False, "sketches": False})["undo"]
379
+
380
+ def close(self) -> None:
381
+ proc, self._proc = self._proc, None
382
+ if proc is None:
383
+ return
384
+ try:
385
+ if proc.stdin:
386
+ try:
387
+ proc.stdin.close()
388
+ except OSError:
389
+ pass
390
+ try:
391
+ proc.wait(timeout=10)
392
+ except subprocess.TimeoutExpired:
393
+ proc.kill()
394
+ proc.wait()
395
+ finally:
396
+ if proc.poll() is None:
397
+ proc.kill()
398
+ proc.wait()
399
+
400
+
401
+ def roll_back(engine: Engine, depth: int, timeline: list[int] | None = None) -> None:
402
+ """Undo until the engine's undo stack is back at ``depth`` (bounded, never loops forever).
403
+
404
+ The bound is the point: `while engine.undo_depth() > depth: engine.undo()` spins forever against
405
+ an engine whose depth stops moving, and it is the depth reading itself that is least trustworthy
406
+ after something went wrong. One counted pass, then an explicit error if the stack is still above
407
+ the target, so a design left dirty is reported instead of silently replayed on.
408
+
409
+ **The undo stack caps at 200 steps**, so on a long design the depth target is met without a
410
+ single undo and this used to return quietly having done nothing. Measured on
411
+ `Caja parametrica v2`, whose twelve sketches take the design past the cap: two of the oracle's
412
+ trial extrudes survived into the saved file, named `f3d2solidcraft trial`, and a feature reported
413
+ `failed` kept whatever it had already built. So callers pass the timeline they expect to be left
414
+ with, and anything that outlived the undo is deleted by id — which is sound precisely here,
415
+ because a trial and a failed feature are both the last thing in the design, with nothing built on
416
+ them.
417
+ """
418
+ for _ in range(max(engine.undo_depth() - depth, 0)):
419
+ engine.undo()
420
+ if engine.undo_depth() > depth:
421
+ raise EngineError(f"rollback left the undo stack above depth {depth}")
422
+ if timeline is None:
423
+ return
424
+ expected = set(timeline)
425
+ extra = [feature for feature in engine.timeline_ids() if feature not in expected]
426
+ if not extra:
427
+ return
428
+ try:
429
+ engine.execute("timeline.delete", {"features": extra})
430
+ except EngineError as exc:
431
+ raise EngineError(
432
+ f"the undo left {len(extra)} feature(s) behind and deleting them failed: {exc}"
433
+ ) from None
434
+ left = [feature for feature in engine.timeline_ids() if feature not in expected]
435
+ if left:
436
+ raise EngineError(f"{len(left)} feature(s) the undo could not reach are still in the design")
437
+
438
+
439
+ @contextmanager
440
+ def rolled_back(engine: Engine, depth: int) -> Iterator[None]:
441
+ """Run a trial inside this block and undo it afterwards, whether or not it worked.
442
+
443
+ While an exception is already on its way out the rollback is best effort. A timed-out RPC has
444
+ already closed the engine, so `undo_depth()` would raise "engine is not running" from the
445
+ cleanup and that would be the only message the user ever sees — in place of
446
+ "no answer within 120 s", which is what actually happened. The first exception wins; a cleanup
447
+ that cannot run on a dead engine has nothing left to say.
448
+ """
449
+ timeline = engine.timeline_ids()
450
+ try:
451
+ yield
452
+ except BaseException:
453
+ try:
454
+ roll_back(engine, depth, timeline)
455
+ except EngineError:
456
+ pass # the exception in flight already says what went wrong; this one would hide it
457
+ raise
458
+ roll_back(engine, depth, timeline)