"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(shadow-account): probe weasyprint once per process
Haozhe Wua3ec4d11d670
diff --git a/agent/src/shadow_account/reporter.py b/agent/src/shadow_account/reporter.pyindex 9db8aa7b3..38da82a62 100644--- a/agent/src/shadow_account/reporter.py+++ b/agent/src/shadow_account/reporter.py@@ -296,19 +296,37 @@ def _load_css() -> str:return font_face + "\n" + css+_WEASYPRINT_HTML: Any = None # weasyprint.HTML once probed; False if unavailable++def _try_render_pdf(html: str, output_dir: Path, shadow_id: str,) -> tuple[Path | None, str]:- """Render PDF via weasyprint, returning (path|None, engine_name)."""- try:- from weasyprint import HTML # type: ignore[import-not-found]- except Exception as exc: # pragma: no cover — import-level failure- logger.warning("weasyprint unavailable (%s); HTML-only output.", exc)+ """Render PDF via weasyprint, returning (path|None, engine_name).++ The import is probed at most once per process. Retrying it after a failure+ is not merely wasteful, it is unsafe: the failed import drops weasyprint's+ cffi ``Lib`` object, whose deallocator ``dlclose()``s the libgobject handle,+ while GLib's quark table keeps static-string keys pointing into the image+ that just went away. A later re-import re-runs libgobject's constructor,+ which looks those keys up and can fault inside ``g_str_equal`` — GNOME bug+ 705535. Three report renders in one process was enough to hit it.+ """+ global _WEASYPRINT_HTML+ if _WEASYPRINT_HTML is False:return None, "html-only"+ if _WEASYPRINT_HTML is None:+ try:+ from weasyprint import HTML # type: ignore[import-not-found]+ except Exception as exc: # pragma: no cover — import-level failure+ _WEASYPRINT_HTML = False+ logger.warning("weasyprint unavailable (%s); HTML-only output.", exc)+ return None, "html-only"+ _WEASYPRINT_HTML = HTMLpdf_path = output_dir / f"{shadow_id}.pdf"try:- HTML(string=html, base_url=str(_TEMPLATES_DIR)).write_pdf(str(pdf_path))+ _WEASYPRINT_HTML(string=html, base_url=str(_TEMPLATES_DIR)).write_pdf(str(pdf_path))except Exception as exc:logger.warning("weasyprint render failed (%s); HTML-only output.", exc)if pdf_path.exists():diff --git a/agent/tests/test_shadow_account.py b/agent/tests/test_shadow_account.pyindex 3427b896f..28093253c 100644--- a/agent/tests/test_shadow_account.py+++ b/agent/tests/test_shadow_account.py@@ -5,7 +5,9 @@ Fixtures are synthesized in-test via tmp_path; no binary fixtures on disk.from __future__ import annotations+import builtinsimport json+import typesfrom pathlib import Pathimport pandas as pd@@ -499,6 +501,75 @@ def test_render_shadow_report_handles_empty_equity(assert "No material counterfactual" in Path(out["html_path"]).read_text(encoding="utf-8")+def test_weasyprint_import_is_probed_once_per_process(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A weasyprint import that failed must never be retried in the process.++ The retry is what crashes: the failed import drops weasyprint's cffi+ ``Lib``, whose deallocator ``dlclose()``s libgobject while GLib's quark+ table still holds static-string keys into that image, so the next import+ re-runs libgobject's constructor and faults (GNOME bug 705535). Three+ report renders in one process were enough to hit it.+ """+ from src.shadow_account import reporter++ monkeypatch.setattr(reporter, "_WEASYPRINT_HTML", None)+ attempts: list[str] = []+ real_import = builtins.__import__++ def counting_import(name: str, *args: object, **kwargs: object) -> object:+ if name == "weasyprint" or name.startswith("weasyprint."):+ attempts.append(name)+ raise ImportError("cannot load library 'libgobject-2.0-0'")+ return real_import(name, *args, **kwargs) # type: ignore[arg-type]++ monkeypatch.setattr(builtins, "__import__", counting_import)++ for _ in range(3):+ assert reporter._try_render_pdf("<html></html>", tmp_path, "sid") == (None, "html-only")++ assert attempts == ["weasyprint"]+++def test_weasyprint_probe_is_cached_when_available(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A successful probe is reused, and still renders on every call."""+ from src.shadow_account import reporter++ monkeypatch.setattr(reporter, "_WEASYPRINT_HTML", None)+ attempts: list[str] = []+ real_import = builtins.__import__++ class _FakeHTML:+ def __init__(self, string: str, base_url: str) -> None:+ self.string = string++ def write_pdf(self, target: str) -> None:+ Path(target).write_bytes(b"%PDF-1.4\n")++ fake = types.ModuleType("weasyprint")+ fake.HTML = _FakeHTML # type: ignore[attr-defined]++ def counting_import(name: str, *args: object, **kwargs: object) -> object:+ if name == "weasyprint":+ attempts.append(name)+ return fake+ return real_import(name, *args, **kwargs) # type: ignore[arg-type]++ monkeypatch.setattr(builtins, "__import__", counting_import)++ for shadow_id in ("first", "second"):+ pdf_path, engine = reporter._try_render_pdf("<html></html>", tmp_path, shadow_id)+ assert engine == "weasyprint"+ assert pdf_path is not None and pdf_path.exists()++ assert attempts == ["weasyprint"]++# ---------------- M5/M6: Tool wrappers + scanner ----------------@pytest.mark.unit