Skip to content

Commit 723cd1e

Browse files
dandydarshanDarshan M Uclaude
authored
Fix silent crash on Python 3.14.0-3.14.3, and --update resuming (2.1.2) (#31)
* Fix silent crash on Python 3.14.0-3.14.3, and --update resuming (2.1.2) PythonMonkey's wheels read CPython's thread state at an offset from 3.14.4+ headers (3.14.4 added a PyThreadState field). On 3.14.0-3.14.3 they read the running Task as the event loop and crash on the first awaited promise, so generate died with no message when the first agent checked a diagram. A native crash raises nothing, so the existing Node fallback never ran. Now the real parse is tried once in a child process; a crash there switches the run to Node with a warning to upgrade Python. PythonMonkey stays in use wherever it works. Reported upstream as PythonMonkey #515, with a 45-job OS/CPU/Python matrix showing only 3.14.3 crashes. After a full rebuild stopped before writing pages (no metadata.json, new graph already saved), --update diffed to no_change and failed on the missing pages on every rerun. It now resumes generation instead. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CXRqenV27WmHS3PtveCubG * Log one warning, not two, when the PythonMonkey probe fails The probe's warning already names the cause and says Node.js is used; the generic "trying system Node.js" line after it said the same thing again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CXRqenV27WmHS3PtveCubG --------- Co-authored-by: Darshan M U <darshan_mu@yahoo.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 33c0ec8 commit 723cd1e

7 files changed

Lines changed: 198 additions & 6 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,22 @@ uses [Semantic Versioning](https://semver.org/).
66

77
## [Unreleased]
88

9+
## [2.1.2] - 2026-11-08
10+
11+
### Fixed
12+
13+
- **`generate` exited silently when the first agent checked a Mermaid
14+
diagram** on Python 3.14.0–3.14.3, on every OS. PythonMonkey's wheels are
15+
built for 3.14.4+ and crash the process on their first awaited promise
16+
([PythonMonkey #515](https://github.com/Distributive-Network/PythonMonkey/issues/515)).
17+
CodeWiki now tries PythonMonkey once in a child process; if that crashes,
18+
it says to upgrade Python and checks diagrams with Node.js for the run.
19+
Where PythonMonkey works it is used as before.
20+
- **`--update` could not resume an unfinished run.** After a full rebuild
21+
stopped before writing pages, the next `--update` found no code changes and
22+
failed on every rerun because the pages were missing. It now generates the
23+
missing pages and keeps the ones already written.
24+
925
## [2.1.1] - 2026-11-07
1026

1127
### Fixed

‎codewiki/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
and an MCP server for IDE-driven documentation generation.
66
"""
77

8-
__version__ = "2.1.1"
8+
__version__ = "2.1.2"
99
__author__ = "CodeWiki Contributors"
1010
__license__ = "MIT"
1111

‎codewiki/cli/adapters/doc_generator.py‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -390,9 +390,13 @@ async def _run_backend_generation(self, backend_config: BackendConfig):
390390
)
391391
self._drop_docs_backup() # updated in place: the backup is not needed
392392
return
393-
# full_fallback / detector_failure: preserve the old docs, rebuild from scratch
394-
self._move_docs_aside()
395-
components, leaf_nodes = doc_generator.graph_builder.build_dependency_graph()
393+
if outcome == "resume":
394+
# Resume below: the cached module tree is reused and existing pages kept.
395+
self._drop_docs_backup()
396+
else:
397+
# full_fallback / detector_failure: preserve the old docs, rebuild from scratch
398+
self._move_docs_aside()
399+
components, leaf_nodes = doc_generator.graph_builder.build_dependency_graph()
396400

397401
# Stage 2: Module Clustering
398402
self.progress_tracker.start_stage(2, "Module Clustering")
@@ -611,6 +615,17 @@ async def _run_incremental_update(
611615
+ "\n ".join(e[:300] for e in record.errors)
612616
)
613617
working_dir = str(self.output_dir.absolute())
618+
if record.outcome == "no_change":
619+
missing = doc_generator.validate_generated_docs(working_dir)
620+
if missing:
621+
# The code matches the saved graph but pages are missing: an earlier run
622+
# stopped before writing them. Generate those, keeping the pages that exist.
623+
self.progress_tracker.note(
624+
f"No code changes, but {len(missing)} module page(s) are missing "
625+
"(an earlier run did not finish); generating them."
626+
)
627+
self.progress_tracker.complete_stage()
628+
return "resume"
614629
if record.outcome in ("incremental", "no_change"):
615630
self._crosslink(doc_generator, working_dir, components)
616631
# create_documentation_metadata rewrites metadata.json from scratch;

‎codewiki/src/be/utils.py‎

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import io
55
import logging
66
import os
7+
import platform
78
import re
89
import shutil
910
import subprocess
@@ -232,7 +233,7 @@ async def _try_pythonmonkey_parse(diagram_content: str) -> str | None:
232233
PythonMonkey itself is unusable (failed import or lost event loop) so the
233234
caller can fall back to system Node.js.
234235
"""
235-
global _PYTHONMONKEY_BROKEN
236+
global _PYTHONMONKEY_BROKEN, _pm_unavailable_warned
236237
if _PYTHONMONKEY_BROKEN:
237238
_warn_pythonmonkey_unavailable_once()
238239
return None
@@ -248,6 +249,10 @@ async def _try_pythonmonkey_parse(diagram_content: str) -> str | None:
248249
# e.g. the web app's worker thread: no main-thread loop to hand off to.
249250
_warn_pythonmonkey_unavailable_once()
250251
return None
252+
if not await _run_in_daemon_thread(_pythonmonkey_probe_passes):
253+
_PYTHONMONKEY_BROKEN = True
254+
_pm_unavailable_warned = True # the probe already said why, and that Node is used
255+
return None
251256

252257
_quiet_stderr_enter()
253258
try:
@@ -280,6 +285,61 @@ async def _try_pythonmonkey_parse(diagram_content: str) -> str | None:
280285
_quiet_stderr_exit()
281286

282287

288+
# A PythonMonkey wheel built against other CPython headers crashes the process on its
289+
# first awaited promise (e.g. Python 3.14.0-3.14.3 with wheels built for 3.14.4+, see
290+
# https://github.com/Distributive-Network/PythonMonkey/issues/515). A native crash
291+
# raises nothing to fall back on, so the real parse is tried once in a child process.
292+
_PROBE_SCRIPT = """
293+
import asyncio, contextlib, io
294+
with contextlib.redirect_stdout(io.StringIO()):
295+
from mermaid_parser.parser import parse_mermaid_py
296+
async def main():
297+
for source in ["flowchart TD\\n A --> B\\n", "flowchart TD\\n A --> --> B(\\n"] * 2:
298+
try:
299+
await parse_mermaid_py(source)
300+
except Exception:
301+
pass # a rejected diagram is fine; only a crash matters
302+
asyncio.run(main())
303+
"""
304+
_PROBE_TIMEOUT_SECONDS = 120.0 # PythonMonkey's first import takes seconds on Windows
305+
_probe_lock = threading.Lock()
306+
_probe_result: bool | None = None
307+
308+
309+
def _native_crash(returncode: int) -> bool:
310+
"""Killed by a signal (POSIX) or an NTSTATUS error such as an access violation (Windows)."""
311+
return returncode < 0 or (returncode & 0xFFFFFFFF) >= 0xC0000000
312+
313+
314+
def _pythonmonkey_probe_passes() -> bool:
315+
"""Whether PythonMonkey parses without crashing here, checked once per process."""
316+
global _probe_result
317+
with _probe_lock:
318+
if _probe_result is None:
319+
try:
320+
result = subprocess.run(
321+
[sys.executable, "-c", _PROBE_SCRIPT],
322+
capture_output=True,
323+
timeout=_PROBE_TIMEOUT_SECONDS,
324+
)
325+
# Only a native crash counts: a Python error (say, PythonMonkey is not
326+
# installed) is raised and handled the same way in this process.
327+
_probe_result = not _native_crash(result.returncode)
328+
if not _probe_result:
329+
logger.warning(
330+
"PythonMonkey failed a test parse (exit code %#x) and would crash "
331+
"CodeWiki: it does not support Python %s. Upgrade Python to the "
332+
"latest patch release to use it; Mermaid diagrams are checked with "
333+
"Node.js meanwhile.",
334+
result.returncode & 0xFFFFFFFF,
335+
platform.python_version(),
336+
)
337+
except (OSError, subprocess.TimeoutExpired) as e:
338+
logger.warning("PythonMonkey test parse did not finish (%s); using Node.js.", e)
339+
_probe_result = False
340+
return _probe_result
341+
342+
283343
async def _parse_with_pythonmonkey(diagram_content: str) -> None:
284344
"""Parse on the main thread; importing here keeps the import there too."""
285345
try:

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
44

55
[project]
66
name = "nc-codewiki"
7-
version = "2.1.1"
7+
version = "2.1.2"
88
description = "Transform codebases into comprehensive documentation using AI-powered analysis"
99
readme = "README.md"
1010
requires-python = ">=3.12"

‎tests/test_mermaid_validation.py‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,3 +268,61 @@ def test_issue_exact_reproduction_repairs_only_diamond(parser):
268268
assert report.content == markdown(case["repaired"])
269269
assert not report.errors and len(report.repairs) == 1
270270
assert len(parser) == 2
271+
272+
273+
def _fresh_probe(monkeypatch, returncode):
274+
"""Reset the once-per-process probe and fake its child process exit code."""
275+
import subprocess
276+
from types import SimpleNamespace
277+
278+
monkeypatch.setattr(utils, "_probe_result", None)
279+
monkeypatch.setattr(utils, "_PYTHONMONKEY_BROKEN", False)
280+
monkeypatch.setattr(utils, "_pm_unavailable_warned", False)
281+
runs = []
282+
283+
def run(*a, **k):
284+
runs.append(a)
285+
return SimpleNamespace(returncode=returncode)
286+
287+
monkeypatch.setattr(subprocess, "run", run)
288+
return runs
289+
290+
291+
@pytest.mark.parametrize("returncode", [-11, 0xC0000005]) # segfault; Windows access violation
292+
def test_crashing_pythonmonkey_falls_back_without_parsing_in_process(
293+
monkeypatch, caplog, returncode
294+
):
295+
"""Python 3.14.0-3.14.3: PythonMonkey's wheels crash the process on the first parse
296+
(PythonMonkey issue #515). The probe sees it in a child, so CodeWiki uses Node."""
297+
runs = _fresh_probe(monkeypatch, returncode)
298+
caplog.set_level("WARNING")
299+
300+
async def must_not_run(source):
301+
pytest.fail("PythonMonkey must not parse in-process after a crashing probe")
302+
303+
monkeypatch.setattr(utils, "_parse_with_pythonmonkey", must_not_run)
304+
assert asyncio.run(utils._try_pythonmonkey_parse("flowchart TD\n A --> B\n")) is None
305+
assert utils._PYTHONMONKEY_BROKEN
306+
asyncio.run(utils._try_pythonmonkey_parse("flowchart TD\n A --> B\n"))
307+
assert len(runs) == 1 # probed once, not per diagram
308+
warnings = [r.getMessage() for r in caplog.records if r.levelname == "WARNING"]
309+
assert len(warnings) == 1 and "Upgrade Python" in warnings[0], warnings
310+
311+
312+
def test_python_error_in_probe_is_not_a_crash(monkeypatch):
313+
"""PythonMonkey not installed exits 1 with an ImportError: handled in-process as before."""
314+
_fresh_probe(monkeypatch, 1)
315+
assert utils._pythonmonkey_probe_passes()
316+
317+
318+
def test_probe_passes_where_pythonmonkey_works(monkeypatch):
319+
import importlib.util
320+
321+
if importlib.util.find_spec("pythonmonkey") is None:
322+
pytest.skip("PythonMonkey is not installed")
323+
import sys
324+
325+
if sys.version_info[:2] == (3, 14) and sys.version_info.micro < 4:
326+
pytest.skip("PythonMonkey crashes on Python 3.14.0-3.14.3 (issue #515)")
327+
monkeypatch.setattr(utils, "_probe_result", None)
328+
assert utils._pythonmonkey_probe_passes()

‎tests/test_updater_graph_store.py‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
import os
77
import time
88

9+
import pytest
10+
911
from codewiki.src.be.updater.graph_store import (
1012
find_any_graph_file,
1113
graph_file_path,
@@ -213,6 +215,47 @@ async def run(self, prev_path, *a):
213215
assert not prev.exists() # was half of a user's 85 MB docs folder
214216

215217

218+
def test_no_change_with_missing_pages_resumes_generation(tmp_path, monkeypatch):
219+
"""A full rebuild that crashed saved the new graph but wrote no pages and no
220+
metadata.json; the next --update diffs to no_change and must not fail on the
221+
missing pages, or every rerun hits the same dead end."""
222+
import asyncio
223+
from pathlib import Path
224+
from types import SimpleNamespace
225+
226+
import codewiki.src.be.updater.orchestrator as orchestrator
227+
from codewiki.cli.adapters.doc_generator import CLIDocumentationGenerator
228+
229+
class Updater:
230+
def __init__(self, *a):
231+
self.record = None
232+
233+
async def run(self, *a):
234+
return SimpleNamespace(outcome="no_change", summary=lambda: {}, errors=[])
235+
236+
monkeypatch.setattr(orchestrator, "IncrementalUpdater", Updater)
237+
gen = object.__new__(CLIDocumentationGenerator)
238+
gen.output_dir, gen.repo_path, gen.commit_id, gen.verbose = (
239+
Path(tmp_path),
240+
tmp_path,
241+
"c2",
242+
False,
243+
)
244+
notes = []
245+
gen.progress_tracker = SimpleNamespace(
246+
start_stage=lambda *a: None, complete_stage=lambda: None, note=notes.append
247+
)
248+
doc_generator = SimpleNamespace(
249+
backend=None,
250+
usage_ledger=SimpleNamespace(in_phase=lambda phase: _null_context()),
251+
validate_generated_docs=lambda wd: ["billing-ui-app-core", "overview"],
252+
create_documentation_metadata=lambda *a: pytest.fail("must not mark the docs complete"),
253+
)
254+
outcome = asyncio.run(gen._run_incremental_update(None, doc_generator, None, None, {}, []))
255+
assert outcome == "resume"
256+
assert "2 module page(s) are missing" in notes[0]
257+
258+
216259
def _null_context():
217260
import contextlib
218261

0 commit comments

Comments
 (0)