"""OpenFOAM subprocess runner with retry, error classification, and quality reporting.
This module provides:
- MeshWorker: interruptible subprocess runner for cartesianMesh via WSL2
- RetryRunner: orchestrates cartesianMesh with up to 3 automatic retries
- CheckMeshWorker / PolyDualWorker: quality-check and conversion workers
- QualityFixWorker: auto-fix loop (mesh -> checkMesh -> fix -> re-mesh)
- analyze_error / parse_checkmesh_output: error and quality parsers
"""
from __future__ import annotations
import re
import os
import ctypes
import shlex
import signal
import struct
import subprocess
import sys
import threading
import time
import enum
import logging
logger = logging.getLogger(__name__)
from contextlib import suppress
from dataclasses import dataclass
from pathlib import Path
from typing import Callable, TYPE_CHECKING
if TYPE_CHECKING:
from polyfoammesh.commercial.parallel_mesh import ParallelMeshEngine
# Monotonic clock for elapsed-time measurement (immune to wall-clock jumps).
_now = time.monotonic
# GMSH stall watchdog. GMSH's surface-meshing loop can hang forever on a bad
# surface (confirmed live: stuck at 40% on "surface 2"; a venturi looping on
# "Serializing surface 46") while emitting no output at all. The volume worker
# tracks the time of the last output line and, if nothing arrives for
# GMSH_STALL_TIMEOUT_S, kills the process tree and retries ONCE in robust mode
# (POLYFOAMMESH_GMSH_ROBUST=1: healing + Delaunay 2D, no optimization). A
# healthy run whose output keeps flowing is never touched, however long it
# takes.
#
# The budget is NOT flat 300 s for every run: a large mesh legitimately goes
# silent for long stretches while GMSH's 3D phase works (measured on the real
# 7M-tet Parte4 part: individual "Computing mesh sizes" gaps of ~54 s, which
# scale with machine load/thread count). `_gmsh_stall_budget_s` scales the
# base 300 s up to GMSH_STALL_MAX_TIMEOUT_S (900 s) with the estimated job
# size, so the robust retry is not killed mid-work; the periodic heartbeat
# also reports the child's CPU usage so a busy-but-silent process is visibly
# different from a dead one.
# Override the threshold with env POLYFOAMMESH_GMSH_STALL_S (seconds).
GMSH_STALL_TIMEOUT_S = 300.0
#: Upper bound of the size-scaled no-output budget (large jobs).
GMSH_STALL_MAX_TIMEOUT_S = 900.0
#: Estimated-cell bounds over which the budget ramps from base to the max.
GMSH_STALL_SMALL_CELLS = 500_000
GMSH_STALL_LARGE_CELLS = 5_000_000
GMSH_STALL_ENV_VAR = "POLYFOAMMESH_GMSH_STALL_S"
GMSH_ROBUST_ENV_VAR = "POLYFOAMMESH_GMSH_ROBUST"
#: Phase C: set alongside POLYFOAMMESH_GMSH_ROBUST on a *signature*-triggered
#: retry only (the venturi MeshAdapt runaway class), enabling the 2D optimizer
#: inside robust mode. Measured A/B: the optimizer is a quality win with no
#: convergence cost on that class, but doubles-to-triples wall time on large
#: STEP parts, so a generic no-output robust retry leaves it off.
GMSH_ROBUST_OPT_ENV_VAR = "POLYFOAMMESH_GMSH_ROBUST_OPT"
#: Phase D guaranteed fallback: the worker sets this on its last-ditch attempt
#: so the wrapper runs the explicit-size path with sizes derived to match the
#: adaptive request's cell target (adaptive sizing OFF). See
#: ``gmsh_wrapper.derive_manual_equivalent_sizes``.
GMSH_MANUAL_EQUIV_ENV_VAR = "POLYFOAMMESH_GMSH_MANUAL_EQUIV"
def _gmsh_stall_timeout_s() -> float:
"""Stall threshold in seconds (env POLYFOAMMESH_GMSH_STALL_S overrides).
Read at call time, not import time, so a test or a user-set env var takes
effect per run. A non-positive or non-numeric override is ignored with a
warning and the module default is used instead.
"""
raw = os.environ.get(GMSH_STALL_ENV_VAR)
if raw:
try:
value = float(raw)
if value > 0:
return value
logger.warning(
"%s=%r must be > 0; using default %ss",
GMSH_STALL_ENV_VAR, raw, GMSH_STALL_TIMEOUT_S,
)
except ValueError:
logger.warning(
"%s=%r is not a number; using default %ss",
GMSH_STALL_ENV_VAR, raw, GMSH_STALL_TIMEOUT_S,
)
return GMSH_STALL_TIMEOUT_S
def _gmsh_stall_env_overridden() -> bool:
"""True when POLYFOAMMESH_GMSH_STALL_S pins an explicit valid threshold.
When the user pins the threshold we must NOT size-scale it — they asked
for exactly that many seconds.
"""
raw = os.environ.get(GMSH_STALL_ENV_VAR)
if not raw:
return False
try:
return float(raw) > 0
except ValueError:
return False
def _gmsh_stall_budget_s(base_s: float, est_cells: int | None = None) -> float:
"""Size-scaled no-output budget: *base_s* (300 s) for small jobs, ramping
linearly in estimated cell count up to ``GMSH_STALL_MAX_TIMEOUT_S`` (900 s)
for large ones.
*est_cells* <= 0 / ``None`` returns *base_s* unchanged, so callers that
cannot estimate a size keep the historical hard budget. The ramp is linear
between ``GMSH_STALL_SMALL_CELLS`` and ``GMSH_STALL_LARGE_CELLS`` and
clamped to the maximum, so the returned value is always >= *base_s* and
<= max(base, GMSH_STALL_MAX_TIMEOUT_S).
"""
if not est_cells or est_cells <= GMSH_STALL_SMALL_CELLS:
return float(base_s)
span = max(1, GMSH_STALL_LARGE_CELLS - GMSH_STALL_SMALL_CELLS)
frac = min(1.0, (float(est_cells) - GMSH_STALL_SMALL_CELLS) / span)
ceiling = max(float(base_s), GMSH_STALL_MAX_TIMEOUT_S)
return float(base_s) + (ceiling - float(base_s)) * frac
def _gmsh_job_cell_estimate(step_path, max_cells_target: int = 0) -> int:
"""Rough cell count of the volume mesh about to be built, to size the
stall budget only.
Prefers the explicit GUI target when set; otherwise falls back to the
adaptive path's own machine cell cap (``gmsh_wrapper._hardware_budget``) —
the number of cells the adaptive sizing is allowed to spend on this
machine, i.e. a machine+detail-scaled "how large can this job be".
Returns 0 when nothing can be estimated (budget stays at the base).
"""
try:
target = int(max_cells_target or 0)
except (TypeError, ValueError):
target = 0
if target > 0:
return target
try:
from polyfoammesh.core.gmsh_wrapper import _hardware_budget
return int(_hardware_budget(None).get("max_cells", 0) or 0)
except Exception:
logger.debug(
"stall watchdog: no job-size estimate for %s", step_path, exc_info=True
)
return 0
def _posix_popen_kwargs() -> dict:
"""Popen kwargs that put a child in its OWN process group/session on POSIX.
Without this, ``os.killpg(os.getpgid(child_pid), SIGKILL)`` would resolve
to the GUI's own process group and kill the application itself. With
``start_new_session=True`` the child becomes a session/group leader, so
its pgid equals its pid and ``killpg(pid)`` can never touch the GUI.
Empty on Windows, where ``taskkill /T`` walks the tree instead — keeping
Windows Popen calls byte-identical.
"""
if sys.platform == "win32":
return {}
return {"start_new_session": True}
[docs]
def poly_wall_patch_names(case_dir: Path | str) -> list[str]:
"""Wall-like patches of a polyMesh ``boundary`` file — the default target
set for the poly BL step (FASE 1): a patch qualifies if its boundary
type is ``wall`` (set by the BC editor / ``set_wall_patch_types``) or its
name explicitly says wall (``*wall*``). GMSH ``surface_N`` patches and
role-named patches (inlet/outlet/opening) do NOT qualify — a raw GMSH
case returns an empty list and the worker falls back to the geometric
inference (``poly_geo_wall_patch_names``), so the default BL never
touches inlet/outlet even without explicit wall naming."""
from polyfoammesh.core.boundary_reader import parse_boundary
bpath = Path(case_dir) / "constant" / "polyMesh" / "boundary"
return [
p.name for p in parse_boundary(bpath)
if p.patch_type == "wall" or "wall" in p.name.lower()
]
[docs]
def poly_geo_wall_patch_names(case_dir: Path | str) -> list[str]:
"""Geometric wall fallback for raw GMSH cases (every patch type
'patch', ``surface_N`` names): infer inlet/outlet from the geometry
(``case_setup.infer_patch_roles``) and treat every other patch as a
wall — so the default BL never touches inlet/outlet even when no patch
is explicitly named/typed wall. Returns [] when the roles cannot be
inferred (e.g. a fully closed domain) — the caller then falls back to
ALL with a warning."""
try:
from polyfoammesh.core.boundary_reader import parse_boundary
from polyfoammesh.core.case_setup import infer_patch_roles
bpath = Path(case_dir) / "constant" / "polyMesh" / "boundary"
patches = parse_boundary(bpath)
roles = infer_patch_roles(Path(case_dir), patches)
return [
p.name for p in patches
if roles.get(p.name, "wall") == "wall" or p.patch_type == "wall"
]
except Exception: # noqa: BLE001 - not inferable (e.g. closed domain)
return []
[docs]
def poly_bl_patch_selection(
case_dir: Path | str,
apply_to_all_override: bool = False,
) -> tuple[list[str] | None, bool, list[str]]:
"""Decide which boundary patches the poly BL step may touch.
Returns ``(patch_names, apply_to_all, notes)``:
- ``patch_names is None`` -> **skip the BL entirely** (nothing safe to
extrude from). The caller must report this rather than extruding.
Three tiers, cheapest and most authoritative first:
1. An explicit user override means "all patches" and is honoured
literally — that is the user's call to make.
2. Boundary type / name, then the geometric inference
(``poly_wall_patch_names`` / ``poly_geo_wall_patch_names``).
3. When both fail (every patch unnamed GMSH ``surface_N`` *and* no
inlet/outlet could be placed — closed domains, external aero,
multi-inlet manifolds), exclude only what is positively known to be
a non-wall and extrude from the rest. If that leaves nothing, skip.
Tier 3 is the one that used to be "apply to ALL". It fired on exactly
the geometries where the least is known, and it put prism stacks in the
inlets and outlets: checkMesh accepts that, so the failure only surfaces
when the solver diverges. A mesh without layers is a recoverable
warning; a mesh with layers in the inlet is a wrong answer.
"""
if apply_to_all_override:
return [], True, []
notes: list[str] = []
try:
walls = poly_wall_patch_names(case_dir)
except Exception: # noqa: BLE001 - best effort
walls = []
if not walls:
walls = poly_geo_wall_patch_names(case_dir)
if walls:
return walls, False, notes
from polyfoammesh.core.patch_roles import split_wall_patches
try:
from polyfoammesh.core.boundary_reader import parse_boundary
all_names = [
p.name
for p in parse_boundary(
Path(case_dir) / "constant" / "polyMesh" / "boundary"
)
]
except Exception: # noqa: BLE001 - best effort
all_names = []
walls2, excluded = split_wall_patches(all_names)
if not walls2:
notes.append(
"no wall patch identified and every boundary patch is named or "
"typed as inlet, outlet or symmetry — boundary layers skipped"
)
return None, False, notes
if excluded:
notes.append(
"excluded non-wall patches: "
+ ", ".join(f"{n} ({r})" for n, r in excluded)
)
return walls2, False, notes
__all__ = [
"ErrorType", "ErrorInfo", "analyze_error",
"MeshWorker", "RetryRunner",
"MeshQualityReport", "parse_checkmesh_output",
"CheckMeshWorker", "PolyDualWorker", "QualityFixWorker", "ParallelMeshWorker",
"DecomposeParWorker", "WslCheckWorker",
"generate_fms",
"poly_wall_patch_names", "poly_geo_wall_patch_names",
"poly_bl_patch_selection",
]
try:
from PySide6.QtCore import QObject, QThread, Signal, Slot, Qt
except ImportError as exc:
raise ImportError(
"PySide6 is required for polyfoammesh. "
"Install with: pip install PySide6"
) from exc
from polyfoammesh.config import OFConfig
from polyfoammesh.octopoda_local import octo
OF_BASHRC = OFConfig().env_script
# ------------------------------------------------------------------
# Phase-0 performance instrumentation (logging only).
#
# A small process-wide stage-time registry plus an optional cProfile hook,
# both switched by the environment. None of this changes mesh outputs:
# - ``_perf_record`` / ``_perf_note`` only store numbers/strings.
# - ``_run_with_profile`` executes the wrapped callable EXACTLY once; when
# POLYFOAMMESH_PROFILE is unset it is a bare passthrough, and when it is
# set a profiling failure is caught and never propagated into the run.
# The pipeline is split across several workers in the same process
# (GmshVolumeWorker -> gmshToFoam -> DualPolyWorker -> checkMesh ->
# decomposePar); each records its own stage into the registry and DualPolyWorker
# emits the aggregated ``[perf] stage times:`` line for the case. Keyed by the
# resolved case dir so a stale/other case can never be attributed here.
# See notes/perf_baseline_phase0.md.
# ------------------------------------------------------------------
PROFILE_ENV_VAR = "POLYFOAMMESH_PROFILE"
_PROFILE_TRUE = ("1", "true", "yes", "on")
#: resolved case dir -> {stage key: float seconds} and {meta key: str}
_PERF_TRACE: dict[str, dict[str, float]] = {}
_PERF_META: dict[str, dict[str, object]] = {}
#: Human-readable order/labels for the ``[perf] stage times:`` line.
_PERF_ORDER: tuple[tuple[str, str], ...] = (
("gmsh", "GMSH"),
("convert", "convert"),
("dual", "dual"),
("dual_write", "dual write"),
("bl_pre", "BL precompute"),
("bl_build", "BL build"),
("bl_reflow", "BL reflow"),
("bl_total", "BL total"),
("checkmesh", "checkMesh"),
("decompose", "decomposePar"),
("total", "total"),
)
def _profile_enabled() -> bool:
"""True when POLYFOAMMESH_PROFILE is set to a truthy value."""
try:
return os.environ.get(PROFILE_ENV_VAR, "").strip().lower() in _PROFILE_TRUE
except Exception: # noqa: BLE001 - never let env parsing break a run
return False
def _perf_key(case_dir) -> str:
try:
return str(Path(case_dir).resolve())
except Exception: # noqa: BLE001
return str(case_dir)
def _perf_reset(case_dir) -> None:
"""Drop any recorded stages for *case_dir* (start of a fresh run)."""
key = _perf_key(case_dir)
_PERF_TRACE.pop(key, None)
_PERF_META.pop(key, None)
def _perf_record(case_dir, stage: str, seconds: float) -> None:
try:
_PERF_TRACE.setdefault(_perf_key(case_dir), {})[stage] = float(seconds)
except Exception: # noqa: BLE001 - instrumentation must never raise
pass
def _perf_note(case_dir, key: str, value) -> None:
try:
_PERF_META.setdefault(_perf_key(case_dir), {})[key] = value
except Exception: # noqa: BLE001
pass
def _perf_format(case_dir) -> str | None:
"""One consistent ``[perf] stage times: ...`` line, or None if empty."""
trace = _PERF_TRACE.get(_perf_key(case_dir))
if not trace:
return None
meta = _PERF_META.get(_perf_key(case_dir), {})
parts: list[str] = []
for key, label in _PERF_ORDER:
val = trace.get(key)
if val is None:
continue
if key == "gmsh":
mode = meta.get("gmsh_mode")
suffix = f" ({mode})" if mode else ""
parts.append(f"GMSH {val:.1f}s{suffix}")
else:
parts.append(f"{label} {val:.1f}s")
if not parts:
return None
return "[perf] stage times: " + " | ".join(parts)
def _perf_log(case_dir, log_fn: Callable[[str], None]) -> None:
"""Emit the aggregated line built so far (best-effort, never raises)."""
try:
line = _perf_format(case_dir)
if line:
log_fn(line)
except Exception: # noqa: BLE001
pass
def _run_with_profile(case_dir, label: str, fn, log_fn: Callable[[str], None]):
"""Call ``fn()`` once; when POLYFOAMMESH_PROFILE is on, also cProfile it.
Writes ``profile_<label>.prof`` into the case dir and logs the top-20
functions by cumulative time as ``[perf] <label> hot: ...`` lines. A
profiling/dump failure is logged and swallowed - the run continues.
"""
if not _profile_enabled():
return fn()
pr = None
try:
import cProfile
pr = cProfile.Profile()
pr.enable()
except Exception as exc: # noqa: BLE001
log_fn(f"[perf] {label} profiling unavailable (ignored): {exc}")
pr = None
try:
return fn()
finally:
if pr is not None:
try:
pr.disable()
path = Path(case_dir) / f"profile_{label}.prof"
pr.dump_stats(str(path))
import pstats
stats = pstats.Stats(pr)
raw = getattr(stats, "stats", {}) or {}
rows = sorted(
raw.items(),
key=lambda kv: kv[1][3], # cumulative time
reverse=True,
)[:20]
log_fn(f"[perf] {label} profile saved: {path}")
for (_fname, _line, name), (cc, nc, _tt, ct, _callers) in rows:
log_fn(
f"[perf] {label} hot: {name} cumtime={ct:.3f}s "
f"tottime={_tt:.3f}s ncalls={nc}"
)
except Exception as exc: # noqa: BLE001 - never crash the run
log_fn(f"[perf] {label} profile dump failed (ignored): {exc}")
# ------------------------------------------------------------------
# Error classification
# ------------------------------------------------------------------
[docs]
class ErrorType(enum.Enum):
NONE = "none"
NON_WATERTIGHT = "non_watertight"
SURFACE_READ = "surface_read"
PATCH_NOT_FOUND = "patch_not_found"
FOAM_FATAL = "foam_fatal"
CRASH = "crash"
NON_MAPPABLE = "non_mappable"
BOUNDARY_NOT_FOUND = "boundary_not_found"
BL_FAILURE = "boundary_layer_failure"
def _extract_detail(full_output: str, max_lines: int = 10) -> str:
"""Extract the last error-relevant lines from the output for detail context."""
lines = [l.strip() for l in full_output.splitlines() if l.strip()]
error_lines = [l for l in lines if any(kw in l.lower() for kw in ["error", "fatal", "fail", "exception", "crash", "segmentation", "abort"])]
if error_lines:
return "\n".join(error_lines[-max_lines:])
# ✅ F-001: return multi-line string instead of single line
return "\n".join(lines[-max_lines:]) if lines else ""
[docs]
@dataclass
class ErrorInfo:
error_type: ErrorType = ErrorType.NONE
message: str = ""
suggestion: str = ""
detail: str = ""
[docs]
def analyze_error(full_output: str) -> ErrorInfo:
"""Classify cartesianMesh errors using cfMesh-specific patterns."""
lo = full_output.lower()
detail = _extract_detail(full_output)
bl_keywords = ["boundary layer", "prism layer", "near-wall layer"]
if any(kw in lo for kw in bl_keywords) and (
"failed" in lo or "collaps" in lo or "uncovered" in lo or "degenerate" in lo
):
return ErrorInfo(
ErrorType.BL_FAILURE,
"Boundary layer generation failed (prism layers collapsed or degenerate).",
"Reducing or disabling boundary layers and retrying.",
detail,
)
if "--> foam fatal error:" in lo or "foam fatal" in lo:
return ErrorInfo(
ErrorType.FOAM_FATAL,
"OpenFOAM encountered a fatal error during meshing.",
"Check the surface STL for issues. Try 'Auto-Suggest Cell Sizes' or repair the CAD geometry.",
detail,
)
if "floating point exception" in lo or "segmentation fault" in lo:
return ErrorInfo(
ErrorType.CRASH,
"cartesianMesh crashed (FPE or segfault).",
"Likely cause: degenerate geometry or extreme cell size ratio. Reduce max/min cell size ratio.",
detail,
)
# cfMesh's own C++ exceptions are frequently thrown as a bare
# `char const*`, which nothing catches -> std::terminate -> SIGABRT.
# The shell then reports "Aborted (core dumped)" and the process exits
# 134. Until this was added, that whole failure mode fell through to
# the empty ErrorInfo() at the bottom, i.e. the app decided "no error
# recognised" while cartesianMesh had in fact core-dumped, so the user
# got a silent/generic failure with no next step.
#
# Reproduced on the bf_roundtrip fixture, which is NOT a 1 m cylinder:
# its STL measures 0.002 m across (create_test_cylinder(1.0, 2.0) is in
# cadquery's native mm, and tessellate_patches converts mm->m). The test
# then asks for maxCellSize 0.25 — cells 125x larger than the whole body.
#
# An earlier version of this comment claimed the crash was "not monotonic
# in cell size" because 0.25/0.10/0.05 abort while 0.15 meshes fine, and
# advised nudging the size. A full sweep on that fixture showed the
# premise was wrong: 0.15 does not mesh fine, it produces 8 cells.
#
# maxCellSize vs bbox exit cells maxCellSize vs bbox exit cells
# 0.25 125x 134 8 0.0025 1.25x 0 8
# 0.20 100x 134 8 0.002 1.0x 0 32
# 0.15 75x 0 8 0.001 0.5x 0 120
# 0.12 60x 134 8 0.0005 0.25x 0 640
# 0.10 50x 134 8 0.0002 0.1x 0 5336
# 0.05 25x 134 8 0.0001 0.05x 0 26768
#
# So there is no lucky value to find. EVERY size at or above the bounding
# box collapses to the same degenerate 8-cell octree; the only thing that
# varies is whether cfMesh aborts or returns 0 with a useless mesh. The
# old advice steered the user straight into that silent-garbage case,
# which is worse than the crash. Refining below the geometry scale is the
# only thing that actually works — hence preflight_cell_size() below,
# which catches this before cfMesh ever runs.
if (
"terminate called after throwing" in lo
or "core dumped" in lo
or "aborted (core dumped)" in lo
):
return ErrorInfo(
ErrorType.CRASH,
"cartesianMesh aborted (uncaught internal cfMesh exception).",
"Most often this means Max Cell Size is too large for the "
"geometry: cells at or above the size of the model itself "
"collapse the octree and cfMesh dies while smoothing the "
"surface. Check the model's real dimensions (a CAD file "
"authored in mm is imported as metres) and set Max Cell Size "
"well below the smallest overall dimension. Do not simply try "
"a nearby value — a size that merely stops the crash can still "
"produce a degenerate mesh.",
detail,
)
if "non-mappable" in lo:
return ErrorInfo(
ErrorType.NON_MAPPABLE,
"Some surface patches could not be mapped to mesh boundaries.",
"This may produce a partial mesh. Check the log for which patches failed.",
detail,
)
if "non-watertight" in lo or "self-intersect" in lo:
return ErrorInfo(
ErrorType.NON_WATERTIGHT,
"Surface is not watertight or self-intersecting.",
"Try repairing the CAD geometry (e.g. fill holes and merge close vertices).",
detail,
)
if (
"boundary file not found" in lo
or "boundary region cannot be found" in lo
or "unable to find boundary" in lo
):
return ErrorInfo(
ErrorType.BOUNDARY_NOT_FOUND,
"OpenFOAM boundary file not found in constant/polyMesh/.",
"The mesh was not created or is incomplete. Check the cartesianMesh log.",
detail,
)
if ("cannot read" in lo or "cannot find file" in lo) and ("surface" in lo or ".stl" in lo):
return ErrorInfo(
ErrorType.SURFACE_READ,
"Cannot read surface STL file.",
"Check that the STL file exists and is not corrupted.",
detail,
)
if "cannot find patch" in lo or "unknown patch" in lo:
return ErrorInfo(
ErrorType.PATCH_NOT_FOUND,
"meshDict references a patch that does not exist in the STL.",
"Regenerate meshDict with the correct patch names.",
detail,
)
return ErrorInfo()
# ------------------------------------------------------------------
# Pre-flight guard — cell size vs geometry scale
# ------------------------------------------------------------------
# cfMesh cannot mesh a body with cells the size of the body. Measured on the
# bf_roundtrip fixture (see the sweep table in analyze_error above): at or
# above 1.25x the bounding box every run collapsed to 8 cells, and 5 of those
# 8 runs died with SIGABRT. At or below 1.0x, every run produced a sane,
# monotonically growing mesh. The failure is therefore predictable from the
# STL alone, with no cfMesh run needed — which is the whole point of doing it
# here rather than reading it out of a core dump afterwards.
# Below this many cells across the SMALLEST bounding-box dimension the run is
# refused. 1.0 is exactly the measured cliff (<=1.0x bbox always worked,
# >=1.25x bbox never did); the guard sits on the measurement rather than on a
# safety factor invented on top of it.
MIN_CELLS_ACROSS_FATAL = 1.0
# Advisory only. NOT a measured cliff: every sample below 4 cells across in
# the sweep was degenerate, but 4 is a round number chosen for margin, not a
# boundary anyone measured. It warns, it never blocks.
MIN_CELLS_ACROSS_WARN = 4.0
@dataclass
class PreflightIssue:
"""A problem detectable before launching cfMesh."""
fatal: bool
message: str
suggestion: str = ""
def _stl_bbox(path: Path) -> tuple[float, float, float] | None:
"""Return the (dx, dy, dz) extent of an STL, or None if unreadable.
Handles both ASCII and binary STL without pulling in trimesh: this runs
on the meshing hot path, and a bounding box is 20 lines of struct work.
Returns None rather than raising — a guard that cannot read the file must
fail OPEN and let cfMesh proceed, never block a run it does not
understand.
"""
try:
size = path.stat().st_size
with path.open("rb") as fh:
head = fh.read(84)
if len(head) < 84:
return None
# Binary STL: 80-byte header + uint32 count + 50 bytes/triangle.
n_tri = int.from_bytes(head[80:84], "little")
if size == 84 + 50 * n_tri and n_tri > 0:
lo = [float("inf")] * 3
hi = [float("-inf")] * 3
for _ in range(n_tri):
rec = fh.read(50)
if len(rec) < 50:
return None
# skip the 12-byte normal, read 3 vertices of 3 floats
coords = struct.unpack("<9f", rec[12:48])
for v in range(3):
for a in range(3):
c = coords[v * 3 + a]
lo[a] = min(lo[a], c)
hi[a] = max(hi[a], c)
return (hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2])
text = path.read_text(errors="replace")
verts = _STL_VERTEX_RE.findall(text)
if not verts:
return None
lo = [float("inf")] * 3
hi = [float("-inf")] * 3
for tri in verts:
for a in range(3):
c = float(tri[a])
lo[a] = min(lo[a], c)
hi[a] = max(hi[a], c)
return (hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2])
except (OSError, ValueError, struct.error):
return None
_STL_VERTEX_RE = re.compile(
r"vertex\s+([-\d.eE+]+)\s+([-\d.eE+]+)\s+([-\d.eE+]+)"
)
_MESHDICT_MAX_CELL_RE = re.compile(r"^\s*maxCellSize\s+([-\d.eE+]+)\s*;", re.MULTILINE)
_MESHDICT_SURFACE_RE = re.compile(r'^\s*surfaceFile\s+"?([^";]+)"?\s*;', re.MULTILINE)
def preflight_cell_size(case_dir: Path | str) -> PreflightIssue | None:
"""Detect a doomed maxCellSize/geometry combination before running cfMesh.
Returns None when the case looks runnable OR when the check cannot be
performed (missing meshDict, non-STL surface, unreadable STL). Never
guesses: an unknown case is allowed through.
"""
case_dir = Path(case_dir)
mesh_dict = case_dir / "system" / "meshDict"
try:
text = mesh_dict.read_text(errors="replace")
except OSError:
return None
m_size = _MESHDICT_MAX_CELL_RE.search(text)
m_surf = _MESHDICT_SURFACE_RE.search(text)
if not m_size or not m_surf:
return None
try:
max_cell = float(m_size.group(1))
except ValueError:
return None
if max_cell <= 0:
return None
surface = (case_dir / m_surf.group(1).strip()).resolve()
if surface.suffix.lower() != ".stl" or not surface.is_file():
# .fms and friends: not parsed here, so say nothing.
return None
bbox = _stl_bbox(surface)
if bbox is None:
return None
# Ignore genuinely flat dimensions (a 2D-ish extrusion): a zero span
# would otherwise report "0 cells across" for a perfectly valid case.
spans = [s for s in bbox if s > 0]
if not spans:
return None
smallest = min(spans)
cells_across = smallest / max_cell
if cells_across >= MIN_CELLS_ACROSS_WARN:
return None
detail = (
f"Max Cell Size is {max_cell:g}, but the surface measures "
f"{bbox[0]:g} x {bbox[1]:g} x {bbox[2]:g} - only "
f"{cells_across:.2f} cells across its smallest dimension."
)
if cells_across >= MIN_CELLS_ACROSS_FATAL:
return PreflightIssue(
fatal=False,
message=f"Max Cell Size is very coarse for this geometry. {detail}",
suggestion=(
f"Consider a Max Cell Size around {smallest / 20:g} "
f"(~20 cells across the model)."
),
)
return PreflightIssue(
fatal=True,
message=f"Max Cell Size is larger than the geometry itself. {detail}",
suggestion=(
"cfMesh cannot mesh a body with cells bigger than the body: the "
"octree collapses to a handful of cells and cartesianMesh "
"usually aborts while smoothing the surface. If the model looks "
f"far smaller than expected, check its units - {bbox[0]:g} m "
"across suggests a file authored in mm and read as metres. "
f"Otherwise set Max Cell Size to about {smallest / 20:g} "
f"(~20 cells across the model)."
),
)
# ------------------------------------------------------------------
# MeshWorker — interruptible subprocess runner
# ------------------------------------------------------------------
[docs]
class MeshWorker(QObject):
"""Runs cartesianMesh via WSL2 in a background QThread.
Reads stdout from a dedicated reader thread (NOT select.select(), which
on Windows only works on sockets, never on pipes) so that interruption
requests are still honoured while the subprocess is silent for a long
time.
Contract: run() ALWAYS emits `finished` exactly once, on every path
including unexpected errors. Callers block on that signal, so a missing
emit is not a lost error message — it is a permanent hang.
"""
log_line = Signal(str)
finished = Signal(int, str)
cell_count_found = Signal(int)
progress_update = Signal(int)
eta_update = Signal(str)
# V1.1: scan stdout line for the cell count (F2)
# cfMesh v2512 output looks like:
# 21027 vertices
# 53740 faces
# 16400 cells <- number FIRST, label SECOND
# We also accept the label-first form (legacy / other formats).
_CELLS_RE = re.compile(
r"(?:\b(\d[\d,]*)\s+cells\b)|(?:\bcells\s+(\d[\d,]*))",
re.IGNORECASE,
)
_PROGRESS_PCT_RE = re.compile(
r"(?:[Pp]rogress|Done)\s*[:=]?\s*(\d{1,3})\s*%",
)
# V1.1: subprocess PID for fallback kill (S7)
_PID_FILE = "process.pid"
# Ordered cfMesh v2512 pipeline stages -> progress-bar bucket start.
# Matched against real cartesianMesh output lines so the bar advances by
# STAGE (read -> octree -> refine -> smooth -> check -> write) instead of
# jumping on the row-count heuristic. Buckets are the plan's example
# ranges (read 0-10, octree 10-40, refine 40-60, smooth 60-80, check
# 80-90, write 90-100). The row-count heuristic remains only as a
# fallback when no stage line and no explicit % is seen.
_STAGE_PATTERNS = [
(re.compile(r"reading surface", re.IGNORECASE), "read", 0),
(re.compile(r"creating octree|building octree", re.IGNORECASE), "octree", 10),
(re.compile(r"refin", re.IGNORECASE), "refine", 40),
(re.compile(r"smooth", re.IGNORECASE), "smooth", 60),
(re.compile(r"checking the mesh|checking mesh", re.IGNORECASE), "check", 80),
(re.compile(r"writing mesh|writing polymesh", re.IGNORECASE), "write", 90),
]
# Maximum wall-clock time for a single meshing run (hours:min:sec)
# 4 hours supports ~25M cells at ~1800 cells/sec sustained throughput.
MAX_RUNTIME_SECONDS = 14400 # 4 hours
def __init__(self, case_dir: Path | str, of_config: OFConfig, parent=None):
super().__init__(parent)
self._case_dir = Path(case_dir).resolve()
self._of_config = of_config
self._pid: int | None = None
self._cell_count_emitted: bool = False
self._start_time: float = 0.0
def _process_line(self, line: str, full_output: list[str]):
"""Append, forward to log panel, and detect the cell count + progress."""
clean = line.rstrip("\n\r")
full_output.append(clean)
self.log_line.emit(clean)
# Progress percentage from explicit OpenFOAM output (highest
# priority — authoritative when present). Also emit an ETA derived
# from it; never invent an ETA without explicit % data.
m = self._PROGRESS_PCT_RE.search(clean)
if m:
try:
pct = int(m.group(1))
self.progress_update.emit(min(pct, 100))
self._emit_eta(pct)
except (ValueError, AttributeError):
pass
return
# Stage match: advance the bar by cfMesh pipeline STAGE (read ->
# octree -> refine -> smooth -> check -> write) instead of by row
# count, so a long single stage doesn't look frozen or jumpy.
stage = self._match_stage(clean)
if stage is not None:
name, bucket = stage
self.progress_update.emit(bucket)
self.log_line.emit(f"[stage] {name}")
return
# Estimate progress from line count — after 500 lines switch to
# indeterminate busy animation so a 10-min large mesh doesn't look
# frozen at 95%. The main window shows setRange(0,0) for value==-1.
n_lines = len(full_output)
if n_lines < 20:
pct = n_lines * 5
self.progress_update.emit(min(int(pct), 19))
elif n_lines < 100:
pct = 20 + (n_lines - 20) * 0.5
self.progress_update.emit(min(int(pct), 59))
elif n_lines < 500:
pct = 60 + (n_lines - 100) * 0.1
self.progress_update.emit(min(int(pct), 94))
else:
# Large mesh: keep bar pulsing + periodic time hint in log
self.progress_update.emit(-1)
if n_lines % 200 == 0:
elapsed = int(_now() - self._start_time) if self._start_time else 0
mins, secs = divmod(elapsed, 60)
self.log_line.emit(f"[meshing] still running... {mins}m{secs:02d}s elapsed ({n_lines} log lines)")
# Cell count detection (unchanged)
if not self._cell_count_emitted:
m = self._CELLS_RE.search(clean)
if m:
raw = m.group(1) or m.group(2)
try:
n = int(raw.replace(",", ""))
self.cell_count_found.emit(n)
self._cell_count_emitted = True
except (ValueError, AttributeError):
logger.debug("Could not parse cell count from line: %s", clean)
def _match_stage(self, clean: str) -> tuple[str, int] | None:
"""Return (stage_name, bucket_start) for a cfMesh stage line, else None."""
for pattern, name, bucket in self._STAGE_PATTERNS:
if pattern.search(clean):
return name, bucket
return None
def _emit_eta(self, pct: int) -> None:
"""Emit an ETA string to the status bar, derived ONLY from an explicit
percentage: eta = elapsed * (100 - pct) / pct. Never invents data."""
if pct <= 0 or not self._start_time:
return
elapsed = _now() - self._start_time
if elapsed <= 0:
return
remaining = elapsed * (100 - pct) / pct
total = elapsed + remaining
self.eta_update.emit(
f"ETA {int(remaining // 60)}m{int(remaining % 60):02d}s "
f"(~{int(total // 60)}m{int(total % 60):02d}s total, {pct}%)"
)
[docs]
@Slot()
def run(self):
valid, msg = OFConfig.validate_case_path(self._case_dir)
if not valid:
self.log_line.emit(f"ERROR: {msg}")
self.finished.emit(1, msg)
return
# Pre-flight: a cell size at or above the model size is a guaranteed
# failure, and cfMesh reports it as a core dump minutes later (or,
# worse, as a successful 8-cell mesh). Catch it here, where we can
# still say something useful about WHY.
issue = preflight_cell_size(self._case_dir)
if issue is not None:
if issue.fatal:
self.log_line.emit(f"ERROR: {issue.message}")
self.log_line.emit(issue.suggestion)
self.finished.emit(1, f"{issue.message}\n{issue.suggestion}")
return
self.log_line.emit(f"WARNING: {issue.message}")
if issue.suggestion:
self.log_line.emit(issue.suggestion)
try:
if hasattr(self._of_config, 'build_serial_tmpfs_command'):
try:
cmd = self._of_config.build_serial_tmpfs_command(self._case_dir)
except Exception:
cmd = self._of_config.build_command(self._case_dir)
else:
cmd = self._of_config.build_command(self._case_dir)
except Exception:
cmd = self._of_config.build_command(self._case_dir)
self.log_line.emit(f"[cmd] {' '.join(cmd)}")
process = None
full_output: list[str] = []
interrupted = False
self._pid = None
_stderr_thread: threading.Thread | None = None
_err_lines: list[str] = []
self._start_time = _now()
try:
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
bufsize=1,
**_posix_popen_kwargs(),
)
self._pid = process.pid
self.progress_update.emit(0)
def _drain_stderr():
if process and process.stderr:
for line in process.stderr:
_err_lines.append(line)
_stderr_thread = threading.Thread(
target=_drain_stderr, daemon=True
)
_stderr_thread.start()
except FileNotFoundError:
self.log_line.emit("ERROR: WSL not found. Is WSL2 installed?")
self.finished.emit(1, "WSL not found")
return
except (OSError, PermissionError) as exc:
self.log_line.emit(f"ERROR: Failed to launch meshing process: {exc}")
self.finished.emit(1, f"Process launch failed: {exc}")
return
except Exception as exc:
self.log_line.emit(f"ERROR: Unexpected meshing launch error: {exc}")
self.finished.emit(1, f"Unexpected error: {exc}")
return
reader_error: Exception | None = None
try:
if process.stdout:
# V1.1: threading-based reader (Windows: select only works on sockets, not pipes)
_stop_reader = threading.Event()
_reader_done = threading.Event()
def _reader():
try:
for line in process.stdout:
if _stop_reader.is_set():
break
self._process_line(line, full_output)
if len(full_output) % 3 == 0:
self.progress_update.emit(-1)
except Exception as exc: # noqa: BLE001 - reported below
# Previously "except Exception: pass". This thread
# reads the mesher's ENTIRE output; swallowing a
# failure here silently truncated the log and left
# the run looking normal, with nothing to diagnose
# from. Hand it to run() instead, which folds it
# into the reported output and fails the run.
nonlocal reader_error
reader_error = exc
logger.exception("cartesianMesh output reader failed")
finally:
_reader_done.set()
_stdout_thread = threading.Thread(target=_reader, daemon=True)
_stdout_thread.start()
# Check interruption every 0.5s while reader is alive
while not _reader_done.wait(timeout=0.5):
if QThread.currentThread().isInterruptionRequested():
self.log_line.emit(
"[cancelled] Interruption requested, killing process..."
)
_stop_reader.set()
interrupted = True
break
if _now() - self._start_time > self.MAX_RUNTIME_SECONDS:
self.log_line.emit(
f"[timeout] Meshing exceeded {self.MAX_RUNTIME_SECONDS}s "
"— killing process."
)
_stop_reader.set()
interrupted = True
break
# Collect any remaining lines after reader finishes
if not _stop_reader.is_set():
_stdout_thread.join(timeout=2)
if not _reader_done.is_set():
# Reader thread still running — wait for it to finish
# rather than reading stdout concurrently (race condition).
_stdout_thread.join(timeout=10)
except Exception as exc:
# MUST NOT propagate: this block used to have only a `finally`,
# so any unexpected exception here escaped run() and skipped the
# `self.finished.emit(...)` at the end of the method. Every
# caller waits on that signal (the GUI's progress flow, and the
# QEventLoop in tests/test_e2e_workflow.py), so the failure did
# not surface as an error — it surfaced as an app that never
# finishes meshing and never says why.
#
# Recorded, not swallowed: it goes to the logger AND into the
# output the caller receives, and execution falls through to the
# normal emit below so the run terminates as a FAILURE instead of
# hanging.
logger.exception("Unexpected error while reading cartesianMesh output")
reader_error = exc # recorded once, appended below with the rest
finally:
if _stderr_thread is not None and _stderr_thread.is_alive():
_stderr_thread.join(timeout=2)
for line in _err_lines:
full_output.append(f"[stderr] {line.rstrip()}")
if process.poll() is None:
process.kill()
# V1.1: fallback kill via os.kill (S7 fix)
if self._pid is not None:
try:
self._kill_process_tree(self._pid, self._of_config.wsl_distro)
except Exception as exc:
logger.debug("Fallback kill failed: %s", exc)
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
logger.warning("Subprocess did not terminate within 5s after kill")
if reader_error is not None:
full_output.append(f"[error] Unexpected meshing error: {reader_error}")
returncode = process.returncode if process.returncode is not None else -1
if reader_error is not None and returncode == 0:
# The mesher process itself may well have exited 0, but we failed
# to read/parse its output, so we cannot claim the run succeeded:
# downstream steps would consume a mesh we never validated.
# Report a failure and let analyze_error()/the caller surface it.
returncode = -1
if interrupted:
full_output.append("[cancelled] Process was interrupted by user request.")
combined = "\n".join(full_output)
log_path = self._case_dir / "log.meshing"
try:
log_path.write_text(combined + "\n", encoding="utf-8", errors="replace")
except OSError:
logger.warning("Could not write log.meshing to %s", log_path)
self.progress_update.emit(100)
self.finished.emit(returncode, combined)
def _kill_process_tree(self, pid: int, wsl_distro: str | None = None):
"""Kill process and its children recursively.
Uses ``taskkill /T`` on Windows, ``killpg`` on POSIX. The OpenFOAM
child is launched with ``start_new_session=True`` (see
``_posix_popen_kwargs``), so its process-group id equals its pid;
``killpg(pid)`` therefore targets the child's own group and can
never SIGKILL the GUI. The ``pid != own_pgid`` guard is a defensive
second line: if a child were ever launched without the new session,
it would share our group and we must NOT killpg it.
Args:
pid: Process ID to terminate.
wsl_distro: Unused on POSIX (kept for API compatibility); WSL
distro name for the Windows fallback.
"""
if sys.platform == "win32":
with suppress(OSError, subprocess.TimeoutExpired):
subprocess.run(
["taskkill", "/PID", str(pid), "/T", "/F"],
capture_output=True,
timeout=5,
)
return
try:
own_pgid = os.getpgid(0)
except OSError:
own_pgid = -1
with suppress(OSError, ProcessLookupError):
if pid != own_pgid:
os.killpg(pid, signal.SIGKILL)
else:
os.kill(pid, signal.SIGKILL)
# ------------------------------------------------------------------
# RetryRunner — orchestrates retries with BL fallback and exit-15 recovery
# ------------------------------------------------------------------
[docs]
class RetryRunner(QObject):
"""Orchestrates cartesianMesh with up to 3 automatic retries on known errors.
V1.1 additions:
- F2: cell_count_relay for real cell count.
- F6: automatic fallback without boundary layers if BL causes failure.
- F7: exit-code 15 treated as non-fatal for unconnected regions.
"""
MAX_RETRIES = 3
cell_count_found = Signal(int)
log_emitted = Signal(str)
cell_count_relay = Signal(int)
progress_update = Signal(int)
eta_update = Signal(str)
_UNCONNECTED_RE = re.compile(r"unconnected|non-mappable", re.IGNORECASE)
def __init__(self, of_config: OFConfig, parent=None):
super().__init__(parent)
self._of_config = of_config
self._attempt = 0
self._case_dir: Path = Path(".")
self._thread: QThread | None = None
self._worker: MeshWorker | None = None
self._is_running = False
self._fix_action: Callable[[ErrorInfo, int], bool] | None = None
self._on_log: Callable[[str], None] | None = None
self._on_finished: Callable[[int, str, int], None] | None = None
self._bl_params: dict | None = None
self._bl_retried: bool = False
self._max_cell: float = 0.05
self._min_cell: float = 0.01
self._patch_cell_size: dict[str, float] | None = None
self._patch_names: list[str] | None = None
@property
def is_running(self) -> bool:
return self._is_running
[docs]
def thread(self) -> QThread | None:
return self._thread
[docs]
def request_stop(self):
self._is_running = False
if self._thread is not None:
self._thread.requestInterruption()
[docs]
def run(
self,
case_dir: Path | str,
on_log: Callable[[str], None] | None = None,
on_finished: Callable[[int, str, int], None] | None = None,
fix_action: Callable[[ErrorInfo, int], bool] | None = None,
bl_params: dict | None = None,
max_cell: float = 0.05,
min_cell: float = 0.01,
patch_cell_size: dict[str, float] | None = None,
patch_names: list[str] | None = None,
):
self._attempt = 0
self._case_dir = Path(case_dir).resolve()
self._on_log = on_log
self._on_finished = on_finished
self._fix_action = fix_action
self._bl_params = bl_params
self._bl_retried = False
self._max_cell = max_cell
self._min_cell = min_cell
self._patch_cell_size = patch_cell_size
self._patch_names = patch_names
self._do_attempt()
# ------------------------------------------------------------------
# internal — B2 fix: no broad sig.disconnect() on relay signals
# ------------------------------------------------------------------
def _cleanup_previous(self):
if self._worker is not None:
try:
self._worker.log_line.disconnect()
except (RuntimeError, TypeError):
pass
try:
self._worker.finished.disconnect()
except (RuntimeError, TypeError):
pass
try:
self._worker.cell_count_found.disconnect()
except (RuntimeError, TypeError):
pass
# V1.1: DO NOT delete worker before thread stops (B14 fix)
self._worker = None
if self._thread is not None:
if self._thread.isRunning():
self._thread.quit()
if not self._thread.wait(30000):
logger.warning("QThread did not quit within 30s — forcing terminate")
self._thread.terminate()
self._thread.wait(3000)
# V1.1: delete thread AFTER it has fully stopped (B14 fix)
self._thread.deleteLater()
self._thread = None
# V1.1: call deleteLater on old worker AFTER thread is done (B14 fix)
if self._worker is not None:
self._worker.deleteLater()
self._worker = None
def _do_attempt(self):
self._attempt += 1
if self._attempt > 1 and self._on_log:
self._on_log(f"[retry {self._attempt}/{self.MAX_RETRIES}]")
self._cleanup_previous()
self._is_running = True
case_str = str(self._case_dir)
octo.log_event("retry_runner", "attempt",
f"attempt={self._attempt}/{self.MAX_RETRIES} case_dir={case_str}")
self._thread = QThread()
self._worker = MeshWorker(self._case_dir, self._of_config)
self._worker.moveToThread(self._thread)
# V1.1: relay connections — bounded to new worker, not disconnected externally (B2 fix)
self._worker.log_line.connect(self.log_emitted, Qt.DirectConnection)
self._worker.cell_count_found.connect(self.cell_count_relay, Qt.DirectConnection)
if self._on_log:
self._worker.log_line.connect(self._on_log, Qt.QueuedConnection)
self._worker.progress_update.connect(self.progress_update, Qt.DirectConnection)
self._worker.eta_update.connect(self.eta_update, Qt.DirectConnection)
self._worker.finished.connect(self._on_attempt_finished, Qt.QueuedConnection)
self._worker.finished.connect(lambda *a: self._thread.quit(), Qt.QueuedConnection)
self._worker.cell_count_found.connect(self.cell_count_found, Qt.QueuedConnection)
self._thread.started.connect(self._worker.run)
self._worker.destroyed.connect(self._thread.quit)
self._thread.start()
def _regenerate_meshdict_without_bl(self):
"""Regenerate meshDict without boundary layers.
Was missing `patch_names=`, so `renameBoundary` never got emitted here
— every inlet/outlet/wall patch silently reverted to cfMesh's default
`wall` type on this fallback. Since this is the SAME RetryRunner the
main "Generate Mesh" path uses (not just an unwired workflow), any real
case whose boundary layers fail — common on complex or thin geometry —
would silently lose correct patch typing on the automatic retry.
"""
from polyfoammesh.core.meshdict_gen import write_meshdict
write_meshdict(
self._case_dir,
max_cell_size=self._max_cell,
min_cell_size=self._min_cell,
patch_cell_size=self._patch_cell_size,
patch_names=self._patch_names,
)
logger.info("Regenerated meshDict without boundary layers.")
@Slot(int, str)
def _on_attempt_finished(self, exit_code: int, output: str):
self._is_running = False
case_str = str(self._case_dir)
octo.log_event("retry_runner", "attempt_finished",
f"exit_code={exit_code} attempt={self._attempt}/{self.MAX_RETRIES} case_dir={case_str}")
# V1.1: F7 — exit code 15 may be non-fatal for unconnected regions
if exit_code == 15 and self._UNCONNECTED_RE.search(output):
if self._on_log:
self._on_log(
"[WARN] Exit code 15 with unconnected/non-mappable regions. "
"Checking for partial mesh..."
)
points_file = self._case_dir / "constant" / "polyMesh" / "points"
if points_file.exists():
logger.info(
"polyMesh/points found despite exit 15; treating as success (F7)."
)
if self._on_log:
self._on_log(
"[meshing] Exit 15 but polyMesh/points exists — "
"partial mesh generated, continuing."
)
if self._on_finished:
self._on_finished(0, output, self._attempt)
self._cleanup_previous()
return
else:
if self._on_log:
self._on_log(
"[WARN] Exit 15 and no polyMesh/points found — "
"mesh generation incomplete."
)
if exit_code == 0:
if self._on_finished:
self._on_finished(exit_code, output, self._attempt)
self._cleanup_previous()
return
# V1.1: F6 — BL fallback: retry once without boundary layers
if (
self._bl_params is not None
and self._bl_params.get("nLayers")
and not self._bl_retried
and exit_code != 0
):
self._bl_retried = True
if self._on_log:
self._on_log(
"[WARN] Boundary layers failed. Retrying without BL..."
)
self._on_log(
"[SUBSTITUTED] Algorithm substituted: boundary layer "
"disabled (it fails on this geometry)."
)
self._on_log("[fallback] Regenerating meshDict without boundaryLayers.")
try:
self._regenerate_meshdict_without_bl()
logger.info(
"BL fallback: meshDict regenerated without BL, retrying (F6)."
)
octo.log_event("retry_runner", "bl_fallback",
f"attempt={self._attempt} case_dir={case_str}")
self._do_attempt()
return
except Exception as exc:
logger.error("BL fallback meshDict regeneration failed: %s", exc)
if self._on_log:
self._on_log(f"[ERROR] BL fallback meshDict failed: {exc}")
error = analyze_error(output)
if error.error_type == ErrorType.NONE:
if self._on_log:
self._on_log(
"[error-detail] No specific pattern recognised "
"- click 'Show Log' for the full log."
)
self._on_log(
"[error-detail] Raw exit code: %d | Last 5 lines:\n %s"
% (exit_code, "\n ".join(output.strip().split("\n")[-5:]))
)
if self._on_finished:
self._on_finished(exit_code, output, self._attempt)
self._cleanup_previous()
return
if self._attempt < self.MAX_RETRIES and self._fix_action and self._fix_action(error, self._attempt):
octo.log_event("retry_runner", "auto_fix_retry",
f"error={error.error_type.value} attempt={self._attempt} case_dir={case_str}")
self._do_attempt()
return
if self._on_log:
self._on_log(f"[error] {error.message}")
self._on_log(f"[suggestion] {error.suggestion}")
if self._on_finished:
self._on_finished(exit_code, output, self._attempt)
self._cleanup_previous()
[docs]
def terminate(self):
"""Kill subprocess and cleanup. Call before starting a new run."""
self._is_running = False
if self._thread is not None and self._thread.isRunning():
self._thread.requestInterruption()
# V1.1: wait a bit for the select loop to pick up the interruption
if not self._thread.wait(30000):
self._thread.terminate()
self._thread.wait(3000)
self._cleanup_previous()
# ------------------------------------------------------------------
# V1.1: MeshQualityReport + checkMesh parsing
# ------------------------------------------------------------------
[docs]
@dataclass
class MeshQualityReport:
"""Structured output from checkMesh."""
cells: int = 0
faces: int = 0
points: int = 0
max_non_ortho: float = 0.0
avg_non_ortho: float = 0.0
max_skewness: float = 0.0
avg_skewness: float = 0.0
max_aspect_ratio: float = 0.0
neg_cells: int = 0
min_volume: float = 0.0
has_fatal: bool = False
raw_output: str = ""
@property
def passed(self) -> bool:
if self.has_fatal or self.neg_cells > 0:
return False
# OpenFOAM can finish with return code 0 while reporting failed
# topology/geometry checks. Do not show a misleading PASS banner.
if re.search(r"Failed\s+\d+\s+mesh\s+checks?", self.raw_output, re.IGNORECASE):
return False
return True
@property
def status(self) -> str:
if self.has_fatal:
return "❌ checkMesh FATAL"
if self.neg_cells > 0:
return f"❌ {self.neg_cells} negative-volume cells"
warns = []
if self.max_non_ortho > 65:
warns.append(f"non-ortho={self.max_non_ortho:.1f}")
if self.max_skewness > 4:
warns.append(f"skewness={self.max_skewness:.2f}")
if self.max_aspect_ratio > 1000:
warns.append(f"aspect={self.max_aspect_ratio:.0f}")
if warns:
return f"⚠️ {', '.join(warns)}"
return "✅ PASS"
[docs]
def summary(self) -> str:
"""One-line summary for logs/status bars."""
return (
f"{self.cells} cells, {self.faces} faces, "
f"{self.points} points — {self.status}"
)
[docs]
def to_dict(self) -> dict:
return {
"metrics": {
"cells": self.cells,
"faces": self.faces,
"points": self.points,
"max_non_ortho": self.max_non_ortho,
"avg_non_ortho": self.avg_non_ortho,
"max_skewness": self.max_skewness,
"avg_skewness": self.avg_skewness,
"max_aspect_ratio": self.max_aspect_ratio,
"neg_cells": self.neg_cells,
"min_volume": self.min_volume,
},
"passed": self.passed,
"status": self.status,
"raw_output": self.raw_output,
}
# Regexes for checkMesh output
_CHECK_CELLS_RE = re.compile(r"cells:\s+(\d+)", re.IGNORECASE)
_CHECK_FACES_RE = re.compile(r"faces:\s+(\d+)", re.IGNORECASE)
_CHECK_POINTS_RE = re.compile(r"points:\s+(\d+)", re.IGNORECASE)
# A float that does NOT swallow a trailing sentence period. checkMesh writes
# "Min volume = 6.30328e-06. Max volume = ..." and a `[\d.eE+-]+` class ate the
# final '.', so float() raised ValueError on real output.
_F = r"[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?"
# Real OpenFOAM v2512 phrasing differs from the older form these regexes were
# written against, and the metrics don't always carry an average:
# "Mesh non-orthogonality Max: 61.5453 average: 15.0436" (colon form)
# "Max skewness = 0.657556 OK." (no average)
# "Max aspect ratio = 39.5564 OK." (no average)
# Requiring "average = " with re.DOTALL meant these silently never matched, so
# quality was reported as 0/perfect regardless of the real mesh. Accept both
# spellings, make the average optional, and stay within one line ([^\n]) so a
# missing average can't drag the match onto an unrelated later line.
_CHECK_NONORTHO_RE = re.compile(
rf"(?:Mesh non-orthogonality\s+Max:|Max non-orthogonality\s*=)\s*({_F})"
rf"(?:[^\n]*?average\s*[:=]\s*({_F}))?",
re.IGNORECASE,
)
_CHECK_SKEW_RE = re.compile(
rf"Max skewness\s*[:=]\s*({_F})(?:[^\n]*?average\s*[:=]\s*({_F}))?",
re.IGNORECASE,
)
_CHECK_ASPECT_RE = re.compile(
rf"Max aspect ratio\s*[:=]\s*({_F})(?:[^\n]*?average\s*[:=]\s*({_F}))?",
re.IGNORECASE,
)
_CHECK_NEGVOL_RE = re.compile(
r"There are\s+(\d+)\s+cells[^\n]*?negative volume"
r"|Writing\s+(\d+)\s+cells with negative volume",
re.IGNORECASE,
)
_CHECK_MINVOL_RE = re.compile(rf"Min volume\s*=\s*({_F})", re.IGNORECASE)
_CHECK_MESH_OK_RE = re.compile(r"^\s*Mesh OK\.", re.IGNORECASE | re.MULTILINE)
_CHECK_FATAL_RE = re.compile(
r"FOAM FATAL|FATAL ERROR|--> FOAM FATAL", re.IGNORECASE
)
[docs]
def parse_checkmesh_output(text: str) -> MeshQualityReport:
"""Parse checkMesh stdout into a structured report."""
r = MeshQualityReport(raw_output=text)
r.has_fatal = bool(_CHECK_FATAL_RE.search(text))
m = _CHECK_CELLS_RE.search(text)
if m:
r.cells = int(m.group(1))
m = _CHECK_FACES_RE.search(text)
if m:
r.faces = int(m.group(1))
m = _CHECK_POINTS_RE.search(text)
if m:
r.points = int(m.group(1))
m = _CHECK_NONORTHO_RE.search(text)
if m:
r.max_non_ortho = float(m.group(1))
if m.group(2) is not None:
r.avg_non_ortho = float(m.group(2))
m = _CHECK_SKEW_RE.search(text)
if m:
r.max_skewness = float(m.group(1))
if m.group(2) is not None:
r.avg_skewness = float(m.group(2))
m = _CHECK_ASPECT_RE.search(text)
if m:
r.max_aspect_ratio = float(m.group(1))
m = _CHECK_NEGVOL_RE.search(text)
if m:
r.neg_cells = int(m.group(1) or m.group(2))
m = _CHECK_MINVOL_RE.search(text)
if m:
r.min_volume = float(m.group(1))
return r
# ------------------------------------------------------------------
# FMS (Feature Mesh Surface) generation via surfaceFeatureEdges
# ------------------------------------------------------------------
[docs]
def generate_fms(
case_dir: Path | str,
angle: float = 60.0,
timeout: int = 60,
) -> Path | None:
"""Run surfaceFeatureEdges to produce an .fms file from the surface STL.
Wraps the WSL2 call to ``surfaceFeatureEdges -angle <angle>``,
run from within the case directory so that output paths are relative
and OpenFOAM can find its config files.
The FMS file is written to ``constant/triSurface/surface.fms``.
Args:
case_dir: OpenFOAM case directory (must contain
``constant/triSurface/surface.stl``).
angle: Feature angle threshold in degrees (default 30).
timeout: Max wall-clock seconds for the WSL call.
Returns:
Path to the generated ``.fms`` file, or ``None`` on failure.
"""
from polyfoammesh.config import OFConfig
cfg = OFConfig()
case_dir = Path(case_dir).resolve()
stl_path = case_dir / "constant" / "triSurface" / "surface.stl"
fms_path = case_dir / "constant" / "triSurface" / "surface.fms"
if not stl_path.exists():
logger.warning("generate_fms: %s not found", stl_path)
return None
linux = cfg._quoted_linux_path(case_dir)
in_stl = "constant/triSurface/surface.stl"
out_fms = "constant/triSurface/surface.fms"
cmd = (
f"source {shlex.quote(cfg.env_script)} 2>/dev/null; "
f"cd {linux} && "
f"surfaceFeatureEdges -angle {angle} {in_stl} {out_fms} 2>&1"
)
try:
r = subprocess.run(
cfg._build_wsl_cmd(cmd),
capture_output=True, text=True, timeout=timeout,
)
if r.returncode == 0 and fms_path.exists():
# Check if the FMS contains actual feature vertices.
# An FMS with 0 feature vertices (only the patch header) does not
# help and may degrade quality on curved surfaces (external_aero).
try:
fms_text = fms_path.read_text(encoding="ascii", errors="replace")
# Format: first non-header line is patch count, second is
# vertex count. If vertex count >= 3 there are real features.
lines = [l.strip() for l in fms_text.splitlines() if l.strip()]
if len(lines) >= 2:
try:
n_verts = int(lines[1])
if n_verts < 3:
logger.info(
"generate_fms: %s has %d feature vertices "
"(< 3), skipping FMS",
fms_path, n_verts,
)
return None
except (ValueError, IndexError):
pass
except OSError:
pass
logger.info("generate_fms: created %s (angle=%.1f°)", fms_path, angle)
return fms_path
logger.warning(
"generate_fms: surfaceFeatureEdges rc=%d", r.returncode,
)
return None
except subprocess.TimeoutExpired:
logger.warning("generate_fms: timed out (%ds)", timeout)
return None
except FileNotFoundError:
logger.warning("generate_fms: WSL not found")
return None
# ------------------------------------------------------------------
# V1.1: CheckMeshWorker — runs checkMesh in a background thread
# ------------------------------------------------------------------
[docs]
class CheckMeshWorker(QObject):
"""Runs checkMesh via WSL2 in a QThread and returns a quality report."""
log_line = Signal(str)
finished = Signal(object)
failed = Signal(str)
def __init__(self, case_dir: Path | str, of_config: OFConfig, parent=None,
pipeline_staged: bool = False):
super().__init__(parent)
self._case_dir = Path(case_dir).resolve()
self._of_config = of_config
self._proc_holder: dict = {}
self._cancelled = False
# Default OFF until validated: run checkMesh inside WSL native storage
# instead of on the slow 9P /mnt/c bridge.
self._pipeline_staged = pipeline_staged
[docs]
@Slot()
def cancel(self):
"""Kill the live subprocess (wsl.exe), if any is running right
now. See GmshSurfaceWorker.cancel for why this exists — same gap
here even though _on_cancel_meshing's _kill_wsl_processes() gives
this one partial coverage already, killing wsl.exe directly by
PID is faster and doesn't depend on process-name matching."""
self._cancelled = True
proc = self._proc_holder.get("proc")
if proc is not None and proc.poll() is None:
_kill_pid_tree(proc.pid)
[docs]
@Slot()
def run(self):
t_checkmesh0 = time.perf_counter()
if self._pipeline_staged:
from polyfoammesh.config import extract_poly_mesh_archive
cmd = self._of_config.build_staged_pipeline_command(
self._case_dir, steps=["checkMesh"],
)
self.log_line.emit(f"[checkMesh] {' '.join(cmd)}")
try:
returncode, stdout_lines, stderr_lines, timed_out = _stream_subprocess(
cmd, None, 600,
on_line=lambda ln: self.log_line.emit(f"[checkMesh] {ln}"),
proc_holder=self._proc_holder,
)
extract_poly_mesh_archive(self._case_dir)
full = "\n".join(stdout_lines) + "\n" + "\n".join(stderr_lines)
except FileNotFoundError:
self.log_line.emit("[checkMesh] WSL not found")
self.failed.emit("WSL not found")
return
except Exception as exc:
if not self._cancelled:
self.log_line.emit(f"[checkMesh] ERROR: {exc}")
self.failed.emit(str(exc))
return
if self._cancelled:
self.log_line.emit("[checkMesh] Cancelled.")
return
if timed_out:
self.log_line.emit("[checkMesh] TIMEOUT (600s)")
self.failed.emit("checkMesh timed out after 600s")
return
report = parse_checkmesh_output(full)
self.log_line.emit(
f"[checkMesh] cells={report.cells} faces={report.faces} "
f"nonOrtho={report.max_non_ortho:.1f} "
f"skewness={report.max_skewness:.2f} "
f"aspectRatio={report.max_aspect_ratio:.0f}"
)
if not report.passed:
self.log_line.emit(f"[checkMesh] {report.status}")
_perf_record(
self._case_dir, "checkmesh",
time.perf_counter() - t_checkmesh0,
)
_perf_log(self._case_dir, self.log_line.emit)
self.finished.emit(report)
return
cmd = self._of_config.build_check_mesh_cmd(self._case_dir)
self.log_line.emit(f"[checkMesh] {' '.join(cmd)}")
try:
returncode, stdout_lines, stderr_lines, timed_out = _stream_subprocess(
cmd, None, 600,
on_line=lambda ln: self.log_line.emit(f"[checkMesh] {ln}"),
proc_holder=self._proc_holder,
)
full = "\n".join(stdout_lines) + "\n" + "\n".join(stderr_lines)
except FileNotFoundError:
self.log_line.emit("[checkMesh] WSL not found")
self.failed.emit("WSL not found")
return
except Exception as exc:
if not self._cancelled:
self.log_line.emit(f"[checkMesh] ERROR: {exc}")
self.failed.emit(str(exc))
return
if self._cancelled:
self.log_line.emit("[checkMesh] Cancelled.")
return
if timed_out:
self.log_line.emit("[checkMesh] TIMEOUT (600s)")
self.failed.emit("checkMesh timed out after 600s")
return
report = parse_checkmesh_output(full)
self.log_line.emit(
f"[checkMesh] cells={report.cells} faces={report.faces} "
f"nonOrtho={report.max_non_ortho:.1f} "
f"skewness={report.max_skewness:.2f} "
f"aspectRatio={report.max_aspect_ratio:.0f}"
)
if not report.passed:
self.log_line.emit(f"[checkMesh] {report.status}")
_perf_record(
self._case_dir, "checkmesh", time.perf_counter() - t_checkmesh0,
)
_perf_log(self._case_dir, self.log_line.emit)
self.finished.emit(report)
# ------------------------------------------------------------------
# PolyDualWorker — polyhedral mesh conversion
# ------------------------------------------------------------------
[docs]
class PolyDualWorker(QObject):
"""Runs polyDualMesh via WSL2 in a background QThread.
polyDualMesh converts the hexahedral mesh from cartesianMesh into
an arbitrary polyhedral mesh (reduces cell count while preserving
surface quality). It writes output to the same case directory.
"""
log_line = Signal(str)
finished = Signal(object)
failed = Signal(str)
def __init__(self, case_dir: Path | str, of_config: OFConfig,
feature_angle: float = 90, parent=None):
super().__init__(parent)
self._case_dir = Path(case_dir).resolve()
self._of_config = of_config
self._feature_angle = feature_angle
[docs]
@Slot()
def run(self):
cmd = self._of_config.build_poly_dual_cmd(
self._case_dir, feature_angle=self._feature_angle,
)
self.log_line.emit(f"[polyDualMesh] {' '.join(cmd)}")
try:
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=300,
)
# Always log stdout/stderr so we can diagnose silent failures
stdout_text = (result.stdout or "").strip()
stderr_text = (result.stderr or "").strip()
if stdout_text:
for line in stdout_text.splitlines()[-20:]:
self.log_line.emit(f"[polyDualMesh] {line}")
if stderr_text:
for line in stderr_text.splitlines()[-10:]:
self.log_line.emit(f"[polyDualMesh:err] {line}")
if result.returncode == 0:
# Verify the mesh actually changed by checking owner file
owner_path = self._case_dir / "constant" / "polyMesh" / "owner"
if owner_path.exists():
logger.info(
"polyDualMesh OK (rc=0), owner file exists: %s",
owner_path,
)
else:
logger.warning(
"polyDualMesh returned rc=0 but owner file NOT found at %s",
owner_path,
)
self.log_line.emit(
f"[polyDualMesh] Conversion OK (featureAngle={self._feature_angle})"
)
self.finished.emit(self._case_dir)
else:
logger.error(
"polyDualMesh FAILED (rc=%d): %s",
result.returncode,
stdout_text[-500:] if stdout_text else "(no stdout)",
)
self.log_line.emit(f"[polyDualMesh] Return code {result.returncode}")
self.failed.emit(f"polyDualMesh returned {result.returncode}")
except subprocess.TimeoutExpired:
self.log_line.emit("[polyDualMesh] TIMEOUT (300s)")
self.failed.emit("polyDualMesh timed out after 300s")
except FileNotFoundError:
self.log_line.emit("[polyDualMesh] WSL not found")
self.failed.emit("WSL not found")
except Exception as exc:
self.log_line.emit(f"[polyDualMesh] ERROR: {exc}")
self.failed.emit(str(exc))
def count_polymesh_prism_cells(case_dir: Path | str) -> int:
"""Number of prism-shaped cells in ``constant/polyMesh`` (best-effort).
A boundary-layer prism has exactly two triangular faces (the base/top
walls) and three quad faces; :func:`bl_cells._prism_like_mask` detects
that shape topologically, with no dependence on patch names. Returns 0
on any read failure — never raises.
WARNING: a few percent of dual-mesh cells are prism-shaped BY
COINCIDENCE (measured: 2012/24286 = 8% on a dual-only cone), so this
count alone must NOT be used to decide whether a boundary layer
exists - see :func:`polymesh_has_boundary_layer`.
"""
try:
import numpy as np
from polyfoammesh.core.bl_cells import _prism_like_mask
from polyfoammesh.core.foam_mesh_io import read_polymesh
poly_dir = Path(case_dir) / "constant" / "polyMesh"
_points, faces, owner, neighbour, _patches = read_polymesh(poly_dir)
if len(faces) == 0 or len(owner) == 0:
return 0
owner = np.asarray(owner, dtype=np.int64).ravel()
neighbour = np.asarray(neighbour, dtype=np.int64).ravel()
n_internal = min(int(neighbour.size), len(faces))
n_cells = int(owner.max()) + 1
if n_internal:
n_cells = max(n_cells, int(neighbour[:n_internal].max()) + 1)
face_sizes = np.fromiter(
(len(f) for f in faces[: len(owner)]), dtype=np.int64,
count=len(owner),
)
mask = _prism_like_mask(
face_sizes, owner, neighbour[:n_internal], n_cells,
)
return int(mask.sum())
except Exception:
logger.debug("count_polymesh_prism_cells failed for %s", case_dir, exc_info=True)
return 0
def polymesh_has_boundary_layer(case_dir: Path | str) -> bool:
"""True only when the polyMesh already carries a REAL boundary layer.
Used to skip the in-house ``bl_poly`` stage when the mesh already has
prisms (GMSH-baked BL or prisms preserved by the mixed dual path): a
second BL would double the near-wall layers.
The bare shape count is not usable here: dual cells are prism-shaped
by coincidence often enough to trip a ``> 0`` test (2012 false
positives on a real dual-only cone -> the in-house BL was skipped on
EVERY run, user report 2026-10-09). A real boundary layer covers
(almost) every wall face with a prism owner — measured coverage 0.89
with BL vs 0.14 without — so require BOTH:
* at least 100 prism-like wall-adjacent cells, and
* prism-like owners on >= 50% of the wall faces.
Returns False on any read failure — never raises.
"""
try:
import numpy as np
from polyfoammesh.core.bl_cells import _prism_like_mask, _wall_patches
from polyfoammesh.core.foam_mesh_io import read_polymesh
poly_dir = Path(case_dir) / "constant" / "polyMesh"
_points, faces, owner, neighbour, patches = read_polymesh(poly_dir)
if len(faces) == 0 or len(owner) == 0:
return False
owner = np.asarray(owner, dtype=np.int64).ravel()
neighbour = np.asarray(neighbour, dtype=np.int64).ravel()
n_faces = min(len(owner), len(faces))
n_internal = min(int(neighbour.size), n_faces)
n_cells = int(owner.max()) + 1
if n_internal:
n_cells = max(n_cells, int(neighbour[:n_internal].max()) + 1)
face_sizes = np.fromiter(
(len(f) for f in faces[:n_faces]), dtype=np.int64, count=n_faces,
)
prism_like = _prism_like_mask(
face_sizes, owner, neighbour[:n_internal], n_cells,
)
wall = _wall_patches(Path(case_dir), patches)
wall_owner = np.zeros(0, dtype=np.int64)
for p in wall:
start = max(int(p.get("startFace", 0)), n_internal)
end = min(start + int(p.get("nFaces", 0)), n_faces)
if end > start:
wall_owner = np.concatenate([wall_owner, owner[start:end]])
if wall_owner.size == 0:
return False
covered = prism_like[wall_owner]
n_covered = int(covered.sum())
coverage = n_covered / float(wall_owner.size)
return n_covered >= 100 and coverage >= 0.5
except Exception:
logger.debug(
"polymesh_has_boundary_layer failed for %s", case_dir, exc_info=True,
)
return False
class DualPolyWorker(QObject):
"""Runs TetPolyDualConverter (tet -> polyhedral by barycentric dual) in a
background QThread.
This is the one and only tet->poly worker this pipeline uses: it builds
the dual complex of the tet mesh (one cell per primal vertex), so poly
coverage is 100% by construction and the boundary is an exact subdivision
of the original surface triangles. See docs/poly_dual_converter.md for the
measured comparison against the retired terminal-face path.
Pure Python + numpy, so it runs directly in a QThread rather than
needing subprocess isolation.
"""
log_line = Signal(str)
finished = Signal(object) # DualPolyResult
failed = Signal(str)
def __init__(self, case_dir: Path | str, bl_params: dict | None = None,
parent=None):
super().__init__(parent)
self._case_dir = Path(case_dir).resolve()
self._bl_params = bl_params or None
self._cancelled = False
def cancel(self) -> None:
self._cancelled = True
@Slot()
def run(self):
from polyfoammesh.core.tet_poly_dual import TetPolyDualConverter
# Stage timing (perf_counter; zero behaviour change). One summary
# line is emitted before finished; the BL engine logs its own
# precompute/build split and exposes it through result.stats.
t_worker0 = time.perf_counter()
self.log_line.emit(
"[poly] Converting tet -> polyhedral mesh (barycentric dual)..."
)
# Back the pristine tet mesh up BEFORE converting, so a later
# checkMesh failure on the poly mesh can be rolled back to the tet
# (the quality-gate policy is a product decision, but the rollback
# must always be possible — the converter overwrites polyMesh).
try:
import shutil
poly_dir = self._case_dir / "constant" / "polyMesh"
backup = self._case_dir / "constant" / "polyMesh_tet_backup"
if poly_dir.exists() and not backup.exists():
shutil.copytree(poly_dir, backup)
self.log_line.emit(
"[poly] Tet mesh backed up to constant/polyMesh_tet_backup "
"(rollback available)"
)
except Exception as exc: # noqa: BLE001 - backup is best-effort
self.log_line.emit(f"[poly] WARN: tet backup failed: {exc}")
try:
# collapse_smooth_edges: ONE polygonal face per boundary vertex
# (the polyDualMesh / STAR-CCM+ boundary topology) instead of the
# exact per-corner subdivision, which emits three quads per
# original boundary triangle. Those three quads TILE the primal
# triangle, so the input triangulation's edges physically survive
# in the mesh — which is why a 100% polyhedral mesh still reads as
# "triangles with a Y inside" on screen, reported repeatedly.
#
# Measured on the user's OWN mesh (the tet backup of the run that
# produced the complaint, 102,080 cells):
# exact: 462,846 boundary faces, all quads, 0 defects
# collapse: 80,111 boundary faces (5.8x fewer), 0 defects,
# shapes {4: 1301, 5: 21580, 6: 40371, 7: 15510,
# 8: 1315, 9: 34} <- genuine polygons
# volume drift: -0.00% in both
# An earlier decision left this OFF based on a deliberately
# hostile synthetic case (a sphere resolved by ~3-10 cells across)
# where the collapsed polygons are non-planar enough to roughly
# double the defect count. On real, properly resolved geometry
# that cost does not materialise: same zero defects, same volume,
# 5.8x fewer boundary faces — and, because bl_poly extrudes one
# prism stack per boundary face, 5.8x fewer boundary-layer cells.
#
# median_faces is left at its default (False): A/B on valve1
# measured True = 1056 residual defects vs False = 1027, i.e. the
# previously forced-on value was slightly WORSE. wedge_cells made
# no difference either way in the same A/B (1056 both) and is
# incompatible with the collapse, which disables it explicitly.
converter = TetPolyDualConverter(
self._case_dir,
log=self.log_line.emit,
cancel=lambda: self._cancelled,
collapse_smooth_edges=True,
boundary_feature_angle=40.0,
collapse_volume_tolerance=0.10,
)
t_dual0 = time.perf_counter()
result = _run_with_profile(
self._case_dir, "dual", converter.run, self.log_line.emit,
)
dual_s = time.perf_counter() - t_dual0
except Exception as exc:
self.log_line.emit(f"[poly] ERROR: {exc}")
self.failed.emit(str(exc))
return
if not result.success:
msg = "; ".join(result.errors) or "Unknown dual conversion error"
self.log_line.emit(f"[poly] FAILED: {msg}")
self.failed.emit(msg)
return
self.log_line.emit(
f"[poly] Conversion OK: {result.n_tets_before:,} tets -> "
f"{result.n_cells_after:,} polyhedra, residual tetrahedra "
f"{result.n_residual_tets} ({result.stage_times.get('total', 0)}s)"
)
if getattr(result, "n_prisms_before", 0):
self.log_line.emit(
f"[poly] {result.n_prisms_before:,} GMSH prism cell(s) carried "
"through the dual conversion verbatim"
)
# boundary layers on the poly mesh (our own advancing-layer engine)
bres = None
# GMSH-baked BL: the converter reports how many input prisms it kept
# (the authoritative count — a stitched prism's side quads are split,
# so the shape detector below cannot see it). The shape detector is a
# second, independent check for a prism-bearing polyMesh that reached
# this worker without going through the mixed dual path. Both are only
# consulted when BL was actually requested, so a no-BL run pays
# nothing.
_has_gmsh_bl = False
if self._bl_params:
_has_gmsh_bl = (
int(getattr(result, "n_prism_cells_after", 0) or 0) > 0
or polymesh_has_boundary_layer(self._case_dir)
)
if self._bl_params and _has_gmsh_bl:
# Adding the in-house BL on top would double the near-wall layers.
self.log_line.emit(
"[poly] GMSH-baked BL detected: skipping the in-house BL stage"
)
elif self._bl_params:
from polyfoammesh.core.bl_poly import PolyBoundaryLayerEngine
bl = dict(self._bl_params)
apply_all = bool(bl.get("applyToAll", False))
self.log_line.emit(
f"[poly] Adding boundary layers: "
f"{bl.get('nLayers', 5)} layers, "
f"first height {bl.get('firstLayerThickness', 0.0):.6g} m, "
f"growth {bl.get('thicknessRatio', 1.2)}"
)
try:
bres = None
kw = dict(
n_layers=int(bl.get("nLayers", 5)),
first_height=float(bl.get("firstLayerThickness", 0.0)),
growth_rate=float(bl.get("thicknessRatio", 1.2)),
# 2026-10-06 BL quality fixes (GUI checkboxes, opt-in):
# the sliver-edge base-face filter and the budget
# termination; 0.0/False reproduce the historical path.
min_base_edge_fraction=float(
bl.get("minBaseEdgeFraction", 0.0) or 0.0
),
terminate_by_budget=bool(bl.get("terminateByBudget", False)),
)
_cc_n_cells = int(max(int(result.n_cells_after or 0), 0))
_cc_n_faces = int(
max(int(getattr(result, "n_internal_faces", 0) or 0), 0)
) + int(
max(int(getattr(result, "n_boundary_faces", 0) or 0), 0)
)
# Safety guard (2026-09-14 root cause, 2026-09-15 measured):
# a real user run at ~5M dual cells (~41M faces) with
# concaveClosure on exhausted 32GB RAM and crashed the whole
# machine. Lane A measured that BL/merge memory scales with
# FACES (~0.8KB/face hex, ~1.0KB/face dual marginal), NOT
# cells (dual meshes carry ~8 faces/cell vs ~3 for hex) -
# so the guard is on faces: 8M faces projects to ~10.8GB
# peak on dual topology (two-point fit: 1.24M -> 2.8GB,
# 6.2M -> 10.5GB build peaks) and hex meshes peak far lower
# (measured 15.06M faces -> 13.05GB). Above the guard the
# stages are skipped rather than risking another crash. Not
# a quality decision, a safety one. See
# notes/ram_crash_rootcause_reasoning.md.
_cc_too_big = (
_cc_n_faces > 8_000_000 if _cc_n_faces > 0
else _cc_n_cells > 1_500_000
)
# Concave closure (decoupled_vertex, H4) is no longer an
# opt-in FIRST choice: it is retried AUTOMATICALLY below when
# the standard robust path fails. Running it first degraded
# quality on geometries the standard path already handles
# (the new binary budget semantics + mesh-aware cap), while
# it remains the only path that closes the layer on
# concave-junction meshes (groove1/slot1, see
# docs/residual_risks.md "FASE 9").
engine = PolyBoundaryLayerEngine(
self._case_dir,
log=self.log_line.emit,
cancel=lambda: self._cancelled,
)
# Single decision point — see poly_bl_patch_selection for why
# the last tier no longer means "apply to ALL".
patch_names, apply_to_all, notes = poly_bl_patch_selection(
self._case_dir, apply_to_all_override=apply_all,
)
for line in notes:
self.log_line.emit(f"[poly] {line}")
def _run_bl(extra_kw):
if apply_all:
return engine.run(apply_to_all=True, **extra_kw)
if patch_names is None:
return None
return engine.run(
patch_names=patch_names, apply_to_all=False, **extra_kw,
)
if apply_all:
self.log_line.emit(
"[poly] BL on ALL boundary patches "
"(override 'Apply BL to all patches' is on)"
)
elif patch_names is None:
pass
else:
self.log_line.emit(
"[poly] BL on wall patches only: "
f"{', '.join(sorted(patch_names))}"
)
bres = _run_with_profile(
self._case_dir, "bl", lambda: _run_bl(kw),
self.log_line.emit,
)
# Fallback chain (2026-10-06): standard robust first (it now
# handles concave features on its own via the binary budget
# semantics and the mesh-aware cap), then the concave closure
# (decoupled_vertex, H4) — the only path that closes the
# layer on concave-junction meshes like groove1/slot1 — then
# a halved first layer below. The size guard protects the
# closure attempt: memory scales with faces (a real ~5M-cell
# run exhausted 32GB RAM and crashed the system).
if bres is None or not bres.success:
if _cc_too_big:
self.log_line.emit(
"[poly] WARN: concave closure fallback skipped — "
"mesh above the faces-based safety limit "
"(memory scales with faces). Continuing without it."
)
else:
self.log_line.emit(
"[poly] BL standard path failed — retrying with "
"concave closure (decoupled_vertex)..."
)
retry = _run_bl(
{**kw, "local_termination": "decoupled_vertex"}
)
if retry is not None and retry.success:
bres = retry
# Last resort: halve the first-layer height. The per-vertex
# inversion guard rejects a stack that is taller than the
# dual's boundary cells can take, and the engine's own
# fallback shrinks the clamp too (which does not help here).
# Measured on the user's Part2 case: h1 7.28e-4 failed at
# every scale, h1/2 succeeded (13,088 prisms, checkMesh
# PASS). The reduction is logged because it changes y+.
if bres is None or not bres.success:
base_h = float(kw.get("first_height", 0.0) or 0.0)
for frac in (0.5, 0.25):
if base_h <= 0.0:
break
kw_h = {**kw, "first_height": base_h * frac}
self.log_line.emit(
"[poly] BL retry: first layer reduced "
f"{1.0 / frac:.0f}x ({base_h * frac:.4g} m) to "
"fit the dual boundary cells — y+ target moves."
)
retry = _run_bl(kw_h)
if retry is not None and retry.success:
bres = retry
break
except Exception as exc: # noqa: BLE001 - keep the poly mesh
self.log_line.emit(f"[poly] WARN: boundary layers failed: {exc}")
bres = None
if bres is not None and bres.success:
self.log_line.emit(
f"[poly] Boundary layers OK: {bres.n_prism_cells:,} prism "
f"cells, total thickness {bres.total_thickness:.6g} m"
)
result.bl_prism_cells = bres.n_prism_cells
result.bl_thickness = bres.total_thickness
if bl.get("concaveClosure") and _cc_too_big:
self.log_line.emit(
"[poly] WARN: post-BL merge repair skipped — same "
"faces-based safety limit as concave closure above."
)
elif bl.get("concaveClosure"):
# Merge repair AFTER the boundary layer (not before -
# measured 2026-09-14: merging concave cells BEFORE
# building the BL regresses aspect ratio 3x on the
# valve; merging the SAME cells AFTER the BL is built
# (so the merge selection sees the real prism geometry
# it sits next to) avoids that regression entirely -
# 340 -> 58 wrong-oriented faces, aspect ratio and
# non-orthogonality unchanged or slightly BETTER, real
# checkMesh. See notes/getme_compactness_reasoning.md
# and docs/residual_risks.md. Reuses the same
# concaveClosure opt-in flag (off by default) rather
# than adding a second checkbox for the same theme.
try:
import polyfoammesh.core.foam_mesh_io as fio
from polyfoammesh.core.poly_cell_merge import (
repair_concave_cells_if_safe,
)
poly_dir = self._case_dir / "constant" / "polyMesh"
pts, fcs, own, nbr, patches = fio.read_polymesh(poly_dir)
fcs = [list(f) for f in fcs]
n_int_m = len(nbr)
n_cells_m = int(max(own.max(), nbr.max())) + 1
fcs2, own2, nbr2, n_int2, n_cells2, patches2, rep = (
repair_concave_cells_if_safe(
pts, fcs, own, nbr, n_int_m, n_cells_m, patches,
)
)
if rep["applied"]:
fio.write_polymesh(
poly_dir, pts, fcs2, own2, nbr2, patches2,
)
self.log_line.emit(
"[poly] Post-BL cell-merge repair applied: "
f"{rep['reason']}"
)
else:
self.log_line.emit(
"[poly] Post-BL cell-merge repair skipped: "
f"{rep['reason']}"
)
except Exception as exc: # noqa: BLE001 - never fail the
# whole mesh over this opt-in extra repair pass
self.log_line.emit(
f"[poly] WARN: post-BL cell-merge repair failed, "
f"mesh kept as built by BL: {exc}"
)
else:
msg = (
"; ".join(bres.errors) if bres is not None
else "engine raised"
)
self.log_line.emit(
f"[poly] WARN: boundary layers skipped — "
f"mesh kept without BL ({msg})"
)
result.bl_prism_cells = 0
result.bl_warning = msg
# One stage-timing summary per poly run (perf_counter).
bl_pre = bl_build = bl_total = 0.0
bl_reflow = 0.0
if bres is not None:
stats = getattr(bres, "stats", {}) or {}
bl_pre = float(stats.get("stage_precompute_s", 0.0) or 0.0)
bl_build = float(stats.get("stage_build_s", 0.0) or 0.0)
bl_total = float(stats.get("stage_total_s", 0.0) or 0.0)
# Present only if bl_poly ever exposes it; harmless no-op today.
bl_reflow = float(stats.get("stage_reflow_s", 0.0) or 0.0)
self.log_line.emit(
f"[poly] stage times: dual {dual_s:.1f}s | "
f"BL precompute {bl_pre:.1f}s | BL build {bl_build:.1f}s | "
f"BL total {bl_total:.1f}s | "
f"total {time.perf_counter() - t_worker0:.1f}s"
)
# Phase-0 aggregate: record this run's stages into the process-wide
# trace and emit ONE consistent "[perf] stage times:" line covering
# every stage known for the case (GMSH/conversion if those workers ran
# earlier in this process, plus dual/BL/write here).
_perf_record(self._case_dir, "dual", dual_s)
dual_stage = getattr(result, "stage_times", {}) or {}
# The converter writes polyMesh itself; report its own write split.
if "write" in dual_stage:
_perf_record(self._case_dir, "dual_write", float(dual_stage["write"]))
if bres is not None:
_perf_record(self._case_dir, "bl_pre", bl_pre)
_perf_record(self._case_dir, "bl_build", bl_build)
_perf_record(self._case_dir, "bl_total", bl_total)
if bl_reflow:
_perf_record(self._case_dir, "bl_reflow", bl_reflow)
_perf_record(self._case_dir, "total", time.perf_counter() - t_worker0)
_perf_log(self._case_dir, self.log_line.emit)
self.finished.emit(result)
[docs]
class DecomposeParWorker(QObject):
"""Runs decomposePar -force in a background QThread to decompose an
existing mesh into processorN/ directories for parallel SOLVING."""
log_line = Signal(str)
finished = Signal(object)
failed = Signal(str)
def __init__(self, case_dir: Path | str, of_config: OFConfig,
n_cores: int, method: str = "scotch", parent=None):
super().__init__(parent)
self._case_dir = Path(case_dir).resolve()
self._of_config = of_config
self._n_cores = n_cores
self._method = method
[docs]
@Slot()
def run(self):
t_decomp0 = time.perf_counter()
try:
cmd = self._of_config.build_decompose_par_cmd(
self._case_dir, self._n_cores, method=self._method,
)
self.log_line.emit(f"[decomposePar] {' '.join(cmd)}")
result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
if result.returncode == 0:
self.log_line.emit("[decomposePar] Decomposition OK")
_perf_record(
self._case_dir, "decompose",
time.perf_counter() - t_decomp0,
)
_perf_log(self._case_dir, self.log_line.emit)
self.finished.emit(self._case_dir)
else:
self.log_line.emit(f"[decomposePar] Return code {result.returncode}")
self.failed.emit(f"decomposePar returned {result.returncode}")
except subprocess.TimeoutExpired:
self.log_line.emit("[decomposePar] TIMEOUT (120s)")
self.failed.emit("decomposePar timed out")
except FileNotFoundError:
self.log_line.emit("[decomposePar] WSL not found")
self.failed.emit("WSL not found")
except Exception as exc:
self.log_line.emit(f"[decomposePar] ERROR: {exc}")
self.failed.emit(str(exc))
[docs]
class ParallelMeshWorker(QObject):
"""Runs ParallelMeshEngine.run() (synchronous, MPI-based) in a
background QThread so it doesn't freeze the GUI's own event loop.
Supports cancellation via cancel(): sets an event that the engine's
polling subprocess runner checks every 0.5s and kills the MPI ranks."""
log_line = Signal(str)
finished = Signal(object) # ParallelMeshResult
failed = Signal(str)
cancelled = Signal() # emitted when user cancels mid-run
def __init__(
self, case_dir: Path | str, of_config: OFConfig,
max_cell: float, min_cell: float, n_cores: int,
patch_names: list[str] | None = None,
method: str = "scotch", parent=None,
bl_params: dict | None = None,
):
super().__init__(parent)
self._case_dir = Path(case_dir).resolve()
self._of_config = of_config
self._max_cell = max_cell
self._min_cell = min_cell
self._n_cores = n_cores
self._patch_names = patch_names
self._method = method
self._bl_params = bl_params
self._engine: ParallelMeshEngine | None = None
[docs]
def cancel(self) -> None:
"""Request cancellation of the running parallel meshing.
Safe to call from any thread; triggers a process-tree kill
inside WSL2 on the next 0.5s poll cycle."""
if self._engine is not None:
self._engine.cancel()
[docs]
@Slot()
def run(self):
try:
from polyfoammesh.commercial.parallel_mesh import (
ParallelMeshEngine, CancelledError,
)
self.log_line.emit(
f"[parallel] Meshing across {self._n_cores} cores..."
)
self._engine = ParallelMeshEngine(self._of_config)
self._engine.setup_case(self._case_dir, n_cores=self._n_cores, method=self._method)
self._engine.set_cell_sizes(self._max_cell, self._min_cell)
self._engine.set_patch_names(self._patch_names)
self._engine.set_bl_params(self._bl_params)
result = self._engine.run()
if result.success:
self.log_line.emit(
f"[parallel] Done: {result.cell_count:,} cells "
f"({result.wall_time_seconds:.1f}s wall time, "
f"{self._n_cores} cores)"
)
self.finished.emit(result)
else:
msg = "; ".join(result.errors) or "unknown error"
self.log_line.emit(f"[parallel] FAILED: {msg}")
self.failed.emit(msg)
except CancelledError:
self.log_line.emit("[parallel] Cancelled by user.")
self.cancelled.emit()
except Exception as exc:
self.log_line.emit(f"[parallel] ERROR: {exc}")
self.failed.emit(str(exc))
[docs]
class WslCheckWorker(QObject):
"""Runs OFConfig.validate() (blocking wsl.exe call) in a background
QThread. WSL2 auto-shuts-down its VM after inactivity, so this can
take well over a minute on a cold boot — running it on the GUI
thread freezes the whole window with no feedback, indistinguishable
from a crash."""
finished = Signal(bool)
def __init__(self, of_config: OFConfig, parent=None):
super().__init__(parent)
self._of_config = of_config
[docs]
@Slot()
def run(self):
try:
ok = self._of_config.validate()
except Exception:
ok = False
self.finished.emit(ok)
# ------------------------------------------------------------------
# V2.0: QualityFixWorker — checkMesh → auto-fix → re-run loop
# ------------------------------------------------------------------
[docs]
class QualityFixWorker(QObject):
"""Runs meshing + checkMesh + auto-fix loop with max 3 iterations.
Uses RetryRunner internally for the meshing step, then runs
checkMesh. If quality checks fail, applies meshDict fixes and
re-runs.
"""
MAX_FIX_ATTEMPTS = 3
log_line = Signal(str)
finished = Signal(int)
failed = Signal(str)
def __init__(self, of_config: OFConfig, parent=None):
super().__init__(parent)
self._of_config = of_config
self._fix_attempts = 0
self._runner: RetryRunner | None = None
self._checkmesh_worker: CheckMeshWorker | None = None
self._checkmesh_thread: QThread | None = None
[docs]
@Slot()
def run(self, case_dir: Path, **kwargs):
self._case_dir = Path(case_dir).resolve()
self._kwargs = kwargs
self._fix_attempts = 0
self._do_meshing_step()
def _do_meshing_step(self):
self.log_line.emit(f"[quality-fix] Meshing step (fix attempt {self._fix_attempts})...")
self._runner = RetryRunner(self._of_config)
def on_finished(exit_code, output, attempts):
if exit_code != 0:
self.log_line.emit(f"[quality-fix] Meshing failed (exit {exit_code})")
self.failed.emit(f"Meshing failed: exit {exit_code}")
return
self._do_checkmesh_step()
self._runner.run(
case_dir=self._case_dir,
on_log=lambda msg: self.log_line.emit(msg),
on_finished=on_finished,
**self._kwargs,
)
def _do_checkmesh_step(self):
self.log_line.emit("[quality-fix] Running checkMesh...")
self._checkmesh_thread = QThread()
self._checkmesh_worker = CheckMeshWorker(self._case_dir, self._of_config)
self._checkmesh_worker.moveToThread(self._checkmesh_thread)
self._checkmesh_worker.log_line.connect(self.log_line)
self._checkmesh_worker.finished.connect(self._on_checkmesh_result)
self._checkmesh_worker.failed.connect(lambda msg: self.failed.emit(msg))
self._checkmesh_worker.finished.connect(self._checkmesh_thread.quit)
self._checkmesh_worker.failed.connect(self._checkmesh_thread.quit)
self._checkmesh_thread.started.connect(self._checkmesh_worker.run)
self._checkmesh_thread.start()
def _on_checkmesh_result(self, report):
if report.passed:
self.log_line.emit("[quality-fix] checkMesh PASSED")
self.finished.emit(0)
return
self._fix_attempts += 1
if self._fix_attempts >= self.MAX_FIX_ATTEMPTS:
self.log_line.emit(
f"[quality-fix] Max fix attempts ({self.MAX_FIX_ATTEMPTS}) reached."
)
self.failed.emit(f"Quality not met after {self.MAX_FIX_ATTEMPTS} attempts")
return
self.log_line.emit(
f"[quality-fix] checkMesh FAILED ({report.status}). "
f"Applying fix #{self._fix_attempts}..."
)
# Auto-fix: use QualityEngine's targeted fix strategies
try:
from polyfoammesh.commercial.quality_engine import QualityEngine, QualityMetrics
qe = QualityEngine()
qm = QualityMetrics(
max_skewness=report.max_skewness,
max_non_orthogonality=report.max_non_ortho,
max_aspect_ratio=report.max_aspect_ratio,
neg_cells=report.neg_cells,
cells=report.cells,
)
fixes = qe._decide_fixes(qm)
if not fixes:
self.log_line.emit("[quality-fix] No applicable fix strategy.")
self.failed.emit("No fix strategy for current quality failure")
return
applied_text = self._case_dir / "system" / "meshDict"
if not applied_text.exists():
self.failed.emit("meshDict not found")
return
text = applied_text.read_text(encoding="ascii")
for fix in fixes:
if fix.action == "relax":
text = QualityEngine._relax_cell_sizes(text, factor=fix.factor or 1.2)
elif fix.action == "reduce_bl":
text = QualityEngine._reduce_boundary_layers(text)
elif fix.action == "disable_bl":
text = QualityEngine._disable_boundary_layers(text)
elif fix.action == "remesh":
text = QualityEngine._coarsen_mesh(text, factor=fix.factor or 1.3)
elif fix.action == "split":
text = QualityEngine._reduce_max_cell(text, factor=fix.factor or 0.7)
self.log_line.emit(
f"[quality-fix] {fix.action}: {fix.detail}"
)
applied_text.write_text(text, encoding="ascii")
self.log_line.emit(f"[quality-fix] meshDict updated ({len(fixes)} fix(es))")
self._do_meshing_step()
except Exception as e:
self.log_line.emit(f"[quality-fix] Fix failed: {e}")
self.failed.emit(str(e))
[docs]
def terminate(self):
if self._runner and self._runner.is_running:
self._runner.terminate()
if self._checkmesh_thread and self._checkmesh_thread.isRunning():
self._checkmesh_thread.quit()
self._checkmesh_thread.wait(3000)
def _gmsh_wrapper_script_cmd(
args: list[str], frozen_flag: str, script_name: str = "gmsh_wrapper.py",
) -> tuple[list[str], str | None]:
"""Build a subprocess command that runs a core/ module's CLI directly
by file path rather than via `python -m polyfoammesh.core.<module>`.
`-m` first fully imports the parent package (polyfoammesh.core),
whose __init__.py already imports several of these modules — so by
the time Python's runpy machinery goes to execute one as __main__,
it's already sitting in sys.modules under its real dotted name. That
triggers Python's own "found in sys.modules ... prior to execution;
this may result in unpredictable behaviour" RuntimeWarning and
re-executes the whole module a second time in the same process —
confirmed from a real run where that warning ended up as the ONLY
stderr content on a non-zero exit, masking whatever the actual
failure was. Running the file directly skips package init entirely.
"""
import sys
frozen = getattr(sys, "frozen", False)
if frozen:
return [sys.executable, frozen_flag] + args[1:], None
script = str(Path(__file__).resolve().with_name(script_name))
run_cwd = str(Path(__file__).resolve().parents[2])
return [sys.executable, script] + args, run_cwd
def _kill_pid_tree(pid: int) -> None:
"""Kill a process and its children by PID for the GMSH-subprocess
workers (WSL/OpenFOAM processes go through
MeshWorker._kill_process_tree instead — this is for the plain
sys.executable child _stream_subprocess launches).
Windows: ``taskkill /T``. POSIX: the child was launched with
``start_new_session=True``, so its process group id equals its pid and
``killpg(pid)`` kills the whole tree without ever hitting the GUI's own
group (guarded explicitly).
"""
import subprocess
from contextlib import suppress
if sys.platform != "win32":
try:
own_pgid = os.getpgid(0)
except OSError:
own_pgid = -1
with suppress(OSError, ProcessLookupError):
if pid != own_pgid:
os.killpg(pid, signal.SIGKILL)
else:
os.kill(pid, signal.SIGKILL)
return
with suppress(OSError, subprocess.TimeoutExpired):
subprocess.run(
["taskkill", "/PID", str(pid), "/T", "/F"],
capture_output=True, timeout=5,
)
# ---------------------------------------------------------------------------
# Windows process hygiene for the GMSH-wrapper subprocesses: the GUI must
# stay responsive while GMSH saturates the machine, and the subprocess must
# NEVER outlive the GUI (an orphaned GMSH keeps meshing for 10-30 min after
# the app is killed, re-saturating the machine and making every relaunch
# crash — confirmed from a real session's WER BEX64 crash-loop and the
# orphan-written mesh.msh files).
# ---------------------------------------------------------------------------
# Job handles that must stay open for KILL_ON_JOB_CLOSE to apply; cleaned
# up when the child exits (see _stream_subprocess).
_JOB_HANDLES: dict[int, int] = {} # proc_handle -> job_handle
# JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE — kills every process in the job when
# the last handle to the job is closed (i.e. when our process dies).
_JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000
_BELOW_NORMAL_PRIORITY_CLASS = 0x00004000
class _IO_COUNTERS(ctypes.Structure):
_fields_ = [
("ReadOperationCount", ctypes.c_ulonglong),
("WriteOperationCount", ctypes.c_ulonglong),
("OtherOperationCount", ctypes.c_ulonglong),
("ReadTransferCount", ctypes.c_ulonglong),
("WriteTransferCount", ctypes.c_ulonglong),
("OtherTransferCount", ctypes.c_ulonglong),
]
class _JOBOBJECT_BASIC_LIMIT_INFORMATION(ctypes.Structure):
_fields_ = [
("PerProcessUserTimeLimit", ctypes.c_longlong),
("PerJobUserTimeLimit", ctypes.c_longlong),
("LimitFlags", ctypes.c_uint32),
("MinimumWorkingSetSize", ctypes.c_size_t),
("MaximumWorkingSetSize", ctypes.c_size_t),
("ActiveProcessLimit", ctypes.c_uint32),
("Affinity", ctypes.c_size_t),
("PriorityClass", ctypes.c_uint32),
("SchedulingClass", ctypes.c_uint32),
]
class _JOBOBJECT_EXTENDED_LIMIT_INFORMATION(ctypes.Structure):
_fields_ = [
("BasicLimitInformation", _JOBOBJECT_BASIC_LIMIT_INFORMATION),
("IoInfo", _IO_COUNTERS),
("ProcessMemoryLimit", ctypes.c_size_t),
("JobMemoryLimit", ctypes.c_size_t),
("PeakProcessMemoryUsed", ctypes.c_size_t),
("PeakJobMemoryUsed", ctypes.c_size_t),
]
# JobInformationClass index for ExtendedLimitInformation.
_JobObjectExtendedLimitInformation = 9
def _harden_windows_child(proc) -> None:
"""Best-effort Windows hardening of a Popen child:
- BelowNormal priority, so GMSH's CPU grind never starves the GUI's
own thread (the "GMSH impalla il sistema" white-screen freeze).
- A Job Object with KILL_ON_JOB_CLOSE, so the child is force-killed
when THIS process dies — no orphaned meshing subprocess left
saturating RAM/CPU after a crash or user kill.
On non-Windows or on any API failure this is a silent no-op: the
child still runs, just unhardened (same behaviour as before).
"""
if os.name != "nt":
return
try:
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
handle = int(proc._handle) # Popen's process handle
if handle:
try:
kernel32.SetPriorityClass(handle, _BELOW_NORMAL_PRIORITY_CLASS)
except Exception:
pass
job = kernel32.CreateJobObjectW(None, None)
if job:
info = _JOBOBJECT_EXTENDED_LIMIT_INFORMATION()
info.BasicLimitInformation.LimitFlags = _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
if kernel32.SetInformationJobObject(
job, _JobObjectExtendedLimitInformation,
ctypes.byref(info), ctypes.sizeof(info),
):
if kernel32.AssignProcessToJobObject(job, handle):
_JOB_HANDLES[handle] = job
except Exception:
logger.debug("Windows child hardening failed (non-fatal)", exc_info=True)
def _release_job(proc) -> None:
"""Drop the module-level job handle for a finished child. Closing our
handle is safe once the child has exited (nothing left to kill)."""
if os.name != "nt" or proc is None:
return
try:
handle = int(proc._handle)
except Exception:
return
try:
job = _JOB_HANDLES.pop(handle, None)
if job:
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
kernel32.CloseHandle(job)
except Exception:
pass
def _process_cpu_seconds(proc) -> float | None:
"""Cumulative CPU time (user+system seconds) of *proc*, best-effort.
Observability for the stall watchdog: a silent GMSH child whose CPU time
keeps climbing is working (HXT's "Computing mesh sizes" phase emits
nothing for a minute at a time), while a flat CPU time means it is really
stuck. Prefers psutil; falls back to the stdlib-only platform APIs
(GetProcessTimes on Windows, /proc on POSIX) so it works in a frozen build
with no extra dependency. Returns ``None`` when no probe is available.
"""
if proc is None:
return None
try:
import psutil # type: ignore
times = psutil.Process(proc.pid).cpu_times()
return float(times.user + times.system)
except Exception:
logger.debug("stall watchdog: psutil CPU probe unavailable", exc_info=True)
if os.name == "nt":
try:
import ctypes
from ctypes import wintypes as _wintypes
class _FILETIME(ctypes.Structure):
_fields_ = [("dwLowDateTime", ctypes.c_ulong),
("dwHighDateTime", ctypes.c_ulong)]
def _ft_to_s(ft):
return ((ft.dwHighDateTime << 32) | ft.dwLowDateTime) / 1e7
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
# A subprocess.Popen exposes _handle, but the watchdog's probe
# only guarantees a pid (the CI runner without psutil passes a
# lightweight object) - OpenProcess by PID covers both.
# Regression: this path used to raise AttributeError on
# anything without _handle and silently return None, failing
# the probe test on the CI runner and blocking a release.
try:
handle = int(proc._handle)
owns_handle = False
except AttributeError:
_PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
kernel32.OpenProcess.restype = _wintypes.HANDLE
kernel32.OpenProcess.argtypes = [
_wintypes.DWORD, _wintypes.BOOL, _wintypes.DWORD,
]
handle = kernel32.OpenProcess(
_PROCESS_QUERY_LIMITED_INFORMATION, False, int(proc.pid)
)
owns_handle = True
if not handle:
return None
try:
creation, exit_t, kernel, user = (
_FILETIME(), _FILETIME(), _FILETIME(), _FILETIME(),
)
ok = kernel32.GetProcessTimes(
handle, ctypes.byref(creation), ctypes.byref(exit_t),
ctypes.byref(kernel), ctypes.byref(user),
)
if ok:
return _ft_to_s(kernel) + _ft_to_s(user)
finally:
if owns_handle:
kernel32.CloseHandle(handle)
except Exception:
logger.debug("stall watchdog: Windows CPU probe failed", exc_info=True)
return None
try:
with open(f"/proc/{proc.pid}/stat", "r", encoding="utf-8") as fh:
fields = fh.read().split()
ticks = os.sysconf("SC_CLK_TCK")
return (int(fields[13]) + int(fields[14])) / float(ticks)
except Exception:
logger.debug("stall watchdog: /proc CPU probe failed", exc_info=True)
return None
# ---------------------------------------------------------------------------
# Phase B: content-aware non-convergence detector.
#
# The no-output watchdog above is structurally blind to GMSH's MeshAdapt 2D
# runaway: output KEEPS arriving (invalid-element warnings and "splitting those
# edges and trying again" retries), and the largest silent gap measured over a
# full runaway was 251 s — just under the 300 s base — so the silence watchdog
# never fires while the surface mesh never converges and no .msh is written.
# This detector reads the CONTENT instead: it is fed every streamed line
# through the same on_line path and tracks the exact signature GMSH emits when
# a surface's curve-recovery loop is not recovering.
#
# Detection rule (measured; see notes/adaptive_runaway_reasoning.md):
# 1. Magnitude: any surface reports >= 100 simultaneously-invalid elements.
# Healthy runs in the corpus peak at 7; the runaway reaches 364..6524
# (>=14x margin). Fires the instant the count is parsed.
# 2. Growth: >= 8 "Splitting those edges and trying again" rounds, the 2D
# phase has run >= 30 s, and the last >= 3 invalid counts are
# non-decreasing. Catches a slow-growth loop that never repeats a large
# count. Healthy runs finish 2D in <5 s with <=4 split rounds.
# The strings are matched verbatim (case-insensitive) so ordinary log output
# cannot trip it.
GMSH_INVALID_MAGNITUDE_THRESHOLD = 100
GMSH_SPLIT_ROUNDS_THRESHOLD = 8
GMSH_SIGNATURE_2D_ELAPSED_S = 30.0
GMSH_INVALID_GROWTH_WINDOW = 3
class GmshSignatureStallDetector:
"""Stateful, content-aware runaway detector for the GMSH volume stream.
One instance per meshing attempt. :meth:`feed` is called for every
streamed line (the same lines forwarded to ``on_line``) and returns
``True`` exactly once, when the non-convergence rule fires; :attr:`fired`
is then safe to poll from the watchdog loop and :attr:`evidence` carries a
human-readable summary for the log/retry message. All state is guarded by
a lock because ``feed`` runs on the stream-reader thread while ``fired`` is
polled on the watchdog thread. A pure parser: it never touches a process.
"""
_INVALID_RE = re.compile(
r"(\d+)\s+elements?\s+remain\s+invalid\s+in\s+surface\s+(\d+)",
re.IGNORECASE,
)
_SPLIT_RE = re.compile(
r"splitting those edges and trying again", re.IGNORECASE
)
_RECOVERED_RE = re.compile(r"all edges recovered", re.IGNORECASE)
_MESH2D_RE = re.compile(r"meshing\s+(?:2d|surface)", re.IGNORECASE)
def __init__(self, clock=_now):
self._clock = clock
self.max_invalid = 0
self.max_invalid_surface: int | None = None
self.split_rounds = 0
self._invalid_counts: list[int] = []
self._first_2d_ts: float | None = None
self._fired = False
self._evidence = ""
self._lock = threading.Lock()
@property
def fired(self) -> bool:
return self._fired
@property
def evidence(self) -> str:
return self._evidence
def _elapsed_2d(self) -> float:
if self._first_2d_ts is None:
return 0.0
return self._clock() - self._first_2d_ts
def _growth_gate(self) -> bool:
"""True when the low-count-but-never-terminating loop is confirmed."""
if self.split_rounds < GMSH_SPLIT_ROUNDS_THRESHOLD:
return False
if self._first_2d_ts is None:
return False
if self._elapsed_2d() < GMSH_SIGNATURE_2D_ELAPSED_S:
return False
window = self._invalid_counts[-GMSH_INVALID_GROWTH_WINDOW:]
if len(window) < GMSH_INVALID_GROWTH_WINDOW:
return False
return all(b >= a for a, b in zip(window, window[1:]))
def feed(self, line: str) -> bool:
"""Inspect one streamed line; return True once the rule fires."""
if self._fired or not line:
return self._fired
with self._lock:
if self._fired:
return True
if self._MESH2D_RE.search(line) and self._first_2d_ts is None:
self._first_2d_ts = self._clock()
m = self._INVALID_RE.search(line)
if m:
try:
count = int(m.group(1))
surface = int(m.group(2))
except (ValueError, IndexError):
count = None
if count is not None:
self._invalid_counts.append(count)
if count > self.max_invalid:
self.max_invalid = count
self.max_invalid_surface = surface
if self._SPLIT_RE.search(line):
self.split_rounds += 1
if self.max_invalid >= GMSH_INVALID_MAGNITUDE_THRESHOLD:
self._fire("magnitude")
elif self._growth_gate():
self._fire("growth")
return self._fired
def _fire(self, gate: str) -> None:
self._fired = True
self._evidence = (
f"{self.max_invalid} elements remain invalid in surface "
f"{self.max_invalid_surface} after {self.split_rounds} split "
f"round(s) in {self._elapsed_2d():.0f}s of 2D meshing "
f"(gate={gate})"
)
def _stream_subprocess(cmd, run_cwd, timeout_s, on_line, env=None,
heartbeat_s: float = 10, proc_holder=None,
stall_s: float | None = None, stall_holder=None,
signature_detector: "GmshSignatureStallDetector | None" = None):
"""Run cmd via Popen, streaming stdout/stderr line-by-line as they
arrive instead of buffering everything until the process exits.
subprocess.run(capture_output=True) blocks with zero output for the
ENTIRE run — confirmed live: a user watching the log during a slow
(not hung, just genuinely producing far more cells than expected for
the geometry) GMSH run saw nothing for 49s and reasonably assumed a
freeze. This streams stdout as it's produced and, if GMSH itself goes
quiet for heartbeat_s (it commonly does mid-phase, e.g. "Computing
interpolated mesh sizes..."), emits a synthetic "still running" line
through the same callback so silence never looks like a hang.
proc_holder: optional mutable dict the caller can inspect from another
thread while this call is still blocking — populated with the live
Popen object as {"proc": proc} immediately after launch. Without this,
nothing outside this function can ever reach the subprocess: Cancel in
the GUI only tore down the QThread that called this (and only after a
3s wait, since the thread is blocked in this loop and never processes
the quit() event) — the actual GMSH child process, spawned here via
Popen, was never touched and kept running orphaned. Confirmed live:
Cancel visually reset the UI but the process stayed alive, and
starting a new run then meant two GMSH processes running at once.
stall_s: opt-in watchdog threshold, in seconds. When set, the time of the
last real output line (stdout OR stderr) is tracked separately from the
heartbeat throttle; if no line arrives for stall_s the process tree is
killed, :func:`_kill_pid_tree` is used (POSIX/Windows aware), and
``stall_holder["stalled"]`` is set to True with ``elapsed_s`` /
``no_output_s``. ``None`` (default) disables the watchdog entirely, so
surface/watertight runs keep their existing behaviour. The heartbeat keeps
firing independently and output flowing resets the stall timer — a long but
alive run is never killed. The caller (GmshVolumeWorker) owns the retry in
robust mode; this helper only kills and reports.
Returns (returncode, stdout_lines, stderr_lines, timed_out).
"""
import os
import subprocess
import threading
import time
# Decoding our end as UTF-8 isn't enough on its own: the child is a
# separate Python process (launched fresh via sys.executable), and on
# Windows it defaults to encoding ITS OWN stdout/stderr as cp1252 —
# confirmed live, a plain em dash in a logger.warning() call came
# through as a single mangled byte no matter how this end decoded it,
# because it was already the wrong bytes by the time we read them.
# PYTHONIOENCODING forces the child's own text streams to UTF-8
# regardless of the platform's console codepage.
child_env = dict(env) if env is not None else dict(os.environ)
child_env["PYTHONIOENCODING"] = "utf-8"
proc = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, encoding="utf-8", errors="backslashreplace",
cwd=run_cwd, env=child_env, bufsize=1,
**_posix_popen_kwargs(),
)
_harden_windows_child(proc)
if proc_holder is not None:
proc_holder["proc"] = proc
stdout_lines: list[str] = []
stderr_lines: list[str] = []
last_activity = [time.monotonic()]
# Separate clock for the stall watchdog: last_activity is bumped by the
# heartbeat itself (to avoid re-printing it), so it must NOT be used to
# decide a stall — a silent child would reset it every heartbeat and the
# watchdog would never fire. last_output only moves on a real line.
last_output = [time.monotonic()]
# Flood protection: a pathological child (e.g. cartesianMesh grinding on
# an invalid mesh) can emit thousands of warning lines/sec; forwarding
# every one to the GUI saturates the GUI thread until the window goes
# white and Windows reports an AppHang. Lines are still ALL captured in
# stdout_lines/stderr_lines (report integrity); only the live on_line
# forwarding is rate-limited, with a suppression note.
_MAX_LINE_RATE_PER_S = 50.0
_rate = {"last_emit": time.monotonic(), "suppressed": 0}
_MAX_STREAM_LINES = 100_000
_stream_budget = {"appends": 0}
def _append_capped(sink, line):
sink.append(line)
_stream_budget["appends"] += 1
if (
_stream_budget["appends"] % 20_000 == 0
and len(sink) > _MAX_STREAM_LINES
):
del sink[: len(sink) - _MAX_STREAM_LINES]
def _pump(stream, sink, prefix):
try:
for line in iter(stream.readline, ""):
line = line.rstrip("\n")
_append_capped(sink, line)
last_activity[0] = time.monotonic()
last_output[0] = last_activity[0]
if signature_detector is not None:
# Content-aware non-convergence check, on the SAME streamed
# line the watchdog already watches (no second consumer).
signature_detector.feed(line)
if line.strip():
now = time.monotonic()
if now - _rate["last_emit"] >= 1.0 / _MAX_LINE_RATE_PER_S:
if _rate["suppressed"]:
on_line(
prefix + f"... ({_rate['suppressed']} lines "
"suppressed from live log) ..."
)
_rate["suppressed"] = 0
on_line(prefix + line if prefix else line)
_rate["last_emit"] = now
else:
_rate["suppressed"] += 1
finally:
try:
stream.close()
except Exception:
pass
# Both streams echoed live, not just stdout: Python's logging module
# sends WARNING+ to stderr by default (no handler configured in the
# gmsh_wrapper.py subprocess), so a logger.warning() call — e.g. the
# domain-scale sizing clamp's own warning — landed in stderr_lines
# and was silently swallowed until/unless the run failed, never
# reaching the live GUI log on an otherwise-successful run. The
# opposite of what a "show everything, always" log is supposed to do.
t_out = threading.Thread(target=_pump, args=(proc.stdout, stdout_lines, ""), daemon=True)
t_err = threading.Thread(target=_pump, args=(proc.stderr, stderr_lines, "[stderr] "), daemon=True)
t_out.start()
t_err.start()
# Observability: make the watchdog's presence explicit (and prove it is
# NOT armed for paths that pass stall_s=None).
if stall_s is not None:
on_line(f"watchdog armed: kill after {int(stall_s)}s with no output")
start = time.monotonic()
timed_out = False
# CPU-time sampler state for the heartbeat: (wall_time, cumulative_cpu_s).
_cpu_prev = [start, _process_cpu_seconds(proc)]
while True:
ret = proc.poll()
if ret is not None:
break
now = time.monotonic()
if now - start > timeout_s:
timed_out = True
proc.kill()
break
if signature_detector is not None and signature_detector.fired:
# Content-aware runaway: GMSH is not silent, it is provably not
# converging. Kill exactly like the no-output path and let the
# caller decide whether to retry in robust mode.
evidence = signature_detector.evidence
elapsed_s = now - start
if stall_holder is not None:
stall_holder["stalled"] = True
stall_holder["signature"] = True
stall_holder["evidence"] = evidence
stall_holder["elapsed_s"] = elapsed_s
stall_holder["no_output_s"] = now - last_output[0]
on_line(
f"watchdog fired: non-convergence ({evidence}) "
f"({int(elapsed_s)}s elapsed) - killing process tree"
)
_kill_pid_tree(proc.pid)
with suppress(Exception):
proc.kill()
break
if stall_s is not None and now - last_output[0] > stall_s:
# No real output for longer than the threshold: GMSH is stuck in a
# surface-recovery loop (or equivalent) and would hang forever.
# Kill the whole tree, record the numbers for the caller, and get
# out — the caller decides whether to retry in robust mode.
no_output_s = now - last_output[0]
elapsed_s = now - start
if stall_holder is not None:
stall_holder["stalled"] = True
stall_holder["elapsed_s"] = elapsed_s
stall_holder["no_output_s"] = no_output_s
on_line(
f"watchdog fired: no output for {int(no_output_s)}s "
f"({int(elapsed_s)}s elapsed) - killing process tree"
)
_kill_pid_tree(proc.pid)
with suppress(Exception):
proc.kill()
break
if now - last_activity[0] > heartbeat_s:
# CPU% over this heartbeat window: a busy-but-silent child shows a
# high number here even though no log line arrived (the exact
# false-positive the raised budget exists to tolerate).
cpu_pct = None
cpu_now = _process_cpu_seconds(proc)
if cpu_now is not None and _cpu_prev[1] is not None:
wall_delta = max(1e-6, now - _cpu_prev[0])
cpu_pct = 100.0 * max(0.0, cpu_now - _cpu_prev[1]) / wall_delta
_cpu_prev[0], _cpu_prev[1] = now, cpu_now
cpu_txt = f", CPU {cpu_pct:.0f}%" if cpu_pct is not None else ", CPU n/a"
on_line(
f"... still running ({int(now - start)}s elapsed, "
f"no output for {int(now - last_output[0])}s{cpu_txt})"
)
last_activity[0] = now
# Poll faster than the heartbeat interval: a 0.5 s sleep against a
# 0.3 s heartbeat made the emission a phase race with the child's
# own output cadence (under load the check could land right after
# every tick and NEVER fire - the "healthy stream" watchdog test
# caught exactly that on the CI/Linux scheduler). Sub-heartbeat
# polling also tightens the stall-detection granularity.
time.sleep(max(0.05, min(0.5, heartbeat_s / 2.0)))
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
pass
t_out.join(timeout=2)
t_err.join(timeout=2)
_release_job(proc)
if _rate["suppressed"]:
on_line(
f"... ({_rate['suppressed']} lines suppressed from live log — "
"output too verbose) ..."
)
_rate["suppressed"] = 0
return proc.returncode, stdout_lines, stderr_lines, timed_out
class GmshSurfaceWorker(QObject):
"""Runs GMSH surface STL generation + sizing in a subprocess.
GMSH's own bundled OpenCASCADE conflicts with cadquery/OCP's OpenCASCADE
when both are loaded in the same process, causing hard native crashes.
Running GMSH in a separate subprocess isolates this completely.
"""
finished = Signal(object) # dict with sizing results
log_line = Signal(str)
failed = Signal(str)
SURFACE_TIMEOUT_S = 180
def __init__(self, geom_path: str, stl_out: Path, detail: str, parent=None):
super().__init__(parent)
self._geom_path = geom_path
self._stl_out = stl_out
self._detail = detail
self._proc_holder: dict = {}
self._cancelled = False
@Slot()
def cancel(self):
"""Kill the live GMSH subprocess, if any is running right now.
Cancel in the GUI previously only tore down the QThread this runs
on — it never reached the actual GMSH child process spawned by
_stream_subprocess, which kept running orphaned (confirmed live:
Cancel visually reset the UI but the process stayed alive, and a
new run then meant two GMSH processes running at once).
"""
self._cancelled = True
proc = self._proc_holder.get("proc")
if proc is not None and proc.poll() is None:
_kill_pid_tree(proc.pid)
@Slot()
def run(self):
import json
args = ["surface", self._geom_path, str(self._stl_out), self._detail]
cmd, run_cwd = _gmsh_wrapper_script_cmd(args, "--gmsh-surface")
self.log_line.emit("[gmsh] Running surface STL generation in subprocess...")
try:
returncode, stdout_lines, stderr_lines, timed_out = _stream_subprocess(
cmd, run_cwd, self.SURFACE_TIMEOUT_S,
on_line=lambda ln: self.log_line.emit(f"[gmsh] {ln}"),
proc_holder=self._proc_holder,
)
except Exception as exc:
if not self._cancelled:
self.failed.emit(str(exc))
return
if self._cancelled:
self.log_line.emit("[gmsh] Surface generation cancelled.")
return
if timed_out:
self.failed.emit(f"GMSH surface exceeded {self.SURFACE_TIMEOUT_S}s")
return
# Parse stdout first — see _gmsh_wrapper_script_cmd's docstring and
# GmshVolumeWorker.run() for why returncode must not gate this.
result = None
non_empty = [ln for ln in stdout_lines if ln.strip()]
if non_empty:
try:
result = json.loads(non_empty[-1])
except json.JSONDecodeError:
result = None
if result is not None:
if not result.get("success"):
self.failed.emit(result.get("error", "Unknown GMSH error"))
return
self.finished.emit(result)
return
if returncode != 0:
self.failed.emit("\n".join(stderr_lines).strip() or f"GMSH surface failed (exit {returncode})")
return
self.failed.emit("GMSH surface: no JSON output produced")
def _parse_gmsh_json(stdout_lines) -> dict | None:
"""Last non-empty stdout line parsed as the wrapper CLI's JSON result.
The wrapper CLI always prints one JSON object as its final stdout line
(``{"success": ..., ...}``), after any GMSH ``Info:`` chatter. Returns
``None`` when there is no parseable JSON (a crash before the CLI's own
handler, for instance).
"""
import json
non_empty = [ln for ln in stdout_lines if ln.strip()]
if not non_empty:
return None
try:
return json.loads(non_empty[-1])
except json.JSONDecodeError:
return None
class GmshVolumeWorker(QObject):
"""Runs GMSH volume mesh generation in a subprocess."""
finished = Signal(object) # dict with path + names
log_line = Signal(str)
failed = Signal(str)
# Keep in sync with gmsh_subprocess.run_gmsh_volume's default (3600 s)
# and solution_adaptive's solver timeout: a Very Fine 20M-cap mesh can
# legitimately take far longer than the old 600 s, which produced false
# "GMSH volume exceeded" failures on real runs.
VOLUME_TIMEOUT_S = 3600
def __init__(self, step_path: str, msh_path: Path, detail: str,
n_layers: int = 0, bl_thickness: float | None = None,
bl_expansion: float = 1.2, refinement_zones: list | None = None,
max_cell_size: float = 0, min_cell_size: float = 0,
max_cells_target: int = 0,
size_field_file: str | Path | None = None,
surface_resolution: str = "medium",
bl_wall_size_floor: float = 0.0,
parent=None):
super().__init__(parent)
# Solution-derived target-size lattice (core.solution_adaptive). Passed
# to the subprocess by env var like refinement_zones — the CLI already
# takes ten positional args and an eleventh would be unreadable.
self._size_field_file = str(size_field_file) if size_field_file else ""
self._step_path = step_path
self._msh_path = msh_path
self._detail = detail
self._n_layers = n_layers
self._bl_thickness = bl_thickness
self._bl_expansion = bl_expansion
self._refinement_zones = refinement_zones or []
self._max_cell_size = max_cell_size
self._min_cell_size = min_cell_size
self._max_cells_target = max_cells_target
# Surface resolution preset + BL<->sizing wall-size floor (0 = off).
self._surface_resolution = surface_resolution or "medium"
self._bl_wall_size_floor = float(bl_wall_size_floor or 0.0)
self._proc_holder: dict = {}
self._cancelled = False
@Slot()
def cancel(self):
"""Kill the live GMSH subprocess, if any is running right now.
See GmshSurfaceWorker.cancel — same gap, same fix: Cancel in the
GUI previously reset the UI without ever touching this worker's
actual subprocess, which kept running orphaned in the background.
"""
self._cancelled = True
proc = self._proc_holder.get("proc")
if proc is not None and proc.poll() is None:
_kill_pid_tree(proc.pid)
@Slot()
def run(self):
import json
import os
# Phase-0 perf: wall-clock the whole GMSH stage (all attempts). The
# mode (normal/robust) is recorded once the attempt loop settles; the
# registry is keyed by the case dir (mesh.msh lives directly in it).
t_gmsh0 = time.perf_counter()
gmsh_case_dir = Path(self._msh_path).resolve().parent
gmsh_mode = "normal"
# A fresh GMSH attempt starts a fresh perf trace for this case.
_perf_reset(gmsh_case_dir)
# Pass refinement zones as JSON via env var (avoids shell-escaping issues)
zones_json = json.dumps(self._refinement_zones) if self._refinement_zones else ""
# Fase 3 P3.4: named flags instead of 10 positional slots.
args = [
"volume",
f"--step={self._step_path}",
f"--msh={self._msh_path}",
f"--detail={self._detail}",
f"--n-layers={self._n_layers}",
f"--bl-thickness={self._bl_thickness or 0}",
f"--bl-expansion={self._bl_expansion}",
f"--max-cell={self._max_cell_size}",
f"--min-cell={self._min_cell_size}",
f"--max-cells-target={self._max_cells_target}",
f"--surface-resolution={self._surface_resolution}",
f"--bl-wall-size-floor={self._bl_wall_size_floor}",
]
cmd, run_cwd = _gmsh_wrapper_script_cmd(args, "--gmsh-volume")
self.log_line.emit("[gmsh] Running volume mesh generation in subprocess...")
env = os.environ.copy()
if zones_json:
env["GMSH_REFINEMENT_ZONES"] = zones_json
if self._size_field_file:
env["GMSH_SOLUTION_SIZE_FIELD"] = self._size_field_file
self.log_line.emit(
f"[gmsh] solution-adaptive size field: {self._size_field_file}"
)
# Attempt chain: normal (MeshAdapt) -> robust (OCC healing + Delaunay
# 2D) -> manual-equivalent (adaptive sizing OFF, explicit sizes derived
# to match the requested cell target). Phase B kills a non-converging
# MeshAdapt runaway on its content signature; Phase D guarantees ONE
# last attempt with adaptive sizing off rather than a bare error while a
# mesh is still achievable. Never loops.
#
# Budget policy: the normal (MeshAdapt) attempt keeps the flat base
# (300 s) so the known 2D hang fails over fast; the robust and manual
# attempts are the ones expected to finish on a pathological surface,
# and a large job legitimately goes silent for minutes during HXT's 3D
# phase (measured ~54 s gaps on a 7M-tet part, scaling with machine
# load), so they get the size-scaled budget up to 900 s. An explicit
# POLYFOAMMESH_GMSH_STALL_S pins every attempt — no scaling.
stall_s = _gmsh_stall_timeout_s()
est_cells = _gmsh_job_cell_estimate(self._step_path, self._max_cells_target)
if _gmsh_stall_env_overridden():
robust_stall_s = stall_s
else:
robust_stall_s = _gmsh_stall_budget_s(stall_s, est_cells)
# Phase D only applies to an adaptive request: with explicit sizes there
# is no "adaptive sizing" to turn off (the caller already made that
# choice and the GUI's own BL/coarser-detail retries cover a failure).
can_fallback = self._max_cell_size <= 0 and self._min_cell_size <= 0
mode = "normal"
signature_retry = False
while True:
attempt_env = dict(env)
attempt_stall_s = stall_s
if mode == "robust":
attempt_env[GMSH_ROBUST_ENV_VAR] = "1"
if signature_retry:
# Phase C: quality optimizer ONLY on the signature retry.
attempt_env[GMSH_ROBUST_OPT_ENV_VAR] = "1"
attempt_stall_s = robust_stall_s
elif mode == "manual":
attempt_env[GMSH_MANUAL_EQUIV_ENV_VAR] = "1"
attempt_stall_s = robust_stall_s
self._proc_holder.clear()
stall_holder: dict = {}
signature_detector = GmshSignatureStallDetector()
try:
returncode, stdout_lines, stderr_lines, timed_out = _stream_subprocess(
cmd, run_cwd, self.VOLUME_TIMEOUT_S, env=attempt_env,
on_line=lambda ln: self.log_line.emit(f"[gmsh] {ln}"),
proc_holder=self._proc_holder,
stall_s=attempt_stall_s,
stall_holder=stall_holder,
signature_detector=signature_detector,
)
except Exception as exc:
if not self._cancelled:
self.failed.emit(str(exc))
return
if self._cancelled:
self.log_line.emit("[gmsh] Volume generation cancelled.")
return
if timed_out:
# Hard ceiling: the GUI must not be held for another attempt.
self.failed.emit(f"GMSH volume exceeded {self.VOLUME_TIMEOUT_S}s")
return
if stall_holder.get("stalled"):
no_output_s = stall_holder.get("no_output_s", 0.0)
signature = bool(stall_holder.get("signature"))
evidence = str(stall_holder.get("evidence", ""))
if mode == "normal":
if signature:
signature_retry = True
self.log_line.emit(
"[gmsh] non-convergence detected: "
f"{evidence} - retrying robust"
)
else:
self.log_line.emit(
"[gmsh] stalled: no output for "
f"{int(no_output_s)}s (surface meshing loop?) - "
"killed; retrying in robust mode (healing + "
"Delaunay 2D, no optimization)"
)
if robust_stall_s > stall_s:
self.log_line.emit(
f"[gmsh] robust stall budget raised to "
f"{int(robust_stall_s)}s (estimated {est_cells:,} "
f"cells; base {int(stall_s)}s)"
)
mode = "robust"
gmsh_mode = "robust"
continue
# robust or manual attempt failed: try the manual-equivalent
# fallback once (robust only), else fail honestly.
if self._start_manual_fallback(
mode, can_fallback, signature, evidence, no_output_s,
):
mode = "manual"
gmsh_mode = "manual"
continue
self._fail_after_stall(mode, signature, evidence, no_output_s)
return
# Attempt completed with real output: parse its result.
# Parse stdout FIRST, even on a non-zero exit: the CLI's own
# except-block always reports a caught error as JSON on stdout
# ({"success": false, "error": "..."}) before calling sys.exit(1)
# — that's the real, specific failure reason. Checking returncode
# first (the previous order) discarded that message in favor of
# raw stderr, which can contain unrelated noise (e.g. Python's
# own "module found in sys.modules" RuntimeWarning from the -m
# invocation). GMSH itself may print "Info:" lines to stdout
# before the JSON, so take the last non-empty line.
result = _parse_gmsh_json(stdout_lines)
if result is not None and result.get("success"):
_perf_record(gmsh_case_dir, "gmsh", time.perf_counter() - t_gmsh0)
_perf_note(gmsh_case_dir, "gmsh_mode", gmsh_mode)
_perf_log(gmsh_case_dir, self.log_line.emit)
self.finished.emit(result)
return
if result is not None:
err = result.get("error", "Unknown GMSH error")
elif returncode != 0:
err = "\n".join(stderr_lines).strip() or (
f"GMSH volume failed (exit {returncode})"
)
else:
err = "GMSH volume: no JSON output produced"
# A robust attempt that errored (not stalled) is still a failed
# robust retry: run the one manual-equivalent attempt if possible.
if self._start_manual_fallback(mode, can_fallback):
mode = "manual"
gmsh_mode = "manual"
continue
self.failed.emit(err)
return
def _start_manual_fallback(
self, mode: str, can_fallback: bool,
signature: bool = False, evidence: str = "", no_output_s: float = 0.0,
) -> bool:
"""Log and approve the one manual-equivalent (adaptive-OFF) attempt.
Returns False when there is no fallback left (not a robust attempt, or
an explicit-size request) — the caller then fails honestly.
"""
if mode != "robust" or not can_fallback:
return False
if signature:
self.log_line.emit(
"[gmsh] non-convergence detected: "
f"{evidence} - robust attempt did not converge"
)
elif no_output_s:
self.log_line.emit(
"[gmsh] robust retry also stalled (no output for "
f"{int(no_output_s)}s)"
)
else:
self.log_line.emit("[gmsh] robust attempt failed")
self.log_line.emit(
"[gmsh] adaptive sizing did not converge on this geometry - "
"meshed with the manual equivalent sizing"
)
return True
def _fail_after_stall(
self, mode: str, signature: bool, evidence: str, no_output_s: float,
) -> None:
"""Emit the honest terminal failure after the last attempt stalled."""
if mode == "manual":
self.log_line.emit(
"[gmsh] manual-equivalent fallback also stalled - giving up."
)
self.failed.emit(
"GMSH volume failed after the adaptive, robust and "
"manual-equivalent attempts (no output for "
f"{int(no_output_s)}s in the manual attempt). The surface is "
"likely unmeshable; see the log above."
)
return
self.log_line.emit(
"[gmsh] robust retry also "
+ ("did not converge" if signature else "stalled")
+ " - giving up."
)
if signature:
self.failed.emit(
"GMSH volume did not converge even in robust mode "
f"({evidence}) after the normal attempt also stalled. The "
"surface is likely unmeshable; see the log above."
)
else:
self.failed.emit(
"GMSH volume stalled twice: no output for "
f"{int(no_output_s)}s in robust mode (healing + "
"Delaunay 2D, no optimization) after the normal "
"attempt also stalled. The surface is likely "
"unmeshable; see the log above."
)
class WatertightWorker(QObject):
"""Runs watertight check + optional pymeshfix repair in a subprocess."""
finished = Signal(object)
log_line = Signal(str)
failed = Signal(str)
TIMEOUT_S = 180
def __init__(self, stl_paths: list[Path], parent=None):
super().__init__(parent)
self._stl_paths = stl_paths
self._proc_holder: dict = {}
self._cancelled = False
@Slot()
def cancel(self):
"""Kill the live subprocess, if any is running right now. See
GmshSurfaceWorker.cancel for why this exists."""
self._cancelled = True
proc = self._proc_holder.get("proc")
if proc is not None and proc.poll() is None:
_kill_pid_tree(proc.pid)
@Slot()
def run(self):
import json
args = ["check"] + [str(p) for p in self._stl_paths]
cmd, run_cwd = _gmsh_wrapper_script_cmd(
args, "--watertight", script_name="geometry_repair.py",
)
self.log_line.emit("[watertight] Checking geometry...")
try:
returncode, stdout_lines, stderr_lines, timed_out = _stream_subprocess(
cmd, run_cwd, self.TIMEOUT_S,
on_line=lambda ln: self.log_line.emit(f"[watertight] {ln}"),
proc_holder=self._proc_holder,
)
except Exception as exc:
if not self._cancelled:
self.failed.emit(str(exc))
return
if self._cancelled:
self.log_line.emit("[watertight] Cancelled.")
return
if timed_out:
self.failed.emit(f"Watertight check exceeded {self.TIMEOUT_S}s")
return
result = None
non_empty = [ln for ln in stdout_lines if ln.strip()]
if non_empty:
try:
result = json.loads(non_empty[-1])
except json.JSONDecodeError:
result = None
if result is not None:
if not result.get("success"):
self.failed.emit(result.get("error", "Unknown error"))
return
self.finished.emit(result)
return
if returncode != 0:
self.failed.emit("\n".join(stderr_lines).strip() or f"Check failed (exit {returncode})")
return
self.failed.emit("Watertight: no JSON output produced")
class ExportWorker(QObject):
"""Export mesh to a format in a background thread.
Signals:
finished(str): emitted with the output path on success.
error_occurred(str): emitted with the error message on failure.
"""
finished = Signal(str)
error_occurred = Signal(str)
def __init__(self, case_dir: Path, fmt: str, output_path: str, of_config=None):
super().__init__()
self._case_dir = case_dir
self._fmt = fmt
self._output_path = output_path
self._of_config = of_config
def run(self):
try:
from polyfoammesh.core.mesh_export import export_mesh
out = export_mesh(self._case_dir, self._fmt, self._output_path, of_config=self._of_config)
self.finished.emit(str(out))
except Exception as e:
self.error_occurred.emit(str(e))
class SolutionAdaptiveWorker(QObject):
"""Runs the solution-adaptive refinement loop in a background QThread.
The loop is solve -> compute a refinement indicator -> remesh from the
original CAD with a solution-derived size field, repeated until the
engineering quantity of interest stops moving (see
``core.solution_adaptive``). Every stage is emitted on ``log_line`` so the
visible GUI log shows solve progress, residuals, indicator statistics, the
target sizing chosen and the cell counts — a multi-minute loop that logged
nothing would be indistinguishable from a hang.
The remesh half is supplied by the caller as *remesh_fn* rather than being
hard-coded here, because the GUI already owns the mesh-generation path
(geometry, detail level, BL settings, patch naming) and duplicating it
would let the adaptive mesh silently diverge from the normal one.
"""
log_line = Signal(str)
finished = Signal(object) # AdaptiveResult
failed = Signal(str)
cycle_done = Signal(int, int) # (cycle, n_cells)
def __init__(self, case_dir: Path | str, bounds: tuple, remesh_fn,
params=None, of_config: OFConfig | None = None, parent=None):
super().__init__(parent)
self._case_dir = Path(case_dir).resolve()
self._bounds = bounds
self._remesh_fn = remesh_fn
self._params = params
self._of_config = of_config or OFConfig()
self._cancelled = False
@Slot()
def cancel(self):
self._cancelled = True
self.log_line.emit(
"[adaptive] Cancel requested — will stop after the current stage."
)
@Slot()
def run(self):
from polyfoammesh.core.solution_adaptive import (
AdaptiveParams, SolutionAdaptiveRefiner,
)
params = self._params or AdaptiveParams()
def _remesh(size_field: Path, cycle: int):
if self._cancelled:
raise RuntimeError("cancelled by user")
case_dir, n_cells = self._remesh_fn(size_field, cycle)
self.cycle_done.emit(cycle, n_cells)
return case_dir, n_cells
try:
refiner = SolutionAdaptiveRefiner(
params=params, of_config=self._of_config,
on_line=self.log_line.emit,
)
result = refiner.run(
initial_case_dir=self._case_dir,
bounds=self._bounds,
remesh_fn=_remesh,
)
except Exception as exc: # noqa: BLE001 — surfaced to the GUI
logger.exception("Solution-adaptive refinement worker failed")
self.failed.emit(str(exc))
return
for line in result.summary().splitlines():
self.log_line.emit(f"[adaptive] {line}")
if result.errors and not result.cycles:
self.failed.emit("; ".join(result.errors))
return
self.finished.emit(result)