diff --git a/CHANGELOG.md b/CHANGELOG.md index d746aab5..4044ded1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,16 @@ user-facing notes live in [`docs/updates/`](docs/updates/) (English and ## Unreleased +### Changed +- Editor: the model reaches the page sooner after the last cell. A settle makes one call into the kernel instead of + three (the cells are listed in the call that publishes the preview), the duplicate settle a boot used to run is gone, + and the settle debounce is 0.12 s. On the six-axis arm the time from the last cell to the preview event went from + about 0.83 s (plus a second, redundant round of 0.27 s) to about 0.36 s. +- Editor: parts are tessellated in the background while the next cell computes (`simplecadapi.scene.prewarm`; + `SCA_NO_PREVIEW_WARM=1` turns it off). `cached_mesh` runs without the interpreter lock for that; a failure is + recorded on the shape back under the lock. +- Preview edge polylines are keyed with one numpy pass instead of one `struct.pack` per point; the bytes are identical. + ## 2.2.7b1 — 2026-10-24 ### Added diff --git a/src/cpp/bindings/python/bind_io.cpp b/src/cpp/bindings/python/bind_io.cpp index 3ac1fb15..bc33f7f4 100644 --- a/src/cpp/bindings/python/bind_io.cpp +++ b/src/cpp/bindings/python/bind_io.cpp @@ -222,8 +222,21 @@ void bind_mesh(py::module_& m) { internal.def( "cached_mesh", [](const Shape& solid, double linear_tolerance, double angular_tolerance) { + // Meshing works on a topology copy (see meshed_copy) and touches no Python object, so it runs without the GIL: + // the editor tessellates parts on a background thread while the next cell computes. A failure is recorded on + // the shape here, with the GIL back. + std::shared_ptr mesh; + std::string error; + { + py::gil_scoped_release release; + mesh = io::cached_mesh_detached(solid, linear_tolerance, angular_tolerance, &error); + } + if (!mesh && !error.empty()) { + Shape handle = solid; + handle.set_runtime("mesh.error", Value(error)); + } // The mesh is shared with the cache and exposed read-only, so handing it out un-const is safe. - return std::const_pointer_cast(io::cached_mesh(solid, linear_tolerance, angular_tolerance)); + return std::const_pointer_cast(mesh); }, py::arg("solid"), py::kw_only(), py::arg("linear_tolerance") = io::kDefaultLinearDeflection, py::arg("angular_tolerance") = io::kDefaultAngularDeflection); diff --git a/src/cpp/include/scad/io/mesh.hpp b/src/cpp/include/scad/io/mesh.hpp index ed31df62..d083f541 100644 --- a/src/cpp/include/scad/io/mesh.hpp +++ b/src/cpp/include/scad/io/mesh.hpp @@ -143,6 +143,10 @@ TriMesh build_solid_trimesh(const Shape& solid, double linear_tolerance = kDefau std::shared_ptr cached_mesh(const Shape& solid, double linear_tolerance = kDefaultLinearDeflection, double angular_tolerance = kDefaultAngularDeflection); +// The same without touching the shape: a failure's diagnostic is stored in `*error` instead of on the shape, so +// the call is safe on a thread that holds no lock on the shape (the editor meshes parts in the background). +std::shared_ptr cached_mesh_detached(const Shape& solid, double linear_tolerance, + double angular_tolerance, std::string* error); // The diagnostic recorded by the last failed cached_mesh on this shape, or "". std::string mesh_error(const Shape& solid); // Drop every cached mesh (tests, memory pressure). diff --git a/src/cpp/src/io/mesh_cache.cpp b/src/cpp/src/io/mesh_cache.cpp index 67ec4733..3864c7b1 100644 --- a/src/cpp/src/io/mesh_cache.cpp +++ b/src/cpp/src/io/mesh_cache.cpp @@ -77,19 +77,29 @@ Cache& cache() { } // namespace -std::shared_ptr cached_mesh(const Shape& solid, double linear_tolerance, double angular_tolerance) { +std::shared_ptr cached_mesh_detached(const Shape& solid, double linear_tolerance, + double angular_tolerance, std::string* error) { if (auto hit = cache().find(solid.wrapped(), linear_tolerance, angular_tolerance)) return hit; try { auto built = std::make_shared(build_solid_trimesh(solid, linear_tolerance, angular_tolerance)); cache().insert(solid.wrapped(), linear_tolerance, angular_tolerance, built); return built; - } catch (const std::exception& error) { - Shape handle = solid; // handles share their entity: this records on the caller's shape - handle.set_runtime(kErrorKey, std::string(error.what())); + } catch (const std::exception& failure) { + if (error != nullptr) *error = failure.what(); return nullptr; } } +std::shared_ptr cached_mesh(const Shape& solid, double linear_tolerance, double angular_tolerance) { + std::string error; + auto mesh = cached_mesh_detached(solid, linear_tolerance, angular_tolerance, &error); + if (!mesh && !error.empty()) { + Shape handle = solid; // handles share their entity: this records on the caller's shape + handle.set_runtime(kErrorKey, error); + } + return mesh; +} + std::string mesh_error(const Shape& solid) { const Value value = solid.get_runtime(kErrorKey); return value.is_string() ? value.as_string() : std::string(); diff --git a/src/simplecadapi/editor/kernel.py b/src/simplecadapi/editor/kernel.py index 70ab77ab..eda0ded0 100644 --- a/src/simplecadapi/editor/kernel.py +++ b/src/simplecadapi/editor/kernel.py @@ -60,6 +60,79 @@ def _locked(method): return wrapper +_CELLS_CODE = ( + "import json as _json\n" + "import marimo._code_mode as _cm\n" + "def _text(_o):\n" + " if _o is None:\n" + " return None\n" + " # CellOutput.data is str | list[Error] | dict[str, Any] — render\n" + " # each shape as plain text instead of its repr.\n" + " _d = getattr(_o, 'data', None)\n" + " if isinstance(_d, str):\n" + " _v = _d\n" + " elif isinstance(_d, dict):\n" + " _v = _d.get('text/plain') or str(_d)\n" + " elif isinstance(_d, (list, tuple)):\n" + " _parts = []\n" + " for _item in _d:\n" + " _m = getattr(_item, 'message', None)\n" + " _parts.append(_m if isinstance(_m, str) else str(_item))\n" + " _v = '\\n'.join(_parts)\n" + " else:\n" + " _v = str(_d) if _d is not None else None\n" + " if isinstance(_v, str):\n" + " if _v.lstrip().startswith('['):\n" + " # marimo serialises mimebundle outputs as a JSON array of\n" + " # ':' strings — prefer the text/plain entry.\n" + " try:\n" + " import json as _json\n" + " _arr = _json.loads(_v)\n" + " except Exception:\n" + " _arr = None\n" + " if isinstance(_arr, list):\n" + " _plain = [str(_x)[len('text/plain:'):] for _x in _arr if isinstance(_x, str) and _x.startswith('text/plain:')]\n" + " _v = _plain[0] if _plain else '\\n'.join(str(_x) for _x in _arr)\n" + " if _v.startswith('text/plain:'):\n" + " _v = _v[len('text/plain:'):]\n" + " if _v.lstrip().startswith('<'):\n" + " import html as _html, re as _re\n" + " _v = _html.unescape(_re.sub(r'<[^>]+>', '', _v)).strip()\n" + " return _v\n" + " return str(_v) if _v is not None else None\n" + "def _failures(_c):\n" + " # An error is the cell's output: a list of marimo error objects.\n" + " _d = getattr(getattr(_c, 'output', None), 'data', None)\n" + " _own, _blocked = [], False\n" + " if isinstance(_d, (list, tuple)):\n" + " for _e in _d:\n" + " _kind = str(getattr(_e, 'exception_type', '') or '')\n" + " _msg = str(getattr(_e, 'msg', _e))\n" + " if _kind == 'Ancestor raised':\n" + " _blocked = True\n" + " else:\n" + " _own.append((_kind + ': ' if _kind else '') + _msg)\n" + " return _own, _blocked\n" + "_ctx = _cm.get_context()\n" + "_rows = []\n" + "for _c in _ctx.cells:\n" + " _st = getattr(_c, 'status', None)\n" + " _own, _blocked = _failures(_c)\n" + " _failed = bool(_own) or _blocked\n" + " _rows.append({\n" + " 'id': _c.id, 'name': _c.name, 'code': _c.code,\n" + " 'status': getattr(_st, 'value', None) if _st is not None else None,\n" + " 'errors': ([str(getattr(_e, 'msg', _e))[:300] for _e in (getattr(_c, 'errors', None) or [])][:4] + [_m[:400] for _m in _own])[:4],\n" + " 'blocked': _blocked,\n" + " 'output': None if _failed else ((_text(_c.output) or '')[:400] if getattr(_c, 'output', None) is not None else None),\n" + " 'console': [t for t in ((_text(_o) or '')[-4000:] for _o in (getattr(_c, 'console_outputs', None) or [])[-4:]) if t],\n" + " })\n" + "print(_json.dumps(_rows))\n" + +) +"""The snippet that lists the notebook's cells in the kernel (prints one JSON line).""" + + class MarimoKernel: def __init__( self, @@ -76,6 +149,8 @@ class MarimoKernel: self.setup_errors: list[str] = [] self._ran = threading.Event() # a run of cells completed (see wait_instantiated) self._own_calls = 0 + self._fresh_cells: tuple[float, list[dict]] | None = None + """The cells the last preview call listed, until anything else runs in the kernel (see :meth:`list_cells`).""" self.write_lock = threading.RLock() self._own_ended = 0.0 self.workspace = self.notebook.parent @@ -280,76 +355,14 @@ class MarimoKernel: cells (the setup cell) are hidden; every other cell, anonymous ones included, is one block of the notebook. Cells are addressed by id. """ + fresh, self._fresh_cells = self._fresh_cells, None + if fresh is not None and time.monotonic() - fresh[0] < 5.0: + return fresh[1] + return self._read_cells(self.execute(_CELLS_CODE)) + + def _read_cells(self, result: dict) -> list[dict]: + """The cells a :data:`_CELLS_CODE` run printed (the setup cell's errors are kept in ``setup_errors``).""" hidden = {"setup"} - result = self.execute( - "import json as _json\n" - "import marimo._code_mode as _cm\n" - "def _text(_o):\n" - " if _o is None:\n" - " return None\n" - " # CellOutput.data is str | list[Error] | dict[str, Any] — render\n" - " # each shape as plain text instead of its repr.\n" - " _d = getattr(_o, 'data', None)\n" - " if isinstance(_d, str):\n" - " _v = _d\n" - " elif isinstance(_d, dict):\n" - " _v = _d.get('text/plain') or str(_d)\n" - " elif isinstance(_d, (list, tuple)):\n" - " _parts = []\n" - " for _item in _d:\n" - " _m = getattr(_item, 'message', None)\n" - " _parts.append(_m if isinstance(_m, str) else str(_item))\n" - " _v = '\\n'.join(_parts)\n" - " else:\n" - " _v = str(_d) if _d is not None else None\n" - " if isinstance(_v, str):\n" - " if _v.lstrip().startswith('['):\n" - " # marimo serialises mimebundle outputs as a JSON array of\n" - " # ':' strings — prefer the text/plain entry.\n" - " try:\n" - " import json as _json\n" - " _arr = _json.loads(_v)\n" - " except Exception:\n" - " _arr = None\n" - " if isinstance(_arr, list):\n" - " _plain = [str(_x)[len('text/plain:'):] for _x in _arr if isinstance(_x, str) and _x.startswith('text/plain:')]\n" - " _v = _plain[0] if _plain else '\\n'.join(str(_x) for _x in _arr)\n" - " if _v.startswith('text/plain:'):\n" - " _v = _v[len('text/plain:'):]\n" - " if _v.lstrip().startswith('<'):\n" - " import html as _html, re as _re\n" - " _v = _html.unescape(_re.sub(r'<[^>]+>', '', _v)).strip()\n" - " return _v\n" - " return str(_v) if _v is not None else None\n" - "def _failures(_c):\n" - " # An error is the cell's output: a list of marimo error objects.\n" - " _d = getattr(getattr(_c, 'output', None), 'data', None)\n" - " _own, _blocked = [], False\n" - " if isinstance(_d, (list, tuple)):\n" - " for _e in _d:\n" - " _kind = str(getattr(_e, 'exception_type', '') or '')\n" - " _msg = str(getattr(_e, 'msg', _e))\n" - " if _kind == 'Ancestor raised':\n" - " _blocked = True\n" - " else:\n" - " _own.append((_kind + ': ' if _kind else '') + _msg)\n" - " return _own, _blocked\n" - "_ctx = _cm.get_context()\n" - "_rows = []\n" - "for _c in _ctx.cells:\n" - " _st = getattr(_c, 'status', None)\n" - " _own, _blocked = _failures(_c)\n" - " _failed = bool(_own) or _blocked\n" - " _rows.append({\n" - " 'id': _c.id, 'name': _c.name, 'code': _c.code,\n" - " 'status': getattr(_st, 'value', None) if _st is not None else None,\n" - " 'errors': ([str(getattr(_e, 'msg', _e))[:300] for _e in (getattr(_c, 'errors', None) or [])][:4] + [_m[:400] for _m in _own])[:4],\n" - " 'blocked': _blocked,\n" - " 'output': None if _failed else ((_text(_c.output) or '')[:400] if getattr(_c, 'output', None) is not None else None),\n" - " 'console': [t for t in ((_text(_o) or '')[-4000:] for _o in (getattr(_c, 'console_outputs', None) or [])[-4:]) if t],\n" - " })\n" - "print(_json.dumps(_rows))\n" - ) for line in (result.get("log") or "").splitlines(): line = line.strip() if line.startswith("["): @@ -567,20 +580,19 @@ class MarimoKernel: self.run_cells(stale) self.wait_idle() - def publish_preview(self, url: str, step: str = "") -> dict: - """Have the kernel preview its product and POST the bytes to *url*. - - Returns ``{"ok": True, ...}`` or ``{"ok": False, "error"}``; a notebook that - has not produced its product yet is an error value, not an exception. - """ - result = self.execute( + @staticmethod + def _preview_code(url: str, step: str) -> str: + return ( "from simplecadapi.runtime.live import publish_preview as _preview\n" "try:\n" f" _p = _preview({url!r}, step={step!r})\n" " print('SCA-PREVIEWED', _p['nodes'], _p['parts'], _p['bytes'])\n" "except Exception as _e:\n" - " print('SCA-PREVIEW-ERROR', type(_e).__name__ + ':', str(_e).splitlines()[0] if str(_e) else '')\n", + " print('SCA-PREVIEW-ERROR', type(_e).__name__ + ':', str(_e).splitlines()[0] if str(_e) else '')\n" ) + + @staticmethod + def _preview_result(result: dict) -> dict: for line in (result.get("log") or "").splitlines(): if line.startswith("SCA-PREVIEWED "): _, nodes, parts, size = line.split(" ") @@ -589,6 +601,19 @@ class MarimoKernel: return {"ok": False, "error": line[len("SCA-PREVIEW-ERROR "):]} return {"ok": False, "error": (result.get("log") or "preview failed").strip()[-300:]} + def publish_preview(self, url: str, step: str = "") -> dict: + """Have the kernel preview its product and POST the bytes to *url*. + + Returns ``{"ok": True, ...}`` or ``{"ok": False, "error"}``; a notebook that + has not produced its product yet is an error value, not an exception. + """ + # Every call into the kernel costs a fixed ~60 ms (marimo queues a scratch cell and waits for it), and a + # settle needs the cells as well: the snippet that lists them rides along, and :meth:`list_cells` hands out + # what it read (see ``_fresh_cells``). + result = self.execute(_CELLS_CODE + self._preview_code(url, step)) + self._fresh_cells = (time.monotonic(), self._read_cells(result)) + return self._preview_result(result) + def entity_info(self, entity_id: str) -> dict | None: """The properties of one entity of the scene last previewed (``None`` if unknown).""" result = self.execute( @@ -640,6 +665,7 @@ class MarimoKernel: that gave up after 10 s killed any cell that ran longer (a ``use`` of a child notebook, a big rebuild). """ + self._fresh_cells = None # anything that runs in the kernel may change the cells self._own_calls += 1 started = time.monotonic() try: diff --git a/src/simplecadapi/editor/server.py b/src/simplecadapi/editor/server.py index f5efdd97..1822c7b8 100644 --- a/src/simplecadapi/editor/server.py +++ b/src/simplecadapi/editor/server.py @@ -141,6 +141,7 @@ class WorkspaceState: self._selection_lock = threading.Lock() self._settle_timer: threading.Timer | None = None self._settle_lock = threading.Lock() + self._settle_dirty = True # a run ended (or the notebook just opened) since the last settle self._last_publish_error = "" self._generation = 0 self._switch_lock = threading.Lock() @@ -937,12 +938,18 @@ class WorkspaceState: with self._settle_lock: if self._settle_timer is not None: self._settle_timer.cancel() - self._settle_timer = threading.Timer(0.4, self._settle_in_thread) + self._settle_dirty = True + self._settle_timer = threading.Timer(0.12, self._settle_in_thread) self._settle_timer.daemon = True self._settle_timer.start() def _settle_in_thread(self) -> None: try: + with self._settle_lock: + if not self._settle_dirty: + # The settle that ran meanwhile (a boot's own, which the run it ended with also asked for) + # already published what these runs made. + return self.settle() except Exception as exc: # never let a timer thread die silently self.hub.broadcast({"type": "status", "error": str(exc)[-300:]}) @@ -953,13 +960,16 @@ class WorkspaceState: if kernel is None: return with self._settle_lock: - self.push_cells() + self._settle_dirty = False # The signature of what is published is taken before it is built. try: self._publish_signature = self._signature(self.notebook) if self.notebook else None except (OSError, ValueError): self._publish_signature = None + # One round trip into the kernel: it lists the cells in the same call that publishes the preview + # (the kernel keeps what it listed for the push below). result = kernel.publish_preview(self.preview_url, step=self.notebook.stem if self.notebook else "") + self.push_cells() if result.get("ok"): self._last_publish_error = "" self._stopped = False diff --git a/src/simplecadapi/runtime/executor.py b/src/simplecadapi/runtime/executor.py index 9ca41301..33875755 100644 --- a/src/simplecadapi/runtime/executor.py +++ b/src/simplecadapi/runtime/executor.py @@ -123,6 +123,7 @@ class SimpleCadExecutor: cache = self._cache_for(scope, cell) restored = _restore(cache, cell, glbls) if restored is not _MISS: + self._warm_preview(cell, glbls) return restored cache = cache if restored is _MISS else None _prefetch(scope, cell, glbls) @@ -134,6 +135,7 @@ class SimpleCadExecutor: _store(cache, cell, glbls, None, error) raise _store(cache, cell, glbls, result, None) + self._warm_preview(cell, glbls) return result async def execute_cell_async(self, cell: CellImpl, glbls: MutableGlobals) -> Any: @@ -143,6 +145,7 @@ class SimpleCadExecutor: cache = self._cache_for(scope, cell) restored = _restore(cache, cell, glbls) if restored is not _MISS: + self._warm_preview(cell, glbls) return restored _prefetch(scope, cell, glbls) try: @@ -153,8 +156,18 @@ class SimpleCadExecutor: _store(cache, cell, glbls, None, error) raise _store(cache, cell, glbls, result, None) + self._warm_preview(cell, glbls) return result + def _warm_preview(self, cell: CellImpl, glbls: MutableGlobals) -> None: + """The editor kernel tessellates what the cell made in the background (see :mod:`..scene.prewarm`).""" + + if self._scope is not None or os.environ.get("SCA_NO_PREVIEW_WARM"): + return + from ..scene import prewarm + + prewarm.submit(glbls[name] for name in cell.defs if name in glbls) + def _apply_saved( self, scope: NotebookScope, cell: CellImpl, glbls: MutableGlobals ) -> None: diff --git a/src/simplecadapi/scene/prewarm.py b/src/simplecadapi/scene/prewarm.py new file mode 100644 index 00000000..90bdeb52 --- /dev/null +++ b/src/simplecadapi/scene/prewarm.py @@ -0,0 +1,86 @@ +"""Tessellate the parts a cell made while the next cell computes (the editor kernel). + +The editor publishes a preview once the cells have settled, and the preview of a part (its mesh and edge polylines) +takes tens of milliseconds -- for an assembly of nineteen parts, about 0.4 s that the person waits for after the last +cell. :func:`preview_solid` keeps its result by the part's geometry, so doing the work earlier costs nothing and +changes nothing: the preview that follows finds every part in the cache. + +The meshing itself runs without the interpreter lock (``cached_mesh``), so it overlaps with the cells that follow. +One daemon thread does the work, in submission order; a failing part is left for the real preview to report. +""" + +from __future__ import annotations + +import queue +import threading +from typing import Any, Iterable, Iterator + +from simplecadapi._cpp import Assembly, Part, Solid + +from .preview import preview_solid + +_BACKLOG = 256 +_queue: "queue.Queue[Solid]" = queue.Queue(maxsize=_BACKLOG) +_worker: threading.Thread | None = None +_lock = threading.Lock() + + +def solids_of(values: Iterable[Any]) -> Iterator[Solid]: + """The solids a preview would draw for *values*: parts' bodies, assemblies' parts' bodies (each once).""" + + seen: set[int] = set() + + def visit(item: Any) -> Iterator[Solid]: + if id(item) in seen: + return + seen.add(id(item)) + if isinstance(item, Part): + body = item.body + if isinstance(body, Solid): + yield body + elif isinstance(item, Assembly): + for component in item.components: + yield from visit(component.item) + elif isinstance(item, Solid): + yield item + + for value in values: + yield from visit(value) + + +def submit(values: Iterable[Any]) -> int: + """Queue the solids of *values* for tessellation; returns how many were queued (never blocks, never raises).""" + + queued = 0 + try: + for solid in solids_of(values): + try: + _queue.put_nowait(solid) + except queue.Full: + break + queued += 1 + except Exception: # noqa: BLE001 - an optimisation: whatever a cell defined, it must not fail the cell + return queued + if queued: + _ensure_worker() + return queued + + +def _ensure_worker() -> None: + global _worker + with _lock: + if _worker is None or not _worker.is_alive(): + _worker = threading.Thread(target=_run, name="sca-preview-warm", daemon=True) + _worker.start() + + +def _run() -> None: + while True: + try: + solid = _queue.get(timeout=30.0) + except queue.Empty: + return # the thread ends when idle; the next submit starts another + try: + preview_solid(solid) + except Exception: # noqa: BLE001 - the preview that follows reports a part that cannot be drawn + pass diff --git a/src/simplecadapi/scene/render_mesh.py b/src/simplecadapi/scene/render_mesh.py index 3bec6101..9536bc53 100644 --- a/src/simplecadapi/scene/render_mesh.py +++ b/src/simplecadapi/scene/render_mesh.py @@ -353,7 +353,6 @@ def _edge_block( points = edge._polyline(float(linear_tolerance), float(angular_tolerance)) except Exception as exc: raise ValueError(f"edge {entity_id} discretization failed") from exc - positions = tuple(cad_to_gltf(point) for point in points) else: from simplecadapi._cpp.occt.BRepAdaptor import BRepAdaptor_Curve from simplecadapi._cpp.occt.GCPnts import GCPnts_TangentialDeflection @@ -374,15 +373,12 @@ def _edge_block( ) except Exception as exc: raise ValueError(f"edge {entity_id} discretization failed") from exc - positions = tuple( - cad_to_gltf(sampler.Value(index)) + points = [ + (float(sampler.Value(index).X()), float(sampler.Value(index).Y()), float(sampler.Value(index).Z())) for index in range(1, sampler.NbPoints() + 1) - ) - segments = [ - (_position_key(positions[index]), _position_key(positions[index + 1])) - for index in range(len(positions) - 1) - if _position_key(positions[index]) != _position_key(positions[index + 1]) - ] + ] + keys = _position_keys(points) + segments = [(keys[index], keys[index + 1]) for index in range(len(keys) - 1) if keys[index] != keys[index + 1]] position_keys = sorted(set(key for segment in segments for key in segment)) key_to_index = {key: index for index, key in enumerate(position_keys)} canonical_segments = tuple(sorted(set((min(key_to_index[a], key_to_index[b]), max(key_to_index[a], key_to_index[b])) for a, b in segments))) @@ -400,6 +396,29 @@ def _edge_block( ) +def _position_keys(points: Sequence[Sequence[float]]) -> list[bytes]: + """The position keys of CAD points (mm, +Z up), as ``_position_key(cad_to_gltf(point))`` for each, in one pass. + + The same arithmetic as the scalar path -- divide in binary64, round to binary32, the profile's zero-sign and + finiteness rules -- so the bytes are identical; numpy does it for the whole polyline at once. + """ + + if len(points) == 0: + return [] + cad = np.asarray(points, dtype=np.float64).reshape(-1, 3) + glt = np.stack([cad[:, 0] / 1000.0, cad[:, 2] / 1000.0, -cad[:, 1] / 1000.0], axis=1) + if not np.isfinite(glt).all(): + raise ValueError("f32 input must be a finite number") + with np.errstate(over="ignore"): + single = glt.astype(" bytes: return struct.pack(" bytes: def _decode_position(key: bytes) -> tuple[float, float, float]: - return tuple(struct.unpack(" tuple[tuple[float, float, float], tuple[float, float, float]]: diff --git a/test/test_editor_latency.py b/test/test_editor_latency.py new file mode 100644 index 00000000..e2928738 --- /dev/null +++ b/test/test_editor_latency.py @@ -0,0 +1,122 @@ +"""The editor's post-run latency: vectorised edge keys, preview prewarm, one kernel round trip per settle.""" + +from __future__ import annotations + +import threading +import time +import unittest +from pathlib import Path +import tempfile + +import numpy as np + +import simplecadapi as scad +from simplecadapi.editor.kernel import MarimoKernel +from simplecadapi.scene import prewarm, preview +from simplecadapi.scene.render_mesh import _position_key, _position_keys, cad_to_gltf + + +class PositionKeysTest(unittest.TestCase): + """``_position_keys`` is ``_position_key(cad_to_gltf(point))`` for each point: same bytes, one numpy pass.""" + + def test_matches_the_scalar_path_byte_for_byte(self) -> None: + rng = np.random.default_rng(7) + points = [tuple(row) for row in rng.uniform(-5000, 5000, size=(500, 3))] + points += [(0.0, -0.0, 1e-46), (-0.0, 0.0, -1e-46), (123456.789, -98765.4321, 3.3e5), (1e12, -1e12, 0.0), (1e-3, 1e-3, 1e-3)] + self.assertEqual(_position_keys(points), [_position_key(cad_to_gltf(point)) for point in points]) + + def test_an_empty_polyline_has_no_keys(self) -> None: + self.assertEqual(_position_keys([]), []) + + def test_the_profile_errors_are_unchanged(self) -> None: + with self.assertRaisesRegex(ValueError, "finite"): + _position_keys([(float("nan"), 0.0, 0.0)]) + with self.assertRaisesRegex(ValueError, "overflowed"): + _position_keys([(1e300, 0.0, 0.0)]) + + +class PrewarmTest(unittest.TestCase): + def setUp(self) -> None: + preview.clear_preview_cache() + + def test_solids_of_finds_parts_assemblies_and_solids_once(self) -> None: + box = scad.make_box_rsolid(10, 10, 10) + part = scad.make_part_rpart(part_id="p", body=box, name="p") + self.assertEqual([s.topo_id for s in prewarm.solids_of([part, part, box])], [box.topo_id, box.topo_id]) + self.assertEqual(list(prewarm.solids_of([1, "x", None, {"a": box}])), []) + + def test_a_submitted_solid_is_in_the_preview_cache_afterwards(self) -> None: + box = scad.make_box_rsolid(12, 8, 5) + key = preview.part_key(box, preview.DEFAULT_LINEAR_TOLERANCE, preview.DEFAULT_ANGULAR_TOLERANCE) + self.assertIsNone(preview._recall(key)) + self.assertEqual(prewarm.submit([box]), 1) + deadline = time.monotonic() + 10 + while preview._recall(key) is None and time.monotonic() < deadline: + time.sleep(0.01) + self.assertIsNotNone(preview._recall(key)) + + def test_nothing_a_cell_defined_can_make_submit_fail(self) -> None: + class Hostile: + def __iter__(self): + raise RuntimeError("boom") + + self.assertEqual(prewarm.submit(Hostile()), 0) + + def test_meshing_beside_other_work_gives_the_same_mesh(self) -> None: + """``cached_mesh`` runs without the interpreter lock: a mesh made on another thread is the one made here.""" + + solid = scad.make_cylinder_rsolid(6, 20) + made: list = [] + worker = threading.Thread(target=lambda: made.append(preview.preview_solid(solid))) + worker.start() + for _ in range(20): + scad.make_box_rsolid(5, 5, 5) # the main thread keeps computing meanwhile + worker.join(10) + self.assertEqual(len(made), 1) + again = preview.preview_solid(solid) + self.assertIs(made[0], again) # served from the cache, not meshed twice + + +class OneRoundTripTest(unittest.TestCase): + """A settle lists the cells in the call that publishes the preview; nothing else reuses that listing.""" + + def kernel(self) -> tuple[MarimoKernel, list[str]]: + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + path = Path(tmp.name) / "n.py" + path.write_text("x = 1\n") + calls: list[str] = [] + kernel = MarimoKernel(path, server_port=8123) + + def run(code: str, timeout) -> dict: # the HTTP call under MarimoKernel.execute, which is the real one + calls.append("preview" if "SCA-PREVIEWED" in code else "cells") + log = '[{"id": "a", "name": "_", "code": "x = 1", "status": "idle"}]\nSCA-PREVIEWED 1 1 10\n' + return {"log": log} + + kernel._execute = run # type: ignore[method-assign] + return kernel, calls + + def test_publishing_lists_the_cells_in_the_same_call(self) -> None: + kernel, calls = self.kernel() + result = kernel.publish_preview("http://x/preview", step="n") + self.assertEqual(result, {"ok": True, "nodes": 1, "parts": 1, "bytes": 10}) + self.assertEqual([c["id"] for c in kernel.list_cells()], ["a"]) + self.assertEqual(calls, ["preview"]) # one call into the kernel, not two + + def test_the_listing_is_used_once(self) -> None: + kernel, calls = self.kernel() + kernel.publish_preview("http://x/preview") + kernel.list_cells() + kernel.list_cells() + self.assertEqual(calls, ["preview", "cells"]) + + def test_a_listing_older_than_the_call_that_followed_is_not_reused(self) -> None: + kernel, calls = self.kernel() + kernel.publish_preview("http://x/preview") + kernel.execute("anything") # something ran in the kernel meanwhile + kernel.list_cells() + self.assertEqual(calls, ["preview", "cells", "cells"]) + + +if __name__ == "__main__": + unittest.main()