fix: second-round review findings (failure pictures, use() owners, refused posts, front end)

- A face or edge query that matches nothing draws the plain solid again (it returned no picture).
- use() memo: a key kept again under another graph id, and eviction, no longer leave a stale owner.
- A refused preview post names what the server said; a picture that cannot be drawn is said on stderr.
- Editor: a client that left while a frame was sent is not registered again; the damaged-model message is accurate.
- Front end: a kept part is a copy, not a view that pins the frame it came in; a dropped frame is warned.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
NiJingzhe
2026-10-29 03:50:36 +08:00
parent d54d0d0baa
commit d941cda14b
10 changed files with 114 additions and 13 deletions
+3
View File
@@ -26,6 +26,9 @@ user-facing notes live in [`docs/updates/`](docs/updates/) (English and
(`use("child.py", id="member")`) with such a record used to fail with `value contains graph node '...' not owned by
active graph 'member'`. A restored cell no longer overwrites its record, and a record is only written under the id
its cache belongs to.
- A face or edge query that matches nothing draws the plain solid in its failure picture again (2.2.6 did; the native port returned no picture).
- A fillet or chamfer that fails, and a ql `exactly()` that fails, attach their picture again (the failing edge as an orange line; the matched faces orange, near misses purple). `test_ql_evidence_highlight_is_visible` stays listed as open: the soft renderer's shading leaves 302 sampled orange pixels where the test asks for more than 400.
- A refused preview post names what the editor server said (`HTTP 400: damaged preview: ...`) instead of only the status line.
### Changed
- A handled failure that used to leave no trace now prints a `[sca] ...` line on stderr: the preview warm-up, an
+8 -4
View File
@@ -10,15 +10,19 @@ export type Envelope = Record<string, unknown> & { type: string };
/** A binary frame is a `preview` envelope and the preview itself: `<u32 big-endian N><N bytes JSON><preview bytes>`
* (`simplecadapi.editor.ws.preview_frame`). The envelope handed to handlers carries the preview as `bytes`. */
function decodeFrame(buffer: ArrayBuffer): Envelope | null {
if (buffer.byteLength < 4) return null;
const damaged = (why: string): null => {
console.warn(`[sca edit] a binary frame was dropped: ${why}`);
return null;
};
if (buffer.byteLength < 4) return damaged("shorter than its length prefix");
const length = new DataView(buffer).getUint32(0, false);
if (buffer.byteLength < 4 + length) return null;
if (buffer.byteLength < 4 + length) return damaged("shorter than its envelope");
try {
const envelope = JSON.parse(new TextDecoder().decode(new Uint8Array(buffer, 4, length))) as Envelope;
envelope["bytes"] = buffer.slice(4 + length);
return envelope;
} catch {
return null;
} catch (error) {
return damaged(`its envelope is not JSON (${error})`);
}
}
type Handler = (envelope: Envelope) => void;
+2 -2
View File
@@ -76,8 +76,8 @@ export function parsePreview(buffer: ArrayBuffer, cache: ReadonlyMap<string, Pre
const header = JSON.parse(new TextDecoder().decode(bytes.subarray(headerStart, headerStart + headerLength))) as Header;
if (header.schema !== "sca-preview-1") throw new Error(`unsupported preview schema: ${header.schema}`);
const base = headerStart + headerLength;
const floats = (ref: ArrayRef) => new Float32Array(buffer, base + ref.offset, ref.count);
const uints = (ref: ArrayRef) => new Uint32Array(buffer, base + ref.offset, ref.count);
const floats = (ref: ArrayRef) => new Float32Array(buffer, base + ref.offset, ref.count).slice(); // a copy: a kept part must not pin the whole frame it came in
const uints = (ref: ArrayRef) => new Uint32Array(buffer, base + ref.offset, ref.count).slice();
const carried = new Map<string, PreviewPart>();
for (const part of header.parts) {
carried.set(part.key, {
+4 -1
View File
@@ -21,6 +21,8 @@ from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Mapping, Optional, Sequence, Set, Tuple
from .._glue.notice import say
# One picture per distinct failure signature (the tests clear it).
_RENDER_DEDUP: Set[Any] = set()
@@ -82,6 +84,7 @@ def provide(kind: str, operation: str, view: str, caption: str, dedup_key: str,
if kind == "render":
return _evidence("render-unavailable", Path(), view,
f"diagnostic render unavailable: {type(error).__name__}: {error}")
say(f"the {kind} picture of {operation} could not be drawn ({type(error).__name__}: {error})")
return None
@@ -183,7 +186,7 @@ def _ql_evidence(scope: Any, matched: Sequence[Any], target_kind: str, dedup_key
edges = list(matched[:8])
if scope.__class__.__name__ == "Solid":
shapes = [scope]
if not edges:
if not shapes and not edges:
return []
path = _draw_solids(operation, shapes, tags=tags, tag_labels=tag_labels, edges=edges, callouts=bool(tags))
except Exception as error: # noqa: BLE001 - a picture must never mask the error it illustrates
+3 -1
View File
@@ -356,7 +356,7 @@ class WorkspaceState:
def remember_model(self, notebook: Path, signature: str, data: bytes) -> None:
"""Keep *data* (a preview) as the model of *notebook* for *signature*, in memory and on disk."""
if not self._is_whole(data):
print("[sca edit] not keeping a model that leaves out parts", file=sys.stderr)
print("[sca edit] not keeping a model that is damaged or leaves out parts", file=sys.stderr)
return
key = notebook.relative_to(self.workspace).as_posix()
self._packages[key] = (signature, data)
@@ -1092,6 +1092,8 @@ class WorkspaceState:
if signing is not None:
signing.done.wait()
signature = signing.value
if signing is None and os.environ.get("SCA_EDITOR_TRACE"):
print("[sca edit] a preview that no settle asked for: not filed", file=sys.stderr, flush=True)
if self.notebook is not None and signature is not None and model:
self.remember_model(self.notebook, signature, model)
self.write_snapshot()
+2 -1
View File
@@ -61,7 +61,8 @@ class WsHub:
except Exception: # the page went away
await self._drop(client)
else:
self._clients[client] = set(keys)
if client in self._clients: # (it may have gone while the frame was being sent)
self._clients[client] = set(keys)
def broadcast(self, message: dict[str, Any]) -> None:
"""Push one JSON message to every connected client (thread-safe)."""
+12 -1
View File
@@ -12,6 +12,7 @@ in the kernel once the cells have settled.
from __future__ import annotations
import json
import time
import urllib.error
import urllib.request
@@ -147,6 +148,16 @@ def _post(url: str, data: bytes, step: str, delta: bool, timeout: float) -> None
response.read()
def _server_words(error: urllib.error.HTTPError) -> str:
"""What the editor server said about a refused post (its JSON ``error``), else the HTTP status line."""
try:
said = json.loads(error.read()).get("error")
except (OSError, ValueError, AttributeError):
said = None
return f"HTTP {error.code}: {said}" if said else str(error)
def publish_preview(url: str, *, step: str = "", timeout: float = 60.0) -> dict[str, Any]:
""":func:`live_preview`, then POST it to *url*; returns a short summary.
@@ -167,7 +178,7 @@ def publish_preview(url: str, *, step: str = "", timeout: float = 60.0) -> dict[
_post(url, data, step, bool(omit), timeout)
except urllib.error.HTTPError as error:
if error.code != 409:
raise
raise RuntimeError(f"publishing the preview to {url} failed: {_server_words(error)}") from error
data = encode_preview(scene) # the server lacks parts: send it all
_post(url, data, step, False, timeout)
except (urllib.error.URLError, OSError) as error:
+10 -3
View File
@@ -83,14 +83,21 @@ def keep(target: Path, id: str | None, overrides: Mapping[str, Any], kept: Kept)
previous = _owners.pop(kept.graph_id, None)
if previous is not None:
_entries.pop(previous, None)
_forget(key) # (this key may have been kept under another graph id: the header id was edited)
if signature is None:
_entries.pop(key, None)
return
_entries[key] = (signature, kept)
_entries.move_to_end(key)
_owners[kept.graph_id] = key
while len(_entries) > _MAX_ENTRIES:
_owners.pop(_entries.popitem(last=False)[1][1].graph_id, None)
_forget(next(iter(_entries)))
def _forget(key: tuple[str, str | None]) -> None:
"""Drop the entry of *key* and, if it is the owner of its graph id, that ownership (the lock is held)."""
entry = _entries.pop(key, None)
if entry is not None and _owners.get(entry[1].graph_id) == key:
del _owners[entry[1].graph_id]
def clear() -> None:
+50
View File
@@ -0,0 +1,50 @@
"""The failure pictures, and what a refused preview post tells the person."""
from __future__ import annotations
import io
import urllib.error
from pathlib import Path
import pytest
import simplecadapi as scad
@pytest.fixture(autouse=True)
def drawing(tmp_path, monkeypatch):
from simplecadapi._cpp import evidence
monkeypatch.delenv("SCA_NO_DIAGNOSTIC_RENDER", raising=False)
monkeypatch.chdir(tmp_path)
evidence._RENDER_DEDUP.clear()
def test_a_query_that_matches_nothing_still_draws_the_solid() -> None:
"""2.2.6 drew the plain solid when a face query matched nothing (the common ``exactly(1)`` found 0)."""
box = scad.make_box_rsolid(10, 10, 10)
with pytest.raises(scad.SimpleCADError) as raised:
scad.ql.faces().where(scad.ql.surface_type("TORUS")).exactly(1).resolve(box)
evidence = raised.value.to_dict()["evidence"]
assert len(evidence) == 1 and evidence[0]["kind"] == "render"
assert Path(evidence[0]["path"]).stat().st_size > 10_000
def test_a_picture_that_cannot_be_drawn_is_said_on_stderr(capsys, monkeypatch) -> None:
from simplecadapi._cpp import evidence
def broken(*args, **kwargs):
raise RuntimeError("no plot")
monkeypatch.setattr(evidence, "_wire_plan", broken)
assert evidence.provide("wire_plan_render", "loft", "plan", "caption", "key", [], {}) is None
assert "could not be drawn (RuntimeError: no plot)" in capsys.readouterr().err
def test_a_refused_preview_post_reports_what_the_server_said() -> None:
from simplecadapi.runtime.live import _server_words
refused = urllib.error.HTTPError("http://x", 400, "Bad Request", {}, io.BytesIO(b'{"ok": false, "error": "damaged preview: KeyError: key"}'))
assert _server_words(refused) == "HTTP 400: damaged preview: KeyError: key"
bare = urllib.error.HTTPError("http://x", 500, "Server Error", {}, io.BytesIO(b"<html>"))
assert "500" in _server_words(bare)
+20
View File
@@ -92,6 +92,26 @@ class UseMemoTest(unittest.TestCase):
self.assertIsNot(again, first) # the first run's nodes are gone from the registry: it has to run again
self.assertEqual([run[0] for run in self.runs], ["child.py", "other.py", "child.py"])
def test_a_key_kept_again_under_another_graph_id_does_not_leave_its_old_owner(self) -> None:
runner.use(self.child, id="one")
owners = dict(usememo._owners)
self.assertEqual(len(owners), 1)
# the same key, now under another graph id (the child's header id was edited)
key = next(iter(usememo._entries))
kept = usememo._entries[key][1]
usememo.keep(self.child, "one", {}, usememo.Kept(kept.product, kept.path, kept.dependencies, "other-graph"))
self.assertEqual(set(usememo._owners), {"other-graph"})
self.assertEqual(usememo._owners["other-graph"], key)
def test_eviction_forgets_the_owner_of_the_evicted_entry_only(self) -> None:
original = usememo._MAX_ENTRIES
usememo._MAX_ENTRIES = 2
self.addCleanup(setattr, usememo, "_MAX_ENTRIES", original)
for name in ("a", "b", "c"):
runner.use(self.child, id=name)
self.assertEqual(len(usememo._entries), 2)
self.assertEqual(set(usememo._owners.values()), set(usememo._entries))
if __name__ == "__main__":
unittest.main()