fix(editor): sca cell finds the editor through proxies and reports what it failed to reach

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 <noreply@anthropic.com>
This commit is contained in:
NiJingzhe
2026-10-15 20:02:04 +08:00
parent 750dad08e2
commit 9b3b1ab2cf
4 changed files with 266 additions and 19 deletions
+58 -11
View File
@@ -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