diff --git a/codewiki/src/be/utils.py b/codewiki/src/be/utils.py index 819fb3ef..09453a5d 100644 --- a/codewiki/src/be/utils.py +++ b/codewiki/src/be/utils.py @@ -1,24 +1,27 @@ import asyncio +import importlib.util +import logging import os import re +import shutil +import subprocess import sys import threading from pathlib import Path from typing import List, Tuple -import logging + import tiktoken logger = logging.getLogger(__name__) -# PythonMonkey (used by mermaid_parser.parse_mermaid_py) binds its JS engine -# to the thread that first imported it — typically the main thread at module -# load time. The caw backend dispatches MCP tool calls on a FastMCP -# daemon-thread event loop, where parse_mermaid_py raises -# "cannot find a running Python event-loop". Recording the main loop here -# lets validate_single_diagram marshal the call back via -# asyncio.run_coroutine_threadsafe so PythonMonkey finds its home loop. +# PythonMonkey (used by mermaid_parser.parse_mermaid_py) is only safe on the +# process main thread. Importing it on another thread segfaults, and using it +# from a non-main thread's loop crashes Python at exit (seen on every version, +# Linux and macOS). The caw backend runs MCP tool calls on a FastMCP daemon +# thread, so it records the main loop here and _try_pythonmonkey_parse hands +# the parse (import included) back to it via asyncio.run_coroutine_threadsafe. _main_loop: "asyncio.AbstractEventLoop | None" = None _main_loop_thread_ident: int | None = None @@ -152,21 +155,34 @@ def extract_mermaid_blocks(content: str) -> List[Tuple[int, str]]: return mermaid_blocks -# PythonMonkey 1.3.1 only supports Python 3.8–3.11. On 3.12+ it still imports, -# but its SpiderMonkey cleanup runs on the wrong thread during _Py_Finalize and -# segfaults at interpreter shutdown (macOS crash dialog after a successful run). -# Skip it proactively so SpiderMonkey is never loaded into the process. -_PYTHONMONKEY_BROKEN = sys.version_info >= (3, 12) +# Set once PythonMonkey fails to import or loses its event loop; validation +# then falls back to system Node.js running the same parser bundle. +_PYTHONMONKEY_BROKEN = False +_NODE_TIMEOUT_SECONDS = 15.0 + +# Disabled: remote fallback through mermaid-py, which sends diagram content to +# https://mermaid.ink (or MERMAID_INK_SERVER). Kept commented out so it can be +# brought back: uncomment this, _parse_via_mermaid_py, the block at the end of +# validate_single_diagram's fallbacks, and mermaid-py in pyproject/requirements. +# _MERMAID_PY_BROKEN = os.environ.get("MERMAID_VALIDATE", "0").strip() != "1" + +# Validation never touches the network: PythonMonkey, then Node, then skip. +_pm_unavailable_warned = False +_skip_warned = False -# mermaid-py validates diagrams by sending them to a remote rendering service -# (https://mermaid.ink by default, overridable via the MERMAID_INK_SERVER env -# var understood by mermaid-py itself) rather than spawning a local Node.js -# subprocess. Note that this sends diagram content to that third-party service. -# It can still hang or fail when the service is unreachable (no network egress, -# DNS/firewall issues, or an outage). Enabled by default; set MERMAID_VALIDATE=0 -# to disable. -_MERMAID_PY_BROKEN = os.environ.get("MERMAID_VALIDATE", "1") == "0" -_MERMAID_PY_PROBED = True # Skip probing — rely on env var + +def _warn_pythonmonkey_unavailable_once() -> None: + global _pm_unavailable_warned + if not _pm_unavailable_warned: + _pm_unavailable_warned = True + logger.warning("PythonMonkey Mermaid validation is unavailable; trying system Node.js.") + + +def _warn_validation_skipped_once(reason: str) -> None: + global _skip_warned + if not _skip_warned: + _skip_warned = True + logger.warning("Mermaid validation skipped: %s", reason) # PythonMonkey prints JS noise to stderr, so validation points sys.stderr at @@ -201,38 +217,47 @@ async def _try_pythonmonkey_parse(diagram_content: str) -> str | None: """Attempt to parse via PythonMonkey/mermaid-parser-py. Returns the extracted parse-error message, "" on success, or None when - PythonMonkey itself is unusable (broken JS event loop binding on - Python 3.13+) so the caller can fall back to mermaid-py. + PythonMonkey itself is unusable (failed import or lost event loop) so the + caller can fall back to system Node.js. """ global _PYTHONMONKEY_BROKEN if _PYTHONMONKEY_BROKEN: + _warn_pythonmonkey_unavailable_once() return None - try: - from mermaid_parser.parser import parse_mermaid_py - except Exception: - _PYTHONMONKEY_BROKEN = True + on_main_thread = threading.current_thread() is threading.main_thread() + via_main_loop = ( + not on_main_thread + and _main_loop is not None + and _main_loop.is_running() + and _main_loop_thread_ident == threading.main_thread().ident + ) + if not (on_main_thread or via_main_loop): + # e.g. the web app's worker thread: no main-thread loop to hand off to. + _warn_pythonmonkey_unavailable_once() return None _quiet_stderr_enter() try: - if ( - _main_loop is not None - and _main_loop.is_running() - and threading.get_ident() != _main_loop_thread_ident - ): - fut = asyncio.run_coroutine_threadsafe(parse_mermaid_py(diagram_content), _main_loop) + if via_main_loop: + fut = asyncio.run_coroutine_threadsafe( + _parse_with_pythonmonkey(diagram_content), _main_loop + ) await asyncio.wrap_future(fut) else: - await parse_mermaid_py(diagram_content) + await _parse_with_pythonmonkey(diagram_content) return "" + except ImportError: + _PYTHONMONKEY_BROKEN = True + _warn_pythonmonkey_unavailable_once() + return None except Exception as e: error_str = str(e) - # PythonMonkey 1.3.1 only supports Python 3.8-3.11; on newer Pythons - # every JS call raises this. Latch the failure once so subsequent - # diagrams skip the broken path and go straight to mermaid-py. + # Raised when called off PythonMonkey's home loop. Latch the failure + # once so later diagrams skip straight to Node. if "cannot find a running Python event-loop" in error_str: _PYTHONMONKEY_BROKEN = True + _warn_pythonmonkey_unavailable_once() return None match = re.search(r"Error:(.*?)(?=Stack Trace:|$)", error_str, re.DOTALL) if match: @@ -243,27 +268,87 @@ async def _try_pythonmonkey_parse(diagram_content: str) -> str | None: _quiet_stderr_exit() -def _parse_via_mermaid_py(diagram_content: str) -> str: - """Validate via mermaid-py. Returns parse-error text, or "" if valid. +async def _parse_with_pythonmonkey(diagram_content: str) -> None: + """Parse on the main thread; importing here keeps the import there too.""" + try: + from mermaid_parser.parser import parse_mermaid_py + except Exception as e: + raise ImportError("PythonMonkey is unavailable") from e + await parse_mermaid_py(diagram_content) - mermaid-py raises MermaidError on parse failure and returns an SVG body - on success — we must drive the result off the exception, not the body - text, otherwise a successful SVG gets reported as a parse error. - """ - import mermaid as md +def _resolve_node_executable() -> str | None: + override = os.environ.get("CODEWIKI_NODE_PATH", "").strip() + if override: + return override if Path(override).is_file() else None + return shutil.which("node") + + +# Reads the diagram on stdin, exits 0 if it parses, else 1 with the error on stderr. +_NODE_PARSE_SCRIPT = ( + 'const parse = require(process.argv[1]); let s = "";' + 'process.stdin.on("data", (d) => (s += d)).on("end", () => parse(s).then(' + "() => process.exit(0)," + "(e) => { process.stderr.write(String((e && e.message) || e)); process.exit(1); }));" +) + + +def _parse_via_node(diagram_content: str) -> str | None: + """Validate with system Node.js running mermaid-parser-py's own bundle. + + Returns the parse-error message, "" on success, or None (after one + warning) when Node or the bundle is missing or the run fails. + """ + node = _resolve_node_executable() + if node is None: + _warn_validation_skipped_once( + "Node.js not found on PATH (set CODEWIKI_NODE_PATH to point at it)." + ) + return None + # find_spec does not run mermaid_parser/__init__, which imports PythonMonkey. + spec = importlib.util.find_spec("mermaid_parser") + bundle = Path(spec.origin).parent / "js" / "parser.bundle.js" if spec and spec.origin else None + if bundle is None or not bundle.is_file(): + _warn_validation_skipped_once("mermaid-parser-py's parser.bundle.js was not found.") + return None try: - md.Mermaid(diagram_content) + result = subprocess.run( + [node, "-e", _NODE_PARSE_SCRIPT, str(bundle)], + input=diagram_content, + capture_output=True, + text=True, + encoding="utf-8", + timeout=_NODE_TIMEOUT_SECONDS, + ) + except (OSError, subprocess.TimeoutExpired) as e: + _warn_validation_skipped_once(f"Node.js validator failed to run ({e}).") + return None + if result.returncode == 0: return "" - except Exception as e: - return str(e) + return result.stderr.strip() or "Mermaid parse failed (no message from Node.js)" + + +# def _parse_via_mermaid_py(diagram_content: str) -> str: +# """Validate via mermaid-py. Returns parse-error text, or "" if valid. +# +# mermaid-py raises MermaidError on parse failure and returns an SVG body +# on success — we must drive the result off the exception, not the body +# text, otherwise a successful SVG gets reported as a parse error. +# """ +# import mermaid as md +# +# try: +# md.Mermaid(diagram_content) +# return "" +# except Exception as e: +# return str(e) def _run_in_daemon_thread(fn, *args) -> "asyncio.Future": """Run fn in a daemon thread and return an awaitable for its result. Unlike asyncio.to_thread, a thread left hanging after wait_for times out - (mermaid-py's requests.get has no timeout) does not block interpreter exit. + does not block interpreter exit. """ import threading @@ -300,35 +385,32 @@ async def validate_single_diagram(diagram_content: str, diagram_num: int, line_s Returns: Error message if invalid, empty string if valid """ - global _MERMAID_PY_BROKEN core_error = await _try_pythonmonkey_parse(diagram_content) if core_error is None: - if _MERMAID_PY_BROKEN: - # Validation disabled/unavailable is not a syntax error — a - # non-empty return here would make callers report valid diagrams - # as broken and send agents into fix loops. - logger.debug( - "Diagram %d: validation skipped (mermaid-py disabled or unavailable)", diagram_num - ) - return "" try: core_error = await asyncio.wait_for( - _run_in_daemon_thread(_parse_via_mermaid_py, diagram_content), - timeout=15.0, + _run_in_daemon_thread(_parse_via_node, diagram_content), + timeout=_NODE_TIMEOUT_SECONDS + 5.0, ) except asyncio.TimeoutError: - # Inconclusive, not a parse failure. Latch so the remaining - # diagrams (and later calls) don't each block 15s on the same - # unreachable rendering service. - _MERMAID_PY_BROKEN = True - logger.warning( - "Diagram %d: mermaid validation timed out (15s); skipping further validation", - diagram_num, - ) - return "" - except Exception as e: - return f" Diagram {diagram_num}: Exception during validation - {str(e)}" - + core_error = None + _warn_validation_skipped_once("Node.js validator timed out.") + # Disabled remote fallback (see _MERMAID_PY_BROKEN above); needs + # `global _MERMAID_PY_BROKEN` at the top of this function. + # if core_error is None and not _MERMAID_PY_BROKEN: + # try: + # core_error = await asyncio.wait_for( + # _run_in_daemon_thread(_parse_via_mermaid_py, diagram_content), + # timeout=_NODE_TIMEOUT_SECONDS, + # ) + # except asyncio.TimeoutError: + # # Latch so later diagrams don't each block 15s on the same service. + # _MERMAID_PY_BROKEN = True + # core_error = None + # except Exception as e: + # return f" Diagram {diagram_num}: Exception during validation - {str(e)}" + # Validation unavailable is not a syntax error: a non-empty return here would + # make callers report valid diagrams as broken and send agents into fix loops. if not core_error: return "" diff --git a/guides/mcp-ide-mode.md b/guides/mcp-ide-mode.md index cbd41d7f..ce14c423 100644 --- a/guides/mcp-ide-mode.md +++ b/guides/mcp-ide-mode.md @@ -177,7 +177,8 @@ scope. **Mermaid validation errors.** The agent gets the validator's message back and fixes the diagram. If every -diagram fails, check that `mermaid-py` is installed. +diagram is skipped, PythonMonkey and Node.js are both unavailable: install +Node.js (or set `CODEWIKI_NODE_PATH`) and check the log for the warning. **Documentation in another language.** Tell the agent: "Write the wiki in English" or "Use Chinese for the diff --git a/pyproject.toml b/pyproject.toml index 3ec2c553..1db328fc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -58,7 +58,7 @@ dependencies = [ "psutil>=7.0.0", "PyYAML>=6.0.2", "mermaid-parser-py>=0.0.2", - "mermaid-py>=0.8.0", + # "mermaid-py>=0.8.0", # disabled mermaid.ink fallback, see codewiki/src/be/utils.py "fastapi>=0.116.0", "uvicorn>=0.35.0", "python-multipart>=0.0.20", @@ -72,8 +72,8 @@ dependencies = [ [external] # Node.js/npm are required at *install* time by PythonMonkey (pulled in via # mermaid-parser-py), whose pminit helper shells out to npm to populate its JS -# dependencies. mermaid-py itself does not need Node.js: it validates diagrams -# with an HTTP call to a remote rendering service (mermaid.ink by default). +# dependencies. At run time Mermaid validation uses PythonMonkey, else system +# Node.js on the same bundle, else it is skipped; it never calls a web service. build-requires = [ { name = "nodejs", version = ">=14.0.0" } ] diff --git a/requirements.txt b/requirements.txt index b063756f..b5334d30 100644 --- a/requirements.txt +++ b/requirements.txt @@ -70,8 +70,8 @@ MarkupSafe==3.0.2 matplotlib-inline==0.1.7 mcp==1.16.0 mdurl==0.1.2 +# mermaid-py==0.8.0 # disabled mermaid.ink fallback mermaid-parser-py==0.0.2 -mermaid-py==0.8.0 mistralai==1.9.10 multidict==6.6.3 nest-asyncio==1.6.0 @@ -116,7 +116,7 @@ pyperclip==1.9.0 python-dateutil==2.9.0.post0 python-dotenv==1.1.1 python-multipart==0.0.20 -pythonmonkey==1.2.0 +pythonmonkey==1.4.1 pytz==2025.2 PyYAML==6.0.2 pyzmq==27.0.1 diff --git a/tests/test_compiled_wheel.py b/tests/test_compiled_wheel.py index ce9662fd..1e935545 100644 --- a/tests/test_compiled_wheel.py +++ b/tests/test_compiled_wheel.py @@ -14,6 +14,8 @@ import inspect import json import pkgutil +import subprocess +import sys from pathlib import Path import pytest @@ -232,3 +234,94 @@ def scripted(messages, info): page = (out / "Core.md").read_text(encoding="utf-8") assert page.startswith("# Core") assert "```mermaid" in page + + +# --------------------------------------------------------------------------- +# Mermaid validation through PythonMonkey, called the way the caw backend does +# --------------------------------------------------------------------------- + +# Runs in a subprocess: the failure this guards against is a segfault. +_CAW_MERMAID_SCRIPT = r""" +import asyncio +import shutil +import sys +import tempfile +import threading + +import codewiki.src.be.utils as u + + +def write(text): + with tempfile.NamedTemporaryFile("w", suffix=".md", delete=False) as f: + f.write(text) + return f.name + + +async def check(): + good = await u.validate_mermaid_diagrams(write("```mermaid\ngraph TD\n A --> B\n```\n"), "good.md") + bad = await u.validate_mermaid_diagrams(write("```mermaid\ngraph TD\n A -->\n```\n"), "bad.md") + return good, bad + + +async def caw_backend(): + # As CawBackend.run_module_agent: register the loop, run the agent in a + # worker thread, and FastMCP calls the tool on a daemon thread of its own. + u.set_main_loop(asyncio.get_running_loop()) + + def agent(): + out = {} + t = threading.Thread(target=lambda: out.update(r=asyncio.run(check())), daemon=True) + t.start() + t.join() + return out["r"] + + return await asyncio.to_thread(agent) + + +def run(): + good, bad = asyncio.run(caw_backend()) + if threading.current_thread() is threading.main_thread(): + assert "pythonmonkey" in sys.modules, "PythonMonkey was not used" + assert "syntax correct" in good, good + assert "errors found" in bad, bad + else: + # Off the main thread PythonMonkey would crash Python at exit; it must + # not be loaded at all (validation falls back to system Node.js). + assert "pythonmonkey" not in sys.modules, "PythonMonkey loaded off the main thread" + if shutil.which("node"): + assert "syntax correct" in good, good + assert "errors found" in bad, bad + + +errors = [] +if sys.argv[1] == "main": + run() +else: # the web app runs generation on a background worker thread + def target(): + try: + run() + except BaseException as e: + errors.append(e) + + t = threading.Thread(target=target) + t.start() + t.join() +if errors: + raise errors[0] +print("ok") +""" + + +@pytest.mark.parametrize("loop_thread", ["main", "background"]) +def test_caw_mermaid_validation_through_pythonmonkey(loop_thread): + proc = subprocess.run( + [sys.executable, "-X", "faulthandler", "-c", _CAW_MERMAID_SCRIPT, loop_thread], + capture_output=True, + text=True, + timeout=300, + ) + assert proc.returncode == 0 and proc.stdout.strip().endswith("ok"), ( + proc.returncode, + proc.stdout[-2000:], + proc.stderr[-3000:], + )