Skip to content

Commit 25d9a7e

Browse files
dandydarshanDarshan M UclaudeBrahmendraBachi
authored
Mermaid validation: PythonMonkey on main thread, then system Node, never mermaid.ink (#1)
* Use PythonMonkey only on the main thread; drop the Python 3.12+ skip PythonMonkey crashes Python when it is imported on a non-main thread (segfault during validation, caw's FastMCP tool thread) or used from a non-main thread's loop (segfault at exit, the web app's worker thread). This happens with 1.2.0 and 1.4.1 on Linux and macOS, on every Python version tested; the old "3.12+ only" diagnosis was wrong, so the version skip just sent all validation to mermaid.ink. Now the parse, import included, always runs on the main thread: directly, or handed to the main loop via run_coroutine_threadsafe. Off the main thread with no main loop to hand off to, validation falls back to mermaid-py. Bump pythonmonkey to 1.4.1. The new test runs both thread layouts in a subprocess, so a segfault fails it instead of killing pytest. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(ui): Sending mermaid validation traffic to local nodejs validator * solve lint error * remove duplicate function declaration * revert python monkey break to false * Mermaid validation: PythonMonkey, then system Node, then skip; no network The Node fallback ran codewiki/mermaid_node/validate.mjs, which was not in package-data (so missing from wheels) and npm-installed mermaid into site-packages at run time (network access, writable install dir, a second mermaid version). Node now runs mermaid-parser-py's own parser.bundle.js, the same file PythonMonkey loads: no npm, no lock file, same parse errors. Drop the mermaid.ink fallback (mermaid-py, MERMAID_VALIDATE). If neither PythonMonkey nor Node can run, log one warning and skip validation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011nNK4oKT17vZwKhUezJQ5z * Keep the mermaid.ink fallback as commented-out code Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011nNK4oKT17vZwKhUezJQ5z --------- Co-authored-by: Darshan M U <darshan_mu@yahoo.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Brahmendra Bachi <hari8185008552@gmail.com>
1 parent 810f177 commit 25d9a7e

5 files changed

Lines changed: 254 additions & 78 deletions

File tree

‎codewiki/src/be/utils.py‎

Lines changed: 154 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,27 @@
11
import asyncio
2+
import importlib.util
3+
import logging
24
import os
35
import re
6+
import shutil
7+
import subprocess
48
import sys
59
import threading
610
from pathlib import Path
711
from typing import List, Tuple
8-
import logging
12+
913
import tiktoken
1014

1115

1216
logger = logging.getLogger(__name__)
1317

1418

15-
# PythonMonkey (used by mermaid_parser.parse_mermaid_py) binds its JS engine
16-
# to the thread that first imported it — typically the main thread at module
17-
# load time. The caw backend dispatches MCP tool calls on a FastMCP
18-
# daemon-thread event loop, where parse_mermaid_py raises
19-
# "cannot find a running Python event-loop". Recording the main loop here
20-
# lets validate_single_diagram marshal the call back via
21-
# asyncio.run_coroutine_threadsafe so PythonMonkey finds its home loop.
19+
# PythonMonkey (used by mermaid_parser.parse_mermaid_py) is only safe on the
20+
# process main thread. Importing it on another thread segfaults, and using it
21+
# from a non-main thread's loop crashes Python at exit (seen on every version,
22+
# Linux and macOS). The caw backend runs MCP tool calls on a FastMCP daemon
23+
# thread, so it records the main loop here and _try_pythonmonkey_parse hands
24+
# the parse (import included) back to it via asyncio.run_coroutine_threadsafe.
2225
_main_loop: "asyncio.AbstractEventLoop | None" = None
2326
_main_loop_thread_ident: int | None = None
2427

@@ -152,21 +155,34 @@ def extract_mermaid_blocks(content: str) -> List[Tuple[int, str]]:
152155
return mermaid_blocks
153156

154157

155-
# PythonMonkey 1.3.1 only supports Python 3.8–3.11. On 3.12+ it still imports,
156-
# but its SpiderMonkey cleanup runs on the wrong thread during _Py_Finalize and
157-
# segfaults at interpreter shutdown (macOS crash dialog after a successful run).
158-
# Skip it proactively so SpiderMonkey is never loaded into the process.
159-
_PYTHONMONKEY_BROKEN = sys.version_info >= (3, 12)
158+
# Set once PythonMonkey fails to import or loses its event loop; validation
159+
# then falls back to system Node.js running the same parser bundle.
160+
_PYTHONMONKEY_BROKEN = False
161+
_NODE_TIMEOUT_SECONDS = 15.0
162+
163+
# Disabled: remote fallback through mermaid-py, which sends diagram content to
164+
# https://mermaid.ink (or MERMAID_INK_SERVER). Kept commented out so it can be
165+
# brought back: uncomment this, _parse_via_mermaid_py, the block at the end of
166+
# validate_single_diagram's fallbacks, and mermaid-py in pyproject/requirements.
167+
# _MERMAID_PY_BROKEN = os.environ.get("MERMAID_VALIDATE", "0").strip() != "1"
168+
169+
# Validation never touches the network: PythonMonkey, then Node, then skip.
170+
_pm_unavailable_warned = False
171+
_skip_warned = False
160172

161-
# mermaid-py validates diagrams by sending them to a remote rendering service
162-
# (https://mermaid.ink by default, overridable via the MERMAID_INK_SERVER env
163-
# var understood by mermaid-py itself) rather than spawning a local Node.js
164-
# subprocess. Note that this sends diagram content to that third-party service.
165-
# It can still hang or fail when the service is unreachable (no network egress,
166-
# DNS/firewall issues, or an outage). Enabled by default; set MERMAID_VALIDATE=0
167-
# to disable.
168-
_MERMAID_PY_BROKEN = os.environ.get("MERMAID_VALIDATE", "1") == "0"
169-
_MERMAID_PY_PROBED = True # Skip probing — rely on env var
173+
174+
def _warn_pythonmonkey_unavailable_once() -> None:
175+
global _pm_unavailable_warned
176+
if not _pm_unavailable_warned:
177+
_pm_unavailable_warned = True
178+
logger.warning("PythonMonkey Mermaid validation is unavailable; trying system Node.js.")
179+
180+
181+
def _warn_validation_skipped_once(reason: str) -> None:
182+
global _skip_warned
183+
if not _skip_warned:
184+
_skip_warned = True
185+
logger.warning("Mermaid validation skipped: %s", reason)
170186

171187

172188
# 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:
201217
"""Attempt to parse via PythonMonkey/mermaid-parser-py.
202218
203219
Returns the extracted parse-error message, "" on success, or None when
204-
PythonMonkey itself is unusable (broken JS event loop binding on
205-
Python 3.13+) so the caller can fall back to mermaid-py.
220+
PythonMonkey itself is unusable (failed import or lost event loop) so the
221+
caller can fall back to system Node.js.
206222
"""
207223
global _PYTHONMONKEY_BROKEN
208224
if _PYTHONMONKEY_BROKEN:
225+
_warn_pythonmonkey_unavailable_once()
209226
return None
210227

211-
try:
212-
from mermaid_parser.parser import parse_mermaid_py
213-
except Exception:
214-
_PYTHONMONKEY_BROKEN = True
228+
on_main_thread = threading.current_thread() is threading.main_thread()
229+
via_main_loop = (
230+
not on_main_thread
231+
and _main_loop is not None
232+
and _main_loop.is_running()
233+
and _main_loop_thread_ident == threading.main_thread().ident
234+
)
235+
if not (on_main_thread or via_main_loop):
236+
# e.g. the web app's worker thread: no main-thread loop to hand off to.
237+
_warn_pythonmonkey_unavailable_once()
215238
return None
216239

217240
_quiet_stderr_enter()
218241
try:
219-
if (
220-
_main_loop is not None
221-
and _main_loop.is_running()
222-
and threading.get_ident() != _main_loop_thread_ident
223-
):
224-
fut = asyncio.run_coroutine_threadsafe(parse_mermaid_py(diagram_content), _main_loop)
242+
if via_main_loop:
243+
fut = asyncio.run_coroutine_threadsafe(
244+
_parse_with_pythonmonkey(diagram_content), _main_loop
245+
)
225246
await asyncio.wrap_future(fut)
226247
else:
227-
await parse_mermaid_py(diagram_content)
248+
await _parse_with_pythonmonkey(diagram_content)
228249
return ""
250+
except ImportError:
251+
_PYTHONMONKEY_BROKEN = True
252+
_warn_pythonmonkey_unavailable_once()
253+
return None
229254
except Exception as e:
230255
error_str = str(e)
231-
# PythonMonkey 1.3.1 only supports Python 3.8-3.11; on newer Pythons
232-
# every JS call raises this. Latch the failure once so subsequent
233-
# diagrams skip the broken path and go straight to mermaid-py.
256+
# Raised when called off PythonMonkey's home loop. Latch the failure
257+
# once so later diagrams skip straight to Node.
234258
if "cannot find a running Python event-loop" in error_str:
235259
_PYTHONMONKEY_BROKEN = True
260+
_warn_pythonmonkey_unavailable_once()
236261
return None
237262
match = re.search(r"Error:(.*?)(?=Stack Trace:|$)", error_str, re.DOTALL)
238263
if match:
@@ -243,27 +268,87 @@ async def _try_pythonmonkey_parse(diagram_content: str) -> str | None:
243268
_quiet_stderr_exit()
244269

245270

246-
def _parse_via_mermaid_py(diagram_content: str) -> str:
247-
"""Validate via mermaid-py. Returns parse-error text, or "" if valid.
271+
async def _parse_with_pythonmonkey(diagram_content: str) -> None:
272+
"""Parse on the main thread; importing here keeps the import there too."""
273+
try:
274+
from mermaid_parser.parser import parse_mermaid_py
275+
except Exception as e:
276+
raise ImportError("PythonMonkey is unavailable") from e
277+
await parse_mermaid_py(diagram_content)
248278

249-
mermaid-py raises MermaidError on parse failure and returns an SVG body
250-
on success — we must drive the result off the exception, not the body
251-
text, otherwise a successful SVG gets reported as a parse error.
252-
"""
253-
import mermaid as md
254279

280+
def _resolve_node_executable() -> str | None:
281+
override = os.environ.get("CODEWIKI_NODE_PATH", "").strip()
282+
if override:
283+
return override if Path(override).is_file() else None
284+
return shutil.which("node")
285+
286+
287+
# Reads the diagram on stdin, exits 0 if it parses, else 1 with the error on stderr.
288+
_NODE_PARSE_SCRIPT = (
289+
'const parse = require(process.argv[1]); let s = "";'
290+
'process.stdin.on("data", (d) => (s += d)).on("end", () => parse(s).then('
291+
"() => process.exit(0),"
292+
"(e) => { process.stderr.write(String((e && e.message) || e)); process.exit(1); }));"
293+
)
294+
295+
296+
def _parse_via_node(diagram_content: str) -> str | None:
297+
"""Validate with system Node.js running mermaid-parser-py's own bundle.
298+
299+
Returns the parse-error message, "" on success, or None (after one
300+
warning) when Node or the bundle is missing or the run fails.
301+
"""
302+
node = _resolve_node_executable()
303+
if node is None:
304+
_warn_validation_skipped_once(
305+
"Node.js not found on PATH (set CODEWIKI_NODE_PATH to point at it)."
306+
)
307+
return None
308+
# find_spec does not run mermaid_parser/__init__, which imports PythonMonkey.
309+
spec = importlib.util.find_spec("mermaid_parser")
310+
bundle = Path(spec.origin).parent / "js" / "parser.bundle.js" if spec and spec.origin else None
311+
if bundle is None or not bundle.is_file():
312+
_warn_validation_skipped_once("mermaid-parser-py's parser.bundle.js was not found.")
313+
return None
255314
try:
256-
md.Mermaid(diagram_content)
315+
result = subprocess.run(
316+
[node, "-e", _NODE_PARSE_SCRIPT, str(bundle)],
317+
input=diagram_content,
318+
capture_output=True,
319+
text=True,
320+
encoding="utf-8",
321+
timeout=_NODE_TIMEOUT_SECONDS,
322+
)
323+
except (OSError, subprocess.TimeoutExpired) as e:
324+
_warn_validation_skipped_once(f"Node.js validator failed to run ({e}).")
325+
return None
326+
if result.returncode == 0:
257327
return ""
258-
except Exception as e:
259-
return str(e)
328+
return result.stderr.strip() or "Mermaid parse failed (no message from Node.js)"
329+
330+
331+
# def _parse_via_mermaid_py(diagram_content: str) -> str:
332+
# """Validate via mermaid-py. Returns parse-error text, or "" if valid.
333+
#
334+
# mermaid-py raises MermaidError on parse failure and returns an SVG body
335+
# on success — we must drive the result off the exception, not the body
336+
# text, otherwise a successful SVG gets reported as a parse error.
337+
# """
338+
# import mermaid as md
339+
#
340+
# try:
341+
# md.Mermaid(diagram_content)
342+
# return ""
343+
# except Exception as e:
344+
# return str(e)
260345

261346

262347
def _run_in_daemon_thread(fn, *args) -> "asyncio.Future":
263348
"""Run fn in a daemon thread and return an awaitable for its result.
264349
265350
Unlike asyncio.to_thread, a thread left hanging after wait_for times out
266-
(mermaid-py's requests.get has no timeout) does not block interpreter exit.
351+
does not block interpreter exit.
267352
"""
268353
import threading
269354

@@ -300,35 +385,32 @@ async def validate_single_diagram(diagram_content: str, diagram_num: int, line_s
300385
Returns:
301386
Error message if invalid, empty string if valid
302387
"""
303-
global _MERMAID_PY_BROKEN
304388
core_error = await _try_pythonmonkey_parse(diagram_content)
305389
if core_error is None:
306-
if _MERMAID_PY_BROKEN:
307-
# Validation disabled/unavailable is not a syntax error — a
308-
# non-empty return here would make callers report valid diagrams
309-
# as broken and send agents into fix loops.
310-
logger.debug(
311-
"Diagram %d: validation skipped (mermaid-py disabled or unavailable)", diagram_num
312-
)
313-
return ""
314390
try:
315391
core_error = await asyncio.wait_for(
316-
_run_in_daemon_thread(_parse_via_mermaid_py, diagram_content),
317-
timeout=15.0,
392+
_run_in_daemon_thread(_parse_via_node, diagram_content),
393+
timeout=_NODE_TIMEOUT_SECONDS + 5.0,
318394
)
319395
except asyncio.TimeoutError:
320-
# Inconclusive, not a parse failure. Latch so the remaining
321-
# diagrams (and later calls) don't each block 15s on the same
322-
# unreachable rendering service.
323-
_MERMAID_PY_BROKEN = True
324-
logger.warning(
325-
"Diagram %d: mermaid validation timed out (15s); skipping further validation",
326-
diagram_num,
327-
)
328-
return ""
329-
except Exception as e:
330-
return f" Diagram {diagram_num}: Exception during validation - {str(e)}"
331-
396+
core_error = None
397+
_warn_validation_skipped_once("Node.js validator timed out.")
398+
# Disabled remote fallback (see _MERMAID_PY_BROKEN above); needs
399+
# `global _MERMAID_PY_BROKEN` at the top of this function.
400+
# if core_error is None and not _MERMAID_PY_BROKEN:
401+
# try:
402+
# core_error = await asyncio.wait_for(
403+
# _run_in_daemon_thread(_parse_via_mermaid_py, diagram_content),
404+
# timeout=_NODE_TIMEOUT_SECONDS,
405+
# )
406+
# except asyncio.TimeoutError:
407+
# # Latch so later diagrams don't each block 15s on the same service.
408+
# _MERMAID_PY_BROKEN = True
409+
# core_error = None
410+
# except Exception as e:
411+
# return f" Diagram {diagram_num}: Exception during validation - {str(e)}"
412+
# Validation unavailable is not a syntax error: a non-empty return here would
413+
# make callers report valid diagrams as broken and send agents into fix loops.
332414
if not core_error:
333415
return ""
334416

‎guides/mcp-ide-mode.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,8 @@ scope.
177177

178178
**Mermaid validation errors.**
179179
The agent gets the validator's message back and fixes the diagram. If every
180-
diagram fails, check that `mermaid-py` is installed.
180+
diagram is skipped, PythonMonkey and Node.js are both unavailable: install
181+
Node.js (or set `CODEWIKI_NODE_PATH`) and check the log for the warning.
181182

182183
**Documentation in another language.**
183184
Tell the agent: "Write the wiki in English" or "Use Chinese for the

‎pyproject.toml‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ dependencies = [
5858
"psutil>=7.0.0",
5959
"PyYAML>=6.0.2",
6060
"mermaid-parser-py>=0.0.2",
61-
"mermaid-py>=0.8.0",
61+
# "mermaid-py>=0.8.0", # disabled mermaid.ink fallback, see codewiki/src/be/utils.py
6262
"fastapi>=0.116.0",
6363
"uvicorn>=0.35.0",
6464
"python-multipart>=0.0.20",
@@ -72,8 +72,8 @@ dependencies = [
7272
[external]
7373
# Node.js/npm are required at *install* time by PythonMonkey (pulled in via
7474
# mermaid-parser-py), whose pminit helper shells out to npm to populate its JS
75-
# dependencies. mermaid-py itself does not need Node.js: it validates diagrams
76-
# with an HTTP call to a remote rendering service (mermaid.ink by default).
75+
# dependencies. At run time Mermaid validation uses PythonMonkey, else system
76+
# Node.js on the same bundle, else it is skipped; it never calls a web service.
7777
build-requires = [
7878
{ name = "nodejs", version = ">=14.0.0" }
7979
]

‎requirements.txt‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,8 +70,8 @@ MarkupSafe==3.0.2
7070
matplotlib-inline==0.1.7
7171
mcp==1.16.0
7272
mdurl==0.1.2
73+
# mermaid-py==0.8.0 # disabled mermaid.ink fallback
7374
mermaid-parser-py==0.0.2
74-
mermaid-py==0.8.0
7575
mistralai==1.9.10
7676
multidict==6.6.3
7777
nest-asyncio==1.6.0
@@ -116,7 +116,7 @@ pyperclip==1.9.0
116116
python-dateutil==2.9.0.post0
117117
python-dotenv==1.1.1
118118
python-multipart==0.0.20
119-
pythonmonkey==1.2.0
119+
pythonmonkey==1.4.1
120120
pytz==2025.2
121121
PyYAML==6.0.2
122122
pyzmq==27.0.1

0 commit comments

Comments
 (0)