11import asyncio
2+ import importlib .util
3+ import logging
24import os
35import re
6+ import shutil
7+ import subprocess
48import sys
59import threading
610from pathlib import Path
711from typing import List , Tuple
8- import logging
12+
913import tiktoken
1014
1115
1216logger = 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
262347def _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
0 commit comments