From 9b3b1ab2cfd5ff4e488be4bf92171bb7f246bcdc Mon Sep 17 00:00:00 2001 From: NiJingzhe <1448976235@qq.com> Date: Thu, 15 Oct 2026 20:02:04 +0800 Subject: [PATCH] fix(editor): sca cell finds the editor through proxies and reports what it failed to reach MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A container's http_proxy swallowed the health check of a 127.0.0.1 editor url and the miss was read as "no editor is running" — both the record's url (now always the loopback) and the check (now a proxy-bypassing opener) are fixed, and a record whose server does not answer is an error naming the record and url, not a silent fallthrough. Reading the file as a fallback says so on stderr. Cell feedback: put/insert/run carry console and the not-healthy dependents, the swept dependents run, and a failing cell names its upstream (the failing ancestors first) with marimo's own dependency semantics. Co-Authored-By: Claude Sonnet 5.5 --- src/simplecadapi/editor/cli.py | 69 +++++++++++--- src/simplecadapi/editor/server.py | 75 +++++++++++++-- src/simplecadapi/runtime/_marimo.py | 5 +- test/test_editor.py | 136 +++++++++++++++++++++++++++- 4 files changed, 266 insertions(+), 19 deletions(-) diff --git a/src/simplecadapi/editor/cli.py b/src/simplecadapi/editor/cli.py index 912babd7..8368c7d3 100644 --- a/src/simplecadapi/editor/cli.py +++ b/src/simplecadapi/editor/cli.py @@ -154,23 +154,51 @@ def _print_json(report: dict[str, Any]) -> None: print(json.dumps(report, indent=2, ensure_ascii=False)) -def _find_editor(start: Path) -> tuple[Path, str] | None: - """The running editor whose workspace holds *start*: ``(workspace, base url)``.""" - import json +def _opener() -> Any: + """An opener that bypasses the proxy environment for the local editor. + + The editor is on this machine (its url is 127.0.0.1); a container's + ``http_proxy`` does not know that and swallows the request, which once + read as "no editor is running" while one was. + """ import urllib.request + return urllib.request.build_opener(urllib.request.ProxyHandler({})) + + +def _find_editor(start: Path) -> tuple[Path, str] | None: + """The running editor whose workspace holds *start*: ``(workspace, base url)``. + + A record whose server does not answer is an error, not a stale record to + skip quietly: "an editor was running here" is exactly the belief that + must not be dropped in silence. + """ + import json + import urllib.error + here = start.expanduser().resolve() + unreachable: list[str] = [] + opener = _opener() for directory in (here, *here.parents): record = directory / ".sca-editor" / "server.json" if not record.is_file(): continue try: url = json.loads(record.read_text(encoding="utf-8"))["url"] - with urllib.request.urlopen(f"{url}/api/health", timeout=1.5): + except (OSError, ValueError, KeyError) as error: + unreachable.append(f"{record}: unreadable ({error})") + continue + try: + with opener.open(f"{url}/api/health", timeout=1.5): pass - except (OSError, ValueError, KeyError): - continue # a stale record: the editor is gone + except urllib.error.HTTPError: + pass # an editor that answers at all is running + except OSError as error: + unreachable.append(f"found {record} but {url} is unreachable: {error}") + continue return directory, str(url) + if unreachable: + raise ValueError("; ".join(unreachable)) return None @@ -184,7 +212,7 @@ def _call(url: str, path: str, body: dict | None = None) -> dict[str, Any]: url + path, data=data, headers={"Content-Type": "application/json"}, method="GET" if body is None else "POST" ) try: - with urllib.request.urlopen(request, timeout=300) as response: + with _opener().open(request, timeout=300) as response: return json.loads(response.read()) except urllib.error.HTTPError as error: try: @@ -196,7 +224,13 @@ def _call(url: str, path: str, body: dict | None = None) -> dict[str, Any]: def _session(args: argparse.Namespace, *, write: bool) -> tuple[str | None, Path | None, str]: """``(editor url or None, notebook path or None, relative notebook name)`` for a cell command.""" start = args.workspace or (args.notebook.parent if args.notebook else Path.cwd()) - found = _find_editor(start) + try: + found = _find_editor(start) + except ValueError as error: + if write: + raise + _warn(f"editor not reached: {error}") + found = None notebook = args.notebook.expanduser().resolve() if args.notebook else None if found is None: if write: @@ -206,6 +240,7 @@ def _session(args: argparse.Namespace, *, write: bool) -> tuple[str | None, Path ) if notebook is None: raise ValueError("no editor is running here; name the notebook with --notebook") + _warn(f"no editor is running on this workspace; reading the file: {notebook.name}") return None, notebook, notebook.name workspace, url = found open_path = _call(url, "/api/cells").get("notebook") @@ -221,9 +256,17 @@ def _session(args: argparse.Namespace, *, write: bool) -> tuple[str | None, Path f"the editor has {open_path} open, not {relative}: edit {relative} directly " "(the editor does not hold it), or open it in the editor first" ) + _warn(f"the editor has {open_path} open; reading {relative} from the file") return None, notebook, relative +def _warn(message: str) -> None: + """Say a fallback out loud: silence once read as "the editor agreed".""" + import sys + + print(f"warning: {message}", file=sys.stderr) + + def _cells_from_file(notebook: Path) -> list[dict[str, Any]]: from ..runtime._marimo import parse_notebook @@ -239,7 +282,7 @@ def _cells_from_file(notebook: Path) -> list[dict[str, Any]]: def _slim(report: dict[str, Any], *, code: bool) -> dict[str, Any]: if "cells" not in report: return report - keep = ("index", "key", "name", "title", "status", "errors", "output", "ref", "readonly") + keep = ("index", "key", "name", "title", "status", "errors", "output", "console", "upstream", "ref", "readonly") return { **report, "cells": [ @@ -290,8 +333,12 @@ def _write_op(args: argparse.Namespace, op: str, body: dict[str, Any]) -> tuple[ return _slim(report, code=False), 1 touched = set(report.get("touched", [])) report = _slim(report, code=False) - # What the change did: the touched cells with their state; the rest as a count. - report["cells"] = [c for c in report["cells"] if c.get("index") in touched] or report["cells"] + # What the change did: the touched cells with their state, plus any cell + # that is not healthy after the run — a rerun dependent failing is the + # feedback the edit was after, hiding it once read as "the edit was fine". + report["cells"] = [ + c for c in report["cells"] if c.get("index") in touched or c.get("errors") or c.get("blocked") + ] or report["cells"] return report, 0 diff --git a/src/simplecadapi/editor/server.py b/src/simplecadapi/editor/server.py index 02e4650c..1015b14d 100644 --- a/src/simplecadapi/editor/server.py +++ b/src/simplecadapi/editor/server.py @@ -37,6 +37,7 @@ from starlette.websockets import WebSocketDisconnect from ..runtime.cells import cell_keys from ..runtime.config import NotebookConfig, read_notebook_config +from ..runtime._marimo import compile_cell from ..runtime.params import ( ParamSpec, commit_field_value, @@ -601,7 +602,7 @@ class WorkspaceState: # -- the same cell edits, for an agent (``sca cell``) ------------------------- def _brief(self, number: int, cell: dict) -> dict: - return { + brief = { "index": number, "id": cell["id"], "key": cell.get("key"), @@ -615,13 +616,34 @@ class WorkspaceState: "ref": cell.get("ref"), "code": cell["code"], } + if cell.get("blocked"): + # The cell did not itself fail: an ancestor did (its report says which). + brief["blocked"] = True + return brief def cells_report(self, *, refresh: bool = True) -> dict: if refresh and self.kernel is not None: self.push_cells() + upstream = _upstream_of(self.cells) + place = {cell["id"]: (number, cell) for number, cell in enumerate(self.cells, start=1)} + briefs = [] + for number, cell in enumerate(self.cells, start=1): + brief = self._brief(number, cell) + if brief["errors"] or brief.get("blocked"): + # The cell the error names is often not the one at fault: say + # what it reads, the failing ancestors first. + brief["upstream"] = [ + { + "index": place[dep][0], + "name": place[dep][1].get("name"), + "failing": bool(place[dep][1].get("errors")), + } + for dep in sorted(upstream.get(cell["id"], ()), key=lambda cid: place[cid][0]) + ] + briefs.append(brief) return { "notebook": self.notebook.relative_to(self.workspace).as_posix() if self.notebook else None, - "cells": [self._brief(n, c) for n, c in enumerate(self.cells, start=1)], + "cells": briefs, } def _find_cell(self, ref: Any) -> dict: @@ -654,9 +676,16 @@ class WorkspaceState: if body.get("base") is not None and _module_code(str(body["base"])).strip() != _module_code(cell["code"]).strip(): return {"error": "conflict: the cell changed since you read it", "theirs": cell["code"]} if code.strip() != _module_code(cell["code"]).strip(): - (kernel.edit_cell if body.get("run", True) else kernel.save_cell)(cell["id"], code) + run = bool(body.get("run", True)) + (kernel.edit_cell if run else kernel.save_cell)(cell["id"], code) + if run: + # The edit runs the cell itself; the sweep adds the + # dependents it made stale — their state is the + # feedback the caller asked for. + kernel.wait_idle() + kernel.run_until_settled([]) elif body.get("run", True): - kernel.run_cells([cell["id"]]) + kernel.run_until_settled([cell["id"]]) touched = [cell["id"]] elif op == "insert": after = body.get("after") @@ -668,9 +697,11 @@ class WorkspaceState: anchor = self._find_cell(after)["id"] code = _module_code(str(body.get("code", ""))) or "# new cell" name = str(body["name"]) if body.get("name") else None - created = _created_id(kernel.create_cell_after(anchor, code, name, run=bool(body.get("run", True)))) + created = _created_id(kernel.create_cell_after(anchor, code, name, run=False)) if created is None: return {"error": "the kernel did not create the cell"} + if body.get("run", True): + kernel.run_until_settled([created]) touched = [created] elif op == "delete": cell = self._find_cell(body.get("cell")) @@ -1430,8 +1461,10 @@ class WorkspaceState: directory.mkdir(parents=True, exist_ok=True) import os + # The record is read on this machine, so the url is always the + # loopback: a 0.0.0.0 url is no address (and walks into proxies). (directory / "server.json").write_text( - json.dumps({"url": f"http://{host}:{self.port}", "pid": os.getpid(), "workspace": str(self.workspace)}), + json.dumps({"url": f"http://127.0.0.1:{self.port}", "pid": os.getpid(), "workspace": str(self.workspace)}), encoding="utf-8", ) except OSError: @@ -1486,6 +1519,36 @@ class WorkspaceState: self.hub.broadcast({"type": "status", "exported": str(target)}) +def _upstream_of(cells: list[dict]) -> dict[str, set[str]]: + """Per cell id: the ids of the cells it (transitively) reads. + + Compiled with marimo's own cell compiler, so a name is a dependency + exactly when marimo's dataflow says so; a cell mid-edit (its code does + not compile) contributes no edges rather than wrong ones. + """ + owner: dict[str, str] = {} + refs: dict[str, frozenset[str]] = {} + for cell in cells: + try: + impl = compile_cell(_module_code(cell["code"]), cell["id"]) + except Exception: + refs[cell["id"]] = frozenset() + continue + refs[cell["id"]] = impl.refs + for name in impl.defs: + owner.setdefault(name, cell["id"]) + direct = {cid: {owner[name] for name in names if name in owner and owner[name] != cid} for cid, names in refs.items()} + closure: dict[str, set[str]] = {} + + def walk(cid: str) -> set[str]: + if cid not in closure: + closure[cid] = set() # marimo forbids cycles; the placeholder guards one anyway + closure[cid] = set().union(*(walk(dep) | {dep} for dep in direct.get(cid, ()))) if direct.get(cid) else set() + return closure[cid] + + return {cid: walk(cid) for cid in refs} + + def _module_code(code: str) -> str: """marimo's code_mode compiles cell code as a MODULE: a ``return`` in the cell's own scope (normal in marimo's file format) is a SyntaxError there. diff --git a/src/simplecadapi/runtime/_marimo.py b/src/simplecadapi/runtime/_marimo.py index 2760aea5..9874a967 100644 --- a/src/simplecadapi/runtime/_marimo.py +++ b/src/simplecadapi/runtime/_marimo.py @@ -14,13 +14,14 @@ import marimo from marimo._ast.app import App, InternalApp from marimo._ast.cell import CellImpl from marimo._ast.cell_manager import CellManager -from marimo._ast.compiler import get_filename, solve_source_position +from marimo._ast.compiler import compile_cell, get_filename, solve_source_position from marimo._ast.parse import ( NonMarimoPythonScriptError, is_non_marimo_python_script, parse_notebook, ) from marimo._schemas.serialization import UnparsableCell +from marimo._loggers import suppress_warnings_logs from marimo._session.notebook.serializer import get_notebook_serializer from marimo._runtime.app.script_runner import AppScriptRunner from marimo._runtime.context.types import ( @@ -61,6 +62,7 @@ __all__ = [ "MutableGlobals", "RunResult", "Skip", + "compile_cell", "get_filename", "is_unhashable_stub", "load_notebook", @@ -70,6 +72,7 @@ __all__ = [ "runtime_context_installed", "safe_get_context", "solve_source_position", + "suppress_warnings_logs", ] def load_notebook(path: Path, *, cell_prefix: str) -> App | None: diff --git a/test/test_editor.py b/test/test_editor.py index f704cfae..24595c43 100644 --- a/test/test_editor.py +++ b/test/test_editor.py @@ -129,7 +129,7 @@ class FunctionCellTest(unittest.TestCase): def test_editing_one_is_refused_and_unchanged_code_is_not(self) -> None: state = WorkspaceState(Path(tempfile.gettempdir())) - state.kernel = type("K", (), {"run_cells": lambda self, ids: {}, "wait_idle": lambda self: True})() # type: ignore[assignment] + state.kernel = type("K", (), {"run_until_settled": lambda self, ids: None, "wait_idle": lambda self: True})() # type: ignore[assignment] state.cells = [{"id": "f1", "code": "def f():\n return 1"}] state.schedule_settle = lambda: None # type: ignore[method-assign] refused = state.dispatch_command({"type": "code.edit", "cell": "f1", "code": "def f():\n return 2"}) @@ -1101,3 +1101,137 @@ class PublishErrorReportingTest(unittest.TestCase): with TestClient(create_app(state)) as client, client.websocket_connect("/ws") as ws: self.assertEqual(ws.receive_json()["type"], "hello") self.assertEqual(ws.receive_json(), {"type": "status", "error": self.ERROR}) + + +class EndpointDiscoveryTest(unittest.TestCase): + """How `sca cell` finds the editor, and what it says when it cannot.""" + + def setUp(self) -> None: + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name).resolve() + + def test_server_json_pins_the_loopback_even_for_a_wildcard_host(self) -> None: + state = WorkspaceState(self.root) + state.port = 17611 + state.write_endpoint("0.0.0.0") + record = json.loads((self.root / ".sca-editor" / "server.json").read_text()) + # The record is read on this machine; a 0.0.0.0 url is no address and + # walks into a container's proxy. + self.assertEqual(record["url"], "http://127.0.0.1:17611") + + def test_a_stale_record_is_an_error_that_names_the_record_and_url(self) -> None: + from simplecadapi.editor.cli import _find_editor + + directory = self.root / ".sca-editor" + directory.mkdir() + (directory / "server.json").write_text(json.dumps({"url": "http://127.0.0.1:17612"})) + with self.assertRaisesRegex(ValueError, "server.json.*17612.*unreachable"): + _find_editor(self.root) + + def test_the_health_check_reaches_a_local_editor_through_a_proxy_environment(self) -> None: + import threading + + import uvicorn + + from simplecadapi.editor.cli import _find_editor + from simplecadapi.editor.server import create_app + + path = create_notebook(self.root, "bracket", "part") + state = WorkspaceState(self.root, path) + state.port = 17613 + server = uvicorn.Server(uvicorn.Config(create_app(state), port=state.port, log_level="error")) + threading.Thread(target=server.run, daemon=True).start() + try: + deadline = time.monotonic() + 10 + healthy = False + while time.monotonic() < deadline: + try: + with urllib.request.urlopen(f"http://127.0.0.1:{state.port}/api/health", timeout=1): + healthy = True + break + except OSError: + time.sleep(0.1) + self.assertTrue(healthy, "the test editor did not come up") + directory = self.root / ".sca-editor" + directory.mkdir(exist_ok=True) + (directory / "server.json").write_text(json.dumps({"url": f"http://127.0.0.1:{state.port}"})) + # The old code let urllib honor this proxy for a 127.0.0.1 url and + # read the resulting failure as "no editor is running". + environment = {"http_proxy": "http://127.0.0.1:1", "https_proxy": "http://127.0.0.1:1"} + saved = {name: os.environ.get(name) for name in environment} + os.environ.update(environment) + try: + found = _find_editor(self.root) + finally: + for name, value in saved.items(): + if value is None: + os.environ.pop(name, None) + else: + os.environ[name] = value + self.assertIsNotNone(found) + self.assertEqual(found[1], f"http://127.0.0.1:{state.port}") + finally: + server.should_exit = True + + def test_reading_the_file_without_an_editor_says_so_on_stderr(self) -> None: + import argparse + import contextlib + import io + + from simplecadapi.editor import cli + + path = create_notebook(self.root, "bracket", "part") + args = argparse.Namespace(notebook=path, workspace=None, cell="1") + err = io.StringIO() + with contextlib.redirect_stderr(err): + report, code = cli._cell_ls(args) + self.assertEqual(code, 0) + self.assertEqual(report["source"], "file") + self.assertIn("reading the file", err.getvalue()) + + # A record that does not answer is the misleading one: the warning + # must say the editor was found but not reached. + directory = self.root / ".sca-editor" + directory.mkdir() + (directory / "server.json").write_text(json.dumps({"url": "http://127.0.0.1:17614"})) + err = io.StringIO() + with contextlib.redirect_stderr(err): + report, code = cli._cell_ls(args) + self.assertEqual(code, 0) + self.assertEqual(report["source"], "file") + self.assertIn("editor not reached", err.getvalue()) + self.assertIn("17614", err.getvalue()) + + def test_slim_keeps_the_console_and_the_upstream(self) -> None: + from simplecadapi.editor.cli import _slim + + report = { + "cells": [ + {"index": 1, "status": "idle"}, + {"index": 2, "status": "idle", "console": ["printed"], "upstream": [{"index": 1, "failing": False}]}, + ] + } + slim = _slim(report, code=False) + self.assertNotIn("console", slim["cells"][0]) + self.assertEqual(slim["cells"][1]["console"], ["printed"]) + self.assertEqual(slim["cells"][1]["upstream"], [{"index": 1, "failing": False}]) + + def test_a_failing_cell_names_its_upstream_and_the_failing_ancestor(self) -> None: + state = WorkspaceState(self.root) + state.notebook = self.root / "bracket.py" + state.cells = [ + {"id": "c1", "code": "width = 20"}, + {"id": "c2", "code": "block = scad.make_box_rsolid(width, 10, 5)"}, + {"id": "c3", "code": 'part = scad.Part(part_id="p", body=block)', "errors": ["boom"]}, + {"id": "c4", "code": "print(part)", "blocked": True}, + ] + report = state.cells_report(refresh=False) + by_index = {cell["index"]: cell for cell in report["cells"]} + self.assertNotIn("upstream", by_index[1]) + self.assertEqual(by_index[4].get("blocked"), True) + upstream = by_index[4]["upstream"] + self.assertEqual([row["index"] for row in upstream], [1, 2, 3]) + self.assertEqual([row["failing"] for row in upstream], [False, False, True]) + self.assertEqual([row["index"] for row in by_index[3]["upstream"]], [1, 2]) + self.assertEqual([row["failing"] for row in by_index[3]["upstream"]], [False, False])