From 8fbcd0dbbdf9a45f04fe66850f5de9f4558e664f Mon Sep 17 00:00:00 2001
From: Claude
Date: Thu, 12 Nov 2026 20:28:08 +0000
Subject: [PATCH 01/64] Fix misleading SCF status and stale constant/schema
docs (audit SCF-11)
- freq_calc: the "SCF converged. Computing analytical Hessian..." status
was emitted before mf.converged was read, so an unconverged reference
SCF was announced as converged. Read converged first and word the
status accordingly.
- session_calc: HARTREE_TO_EV comment claimed consistency with PySCF; it
is CODATA 2018, PySCF's nist.HARTREE2EV is CODATA 2014 (negligible).
- vib_cache: module docstring index.json example now shows fps, bgcolor
and the per-mode mac the code actually writes.
The wB97X-D "wb97x + external D3" comments named in the audit were
already corrected by the SCF-2 fix on main.
Text/comment-only; no test.
Contributions:
- Claude (Opus 5.5): code edits, review, and conceptual discussion
- Jonathan Schultz: overall vision, planning, review, and orchestration
Co-authored-by: Jonathan Schultz
Co-authored-by: Claude Opus 5.5
---
quantui/freq_calc.py | 7 +++++--
quantui/session_calc.py | 3 ++-
quantui/vib_cache.py | 5 ++++-
3 files changed, 11 insertions(+), 4 deletions(-)
diff --git a/quantui/freq_calc.py b/quantui/freq_calc.py
index 80174ea9..9706a6f7 100644
--- a/quantui/freq_calc.py
+++ b/quantui/freq_calc.py
@@ -727,9 +727,12 @@ def _status(msg: str) -> None:
f"SCF failed for {molecule.get_formula()} ({method}/{basis}): {exc}"
) from exc
- _status("SCF converged. Computing analytical Hessian...")
-
converged = bool(getattr(mf, "converged", False))
+ _status(
+ "SCF converged. Computing analytical Hessian..."
+ if converged
+ else "SCF did not converge. Computing analytical Hessian anyway..."
+ )
scf_rescue_stage = str(getattr(mf, "scf_rescue_stage", "none") or "none")
n_iterations = int(getattr(mf, "cycles", -1))
diff --git a/quantui/session_calc.py b/quantui/session_calc.py
index d7c76e73..0481c253 100644
--- a/quantui/session_calc.py
+++ b/quantui/session_calc.py
@@ -29,7 +29,8 @@
logger = logging.getLogger(__name__)
-# NIST 2018 CODATA — consistent with PySCF's internal constant
+# CODATA 2018. PySCF's ``pyscf.data.nist.HARTREE2EV`` is the CODATA 2014
+# value 27.21138602; the difference (~6e-8 eV/Ha) is negligible here.
HARTREE_TO_EV: float = 27.211386245988
diff --git a/quantui/vib_cache.py b/quantui/vib_cache.py
index 2f7a58ef..ca12cad3 100644
--- a/quantui/vib_cache.py
+++ b/quantui/vib_cache.py
@@ -23,8 +23,11 @@
"n_frames": 24,
"amplitude": 0.4,
"renderer": "py3dmol",
+ "fps": 12,
+ "bgcolor": "#ffffff",
"modes": {
- "1": {"cached": true, "file": "mode_001.html", "freq_cm1": 1623.4},
+ "1": {"cached": true, "file": "mode_001.html", "mac": "",
+ "freq_cm1": 1623.4},
"2": {"cached": false}
}
}
From 7b4307065d2e4b67403eb40d33f75f048a40a12b Mon Sep 17 00:00:00 2001
From: Claude
Date: Thu, 12 Nov 2026 20:29:50 +0000
Subject: [PATCH 02/64] Engines: case/notation-insensitive basis match, PyFock
ECP guard and spin (audit SCF-12)
- engines.run_calc matched methods case-insensitively but the basis by
exact string, so "sto-3g", "def2-svp" or the Pople parenthesis
notation "6-31G(d)" (same set as "6-31G*") were refused. A new
_match_basis compares case-insensitively and accepts either Pople
notation (config.pople_notation_alias); the request handed to the
engine carries the engine's own listed spelling, so adapters that
compare exactly (PyFock) still accept it.
- PyFock: def2 basis sets put an ECP on every element after Kr (Z > 36);
PyFock applies none, so such molecules would run all-electron against
a valence-only basis. _validate_request now refuses them with a
message pointing at PySCF.
- PyFock single-point SessionResult left multiplicity=None; it is now
set from the request (always 1 on this engine).
Not changed (needs a PyFock install to verify): the process-global
stdout/stderr redirect and the coordinate-unit check.
Tests: test_engines_registry run_calc basis matching (parametrised) and
unknown-basis rejection; test_pyfock_engine ECP rejection, the Z > 36
helper, and multiplicity on the native result. All new tests fail on
the old code.
Contributions:
- Claude (Opus 5.5): code edits, review, and conceptual discussion
- Jonathan Schultz: overall vision, planning, review, and orchestration
Co-authored-by: Jonathan Schultz
Co-authored-by: Claude Opus 5.5
---
quantui/engines/__init__.py | 43 ++++++++++++++++++-------
quantui/engines/pyfock_engine.py | 31 +++++++++++++++++-
tests/test_engines_registry.py | 54 ++++++++++++++++++++++++++++++++
tests/test_pyfock_engine.py | 18 +++++++++++
4 files changed, 133 insertions(+), 13 deletions(-)
diff --git a/quantui/engines/__init__.py b/quantui/engines/__init__.py
index 9cfbc81e..2badaa7c 100644
--- a/quantui/engines/__init__.py
+++ b/quantui/engines/__init__.py
@@ -2,8 +2,9 @@
from __future__ import annotations
+import dataclasses
import sys
-from typing import Literal
+from typing import Iterable, Literal, Optional
from .base import (
CALC_TYPES,
@@ -89,6 +90,23 @@ def resolve_engine(preferred: EnginePreference | None = None) -> QuantumEngine:
return by_id[choice]
+def _match_basis(requested: str, supported: Iterable[str]) -> Optional[str]:
+ """Return the engine's own spelling of ``requested``, or ``None``.
+
+ Basis names are case-insensitive (``sto-3g`` is ``STO-3G``) and the two
+ Pople notations name the same set (``6-31G(d)`` is ``6-31G*``), so the
+ match ignores case and accepts either notation. The engine's listed
+ spelling is returned so adapters that compare exactly still accept it.
+ """
+ from quantui.config import pople_notation_alias
+
+ wanted = str(requested).strip().upper()
+ for name in supported:
+ if wanted in (name.upper(), pople_notation_alias(name).upper()):
+ return name
+ return None
+
+
def run_calc(
request: EngineRequest,
preferred: EnginePreference | None = None,
@@ -112,17 +130,18 @@ def run_calc(
"Choose one of the methods shown in the engine-gated menu."
),
)
- if (
- caps.supported_basis_sets is not None
- and request.basis not in caps.supported_basis_sets
- ):
- raise UnsupportedCapabilityError(
- f"{caps.display_name} does not support basis {request.basis!r}.",
- user_message=(
- f"{request.basis} is not available with {caps.display_name}. "
- "Choose one of the basis sets shown in the engine-gated menu."
- ),
- )
+ if caps.supported_basis_sets is not None:
+ basis = _match_basis(request.basis, caps.supported_basis_sets)
+ if basis is None:
+ raise UnsupportedCapabilityError(
+ f"{caps.display_name} does not support basis {request.basis!r}.",
+ user_message=(
+ f"{request.basis} is not available with {caps.display_name}. "
+ "Choose one of the basis sets shown in the engine-gated menu."
+ ),
+ )
+ if basis != request.basis:
+ request = dataclasses.replace(request, basis=basis)
return engine.run(request)
diff --git a/quantui/engines/pyfock_engine.py b/quantui/engines/pyfock_engine.py
index 69fb16dc..de8847bd 100644
--- a/quantui/engines/pyfock_engine.py
+++ b/quantui/engines/pyfock_engine.py
@@ -197,6 +197,8 @@ def _run_single_point(self, request: EngineRequest) -> EngineResult:
gpu_name=_gpu_name,
)
native = result.to_session_result()
+ # EngineResult carries no spin; PyFock only runs closed-shell singlets.
+ native.multiplicity = request.multiplicity
_attach_analysis(native, mol, basis, dft, density, atoms, coordinates, warnings)
result.native_result = native
return result
@@ -283,7 +285,34 @@ def _validate_request(self, request: EngineRequest) -> None:
"PyFock solvent models are not enabled.",
user_message="Implicit solvent is not available with PyFock.",
)
- _molecule_arrays(request.molecule)
+ atoms, _coords = _molecule_arrays(request.molecule)
+ heavy = _ecp_elements(atoms)
+ if heavy:
+ raise UnsupportedCapabilityError(
+ f"PyFock has no ECP support for {', '.join(heavy)}.",
+ user_message=(
+ f"{', '.join(heavy)} need an effective core potential "
+ "(ECP) with the def2 basis sets, which PyFock does not "
+ "apply. Select PySCF for elements beyond krypton."
+ ),
+ )
+
+
+# def2 basis sets put an ECP on every element after Kr (Z > 36); PyFock would
+# run those all-electron against a valence-only basis (garbage energies).
+_MAX_ALL_ELECTRON_Z = 36
+
+
+def _ecp_elements(atoms) -> list:
+ """Element symbols in ``atoms`` that need a def2 ECP, sorted, unique."""
+ from quantui.config import ATOMIC_NUMBERS
+
+ found = set()
+ for atom in atoms:
+ sym = str(atom).strip().title()
+ if ATOMIC_NUMBERS.get(sym, 0) > _MAX_ALL_ELECTRON_Z:
+ found.add(sym)
+ return sorted(found)
def _load_pyfock_api():
diff --git a/tests/test_engines_registry.py b/tests/test_engines_registry.py
index c96bedc2..f6e36457 100644
--- a/tests/test_engines_registry.py
+++ b/tests/test_engines_registry.py
@@ -209,6 +209,60 @@ def test_run_calc_calls_resolved_engine(self):
assert actual is expected
mocked_run.assert_called_once_with(request)
+ @pytest.mark.parametrize(
+ ("engine_cls", "requested", "expected"),
+ [
+ (PyfockEngine, "def2-svp", "def2-SVP"),
+ (PyfockEngine, "DEF2-TZVP", "def2-TZVP"),
+ (PyscfEngine, "sto-3g", "STO-3G"),
+ (PyscfEngine, "6-31G(d)", "6-31G*"),
+ (PyscfEngine, "6-31g(d,p)", "6-31G**"),
+ (PyscfEngine, "6-31+G(d)", "6-31+G*"),
+ ],
+ )
+ def test_run_calc_basis_match_ignores_case_and_pople_notation(
+ self, engine_cls, requested, expected
+ ):
+ """Audit SCF-12: basis names are matched like methods (case-insensitive)
+ and either Pople notation is accepted; the engine gets its own spelling."""
+ engine = engine_cls()
+ request = EngineRequest(
+ request_id="req-b",
+ calc_type="single_point",
+ method="PBE",
+ basis=requested,
+ charge=0,
+ multiplicity=1,
+ molecule={"atoms": ["He"], "coordinates": [[0.0, 0.0, 0.0]]},
+ )
+ with (
+ patch("quantui.engines.resolve_engine", return_value=engine),
+ patch.object(engine, "run", return_value="ok") as mocked_run,
+ ):
+ assert run_calc(request) == "ok"
+ assert mocked_run.call_args.args[0].basis == expected
+
+ def test_run_calc_rejects_unknown_basis(self):
+ from quantui.engines import UnsupportedCapabilityError
+
+ engine = PyfockEngine()
+ request = EngineRequest(
+ request_id="req-x",
+ calc_type="single_point",
+ method="PBE",
+ basis="6-31G(d)",
+ charge=0,
+ multiplicity=1,
+ molecule={"atoms": ["He"], "coordinates": [[0.0, 0.0, 0.0]]},
+ )
+ with (
+ patch("quantui.engines.resolve_engine", return_value=engine),
+ patch.object(engine, "run") as mocked_run,
+ pytest.raises(UnsupportedCapabilityError),
+ ):
+ run_calc(request)
+ mocked_run.assert_not_called()
+
def test_request_portable_dict_excludes_runtime_objects(self):
stream = object()
checkpoint = object()
diff --git a/tests/test_pyfock_engine.py b/tests/test_pyfock_engine.py
index b1073d51..a27b60b5 100644
--- a/tests/test_pyfock_engine.py
+++ b/tests/test_pyfock_engine.py
@@ -131,6 +131,7 @@ def test_water_result_and_stdout_capture(self):
assert result.native_result.engine_id == "pyfock"
assert result.native_result.density_fit is True
assert result.native_result.scf_variant == "RKS"
+ assert result.native_result.multiplicity == 1 # audit SCF-12
assert result.native_result.mo_energy_hartree.tolist() == [-0.8, -0.4, 0.1]
assert result.native_result.mo_coeff.shape == (3, 3)
assert result.native_result.mulliken_charges == pytest.approx([6.0, 0.0, 0.0])
@@ -162,6 +163,23 @@ def test_unsupported_science_is_rejected_early(self, field, value, message):
PyfockEngine().run(_request(**{field: value}))
assert message in exc.value.user_message
+ def test_elements_needing_an_ecp_are_rejected(self):
+ """Audit SCF-12: def2 puts an ECP on Z > 36; PyFock applies none."""
+ mol = {
+ "atoms": ["H", "I"],
+ "coordinates": [[0.0, 0.0, 0.0], [0.0, 0.0, 1.61]],
+ }
+ with pytest.raises(UnsupportedCapabilityError) as exc:
+ PyfockEngine().run(_request(molecule=mol))
+ assert "I" in str(exc.value)
+ assert "effective core potential" in exc.value.user_message
+
+ def test_krypton_and_lighter_are_not_ecp_rejected(self):
+ from quantui.engines.pyfock_engine import _ecp_elements
+
+ assert _ecp_elements(["H", "Br", "Kr", "C"]) == []
+ assert _ecp_elements(["Rb", "I", "Xe", "I"]) == ["I", "Rb", "Xe"]
+
def test_third_party_failure_becomes_error_result(self):
class FailingDFT(_FakeDFT):
def scf(self):
From 2a344730b842c903670f1623f67bea9254a1c8ef Mon Sep 17 00:00:00 2001
From: Claude
Date: Thu, 12 Nov 2026 20:32:34 +0000
Subject: [PATCH 03/64] SCF hygiene: one GPU opt-out parser, one host-array
helper, locked vib index (audit SCF-13)
- QUANTUI_DISABLE_GPU accepted only 1/true/True in gpu_offload and
pyfock_gpu, while freq_ir_workers._truthy (which claims to match it)
accepts 1/true/yes/on in any case. New gpu_offload.env_gpu_disabled()
uses the _truthy convention; both GPU probes call it.
- session_calc: the run-body closure _to_numpy_array duplicated
_host_array line for line; removed and the gap extraction now calls
_host_array. The existing regression test that pinned the closure's
name (test_bug_regressions_2026_05_25) now exercises _host_array and
checks the gap extraction uses it.
- vib_cache.save_cached_html: the index read-modify-write is now under
an in-process lock, so concurrent saves of different modes can't drop
each other's manifest entry.
- scf_robust: the bootstrap SCF now inherits the target's per-cycle
callback, so a Cancel click also stops the bootstrap stage.
Not done (design/perf, out of scope for a Low fix): merging the IR and
Raman displaced-SCF loops; skipping the bootstrap when the target is
itself plain RHF/UHF.
Tests: test_gpu_offload env_gpu_disabled true/false values,
test_pyfock_gpu opt-out with "yes", test_vib_cache concurrent saves,
test_scf_robust bootstrap callback. The pyfock_gpu, vib_cache and
scf_robust tests fail on the old code.
Contributions:
- Claude (Opus 5.5): code edits, review, and conceptual discussion
- Jonathan Schultz: overall vision, planning, review, and orchestration
Co-authored-by: Jonathan Schultz
Co-authored-by: Claude Opus 5.5
---
quantui/gpu_offload.py | 13 ++-
quantui/pyfock_gpu.py | 5 +-
quantui/scf_robust.py | 3 +
quantui/session_calc.py | 26 +----
quantui/vib_cache.py | 131 ++++++++++++-----------
tests/test_bug_regressions_2026_05_25.py | 28 ++---
tests/test_gpu_offload.py | 18 ++++
tests/test_pyfock_gpu.py | 10 ++
tests/test_scf_robust.py | 18 ++++
tests/test_vib_cache.py | 36 +++++++
10 files changed, 183 insertions(+), 105 deletions(-)
diff --git a/quantui/gpu_offload.py b/quantui/gpu_offload.py
index c74ff5a7..2fd7450d 100644
--- a/quantui/gpu_offload.py
+++ b/quantui/gpu_offload.py
@@ -93,6 +93,17 @@
"TITAN V",
)
+
+def env_gpu_disabled() -> bool:
+ """True when ``QUANTUI_DISABLE_GPU`` is set to a truthy value.
+
+ Accepts ``1``/``true``/``yes``/``on`` in any case — the same convention as
+ the other ``QUANTUI_*`` switches (``freq_ir_workers._truthy``).
+ """
+ value = os.environ.get("QUANTUI_DISABLE_GPU", "")
+ return value.strip().lower() in ("1", "true", "yes", "on")
+
+
# Reason strings for the "GPU not in use" cases, surfaced by `quantui gpu check`
# and the System Settings tab. Kept here so the CLI and the UI can't drift from the
# probe's actual logic (they previously re-derived it, which is how a broken
@@ -158,7 +169,7 @@ def _probe_gpu() -> Tuple[bool, Optional[str], str]:
Failures at any step are swallowed and logged; this never raises.
"""
- if os.environ.get("QUANTUI_DISABLE_GPU", "").strip() in ("1", "true", "True"):
+ if env_gpu_disabled():
return (False, None, _REASON_ENV_DISABLED)
if not _gpu_enabled_in_settings():
return (False, None, _REASON_SETTINGS_DISABLED)
diff --git a/quantui/pyfock_gpu.py b/quantui/pyfock_gpu.py
index 204907d2..29fd2d43 100644
--- a/quantui/pyfock_gpu.py
+++ b/quantui/pyfock_gpu.py
@@ -13,7 +13,6 @@
from __future__ import annotations
import logging
-import os
from functools import lru_cache
from typing import Any, Optional
@@ -54,7 +53,9 @@ def _device_name(cupy_module: Any) -> str:
@lru_cache(maxsize=1)
def _probe_pyfock_gpu() -> tuple[bool, Optional[str], str]:
"""Return ``(available, device_name, reason)`` for the PyFock GPU path."""
- if os.environ.get("QUANTUI_DISABLE_GPU", "").strip() in ("1", "true", "True"):
+ from .gpu_offload import env_gpu_disabled
+
+ if env_gpu_disabled():
return False, None, _REASON_ENV_DISABLED
if not _gpu_enabled_in_settings():
return False, None, _REASON_SETTINGS_DISABLED
diff --git a/quantui/scf_robust.py b/quantui/scf_robust.py
index 73bfe6e6..3e7ef508 100644
--- a/quantui/scf_robust.py
+++ b/quantui/scf_robust.py
@@ -150,6 +150,9 @@ def _status(msg: str) -> None:
mol = mf.mol
bootstrap = _scf.UHF(mol) if mol.spin != 0 else _scf.RHF(mol)
bootstrap.verbose = 0
+ # Same per-cycle hook as the target (cancel/progress), so a Cancel click
+ # also stops the bootstrap SCF instead of waiting for it to finish.
+ bootstrap.callback = getattr(mf, "callback", None)
bootstrap.kernel()
energy = float(mf.kernel(dm0=bootstrap.make_rdm1(), **kernel_kwargs))
if mf.converged:
diff --git a/quantui/session_calc.py b/quantui/session_calc.py
index 0481c253..090af966 100644
--- a/quantui/session_calc.py
+++ b/quantui/session_calc.py
@@ -1080,35 +1080,15 @@ def _run_session_calc_body(
converged = scf_converged and bool(cc_converged)
n_iterations = int(getattr(mf, "cycles", -1))
- import numpy as _np
-
- def _to_numpy_array(arr: Any) -> Any:
- """Convert ``arr`` to a NumPy array, transferring from GPU if needed.
-
- gpu4pyscf returns CuPy arrays (``mf.mo_occ`` / ``mo_energy`` / ``mo_coeff``
- on a GPU-offloaded run). ``numpy.array(cupy_array)`` raises (NumPy refuses
- implicit device→host transfers), so probe for CuPy's ``.get()`` host copy
- first. Returns ``None`` unchanged.
- """
- if arr is None:
- return None
- # CuPy arrays have a ``.get()`` method (synchronous device→host copy).
- # Probe for it rather than importing cupy, so the CPU-only path doesn't
- # pull cupy onto the import graph.
- get = getattr(arr, "get", None)
- if callable(get) and type(arr).__module__.startswith("cupy"):
- return _np.asarray(get())
- return _np.asarray(arr)
-
homo_lumo_gap_ev: Optional[float] = None
try:
- # Route through _to_numpy_array: on a GPU-offloaded run mf.mo_occ /
- # mo_energy are CuPy arrays, and the old ``_np.array(mo_occ_ref)`` here
+ # Route through _host_array: on a GPU-offloaded run mf.mo_occ /
+ # mo_energy are CuPy arrays, and the old ``np.array(mo_occ_ref)`` here
# raised (silently → gap None). Same CuPy fix the MO-array extraction
# below already had; this block was overlooked.
# UHF/UKS: (2, n_mo) -- the gap spans both spin channels.
_gap_ha = homo_lumo_gap_hartree(
- _to_numpy_array(mf.mo_energy), _to_numpy_array(mf.mo_occ)
+ _host_array(mf.mo_energy), _host_array(mf.mo_occ)
)
if _gap_ha is not None:
homo_lumo_gap_ev = float(_gap_ha * HARTREE_TO_EV)
diff --git a/quantui/vib_cache.py b/quantui/vib_cache.py
index ca12cad3..ac43ac50 100644
--- a/quantui/vib_cache.py
+++ b/quantui/vib_cache.py
@@ -70,12 +70,18 @@
import os
import re
import secrets
+import threading
from pathlib import Path
from typing import Optional, cast
_SCHEMA_VERSION = 1
_LOG = logging.getLogger(__name__)
+# Serialises the index read-modify-write in save_cached_html, so two modes
+# saved concurrently (e.g. from a background render thread) can't drop each
+# other's manifest entry. In-process only.
+_INDEX_LOCK = threading.Lock()
+
# Floating-point tolerance when comparing saved vs requested amplitude. Avoids
# spurious cache misses when 0.4 round-trips through JSON serialization.
_AMPLITUDE_TOL = 1e-6
@@ -259,71 +265,72 @@ def save_cached_html(
)
return
- idx = load_index(result_dir)
- if (
- idx.get("_schema_version") != _SCHEMA_VERSION
- or idx.get("n_frames") != n_frames
- or not _amplitude_matches(idx.get("amplitude"), amplitude)
- or idx.get("renderer") != renderer
- or idx.get("fps") != fps
- or idx.get("bgcolor") != bgcolor
- ):
- idx = {
- "_schema_version": _SCHEMA_VERSION,
- "n_frames": n_frames,
- "amplitude": amplitude,
- "renderer": renderer,
- "fps": fps,
- "bgcolor": bgcolor,
- "modes": {},
- }
-
- fname = f"mode_{mode_number:03d}.html"
- html_path = cdir / fname
- tmp_html = html_path.with_suffix(html_path.suffix + ".tmp")
- try:
- tmp_html.write_text(html, encoding="utf-8")
- os.replace(tmp_html, html_path)
- except OSError as exc:
- _LOG.warning(
- "Failed to save cached html to %s (%s)",
- html_path,
- exc,
- )
+ with _INDEX_LOCK:
+ idx = load_index(result_dir)
+ if (
+ idx.get("_schema_version") != _SCHEMA_VERSION
+ or idx.get("n_frames") != n_frames
+ or not _amplitude_matches(idx.get("amplitude"), amplitude)
+ or idx.get("renderer") != renderer
+ or idx.get("fps") != fps
+ or idx.get("bgcolor") != bgcolor
+ ):
+ idx = {
+ "_schema_version": _SCHEMA_VERSION,
+ "n_frames": n_frames,
+ "amplitude": amplitude,
+ "renderer": renderer,
+ "fps": fps,
+ "bgcolor": bgcolor,
+ "modes": {},
+ }
+
+ fname = f"mode_{mode_number:03d}.html"
+ html_path = cdir / fname
+ tmp_html = html_path.with_suffix(html_path.suffix + ".tmp")
try:
- if tmp_html.exists():
- tmp_html.unlink()
- except OSError:
- pass
- return
-
- mac = _mac(html)
- if mac is None:
- return
- modes = idx.setdefault("modes", {})
- modes[str(mode_number)] = {
- "cached": True,
- "file": fname,
- "mac": mac,
- "freq_cm1": float(freq_cm1) if freq_cm1 is not None else None,
- }
+ tmp_html.write_text(html, encoding="utf-8")
+ os.replace(tmp_html, html_path)
+ except OSError as exc:
+ _LOG.warning(
+ "Failed to save cached html to %s (%s)",
+ html_path,
+ exc,
+ )
+ try:
+ if tmp_html.exists():
+ tmp_html.unlink()
+ except OSError:
+ pass
+ return
+
+ mac = _mac(html)
+ if mac is None:
+ return
+ modes = idx.setdefault("modes", {})
+ modes[str(mode_number)] = {
+ "cached": True,
+ "file": fname,
+ "mac": mac,
+ "freq_cm1": float(freq_cm1) if freq_cm1 is not None else None,
+ }
- index_path = cdir / "index.json"
- tmp_idx = index_path.with_suffix(index_path.suffix + ".tmp")
- try:
- tmp_idx.write_text(json.dumps(idx, indent=2), encoding="utf-8")
- os.replace(tmp_idx, index_path)
- except OSError as exc:
- _LOG.warning(
- "Failed to save cache index to %s (%s)",
- index_path,
- exc,
- )
+ index_path = cdir / "index.json"
+ tmp_idx = index_path.with_suffix(index_path.suffix + ".tmp")
try:
- if tmp_idx.exists():
- tmp_idx.unlink()
- except OSError:
- pass
+ tmp_idx.write_text(json.dumps(idx, indent=2), encoding="utf-8")
+ os.replace(tmp_idx, index_path)
+ except OSError as exc:
+ _LOG.warning(
+ "Failed to save cache index to %s (%s)",
+ index_path,
+ exc,
+ )
+ try:
+ if tmp_idx.exists():
+ tmp_idx.unlink()
+ except OSError:
+ pass
def _amplitude_matches(saved: object, requested: float) -> bool:
diff --git a/tests/test_bug_regressions_2026_05_25.py b/tests/test_bug_regressions_2026_05_25.py
index b57dc470..98563afc 100644
--- a/tests/test_bug_regressions_2026_05_25.py
+++ b/tests/test_bug_regressions_2026_05_25.py
@@ -62,16 +62,11 @@ def __array__(self, dtype=None):
def _extract_to_numpy(arr):
- """Re-implementation of the closure to keep the test independent of
- session_calc's import side effects. Mirrors the production helper:
- detect CuPy by ``.get()`` callable + module prefix, otherwise pass
- through ``np.asarray``."""
- if arr is None:
- return None
- get = getattr(arr, "get", None)
- if callable(get) and type(arr).__module__.startswith("cupy"):
- return np.asarray(get())
- return np.asarray(arr)
+ """The production helper (audit SCF-13: the old run_in_session closure
+ ``_to_numpy_array`` was a duplicate of ``session_calc._host_array``)."""
+ from quantui.session_calc import _host_array
+
+ return _host_array(arr)
class TestBugA_CupyAwareConversion:
@@ -97,15 +92,14 @@ def test_bare_numpy_conversion_of_cupy_like_raises(self):
with pytest.raises(TypeError):
np.array(fake)
- def test_production_helper_uses_to_numpy_array(self):
- # Confirm the actual session_calc body contains the
- # ``_to_numpy_array`` helper (so a future refactor that drops it
- # breaks this test loudly).
+ def test_production_helper_uses_host_array(self):
+ # The SCF gap extraction must go through the CuPy-aware helper
+ # (so a future refactor that drops it breaks this test loudly).
from quantui import session_calc
- src = inspect.getsource(session_calc)
- assert "_to_numpy_array" in src
- assert "cupy" in src.lower()
+ src = inspect.getsource(session_calc._run_session_calc_body)
+ assert "_host_array(mf.mo_energy)" in src
+ assert "_to_numpy_array" not in inspect.getsource(session_calc)
# =====================================================================
diff --git a/tests/test_gpu_offload.py b/tests/test_gpu_offload.py
index b646ad25..8a77ea33 100644
--- a/tests/test_gpu_offload.py
+++ b/tests/test_gpu_offload.py
@@ -11,6 +11,8 @@
import sys
from unittest.mock import patch
+import pytest
+
from quantui.gpu_offload import (
_GPU_UNSUPPORTED_METHODS,
is_gpu_available,
@@ -58,6 +60,22 @@ def test_disable_env_var_accepts_true_string(self, monkeypatch):
available, _name = is_gpu_available()
assert available is False
+ @pytest.mark.parametrize("value", ["1", "TRUE", "yes", "On", " true "])
+ def test_env_gpu_disabled_matches_quantui_truthy(self, monkeypatch, value):
+ """Audit SCF-13: same accepted values as freq_ir_workers._truthy."""
+ from quantui.freq_ir_workers import _truthy
+ from quantui.gpu_offload import env_gpu_disabled
+
+ monkeypatch.setenv("QUANTUI_DISABLE_GPU", value)
+ assert env_gpu_disabled() is True is _truthy(value)
+
+ @pytest.mark.parametrize("value", ["", "0", "false", "no", "off"])
+ def test_env_gpu_disabled_false_values(self, monkeypatch, value):
+ from quantui.gpu_offload import env_gpu_disabled
+
+ monkeypatch.setenv("QUANTUI_DISABLE_GPU", value)
+ assert env_gpu_disabled() is False
+
def test_missing_env_var_does_not_force_cpu(self, monkeypatch):
monkeypatch.delenv("QUANTUI_DISABLE_GPU", raising=False)
_clear_cache()
diff --git a/tests/test_pyfock_gpu.py b/tests/test_pyfock_gpu.py
index b1ea46f2..3db97dd2 100644
--- a/tests/test_pyfock_gpu.py
+++ b/tests/test_pyfock_gpu.py
@@ -53,6 +53,16 @@ def test_process_opt_out_wins_over_cupy(monkeypatch):
assert "QUANTUI_DISABLE_GPU" in probe_pyfock_gpu()[2]
+def test_process_opt_out_accepts_yes(monkeypatch):
+ """Audit SCF-13: same truthy values as the gpu4pyscf probe."""
+ monkeypatch.setitem(sys.modules, "cupy", _fake_cupy())
+ monkeypatch.setenv("QUANTUI_DISABLE_GPU", "yes")
+ clear_pyfock_gpu_probe_cache()
+
+ assert probe_pyfock_gpu()[0] is False
+ assert "QUANTUI_DISABLE_GPU" in probe_pyfock_gpu()[2]
+
+
def test_per_calculation_opt_out_does_not_probe(monkeypatch):
def fail_probe():
raise AssertionError("GPU probe should not run for explicit opt-out")
diff --git a/tests/test_scf_robust.py b/tests/test_scf_robust.py
index a8000142..3e082a29 100644
--- a/tests/test_scf_robust.py
+++ b/tests/test_scf_robust.py
@@ -316,3 +316,21 @@ def test_bootstrap_rescue_recovers_a_forced_non_convergence(self):
assert mf.converged is True
assert mf.scf_rescue_stage == SCF_RESCUE_BOOTSTRAP
assert energy == pytest.approx(reference_energy, abs=1e-6)
+
+ def test_bootstrap_scf_inherits_the_cancel_callback(self):
+ """Audit SCF-13: the per-cycle cancel/progress hook must reach the
+ bootstrap SCF too, so a Cancel click stops it."""
+ from pyscf import scf
+
+ from quantui.cancellation import attach_scf_cancel_callback
+
+ mf = scf.RHF(self._water_mol())
+ mf.verbose = 0
+ mf.max_cycle = 1 # force the bootstrap stage
+ seen = []
+ attach_scf_cancel_callback(
+ mf, lambda: False, progress_cb=lambda envs: seen.append(envs.get("mf"))
+ )
+ run_scf_with_rescue(mf)
+ assert mf.scf_rescue_stage == SCF_RESCUE_BOOTSTRAP
+ assert any(obj is not None and obj is not mf for obj in seen)
diff --git a/tests/test_vib_cache.py b/tests/test_vib_cache.py
index 67d39d12..5dd6841f 100644
--- a/tests/test_vib_cache.py
+++ b/tests/test_vib_cache.py
@@ -138,6 +138,42 @@ def test_multiple_modes_share_index(self, tmp_path):
)
assert loaded == f"mode {mode}"
+ def test_concurrent_saves_keep_every_mode(self, tmp_path, monkeypatch):
+ """Audit SCF-13: the index read-modify-write is serialised, so modes
+ saved from concurrent threads don't drop each other's entry."""
+ import threading
+ import time
+
+ rd = _make_result_dir(tmp_path)
+ real_load = vib_cache.load_index
+
+ def _slow_load(result_dir):
+ idx = real_load(result_dir)
+ time.sleep(0.05) # widen the read-modify-write window
+ return idx
+
+ monkeypatch.setattr(vib_cache, "load_index", _slow_load)
+
+ def _save(mode):
+ vib_cache.save_cached_html(
+ rd,
+ mode,
+ f"mode {mode}",
+ freq_cm1=1000.0 + mode,
+ n_frames=24,
+ amplitude=0.4,
+ renderer="py3dmol",
+ fps=10,
+ )
+
+ threads = [threading.Thread(target=_save, args=(m,)) for m in range(1, 5)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join()
+ idx = real_load(rd)
+ assert set(idx["modes"].keys()) == {"1", "2", "3", "4"}
+
class TestHasCachedMatching:
def setup_method(self):
From 9c9c97c96c413c2063369462cbb84e526467a267 Mon Sep 17 00:00:00 2001
From: Claude
Date: Thu, 12 Nov 2026 20:33:31 +0000
Subject: [PATCH 04/64] Tests: IRC descent-then-BFGS fallback keeps every
descent frame (audit GEOM-8)
GEOM-8 (the fallback deleted frame irc_steps + 1, which is a real
descent point whenever the steepest descent took steps, and kept BFGS's
repeated start) was already fixed on main by 5ec16f4 (GEOM-1): the
index is now taken just before BFGS. The existing endpoint tests only
cover the case where the descent converges on its own, so BFGS never
runs. This adds the missing case: descent capped at three accepted
steps, BFGS finishes; asserts no repeated frame and that each descent
step sits at its expected trajectory index. Fails when the deletion
index is taken before the descent (the GEOM-8 shape).
No code change.
Contributions:
- Claude (Opus 5.5): code edits, review, and conceptual discussion
- Jonathan Schultz: overall vision, planning, review, and orchestration
Co-authored-by: Jonathan Schultz
Co-authored-by: Claude Opus 5.5
---
tests/test_irc_endpoint.py | 34 ++++++++++++++++++++++++++++++++++
1 file changed, 34 insertions(+)
diff --git a/tests/test_irc_endpoint.py b/tests/test_irc_endpoint.py
index 46192a45..54b51618 100644
--- a/tests/test_irc_endpoint.py
+++ b/tests/test_irc_endpoint.py
@@ -108,3 +108,37 @@ def test_failure_near_the_minimum_ends_converged_without_duplicates(monkeypatch)
xyz = [np.asarray(f.coordinates) for f in branch.trajectory]
steps = [np.abs(b - a).max() for a, b in zip(xyz, xyz[1:])]
assert min(steps) > 0, "a frame is repeated"
+
+
+def test_descent_then_bfgs_drops_only_the_repeated_frame(monkeypatch):
+ # Audit GEOM-8: far enough out that steepest descent runs out of steps
+ # (some accepted) and BFGS finishes. Only BFGS's repeated start frame
+ # may be dropped: no duplicate, and every descent point kept.
+ import quantui.irc as irc
+
+ descents = [] # per branch: positions of each accepted descent step
+ real_descent = irc._steepest_descent
+
+ def _short_descent(atoms, record, **kw):
+ seen = []
+ descents.append(seen)
+
+ def _rec():
+ seen.append(atoms.get_positions().copy())
+ record()
+
+ return real_descent(atoms, _rec, **{**kw, "max_steps": 3})
+
+ monkeypatch.setattr(irc, "_steepest_descent", _short_descent)
+ far = MINIMUM + np.array([[0, 0, 0], [0, 0, 0], [2.0, 0.0, 1.5]])
+ r = _run(monkeypatch, far)
+ assert len(descents) == 2 and all(descents), "descent must take steps"
+ for branch, seen in zip((r.forward, r.reverse), descents):
+ assert branch.converged
+ assert _end_force(branch) < 0.05
+ xyz = [np.asarray(f.coordinates) for f in branch.trajectory]
+ steps = [np.abs(b - a).max() for a, b in zip(xyz, xyz[1:])]
+ assert min(steps) > 0, "a frame is repeated"
+ # start, Sella's unrecorded end, then each descent step in order
+ for k, pos in enumerate(seen):
+ np.testing.assert_allclose(xyz[2 + k], pos, atol=1e-9)
From ec54bdc3750d02a3990ed848e6f9a9fb5815c102 Mon Sep 17 00:00:00 2001
From: Claude
Date: Thu, 12 Nov 2026 20:34:55 +0000
Subject: [PATCH 05/64] TS verdict: soft imaginary mode is inconclusive; empty
check not "skipped" (audit GEOM-9)
- classify_stationary_point counted only imaginary values above 50 cm-1,
so a real soft TS (torsional barriers, 20-50i) with no larger mode was
reported "Not a transition state ... ended at a minimum". With no
large imaginary value but at least one small one, the verdict is now
"Inconclusive": soft TS or numerical noise, animate the mode and
tighten convergence. n_imaginary is unchanged (0), so nothing that
keys on the count changes. The TS help text lists the new verdict.
- apply_frequency_check left the placeholder "Frequency check skipped."
when the check ran but returned no frequencies; it now says the check
ran and produced no vibrational frequencies (prefixed with the
not-converged note when the search did not converge).
Tests: test_ts_search TestVerdict small-only-imaginary verdict and the
empty-frequencies verdict (run_freq_calc stubbed). Both fail on the
old code.
Contributions:
- Claude (Opus 5.5): code edits, review, and conceptual discussion
- Jonathan Schultz: overall vision, planning, review, and orchestration
Co-authored-by: Jonathan Schultz
Co-authored-by: Claude Opus 5.5
---
quantui/help_content.py | 3 +++
quantui/ts_search.py | 25 +++++++++++++++++++++++++
tests/test_ts_search.py | 32 ++++++++++++++++++++++++++++++++
3 files changed, 60 insertions(+)
diff --git a/quantui/help_content.py b/quantui/help_content.py
index 07fb435e..4500ed24 100644
--- a/quantui/help_content.py
+++ b/quantui/help_content.py
@@ -812,6 +812,9 @@
"way, it is the TS of a different process."
"No imaginary frequency — the search slid down to a "
"minimum. Start closer to the barrier top."
+ "Inconclusive — only a small imaginary value (below "
+ "50 cm⁻¹): a soft transition state (e.g. a torsion) or numerical "
+ "noise. Animate it, tighten convergence and check again."
"Two or more — a higher-order saddle point (a maximum in "
"more than one direction). Displace along the extra mode(s) and "
"search again."
diff --git a/quantui/ts_search.py b/quantui/ts_search.py
index c3f35489..d404bc06 100644
--- a/quantui/ts_search.py
+++ b/quantui/ts_search.py
@@ -64,6 +64,19 @@ def classify_stationary_point(frequencies_cm1: List[float]) -> tuple:
f"({abs(imag[0]):.0f}i cm⁻¹). Animate that mode in the Vibrational "
"panel to check it is the reaction you intended."
)
+ elif n == 0 and small:
+ # A real soft TS (torsions, 20–50i cm⁻¹) and residual-rotation noise
+ # look the same here, so don't call it a minimum.
+ verdict = (
+ f"Inconclusive: no imaginary frequency above "
+ f"{IMAGINARY_NOISE_CM1:.0f} cm⁻¹, but a small one "
+ f"({abs(min(small)):.0f}i cm⁻¹). This is either a soft transition "
+ "state (e.g. a torsional barrier) or numerical noise. Animate that "
+ "mode in the Vibrational panel: if it is the motion you intended, "
+ "tighten convergence (smaller force threshold, finer grid) and "
+ "check again."
+ )
+ return n, imag, verdict
elif n == 0:
verdict = (
"Not a transition state: no imaginary frequency, so the search "
@@ -391,6 +404,18 @@ def apply_frequency_check(
imag,
verdict,
)
+ else:
+ # The check ran but produced no frequencies (e.g. the Hessian step
+ # failed): say so rather than leave "Frequency check skipped."
+ result.verdict = (
+ "The frequency check ran but returned no vibrational frequencies "
+ "(see the log above), so this geometry could not be classified."
+ )
+ if not result.search_converged:
+ result.verdict = (
+ "The search did NOT converge (forces still above the "
+ "threshold). " + result.verdict
+ )
result.converged = bool(result.search_converged and freq.converged)
stream.write(f"\n{result.verdict}\n")
return result
diff --git a/tests/test_ts_search.py b/tests/test_ts_search.py
index 7d95fc37..efc2d198 100644
--- a/tests/test_ts_search.py
+++ b/tests/test_ts_search.py
@@ -32,6 +32,38 @@ def test_small_values_are_noise(self):
n, _, verdict = classify_stationary_point([-1246.0, -12.0, 2000.0])
assert n == 1 and "numerical noise" in verdict
+ def test_only_a_small_imaginary_is_inconclusive_not_a_minimum(self):
+ # Audit GEOM-9: a soft torsional TS (20-50i) must not read as a minimum.
+ n, imag, verdict = classify_stationary_point([-35.0, 300.0, 2000.0])
+ assert n == 0 and imag == []
+ assert verdict.startswith("Inconclusive") and "35i" in verdict
+ assert "minimum" not in verdict
+
+ def test_empty_frequencies_are_not_reported_as_skipped(self, monkeypatch):
+ # Audit GEOM-9: the check ran, so "Frequency check skipped." is wrong.
+ from types import SimpleNamespace
+
+ import quantui.freq_calc as freq_calc
+ from quantui.ts_search import apply_frequency_check
+
+ freq = SimpleNamespace(frequencies_cm1=[], energy_hartree=-1.0, converged=False)
+ monkeypatch.setattr(freq_calc, "run_freq_calc", lambda *a, **k: freq)
+ r = TSResult(
+ formula="CHN",
+ method="RHF",
+ basis="STO-3G",
+ molecule=HCN_GUESS,
+ energy_hartree=-91.0,
+ converged=True,
+ search_converged=True,
+ n_steps=4,
+ verdict="Frequency check skipped.",
+ )
+ apply_frequency_check(r, progress_stream=io.StringIO())
+ assert "skipped" not in r.verdict
+ assert "no vibrational frequencies" in r.verdict
+ assert r.n_imaginary is None and not r.converged
+
class TestResultObject:
def test_spectra_block_and_frequency_delegation(self):
From 4c43fac77419195b0617fb2a35f701f4c8ec6b39 Mon Sep 17 00:00:00 2001
From: Claude
Date: Thu, 12 Nov 2026 20:37:50 +0000
Subject: [PATCH 06/64] Promote open-shell RHF to UHF in TD-DFT, TS search and
IRC (audit GEOM-10)
scf.RHF on an open-shell molecule silently becomes ROHF, which PySCF
cannot use for TDHF (TD-DFT failed: "'NoneType' object is not
callable", empty spectrum) or for the analytic Hessian the TS search
and IRC need (NotImplementedError). The reorganization-energy workflow
already promoted RHF/HF to UHF for open-shell species
(_promote_method); the other three paths did not.
New reorganization_energy.promote_open_shell_hf wraps _promote_method
and writes a one-line note to the progress stream when it promotes.
run_tddft_calc (SCF body), run_ts_search and run_irc call it before
building the SCF / calculator, so the run and the result's method label
are UHF.
Tests: tests/test_open_shell_rhf_promotion.py: helper cases; TS search
and IRC hand "UHF" to the calculator (stubbed); real OH radical
RHF/6-31G TD-DFT runs as UHF with converged roots. The three path tests
fail on the old code.
Contributions:
- Claude (Opus 5.5): code edits, review, and conceptual discussion
- Jonathan Schultz: overall vision, planning, review, and orchestration
Co-authored-by: Jonathan Schultz
Co-authored-by: Claude Opus 5.5
---
quantui/irc.py | 4 ++
quantui/reorganization_energy.py | 21 +++++++
quantui/tddft_calc.py | 4 ++
quantui/ts_search.py | 4 ++
tests/test_open_shell_rhf_promotion.py | 78 ++++++++++++++++++++++++++
5 files changed, 111 insertions(+)
create mode 100644 tests/test_open_shell_rhf_promotion.py
diff --git a/quantui/irc.py b/quantui/irc.py
index 00f6a6b3..cf01b8c7 100644
--- a/quantui/irc.py
+++ b/quantui/irc.py
@@ -316,6 +316,10 @@ def run_irc(
raise ImportError("ASE calculator support is unavailable.")
stream: IO[str] = progress_stream if progress_stream is not None else sys.stdout
solvent = resolve_solvent(solvent)
+ # Open-shell + RHF would run ROHF: no analytic Hessian (audit GEOM-10).
+ from .reorganization_energy import promote_open_shell_hf
+
+ method = promote_open_shell_hf(method, molecule.multiplicity, stream)
stream.write(
"\n── Intrinsic reaction coordinate (Sella IRC, mass-weighted) ──\n"
f" {molecule.get_formula()} {method}/{basis}"
diff --git a/quantui/reorganization_energy.py b/quantui/reorganization_energy.py
index 851289c5..49509a05 100644
--- a/quantui/reorganization_energy.py
+++ b/quantui/reorganization_energy.py
@@ -412,6 +412,27 @@ def _promote_method(method: str, multiplicity: int) -> str:
return method
+def promote_open_shell_hf(
+ method: str, multiplicity: int, stream: Optional[IO[str]] = None
+) -> str:
+ """:func:`_promote_method`, with a note on *stream* when it promotes.
+
+ For callers that take a user-chosen method (TD-DFT, TS search, IRC):
+ ``scf.RHF`` on an open-shell molecule silently becomes ROHF, which has no
+ TDHF, analytic Hessian or IRC support in PySCF and fails cryptically.
+ """
+ promoted = _promote_method(method, multiplicity)
+ if promoted != method and stream is not None:
+ try:
+ stream.write(
+ f"\nNote: {method} cannot treat an open-shell molecule "
+ f"(multiplicity {multiplicity}); running {promoted} instead.\n"
+ )
+ except Exception: # noqa: BLE001 — best-effort note
+ pass
+ return promoted
+
+
def _ion_multiplicity(molecule: Molecule, ion_charge: int) -> int:
"""Low-spin multiplicity for an ion at ``ion_charge``.
diff --git a/quantui/tddft_calc.py b/quantui/tddft_calc.py
index 898de472..2e661e39 100644
--- a/quantui/tddft_calc.py
+++ b/quantui/tddft_calc.py
@@ -377,6 +377,10 @@ def _run_tddft_calc_body(
build_mole(mol)
# ── SCF ──────────────────────────────────────────────────────────────────
+ # Open-shell + RHF would run ROHF, which has no TDHF (audit GEOM-10).
+ from .reorganization_energy import promote_open_shell_hf
+
+ method = promote_open_shell_hf(method, molecule.multiplicity, stream)
method_upper = method.upper()
using_hf = method_upper in ("RHF", "UHF")
diff --git a/quantui/ts_search.py b/quantui/ts_search.py
index d404bc06..7191a06f 100644
--- a/quantui/ts_search.py
+++ b/quantui/ts_search.py
@@ -267,6 +267,10 @@ def run_ts_search(
raise ImportError("ASE calculator support is unavailable.")
stream: IO[str] = progress_stream if progress_stream is not None else sys.stdout
solvent = resolve_solvent(solvent)
+ # Open-shell + RHF would run ROHF: no analytic Hessian (audit GEOM-10).
+ from .reorganization_energy import promote_open_shell_hf
+
+ method = promote_open_shell_hf(method, molecule.multiplicity, stream)
atoms = Atoms(list(molecule.atoms), positions=molecule.coordinates)
calc = _QuantUIPySCFCalc(
diff --git a/tests/test_open_shell_rhf_promotion.py b/tests/test_open_shell_rhf_promotion.py
new file mode 100644
index 00000000..6cbd1521
--- /dev/null
+++ b/tests/test_open_shell_rhf_promotion.py
@@ -0,0 +1,78 @@
+"""Open-shell + "RHF" is promoted to UHF in TD-DFT, TS search and IRC (audit GEOM-10).
+
+``scf.RHF`` on an open-shell molecule silently becomes ROHF, which PySCF
+cannot use for TDHF ("'NoneType' object is not callable") or for the
+analytic Hessian the TS search and IRC need (NotImplementedError).
+"""
+
+from __future__ import annotations
+
+import io
+
+import pytest
+
+from quantui.molecule import Molecule
+from quantui.reorganization_energy import promote_open_shell_hf
+
+OH = Molecule(["O", "H"], [[0.0, 0.0, 0.0], [0.0, 0.0, 0.97]], multiplicity=2)
+
+
+class _Stop(Exception):
+ pass
+
+
+def _capture_calc_method(monkeypatch):
+ import quantui.optimizer as optimizer
+
+ seen = {}
+
+ class _Calc:
+ def __init__(self, **kwargs):
+ seen.update(kwargs)
+ raise _Stop
+
+ monkeypatch.setattr(optimizer, "_QuantUIPySCFCalc", _Calc)
+ return seen
+
+
+@pytest.mark.parametrize(
+ ("method", "mult", "expected"),
+ [("RHF", 2, "UHF"), ("hf", 3, "UHF"), ("RHF", 1, "RHF"), ("B3LYP", 2, "B3LYP")],
+)
+def test_promote_open_shell_hf(method, mult, expected):
+ stream = io.StringIO()
+ assert promote_open_shell_hf(method, mult, stream) == expected
+ assert ("open-shell" in stream.getvalue()) == (expected != method)
+
+
+def test_ts_search_promotes_rhf(monkeypatch):
+ pytest.importorskip("sella")
+ from quantui.ts_search import run_ts_search
+
+ seen = _capture_calc_method(monkeypatch)
+ stream = io.StringIO()
+ with pytest.raises(_Stop):
+ run_ts_search(OH, "RHF", "STO-3G", progress_stream=stream)
+ assert seen["method"] == "UHF"
+ assert "running UHF instead" in stream.getvalue()
+
+
+def test_irc_promotes_rhf(monkeypatch):
+ pytest.importorskip("sella")
+ from quantui.irc import run_irc
+
+ seen = _capture_calc_method(monkeypatch)
+ with pytest.raises(_Stop):
+ run_irc(OH, "RHF", "STO-3G", progress_stream=io.StringIO())
+ assert seen["method"] == "UHF"
+
+
+def test_tddft_rhf_open_shell_runs_as_uhf():
+ pytest.importorskip("pyscf")
+ from quantui.tddft_calc import run_tddft_calc
+
+ stream = io.StringIO()
+ r = run_tddft_calc(OH, "RHF", "6-31G", nstates=2, progress_stream=stream)
+ assert r.method == "UHF" and r.scf_variant == "UHF"
+ assert r.converged and len(r.excitation_energies_ev) == 2
+ assert "TD-DFT failed" not in stream.getvalue()
From 1833fc66f89c080a10a9a42d0f3cb09057be58af Mon Sep 17 00:00:00 2001
From: Claude
Date: Thu, 12 Nov 2026 20:38:31 +0000
Subject: [PATCH 07/64] Reorg: a channel is converged only if the neutral opt
converged too (audit GEOM-11)
Each channel's lambda uses both the neutral and the ion geometry, but
ReorgChannelResult.converged was taken from the ion optimization alone,
so a channel built on an unconverged neutral geometry read "converged"
(only the overall flag caught it). The channel flag now requires both.
Test: test_reorganization_energy
test_channel_converged_includes_the_neutral_optimization (optimizer and
single points stubbed); fails on the old code.
Contributions:
- Claude (Opus 5.5): code edits, review, and conceptual discussion
- Jonathan Schultz: overall vision, planning, review, and orchestration
Co-authored-by: Jonathan Schultz
Co-authored-by: Claude Opus 5.5
---
quantui/reorganization_energy.py | 3 ++-
tests/test_reorganization_energy.py | 23 +++++++++++++++++++++++
2 files changed, 25 insertions(+), 1 deletion(-)
diff --git a/quantui/reorganization_energy.py b/quantui/reorganization_energy.py
index 49509a05..004e4baf 100644
--- a/quantui/reorganization_energy.py
+++ b/quantui/reorganization_energy.py
@@ -702,7 +702,8 @@ def _leg_checkpoint(
lambda1_hartree=lambda1,
lambda2_hartree=lambda2,
lambda_hartree=lambda_total,
- converged=bool(ion_opt.converged),
+ # Both geometries feed λ: the shared neutral opt counts too.
+ converged=bool(neutral_opt.converged) and bool(ion_opt.converged),
ion_molecule=ion_mol,
s2_neutral_at_neutral=s2_neutral_at_neutral,
s2_ion_at_ion=s2_ion_at_ion,
diff --git a/tests/test_reorganization_energy.py b/tests/test_reorganization_energy.py
index abe704b4..f353e651 100644
--- a/tests/test_reorganization_energy.py
+++ b/tests/test_reorganization_energy.py
@@ -145,3 +145,26 @@ def test_invalid_mode_raises(self):
def test_valid_modes_constant(self):
assert set(VALID_MODES) == {"hole", "electron", "both"}
+
+
+def test_channel_converged_includes_the_neutral_optimization(monkeypatch):
+ """Audit GEOM-11: λ uses both geometries, so an unconverged neutral
+ optimization makes every channel unconverged, not just the overall flag."""
+ from types import SimpleNamespace
+
+ import quantui.reorganization_energy as R
+
+ def _fake_opt(*, molecule, **kw):
+ neutral = "neutral" in str(kw.get("status_label", ""))
+ return SimpleNamespace(molecule=molecule, n_steps=1, converged=not neutral)
+
+ monkeypatch.setattr(R, "optimize_geometry", _fake_opt)
+ monkeypatch.setattr(
+ R,
+ "run_in_session",
+ lambda **kw: SimpleNamespace(converged=True, energy_hartree=-1.0),
+ )
+ h2 = Molecule(["H", "H"], [[0, 0, 0], [0, 0, 0.74]])
+ res = R.run_reorganization_energy(h2, mode="both", method="RHF", basis="STO-3G")
+ assert res.converged is False
+ assert [ch.converged for ch in res.channels] == [False, False]
From 4ec4cc426097dd7412694c0c0b9c974fa53c3c74 Mon Sep 17 00:00:00 2001
From: Claude
Date: Thu, 12 Nov 2026 20:40:36 +0000
Subject: [PATCH 08/64] PES scan: show calculator notices, keep log-grid
direction, honest range label (audit GEOM-11)
- run_pes_scan built the shared calculator without a progress stream,
so its D3-missing and SCF-rescue notices never reached the scan log
(and its status heartbeat said "Optimizing geometry"). It now gets
the scan's stream and status_label="PES scan".
- A descending log-spaced bond range (start > stop) was silently
reversed into an ascending one, both in run_pes_scan and in
pes_scan_ui.build_scan_grid, so the scan ran the other way.
np.geomspace(start, stop) keeps the requested direction (same points).
- PESScanResult.summary() labelled max - min of the scan "Barrier
height"; it is only a barrier for a scan that runs from a minimum over
the barrier top. Relabelled "Energy range", as the result card
already says.
- Removed pes_scan_ui._clamp_selection (no callers).
Tests: test_pes_scan stream handed to the calculator (stubbed) and a
real H2 RHF/STO-3G descending log scan (direction + summary label);
test_pes_scan_ui descending log grid. All three fail on the old code.
Contributions:
- Claude (Opus 5.5): code edits, review, and conceptual discussion
- Jonathan Schultz: overall vision, planning, review, and orchestration
Co-authored-by: Jonathan Schultz
Co-authored-by: Claude Opus 5.5
---
quantui/pes_scan.py | 16 +++++++----
quantui/pes_scan_ui.py | 11 ++-----
tests/test_pes_scan.py | 60 +++++++++++++++++++++++++++++++++++++++
tests/test_pes_scan_ui.py | 7 +++++
4 files changed, 81 insertions(+), 13 deletions(-)
diff --git a/quantui/pes_scan.py b/quantui/pes_scan.py
index 1c990aee..857b618d 100644
--- a/quantui/pes_scan.py
+++ b/quantui/pes_scan.py
@@ -145,7 +145,9 @@ def summary(self) -> str:
return "No scan points computed."
e_min = min(finite)
e_max = max(finite)
- barrier = (e_max - e_min) * _HARTREE_TO_KCAL
+ # max − min over the scan: not a barrier unless the scan runs from a
+ # minimum over the barrier top (the result card says "Energy range").
+ e_range = (e_max - e_min) * _HARTREE_TO_KCAL
min_idx = self.energies_hartree.index(e_min)
lines = [
"=" * 60,
@@ -158,7 +160,7 @@ def summary(self) -> str:
f" → {self.scan_parameter_values[-1]:.3f} {self.scan_unit}",
f" Scan points : {self.n_steps}",
f" Min energy : {e_min:.8f} Ha (point {min_idx + 1})",
- f" Barrier height : {barrier:.2f} kcal/mol",
+ f" Energy range : {e_range:.2f} kcal/mol",
f" All converged : {'Yes' if self.converged_all else 'No'}",
"=" * 60,
]
@@ -476,15 +478,19 @@ def run_pes_scan(
# --- Set up ASE atoms + PySCF calculator ---
atoms = molecule_to_atoms(molecule)
+ _stream: IO[str] = progress_stream if progress_stream is not None else sys.stdout
+ # The stream lets the calculator's D3-missing and SCF-rescue notices
+ # reach the scan log (they were dropped without it).
atoms.calc = _QuantUIPySCFCalc(
method=method,
basis=basis,
charge=molecule.charge,
spin=molecule.multiplicity - 1,
scf_rescue=scf_rescue,
+ progress_stream=_stream,
+ status_label="PES scan",
)
- _stream: IO[str] = progress_stream if progress_stream is not None else sys.stdout
_null = io.StringIO()
# Cooperative cancel — checked between scan points, per BFGS step,
@@ -504,8 +510,8 @@ def run_pes_scan(
and stop > 0
and start != stop
):
- lo, hi = (start, stop) if start < stop else (stop, start)
- scan_values = np.geomspace(lo, hi, steps).tolist()
+ # Keep the requested direction (descending stays descending).
+ scan_values = np.geomspace(start, stop, steps).tolist()
else:
scan_values = np.linspace(start, stop, steps).tolist()
diff --git a/quantui/pes_scan_ui.py b/quantui/pes_scan_ui.py
index a08a5ee9..7cebeef5 100644
--- a/quantui/pes_scan_ui.py
+++ b/quantui/pes_scan_ui.py
@@ -260,17 +260,12 @@ def build_scan_grid(
and stop > 0
and start != stop
):
- lo, hi = (start, stop) if start < stop else (stop, start)
- return [float(v) for v in np.geomspace(lo, hi, steps).tolist()]
+ # geomspace keeps the requested direction (a descending range stays
+ # descending; it used to be silently reversed).
+ return [float(v) for v in np.geomspace(start, stop, steps).tolist()]
return [float(v) for v in np.linspace(start, stop, steps).tolist()]
-def _clamp_selection(values: Sequence[int], n_atoms: int) -> List[int]:
- if n_atoms < 1:
- return list(values)
- return [max(1, min(int(v), n_atoms)) for v in values]
-
-
def scan_range_bounds(scan_type: str) -> Tuple[Optional[float], Optional[float]]:
"""``(min, max)`` for start/stop widgets; ``None`` means unbounded."""
if scan_type.lower() == "bond":
diff --git a/tests/test_pes_scan.py b/tests/test_pes_scan.py
index 2070741b..33ed7ee0 100644
--- a/tests/test_pes_scan.py
+++ b/tests/test_pes_scan.py
@@ -858,3 +858,63 @@ def test_dihedral_scan_converges_without_nan(self):
)
assert result.converged_all is True
assert all(e == e for e in result.energies_hartree) # no NaN
+
+
+def test_scan_calculator_gets_the_progress_stream(monkeypatch):
+ """Audit GEOM-11: D3-missing and SCF-rescue notices come from the shared
+ calculator, which used to be built without the scan's stream."""
+ pytest.importorskip("ase")
+ import io
+
+ import quantui.pes_scan as pes_scan
+
+ seen = {}
+
+ class _Stop(Exception):
+ pass
+
+ class _Calc:
+ def __init__(self, **kwargs):
+ seen.update(kwargs)
+ raise _Stop
+
+ monkeypatch.setattr(pes_scan, "_QuantUIPySCFCalc", _Calc)
+ stream = io.StringIO()
+ with pytest.raises(_Stop):
+ pes_scan.run_pes_scan(
+ _h2(),
+ scan_type="bond",
+ atom_indices=[0, 1],
+ start=0.7,
+ stop=0.8,
+ steps=2,
+ progress_stream=stream,
+ )
+ assert seen["progress_stream"] is stream
+
+
+def test_descending_log_scan_runs_in_the_requested_direction():
+ """Audit GEOM-11: the log grid was silently reversed for start > stop;
+ the summary calls max − min an energy range, not a barrier."""
+ pytest.importorskip("pyscf")
+ pytest.importorskip("ase")
+ import io
+
+ from quantui.pes_scan import run_pes_scan
+
+ r = run_pes_scan(
+ _h2(),
+ method="RHF",
+ basis="STO-3G",
+ scan_type="bond",
+ atom_indices=[0, 1],
+ start=1.0,
+ stop=0.7,
+ steps=3,
+ grid="log",
+ progress_stream=io.StringIO(),
+ )
+ vals = list(r.scan_parameter_values)
+ assert vals[0] == pytest.approx(1.0) and vals[-1] == pytest.approx(0.7)
+ assert vals == sorted(vals, reverse=True)
+ assert "Energy range" in r.summary() and "Barrier" not in r.summary()
diff --git a/tests/test_pes_scan_ui.py b/tests/test_pes_scan_ui.py
index ee17ac5c..b9ccd68e 100644
--- a/tests/test_pes_scan_ui.py
+++ b/tests/test_pes_scan_ui.py
@@ -165,6 +165,13 @@ def test_log_bond_grid(self):
assert vals[-1] == pytest.approx(2.0)
assert vals[1] > vals[0]
+ def test_descending_log_bond_grid_keeps_direction(self):
+ # Audit GEOM-11: a descending log range used to come back ascending.
+ vals = build_scan_grid(2.0, 0.5, 4, scan_type="bond", grid="log")
+ assert vals[0] == pytest.approx(2.0)
+ assert vals[-1] == pytest.approx(0.5)
+ assert vals == sorted(vals, reverse=True)
+
class TestScanRangeAroundCurrent:
def test_angle_window_around_current(self):
From 37aced76fc4f4236e44ee63c7f12714e50aab108 Mon Sep 17 00:00:00 2001
From: Claude
Date: Thu, 12 Nov 2026 20:41:33 +0000
Subject: [PATCH 09/64] Optimizer: right atom in the frozen-index error, GPU
banner once (audit GEOM-11)
- A negative frozen-atom index failed the range check but the message
named the largest (valid) index instead: frozen_atoms=[-1, 1] on water
said "Frozen atom 2 does not exist". It now names the offending index.
- _QuantUIPySCFCalc wrote the "GPU offload active" banner on every force
evaluation (it is rebuilt per geometry); it is now written once per
run, when the calculator first offloads.
Tests: test_structure_edit test_bad_frozen_lists (negative index case);
test_optimizer test_gpu_banner_is_written_once_per_run (try_to_gpu
stubbed to report a GPU, H2 RHF/STO-3G). Both fail on the old code.
The banner itself still needs a look on a real GPU host (local/H200).
Contributions:
- Claude (Opus 5.5): code edits, review, and conceptual discussion
- Jonathan Schultz: overall vision, planning, review, and orchestration
Co-authored-by: Jonathan Schultz
Co-authored-by: Claude Opus 5.5
---
quantui/optimizer.py | 21 +++++++++++++--------
tests/test_optimizer.py | 23 +++++++++++++++++++++++
tests/test_structure_edit.py | 3 +++
3 files changed, 39 insertions(+), 8 deletions(-)
diff --git a/quantui/optimizer.py b/quantui/optimizer.py
index dd8a2dfe..efa95657 100644
--- a/quantui/optimizer.py
+++ b/quantui/optimizer.py
@@ -279,14 +279,16 @@ def calculate(
mf, _gpu_used, _gpu_name = try_to_gpu(mf, method_upper)
if _gpu_used:
+ # Announce once per run, not on every force evaluation.
+ if not self.gpu_used:
+ try:
+ self.progress_stream.write(
+ f"\n🚀 GPU offload active — running on {_gpu_name}\n"
+ )
+ except Exception: # noqa: BLE001 — stream is user-owned
+ pass
self.gpu_used = True
self.gpu_name = _gpu_name
- try:
- self.progress_stream.write(
- f"\n🚀 GPU offload active — running on {_gpu_name}\n"
- )
- except Exception: # noqa: BLE001 — stream is user-owned
- pass
mf.verbose = 0
mf.stdout = _sink
@@ -720,9 +722,12 @@ def optimize_geometry(
atoms = molecule_to_atoms(start_molecule)
_frozen = sorted({int(i) for i in (frozen_atoms or [])})
if _frozen:
- if _frozen[0] < 0 or _frozen[-1] >= len(atoms):
+ _bad = [i for i in _frozen if i < 0 or i >= len(atoms)]
+ if _bad:
+ # Report the offending (0-based) index as a 1-based atom number;
+ # a negative index used to report the last atom instead.
raise ValueError(
- f"Frozen atom {_frozen[-1] + 1} does not exist "
+ f"Frozen atom {_bad[0] + 1} does not exist "
f"(this structure has {len(atoms)} atoms)."
)
if len(_frozen) >= len(atoms):
diff --git a/tests/test_optimizer.py b/tests/test_optimizer.py
index a40824f4..14fda641 100644
--- a/tests/test_optimizer.py
+++ b/tests/test_optimizer.py
@@ -651,3 +651,26 @@ def test_gate_does_not_require_ase_calculators_pyscf(self):
if __name__ == "__main__":
pytest.main([__file__, "-v", "--tb=short"])
+
+
+def test_gpu_banner_is_written_once_per_run(monkeypatch):
+ """Audit GEOM-11: the GPU banner used to repeat on every force call."""
+ pytest.importorskip("pyscf")
+ if not ASE_AVAILABLE:
+ pytest.skip("ASE not installed")
+ import quantui.gpu_offload as gpu_offload
+ from quantui.optimizer import optimize_geometry
+
+ monkeypatch.setattr(
+ gpu_offload, "try_to_gpu", lambda mf, method=None: (mf, True, "Fake GPU")
+ )
+ stream = io.StringIO()
+ res = optimize_geometry(
+ Molecule(["H", "H"], [[0.0, 0.0, 0.0], [0.0, 0.0, 0.9]]),
+ "RHF",
+ "STO-3G",
+ progress_stream=stream,
+ steps=5,
+ )
+ assert res.n_steps >= 2
+ assert stream.getvalue().count("GPU offload active") == 1
diff --git a/tests/test_structure_edit.py b/tests/test_structure_edit.py
index eac07dc5..9eae8b60 100644
--- a/tests/test_structure_edit.py
+++ b/tests/test_structure_edit.py
@@ -151,6 +151,9 @@ def test_bad_frozen_lists(self):
optimize_geometry(WATER, "RHF", "STO-3G", frozen_atoms=[7])
with pytest.raises(ValueError, match="nothing to optimize"):
optimize_geometry(WATER, "RHF", "STO-3G", frozen_atoms=[0, 1, 2])
+ # Audit GEOM-11: a negative index names itself, not the last atom.
+ with pytest.raises(ValueError, match="Frozen atom 0 does not exist"):
+ optimize_geometry(WATER, "RHF", "STO-3G", frozen_atoms=[-1, 1])
class TestEditPanel:
From b8a988278c578348e5cf35d166ad6c9762c1dc8b Mon Sep 17 00:00:00 2001
From: Claude
Date: Thu, 12 Nov 2026 20:32:19 +0000
Subject: [PATCH 10/64] Batch worker: required final single point, traceback,
elapsed/warnings (audit HPC-14)
The batch worker diverged from the interactive run:
- Geometry Opt ran the app's required final single point only with a
solvent; gas-phase batch optimizations kept the optimizer's last-step
SCF data and never got NPA charges / bond orders.
- A "geometry optimization before the calculation" for Frequency,
TD-DFT, NMR and PES Scan skipped the required single point the app
runs as a convergence gate (on failure the app abandons the pre-opt
and runs at the input geometry).
- A worker failure logged str(exc) only; no traceback anywhere.
- elapsed_s and warnings lived only on the in-memory CalculationResult
and were never written to result.json.
Fix: a shared _run_required_single_point helper (run_in_session with the
request's solvent and scf_rescue; raises if unconverged). Geometry Opt
always runs it and folds the same fields as app.py (energy, MOs,
pyscf_mol_atom/basis, atom symbols, Mulliken/NPA charges, bond orders,
dipole). _maybe_run_preopt runs it for every calc type except
single_point, before caching the pre-opt geometry, inside the existing
fall-back-to-input-geometry try block. The worker boundary appends
traceback.format_exc() to live.log, and result.json gains elapsed_s and
warnings.
Still differs (not changed): the worker ignores the quantum_engine
preference (it is not carried in the batch request; plumbing it is a
design change) and calls PySCF directly rather than via engines.run_calc.
Tests: TestInteractiveParity in tests/test_backends_worker.py (5 of 6
fail on the old worker). Optimizer-only mocks in test_backends_worker
and test_freq_saddle_retry now stub run_in_session via an autouse
fixture so they stay PySCF-free (Windows CI).
Contributions:
- Claude (Opus 5.5): code edits, review, and conceptual discussion
- Jonathan Schultz: overall vision, planning, review, and orchestration
Co-authored-by: Jonathan Schultz
Co-authored-by: Claude Opus 5.5
---
quantui/backends/worker.py | 154 ++++++++++++++++++++----------
tests/test_backends_worker.py | 161 ++++++++++++++++++++++++++++++++
tests/test_freq_saddle_retry.py | 10 ++
3 files changed, 277 insertions(+), 48 deletions(-)
diff --git a/quantui/backends/worker.py b/quantui/backends/worker.py
index ff7252db..4651c847 100644
--- a/quantui/backends/worker.py
+++ b/quantui/backends/worker.py
@@ -30,6 +30,7 @@
import os
import sys
import time
+import traceback
from pathlib import Path
from typing import Any, Callable
@@ -293,6 +294,20 @@ def _maybe_run_preopt(
staging_dir,
f"Geometry optimization {conv} in {pre_opt.n_steps} steps. E = {energy:.8f} Ha",
)
+ # The app runs a required single point on the pre-optimized geometry
+ # before every calc type except Single Point (which is itself that
+ # single point); if it does not converge, the whole pre-opt is
+ # abandoned and the calculation runs at the input geometry. Same
+ # here, before the geometry is cached, so a reused cache has passed
+ # it (audit HPC-14).
+ if request.calc_type != "single_point":
+ _run_required_single_point(
+ request,
+ pre_opt.molecule,
+ staging_dir,
+ log_stream,
+ reason=f"after geometry optimization before {stage_label}",
+ )
if write_preopt_trajectory and getattr(pre_opt, "trajectory", None):
write_trajectory_json(
staging_dir,
@@ -423,6 +438,54 @@ def _ran_at(result: Any, molecule: Any) -> Any:
return result
+# Fields app.py's "Geometry Opt" branch copies from the required final single
+# point onto the optimization result.
+_FINAL_SP_FIELDS = (
+ "mo_energy_hartree",
+ "mo_occ",
+ "mo_coeff",
+ "pyscf_mol_atom",
+ "pyscf_mol_basis",
+ "atom_symbols",
+ "mulliken_charges",
+ "npa_charges",
+ "bond_orders",
+ "dipole_moment_debye",
+ "dipole_vector_debye",
+)
+
+
+def _run_required_single_point(
+ request: CalculationRequest,
+ molecule,
+ staging_dir: Path,
+ log_stream,
+ *,
+ reason: str,
+) -> Any:
+ """Required single point on an optimized geometry (app.py's
+ ``_run_required_final_single_point``): raises if it does not converge."""
+ from quantui.session_calc import run_in_session
+
+ _append_log(
+ staging_dir,
+ f"\n-- Required single-point ({reason}) "
+ "on optimized geometry --------------------------------",
+ )
+ sp_result = run_in_session(
+ molecule=molecule,
+ method=request.method,
+ basis=request.basis,
+ progress_stream=log_stream,
+ solvent=request.solvent,
+ scf_rescue=bool((request.options or {}).get("scf_rescue", True)),
+ )
+ if not bool(getattr(sp_result, "converged", False)):
+ raise RuntimeError("Required post-optimization single-point did not converge.")
+ _append_log(staging_dir, "Required single-point converged on optimized geometry.")
+ return sp_result
+
+
def _run_single_point(
request: CalculationRequest, staging_dir: Path, log_stream
) -> Any:
@@ -503,50 +566,40 @@ def _run_geometry_opt(
frozen_atoms=frozen,
)
- # Mirror app.py's interactive "Geometry Opt" + solvent handling: the
- # optimization itself is solvated (every step), then a required PCM
- # single point on the final geometry supplies the orbitals, populations
- # and final energy, exactly as the app's _run_required_final_single_point.
- if request.solvent:
- _write_progress(
- staging_dir, "running", "Running required solvated single point", 90.0
- )
- _append_log(
- staging_dir,
- "\n-- Required single-point (after geometry optimisation) "
- "on optimized geometry --------------------------------",
- )
- from quantui.session_calc import run_in_session
-
- sp_result = run_in_session(
- molecule=result.molecule,
- method=request.method,
- basis=request.basis,
- progress_stream=log_stream,
- solvent=request.solvent,
- scf_rescue=scf_rescue,
- )
- if not bool(getattr(sp_result, "converged", False)):
- raise RuntimeError(
- "Required post-optimization single-point did not converge."
+ # Mirror app.py's interactive "Geometry Opt": a required single point
+ # (solvated when the optimization was) on the final geometry always
+ # follows, and supplies the final energy, orbitals, populations and
+ # dipole — exactly as the app's _run_required_final_single_point, with
+ # or without a solvent (audit HPC-14).
+ _write_progress(staging_dir, "running", "Running required single point", 90.0)
+ sp_result = _run_required_single_point(
+ request,
+ result.molecule,
+ staging_dir,
+ log_stream,
+ reason="after geometry optimisation",
+ )
+ # ``energy_hartree`` is a read-only property derived from
+ # ``energies_hartree[-1]`` (there is no ``homo_lumo_gap_ev`` field on
+ # ``OptimizationResult`` either) — updating the last trajectory
+ # energy is how app.py's interactive path folds the result in too, so
+ # both surfaces agree on what "the" final energy is.
+ sp_energy = getattr(sp_result, "energy_hartree", None)
+ if (
+ isinstance(getattr(result, "energies_hartree", None), list)
+ and result.energies_hartree
+ and isinstance(sp_energy, (int, float))
+ ):
+ result.energies_hartree[-1] = float(sp_energy)
+ result.converged = bool(result.converged) and bool(sp_result.converged)
+ # Same fields, same fallbacks as app.py's Geometry Opt branch.
+ for field in _FINAL_SP_FIELDS:
+ try:
+ setattr(
+ result, field, getattr(sp_result, field, getattr(result, field, None))
)
- _append_log(
- staging_dir,
- "Required single-point converged on optimized geometry.",
- )
- # ``energy_hartree`` is a read-only property derived from
- # ``energies_hartree[-1]`` (there is no ``homo_lumo_gap_ev`` field on
- # ``OptimizationResult`` either) — updating the last trajectory
- # energy is how app.py's interactive path folds the solvated result
- # in too, so both surfaces agree on what "the" final energy is.
- sp_energy = getattr(sp_result, "energy_hartree", None)
- if (
- isinstance(getattr(result, "energies_hartree", None), list)
- and result.energies_hartree
- and isinstance(sp_energy, (int, float))
- ):
- result.energies_hartree[-1] = float(sp_energy)
- result.converged = bool(result.converged) and bool(sp_result.converged)
+ except (AttributeError, TypeError):
+ pass
return result
@@ -1401,6 +1454,9 @@ def run_worker_request(
except Exception as exc: # noqa: BLE001 — worker boundary
elapsed = time.perf_counter() - t0
msg = str(exc)
+ # The full traceback goes to live.log (the only record a batch job
+ # leaves); the job record keeps the one-line message (audit HPC-14).
+ _append_log(staging_dir, traceback.format_exc().rstrip())
_append_log(staging_dir, msg)
return _error_result(
request,
@@ -1414,6 +1470,13 @@ def run_worker_request(
elapsed = time.perf_counter() - t0
payload = _build_payload(calc_type, outcome, staging_dir, request)
+ warnings: list[str] = []
+ if not bool(payload.get("converged", False)):
+ warnings.append("Calculation did not fully converge")
+ # Kept in result.json too, not only on the in-memory CalculationResult
+ # that nothing reads after the job ends (audit HPC-14).
+ payload["elapsed_s"] = round(elapsed, 3)
+ payload["warnings"] = list(warnings)
if attempt_dir is not None:
# Before result.json: its presence is what marks the attempt done.
names = _apply_descriptive_names(staging_dir, request_path.parent.name)
@@ -1424,11 +1487,6 @@ def run_worker_request(
_update_tracked_record(request, "success", result_dir=str(staging_dir))
_write_progress(staging_dir, "finalizing", "Calculation complete", 100.0)
- warnings: list[str] = []
- converged = bool(payload.get("converged", False))
- if not converged:
- warnings.append("Calculation did not fully converge")
-
return CalculationResult(
request_id=request.request_id,
backend_id="cluster_slurm",
diff --git a/tests/test_backends_worker.py b/tests/test_backends_worker.py
index fcc86366..e2065e52 100644
--- a/tests/test_backends_worker.py
+++ b/tests/test_backends_worker.py
@@ -14,6 +14,19 @@
from quantui.backends.worker import run_worker_request
+@pytest.fixture(autouse=True)
+def _stub_required_single_point():
+ """The worker now runs the app's required single point after every
+ geometry optimization / pre-opt (audit HPC-14). Stub it so tests that
+ mock only the optimizer stay PySCF-free; tests that patch
+ ``run_in_session`` themselves override this."""
+ with patch(
+ "quantui.session_calc.run_in_session",
+ return_value=SimpleNamespace(converged=True, energy_hartree=-1.12),
+ ):
+ yield
+
+
@pytest.fixture
def staging(tmp_path):
staging_dir = tmp_path / "staging" / "job1"
@@ -877,3 +890,151 @@ def test_second_attempt_resumes_the_first_attempts_checkpoint(self, tmp_path):
assert resumable2
assert (job / ".checkpoint").is_dir()
assert not (a1 / ".checkpoint").exists()
+
+
+class TestInteractiveParity:
+ """Batch worker vs interactive run (audit HPC-14)."""
+
+ @staticmethod
+ def _h2():
+ from quantui.molecule import Molecule
+
+ return Molecule(
+ atoms=["H", "H"],
+ coordinates=[[0, 0, 0], [0, 0, 0.74]],
+ charge=0,
+ multiplicity=1,
+ )
+
+ def _opt(self, energy=-1.10):
+ mol = self._h2()
+ return SimpleNamespace(
+ molecule=mol,
+ trajectory=[mol],
+ energies_hartree=[energy],
+ converged=True,
+ n_steps=3,
+ method="RHF",
+ basis="STO-3G",
+ formula="H2",
+ )
+
+ @staticmethod
+ def _set(staging, **fields):
+ data = json.loads((staging / "request.json").read_text())
+ data.update(fields)
+ (staging / "request.json").write_text(json.dumps(data))
+
+ @patch("quantui.session_calc.run_in_session")
+ @patch("quantui.optimizer.optimize_geometry")
+ def test_gas_phase_geometry_opt_runs_required_final_single_point(
+ self, mock_opt, mock_run, staging
+ ):
+ mock_opt.return_value = self._opt()
+ mock_run.return_value = SimpleNamespace(
+ converged=True,
+ energy_hartree=-1.13,
+ atom_symbols=["H", "H"],
+ mulliken_charges=[0.0, 0.0],
+ npa_charges=[0.01, -0.01],
+ bond_orders=[{"i": 0, "j": 1, "order": 1.0}],
+ dipole_moment_debye=0.0,
+ dipole_vector_debye=[0.0, 0.0, 0.0],
+ )
+ self._set(staging, calc_type="geometry_opt", options={"fmax": 0.05})
+
+ outcome = run_worker_request(staging / "request.json")
+ assert outcome.status == "success"
+ mock_run.assert_called_once()
+ assert mock_run.call_args.kwargs["solvent"] is None
+ payload = json.loads((staging / "result.json").read_text())
+ assert payload["energy_hartree"] == -1.13
+ assert payload["npa_charges"] == [0.01, -0.01]
+ assert payload["bond_orders"] == [{"i": 0, "j": 1, "order": 1.0}]
+ assert "Required single-point (after geometry optimisation)" in (
+ staging / "live.log"
+ ).read_text(encoding="utf-8")
+
+ @patch("quantui.session_calc.run_in_session")
+ @patch("quantui.optimizer.optimize_geometry")
+ def test_gas_phase_geometry_opt_unconverged_final_sp_fails(
+ self, mock_opt, mock_run, staging
+ ):
+ mock_opt.return_value = self._opt()
+ mock_run.return_value = SimpleNamespace(converged=False, energy_hartree=-1.0)
+ self._set(staging, calc_type="geometry_opt")
+ assert run_worker_request(staging / "request.json").status == "error"
+
+ @patch("quantui.tddft_calc.run_tddft_calc")
+ @patch("quantui.session_calc.run_in_session")
+ @patch("quantui.optimizer.optimize_geometry")
+ def test_preopt_required_sp_failure_falls_back_to_input_geometry(
+ self, mock_opt, mock_run, mock_tddft, staging
+ ):
+ moved = self._opt()
+ moved.molecule = type(moved.molecule)(
+ atoms=["H", "H"],
+ coordinates=[[0, 0, 0], [0, 0, 0.80]],
+ charge=0,
+ multiplicity=1,
+ )
+ mock_opt.return_value = moved
+ mock_run.return_value = SimpleNamespace(converged=False, energy_hartree=-1.0)
+ mock_tddft.side_effect = RuntimeError("stop here")
+ self._set(staging, calc_type="tddft", options={"preopt_before_run": True})
+
+ run_worker_request(staging / "request.json")
+ mock_run.assert_called_once() # the required SP after the pre-opt
+ # Like the app: the pre-opt is abandoned, the calc gets the input
+ # geometry, and nothing is cached for a resubmission to reuse.
+ used = mock_tddft.call_args.kwargs["molecule"]
+ assert [list(map(float, c)) for c in used.coordinates][1] == [0, 0, 0.74]
+ assert not list(staging.glob("**/preopt_geometry_*.json"))
+ log = (staging / "live.log").read_text(encoding="utf-8")
+ assert "Geometry optimization failed" in log
+
+ @patch("quantui.session_calc.run_in_session")
+ @patch("quantui.optimizer.optimize_geometry")
+ def test_single_point_preopt_has_no_extra_single_point(
+ self, mock_opt, mock_run, staging
+ ):
+ mock_opt.return_value = self._opt()
+ mock_run.return_value = SimpleNamespace(
+ energy_hartree=-1.12,
+ homo_lumo_gap_ev=10.0,
+ converged=True,
+ n_iterations=5,
+ method="RHF",
+ basis="STO-3G",
+ formula="H2",
+ )
+ self._set(staging, options={"preopt_before_run": True})
+ assert run_worker_request(staging / "request.json").status == "success"
+ mock_run.assert_called_once() # the single point itself
+
+ @patch("quantui.session_calc.run_in_session")
+ def test_failure_writes_traceback_to_live_log(self, mock_run, staging):
+ mock_run.side_effect = ValueError("boom in the SCF")
+ outcome = run_worker_request(staging / "request.json")
+ assert outcome.status == "error"
+ log = (staging / "live.log").read_text(encoding="utf-8")
+ assert "Traceback (most recent call last)" in log
+ assert "ValueError: boom in the SCF" in log
+
+ @patch("quantui.session_calc.run_in_session")
+ def test_result_json_keeps_elapsed_and_warnings(self, mock_run, staging):
+ mock_run.return_value = SimpleNamespace(
+ energy_hartree=-1.12,
+ homo_lumo_gap_ev=10.0,
+ converged=False,
+ n_iterations=50,
+ method="RHF",
+ basis="STO-3G",
+ formula="H2",
+ )
+ outcome = run_worker_request(staging / "request.json")
+ payload = json.loads((staging / "result.json").read_text())
+ assert payload["elapsed_s"] == outcome.metrics["elapsed_s"]
+ assert isinstance(payload["elapsed_s"], float)
+ assert payload["warnings"] == ["Calculation did not fully converge"]
+ assert outcome.warnings == payload["warnings"]
diff --git a/tests/test_freq_saddle_retry.py b/tests/test_freq_saddle_retry.py
index 362678de..acea29dc 100644
--- a/tests/test_freq_saddle_retry.py
+++ b/tests/test_freq_saddle_retry.py
@@ -160,6 +160,16 @@ def test_reports_what_is_left_after_one_try(self, capsys):
class TestWorker:
+ @pytest.fixture(autouse=True)
+ def _stub_required_single_point(self):
+ # The worker runs the app's required single point after the pre-opt
+ # (audit HPC-14); keep these tests PySCF-free.
+ with patch(
+ "quantui.session_calc.run_in_session",
+ return_value=SimpleNamespace(converged=True, energy_hartree=-1.1),
+ ):
+ yield
+
@pytest.fixture
def request_path(self, tmp_path):
from quantui.backends.base import CalculationRequest
From 604059dfdf8333d00bf851e240e208706a91d749 Mon Sep 17 00:00:00 2001
From: Claude
Date: Thu, 12 Nov 2026 20:33:35 +0000
Subject: [PATCH 11/64] Batch script: tie PySCF max_memory to the Slurm
allocation (audit HPC-15)
Jobs request 4-128 GB, but nothing told PySCF: every batch calculation
ran with PySCF's 4000 MB max_memory default, falling back to out-of-core
paths on big-memory jobs.
The shared SLURM_SCRIPT_TEMPLATE (used by SlurmBackend and the
quantui-batch launcher) now exports PYSCF_MAX_MEMORY = 80% of the
allocation in MB. It reads Slurm's SLURM_MEM_PER_NODE at run time, so a
--mem given on the sbatch command line (rerun --more-memory) is
honoured, and falls back to the #SBATCH --mem value when that variable
is unset or not plain MB. apptainer exec passes the host environment
through, as it already does for OMP_NUM_THREADS.
Test: test_pyscf_max_memory_follows_the_allocation in
tests/test_backends_slurm.py runs `bash -n` on the generated script and
executes the memory block with and without SLURM_MEM_PER_NODE (fails on
the old template).
Contributions:
- Claude (Opus 5.5): code edits, review, and conceptual discussion
- Jonathan Schultz: overall vision, planning, review, and orchestration
Co-authored-by: Jonathan Schultz
Co-authored-by: Claude Opus 5.5
---
quantui/backends/cluster_config.py | 6 ++++++
tests/test_backends_slurm.py | 32 ++++++++++++++++++++++++++++++
2 files changed, 38 insertions(+)
diff --git a/quantui/backends/cluster_config.py b/quantui/backends/cluster_config.py
index ab63aebb..ebe5fd59 100644
--- a/quantui/backends/cluster_config.py
+++ b/quantui/backends/cluster_config.py
@@ -315,6 +315,12 @@ def build_attempt_setup(job_dir: str) -> str:
echo "Working directory: $(pwd)"
export OMP_NUM_THREADS="${{SLURM_CPUS_PER_TASK:-{cores}}}"
+# PySCF memory cap (MB) = 80% of this job's allocation, so a big-memory job
+# is not held to PySCF's 4000 MB default. Slurm's SLURM_MEM_PER_NODE (MB)
+# reflects a --mem given on the sbatch command line (rerun --more-memory).
+_quantui_mem_mb="${{SLURM_MEM_PER_NODE:-}}"
+case "$_quantui_mem_mb" in ''|*[!0-9]*) _quantui_mem_mb=$(({memory} * 1024)) ;; esac
+export PYSCF_MAX_MEMORY="$((_quantui_mem_mb * 4 / 5))"
{attempt_setup}
{worker_command}
diff --git a/tests/test_backends_slurm.py b/tests/test_backends_slurm.py
index d11dc355..8c69e64d 100644
--- a/tests/test_backends_slurm.py
+++ b/tests/test_backends_slurm.py
@@ -317,6 +317,38 @@ def test_one_task_with_cores_as_cpus(self, tmp_path):
assert "#SBATCH --cpus-per-task=8\n" in text
assert 'OMP_NUM_THREADS="${SLURM_CPUS_PER_TASK:-8}"' in text
+ @pytest.mark.skipif(sys.platform == "win32", reason="runs bash")
+ def test_pyscf_max_memory_follows_the_allocation(self, tmp_path):
+ """PySCF's memory cap is 80% of the job's memory (audit HPC-15)."""
+ import re
+ import shutil
+
+ if shutil.which("bash") is None:
+ pytest.skip("bash not available")
+ text = self._prepare(tmp_path)
+ gb = int(re.search(r"#SBATCH --mem=(\d+)G", text).group(1))
+ script = tmp_path / "submit.slurm"
+ script.write_text(text)
+ assert subprocess.run(["bash", "-n", str(script)]).returncode == 0
+
+ lines = text.splitlines()
+ start = next(i for i, ln in enumerate(lines) if "_quantui_mem_mb=" in ln)
+ end = next(i for i, ln in enumerate(lines) if "PYSCF_MAX_MEMORY=" in ln)
+ block = "\n".join(lines[start : end + 1]) + '\necho "$PYSCF_MAX_MEMORY"\n'
+
+ def run(env_mem):
+ env = {"PATH": "/usr/bin:/bin"}
+ if env_mem is not None:
+ env["SLURM_MEM_PER_NODE"] = env_mem
+ out = subprocess.run(
+ ["bash", "-c", block], env=env, capture_output=True, text=True
+ )
+ return int(out.stdout.strip())
+
+ assert run("10240") == 8192 # Slurm's value wins (e.g. --more-memory)
+ assert run(None) == gb * 1024 * 4 // 5 # the #SBATCH --mem fallback
+ assert run("16G") == gb * 1024 * 4 // 5 # not plain MB → fallback
+
def test_cpu_job_has_no_nv_and_no_gpu_lines(self, tmp_path):
text = self._prepare(tmp_path)
assert "apptainer exec --bind" in text
From 5186e8af6d3047da40cefbbb84b3d689f104020e Mon Sep 17 00:00:00 2001
From: Claude
Date: Thu, 12 Nov 2026 20:36:12 +0000
Subject: [PATCH 12/64] Apptainer CPU image: PYTHONPATH, Voila bounds, build
freeze; drop stale sbatch (audit HPC-16)
- quantui.def %environment exported "/opt/quantui:${PYTHONPATH}", which
with PYTHONPATH unset ends in ":" -- an empty sys.path entry, i.e. the
current directory, so a json.py in a student's folder shadowed the
standard library. Now "/opt/quantui${PYTHONPATH:+:${PYTHONPATH}}".
- The image installed voila unpinned and QuantUI as .[pyscf,ts], so
pyproject's voila>=0.5,<0.6 (and ipykernel) bounds never applied. Voila
is dropped from the unpinned pip line and QuantUI installs
.[pyscf,ts,app].
- The build now records /opt/build-info (pip freeze, conda list, QuantUI
version, build date), as quantui-gpu.def already does.
- apptainer/slurm/quantui-batch.sbatch had drifted from the generated
submit.slurm (no attempt dir, --nv forced, results dir override) and
is removed; both READMEs point at the generated per-job script instead.
Not changed: base images stay pinned by tag (digest pinning needs the
registry), conda packages stay unpinned, and the worker's apptainer exec
gets no --cleanenv / --env PYTHONPATH= (cannot be verified without
Apptainer; --cleanenv would also drop OMP_NUM_THREADS and
PYSCF_MAX_MEMORY). The image itself was not built here.
Tests: TestCpuImageHygiene in tests/test_cpu_container_def.py (text
checks; 3 of 4 fail on the old def, the 4th on the old tree). Extracted
%environment/%post/%runscript/%test of both defs pass `bash -n`.
Contributions:
- Claude (Opus 5.5): code edits, review, and conceptual discussion
- Jonathan Schultz: overall vision, planning, review, and orchestration
Co-authored-by: Jonathan Schultz
Co-authored-by: Claude Opus 5.5
---
apptainer/README.md | 1 -
apptainer/quantui.def | 21 ++++++++++++++----
apptainer/slurm/README.md | 8 ++++---
apptainer/slurm/quantui-batch.sbatch | 31 ---------------------------
tests/test_cpu_container_def.py | 32 ++++++++++++++++++++++++++++
5 files changed, 54 insertions(+), 39 deletions(-)
delete mode 100644 apptainer/slurm/quantui-batch.sbatch
diff --git a/apptainer/README.md b/apptainer/README.md
index 32ed97d7..3e472340 100644
--- a/apptainer/README.md
+++ b/apptainer/README.md
@@ -25,7 +25,6 @@ air-gapped or restricted-network classroom.
| `verify-gpu.sh` | Seven-step (0–6) check that a GPU image really reaches the GPU |
| `_build_env.sh` | Shared build-scratch setup sourced by both build scripts (moves scratch off a small `/tmp`) |
| `slurm/quantui-gpu-test.sbatch` | Batch template for verifying on a cluster |
-| `slurm/quantui-batch.sbatch` | Batch template for running a QuantUI calculation |
| `slurm/README.md` | SLURM batch guide: `quantui-batch`, job folders, operator variables |
| `ncshare-gpu-diagnostic.ipynb` | Interactive diagnostic to run **inside** the image on a GPU node |
| `make_ncshare_diagnostic.py` | Generates that notebook (edit here, not the `.ipynb`) |
diff --git a/apptainer/quantui.def b/apptainer/quantui.def
index 99487c66..fa6c0482 100644
--- a/apptainer/quantui.def
+++ b/apptainer/quantui.def
@@ -40,7 +40,10 @@ FROM: condaforge/miniforge3:26.1.1-3
%environment
export PATH="/opt/conda/envs/quantui/bin:${PATH}"
- export PYTHONPATH="/opt/quantui:${PYTHONPATH}"
+ # No trailing ":" when PYTHONPATH is unset/empty: an empty entry means the
+ # current directory, so a json.py in a student's folder would shadow the
+ # standard library.
+ export PYTHONPATH="/opt/quantui${PYTHONPATH:+:${PYTHONPATH}}"
# Disable user site-packages for reproducibility
export PYTHONNOUSERSITE=1
@@ -128,8 +131,9 @@ FROM: condaforge/miniforge3:26.1.1-3
export PATH="/opt/conda/envs/quantui/bin:${PATH}"
echo "Installing pip packages..."
+ # Not voila: the [app] extra below installs it within QuantUI's own bounds
+ # (an unpinned install here would take whatever Voila release is current).
pip install --no-cache-dir \
- voila \
ase \
py3dmol \
requests
@@ -141,8 +145,17 @@ FROM: condaforge/miniforge3:26.1.1-3
# miss. PySCF itself is already satisfied by the conda package above, so pip
# leaves it alone. Naming the extra keeps this list from going stale
# (ISSUE.18). [ts] adds Sella for Transition State (M-TS TS.5; it pulls in
- # jax/jaxlib, about 380 MB).
- pip install --no-cache-dir -e ".[pyscf,ts]"
+ # jax/jaxlib, about 380 MB). [app] installs Voila and ipykernel within the
+ # bounds pyproject.toml sets for them.
+ pip install --no-cache-dir -e ".[pyscf,ts,app]"
+
+ # What is in the image, as quantui-gpu.def records it: the package
+ # versions (pip and conda), the QuantUI version, and when it was built.
+ mkdir -p /opt/build-info
+ pip freeze > /opt/build-info/pip-freeze.txt
+ conda list -n quantui > /opt/build-info/conda-list.txt
+ python -c "import quantui; print(quantui.__version__)" > /opt/build-info/quantui-version.txt
+ date -u +"%Y-%m-%dT%H:%M:%SZ" > /opt/build-info/build-date.txt
echo "Verifying installation..."
python -c "import quantui; print('QuantUI OK')"
diff --git a/apptainer/slurm/README.md b/apptainer/slurm/README.md
index a9fcb7eb..bbb8f885 100644
--- a/apptainer/slurm/README.md
+++ b/apptainer/slurm/README.md
@@ -6,10 +6,13 @@ Reference scripts for operator-driven NCShare / Apptainer batch jobs.
| File | Purpose |
|------|---------|
-| `quantui-batch.sbatch` | Reference `sbatch` template (partition must be set) |
| `quantui-gpu-test.sbatch` | GPU smoke test (operator use) |
-QuantUI generates per-job scripts automatically when students submit from the UI.
+QuantUI generates a per-job `submit.slurm` in each job folder when a job is
+submitted from the UI or with `quantui-batch`; that generated script is the
+reference for what a QuantUI batch job runs. (The hand-edited
+`quantui-batch.sbatch` template that used to live here had drifted from it and
+was removed.)
## Submitting from a terminal (`quantui-batch`)
@@ -19,7 +22,6 @@ the image there and never imports QuantUI: it is a standard-library Python
3.6+ script that writes the same job folder `SlurmBackend.prepare()` writes
(`request.json`, `submit.slurm`, and the job record the app reads), then
calls `sbatch`. The calculation runs inside the image on a compute node.
-(`quantui-batch.sbatch` above is an unrelated hand-edited reference template.)
The values the launcher has to agree with QuantUI on (element table, method
list, limits, estimate factors, the batch-script template, the image's own
diff --git a/apptainer/slurm/quantui-batch.sbatch b/apptainer/slurm/quantui-batch.sbatch
deleted file mode 100644
index 6b7a8317..00000000
--- a/apptainer/slurm/quantui-batch.sbatch
+++ /dev/null
@@ -1,31 +0,0 @@
-#!/bin/bash
-# quantui-batch.sbatch — run a QuantUI CalculationRequest via the headless worker.
-#
-# Generated per-job copies live in ~/.quantui/staging//submit.slurm.
-# This file is the reference template for operators (NCShare / Apptainer).
-#
-# sbatch --export=ALL,QUANTUI_BATCH_IMAGE=$HOME/quantui-gpu.sif \
-# apptainer/slurm/quantui-batch.sbatch
-#
-# TODO(NCShare): confirm partition and account/QoS with site admin.
-
-#SBATCH --job-name=quantui-batch
-#SBATCH --output=quantui-batch-%j.out
-#SBATCH --error=quantui-batch-%j.err
-#SBATCH --partition=CHANGEME
-#SBATCH --cpus-per-task=4
-#SBATCH --mem=16G
-#SBATCH --time=04:00:00
-
-set -euo pipefail
-
-IMAGE="${QUANTUI_BATCH_IMAGE:-$HOME/quantui-gpu.sif}"
-REQUEST="${QUANTUI_REQUEST_PATH:?Set QUANTUI_REQUEST_PATH to staging/request.json}"
-STAGING="$(dirname "$REQUEST")"
-
-export OMP_NUM_THREADS="${SLURM_CPUS_PER_TASK:-4}"
-export QUANTUI_RESULTS_DIR="${STAGING}/results"
-mkdir -p "$QUANTUI_RESULTS_DIR"
-
-apptainer exec --nv --bind "$HOME:$HOME" --pwd "$STAGING" "$IMAGE" \
- python -m quantui.backends.worker --request "$REQUEST"
diff --git a/tests/test_cpu_container_def.py b/tests/test_cpu_container_def.py
index 895b66d4..f3a4922f 100644
--- a/tests/test_cpu_container_def.py
+++ b/tests/test_cpu_container_def.py
@@ -89,3 +89,35 @@ def test_the_extra_still_lists_both_packages(self):
text = (REPO / "pyproject.toml").read_text(encoding="utf-8")
extra = text.split("\npyscf = [", 1)[1].split("]", 1)[0]
assert '"pyscf-properties"' in extra and "pyscf-dispersion" in extra
+
+
+class TestCpuImageHygiene:
+ """Audit HPC-16 — text checks only; nothing here builds or runs the image."""
+
+ def test_pythonpath_has_no_empty_entry(self, cpu_def_text):
+ # "/opt/quantui:${PYTHONPATH}" with PYTHONPATH unset ends in ":", an
+ # empty entry = the current directory on sys.path (a student's
+ # json.py would shadow the standard library).
+ env = _section(cpu_def_text, "%environment")
+ lines = [ln.strip() for ln in env.splitlines() if "PYTHONPATH=" in ln]
+ assert lines == [
+ 'export PYTHONPATH="/opt/quantui${PYTHONPATH:+:${PYTHONPATH}}"'
+ ]
+
+ def test_voila_comes_from_the_app_extra_with_its_bounds(self, cpu_def_text):
+ post = _section(cpu_def_text, "%post")
+ assert re.search(r'pip install[^\n]*-e\s+"\.\[[^\]]*\bapp\b[^\]]*\]"', post)
+ # No unpinned voila install alongside it (continuation lines included).
+ unpinned = re.findall(
+ r"pip install --no-cache-dir \\\n((?:\s+\S+ \\\n)*\s+\S+)", post
+ )
+ assert unpinned and all("voila" not in block for block in unpinned)
+
+ def test_build_records_a_freeze(self, cpu_def_text):
+ post = _section(cpu_def_text, "%post")
+ assert "pip freeze > /opt/build-info/pip-freeze.txt" in post
+
+ def test_stale_reference_sbatch_is_gone(self):
+ # It had drifted from the generated submit.slurm (no attempt dir,
+ # --nv forced); the generated script is the reference now.
+ assert not (REPO / "apptainer" / "slurm" / "quantui-batch.sbatch").exists()
From ba4094079520f5fb9cfe05ea5f7b54710a76d560 Mon Sep 17 00:00:00 2001
From: Claude
Date: Thu, 12 Nov 2026 20:39:00 +0000
Subject: [PATCH 13/64] Launchers: trailing backslash, apostrophes, set -u,
port probe (audit HPC-18)
- launch-app.bat passed "%SIFDIR%" (ending in "\", which escapes the
closing quote) to wslpath; the folder is now normalised without the
trailing backslash first.
- launch-app/dev/native.bat ran bash -c "cd '%WSLPATH%' && ...", which
broke on an apostrophe in the folder path; they now use wsl --cd, as
launch-native-jupyter.bat already does.
- launch-native.command, launch-native.sh and launch-native-jupyter.sh
source conda.sh / conda activate under set -u, whose activation
scripts read unset variables; nounset is now off for those two lines.
- launch-native.command listed /opt/miniconda3/condabin/conda (the conda
executable, not conda.sh) as a file to source; dropped, and the Intel
Homebrew miniforge prefix added. Its `open` gets `|| true` under set -e.
- Fixed ports + a blind sleep opened whatever already served on
8866/8867. Every Voila launcher now refuses to start when the port is
already answering, and waits for the port to answer (stopping early if
Voila exited, .sh/.command) instead of sleeping a fixed time.
Not changed: `wsl -d Ubuntu` stays hard-coded (choosing a distro is a
decision); the Windows and macOS launchers were not run here.
Tests: tests/test_launcher_scripts.py runs launch-native.sh and
launch-native.command against fake conda/voila in a repo copy whose path
contains an apostrophe: busy port refused, conda activation survives
set -u, a Voila that dies at startup is reported (fails on the old
scripts). All .sh/.command pass `bash -n`.
Contributions:
- Claude (Opus 5.5): code edits, review, and conceptual discussion
- Jonathan Schultz: overall vision, planning, review, and orchestration
Co-authored-by: Jonathan Schultz
Co-authored-by: Claude Opus 5.5
---
launchers/launch-app.bat | 25 +++++--
launchers/launch-dev.bat | 18 ++++-
launchers/launch-native-jupyter.sh | 4 ++
launchers/launch-native.bat | 18 ++++-
launchers/launch-native.command | 43 ++++++++++--
launchers/launch-native.sh | 42 +++++++++--
tests/test_launcher_scripts.py | 108 +++++++++++++++++++++++++++++
7 files changed, 241 insertions(+), 17 deletions(-)
create mode 100644 tests/test_launcher_scripts.py
diff --git a/launchers/launch-app.bat b/launchers/launch-app.bat
index 8cdb71cf..6b2b4da4 100644
--- a/launchers/launch-app.bat
+++ b/launchers/launch-app.bat
@@ -14,9 +14,21 @@ if not exist "%SIFDIR%quantui.sif" (
exit /b 1
)
-REM Convert the folder holding the .sif to a WSL path for portability
+REM Convert the folder holding the .sif to a WSL path for portability. Not
+REM "%SIFDIR%" itself: it ends in "\", which escapes the closing quote.
+for %%i in ("%SIFDIR%.") do set "SIFDIR=%%~fi"
for /f "delims=" %%i in ('wsl wslpath -a "%SIFDIR%"') do set WSLPATH=%%i
+REM Something already serving on 8866 (an earlier run, another app) would be
+REM opened in the browser instead of this one, so refuse to start.
+powershell -NoProfile -Command "$c = New-Object Net.Sockets.TcpClient; try { $c.Connect('127.0.0.1', 8866); $c.Close(); exit 0 } catch { exit 1 }" > nul 2>&1
+if not errorlevel 1 (
+ echo ERROR: port 8866 is already in use - is QuantUI already running?
+ echo Close that window or program first, then run this again.
+ pause
+ exit /b 1
+)
+
REM Per-run login token: without one, any other local user or process could
REM drive the app. WSLENV hands QUANTUI_APP_TOKEN to the WSL side through the
REM environment, not a command line.
@@ -29,12 +41,15 @@ if not defined QUANTUI_APP_TOKEN (
)
if defined WSLENV (set "WSLENV=%WSLENV%:QUANTUI_APP_TOKEN") else (set "WSLENV=QUANTUI_APP_TOKEN")
-REM Launch Voila in a new WSL window (stays open so you can see logs)
-start "QuantUI" wsl -d Ubuntu -- bash -c "cd '%WSLPATH%' && apptainer run quantui.sif app"
+REM Launch Voila in a new WSL window (stays open so you can see logs). --cd
+REM rather than a "cd '...'" inside bash -c, which broke on an apostrophe in
+REM the folder path.
+start "QuantUI" wsl -d Ubuntu --cd "%WSLPATH%" -- bash -c "apptainer run quantui.sif app"
-REM Wait for Voila to start, then open the browser
+REM Wait (up to 90 s) for Voila to answer on the port, then open the browser
echo Waiting for Voila to start...
-timeout /t 6 /nobreak > nul
+powershell -NoProfile -Command "for ($i = 0; $i -lt 90; $i++) { $c = New-Object Net.Sockets.TcpClient; try { $c.Connect('127.0.0.1', 8866); $c.Close(); exit 0 } catch { Start-Sleep -Seconds 1 } }; exit 1" > nul 2>&1
+if errorlevel 1 echo Voila did not answer within 90 s - check the QuantUI WSL window.
start http://localhost:8866/?token=%QUANTUI_APP_TOKEN%
echo.
diff --git a/launchers/launch-dev.bat b/launchers/launch-dev.bat
index e1364f35..b702c748 100644
--- a/launchers/launch-dev.bat
+++ b/launchers/launch-dev.bat
@@ -32,12 +32,26 @@ if not defined QUANTUI_APP_TOKEN (
)
if defined WSLENV (set "WSLENV=%WSLENV%:QUANTUI_APP_TOKEN") else (set "WSLENV=QUANTUI_APP_TOKEN")
+REM Something already serving on 8866 (an earlier run, another app) would be
+REM opened in the browser instead of this one, so refuse to start.
+powershell -NoProfile -Command "$c = New-Object Net.Sockets.TcpClient; try { $c.Connect('127.0.0.1', 8866); $c.Close(); exit 0 } catch { exit 1 }" > nul 2>&1
+if not errorlevel 1 (
+ echo ERROR: port 8866 is already in use - is QuantUI already running?
+ echo Close that window or program first, then run this again.
+ pause
+ exit /b 1
+)
+
REM Uses the local notebook on disk instead of the baked-in copy.
REM Edits to notebooks/ take effect immediately — no container rebuild needed.
-start "QuantUI [dev]" wsl -d Ubuntu -- bash -c "cd '%WSLPATH%' && apptainer exec --cleanenv quantui.sif voila notebooks/molecule_computations.ipynb --no-browser --port=8866 --Voila.ip=127.0.0.1 --Voila.token=$QUANTUI_APP_TOKEN --ServerApp.disable_check_xsrf=True"
+start "QuantUI [dev]" wsl -d Ubuntu --cd "%WSLPATH%" -- bash -c "apptainer exec --cleanenv quantui.sif voila notebooks/molecule_computations.ipynb --no-browser --port=8866 --Voila.ip=127.0.0.1 --Voila.token=$QUANTUI_APP_TOKEN --ServerApp.disable_check_xsrf=True"
+REM The WSL window starts Voila with --cd rather than a "cd '...'" inside bash -c,
+REM which broke on an apostrophe in the folder path. Wait (up to 90 s) for it
+REM to answer on the port, then open the browser.
echo Waiting for Voila to start...
-timeout /t 6 /nobreak > nul
+powershell -NoProfile -Command "for ($i = 0; $i -lt 90; $i++) { $c = New-Object Net.Sockets.TcpClient; try { $c.Connect('127.0.0.1', 8866); $c.Close(); exit 0 } catch { Start-Sleep -Seconds 1 } }; exit 1" > nul 2>&1
+if errorlevel 1 echo Voila did not answer within 90 s - check the QuantUI [dev] WSL window.
start http://localhost:8866/?token=%QUANTUI_APP_TOKEN%
echo.
diff --git a/launchers/launch-native-jupyter.sh b/launchers/launch-native-jupyter.sh
index b2a2de2e..594db437 100755
--- a/launchers/launch-native-jupyter.sh
+++ b/launchers/launch-native-jupyter.sh
@@ -50,9 +50,13 @@ if [ -z "$CONDA_SH" ]; then
echo " https://github.com/conda-forge/miniforge"
exit 1
fi
+# conda's activation scripts read unset variables, which `set -u` turns
+# into a fatal error, so nounset is off for these two lines only.
+set +u
# shellcheck disable=SC1090
source "$CONDA_SH"
conda activate quantui
+set -u
echo "Using Python: $(command -v python)"
echo "Using Jupyter: $(command -v jupyter)"
diff --git a/launchers/launch-native.bat b/launchers/launch-native.bat
index 236b7320..ee1a34cf 100644
--- a/launchers/launch-native.bat
+++ b/launchers/launch-native.bat
@@ -20,6 +20,16 @@ if not defined QUANTUI_APP_TOKEN (
)
if defined WSLENV (set "WSLENV=%WSLENV%:QUANTUI_APP_TOKEN") else (set "WSLENV=QUANTUI_APP_TOKEN")
+REM Something already serving on 8867 (an earlier run, another app) would be
+REM opened in the browser instead of this one, so refuse to start.
+powershell -NoProfile -Command "$c = New-Object Net.Sockets.TcpClient; try { $c.Connect('127.0.0.1', 8867); $c.Close(); exit 0 } catch { exit 1 }" > nul 2>&1
+if not errorlevel 1 (
+ echo ERROR: port 8867 is already in use - is QuantUI already running?
+ echo Close that window or program first, then run this again.
+ pause
+ exit /b 1
+)
+
REM Runs Voila directly from the quantui conda env inside WSL.
REM pip install -e . is skipped when pyproject.toml has not changed since the
REM last install (.dev_install_stamp). quantui/*.py changes are always live in
@@ -39,10 +49,14 @@ REM make EVERY subsequent offline launch retry (and re-delay on) pip — the
REM reinstall is attempted once, then skipped. quantui/*.py + package-data are
REM live in editable mode, so a skipped reinstall is harmless offline; re-run
REM `pip install -e .` manually when online if you add a real dependency.
-start "QuantUI [native]" wsl -d Ubuntu -- bash -c "cd '%WSLPATH%' && for c in ~/miniforge3 ~/miniconda3 ~/anaconda3 /opt/conda; do [ -f $c/etc/profile.d/conda.sh ] && . $c/etc/profile.d/conda.sh && break; done && conda activate quantui && if [ pyproject.toml -nt .dev_install_stamp ] || ! python -c 'import quantui' 2>/dev/null; then pip install -e . -q --timeout=5 --retries=0 && touch .dev_install_stamp || { echo '[QuantUI] editable reinstall skipped (offline?) - using live source'; touch .dev_install_stamp; }; fi; rm -rf quantui/__pycache__ && PYTHONDONTWRITEBYTECODE=1 voila notebooks/molecule_computations.ipynb --no-browser --port=8867 --Voila.ip=127.0.0.1 --Voila.token=$QUANTUI_APP_TOKEN --ServerApp.disable_check_xsrf=True"
+start "QuantUI [native]" wsl -d Ubuntu --cd "%WSLPATH%" -- bash -c "for c in ~/miniforge3 ~/miniconda3 ~/anaconda3 /opt/conda; do [ -f $c/etc/profile.d/conda.sh ] && . $c/etc/profile.d/conda.sh && break; done && conda activate quantui && if [ pyproject.toml -nt .dev_install_stamp ] || ! python -c 'import quantui' 2>/dev/null; then pip install -e . -q --timeout=5 --retries=0 && touch .dev_install_stamp || { echo '[QuantUI] editable reinstall skipped (offline?) - using live source'; touch .dev_install_stamp; }; fi; rm -rf quantui/__pycache__ && PYTHONDONTWRITEBYTECODE=1 voila notebooks/molecule_computations.ipynb --no-browser --port=8867 --Voila.ip=127.0.0.1 --Voila.token=$QUANTUI_APP_TOKEN --ServerApp.disable_check_xsrf=True"
+REM The WSL window starts Voila with --cd rather than a "cd '...'" inside bash -c,
+REM which broke on an apostrophe in the folder path. Wait (up to 90 s) for it
+REM to answer on the port, then open the browser.
echo Waiting for Voila to start...
-timeout /t 6 /nobreak > nul
+powershell -NoProfile -Command "for ($i = 0; $i -lt 90; $i++) { $c = New-Object Net.Sockets.TcpClient; try { $c.Connect('127.0.0.1', 8867); $c.Close(); exit 0 } catch { Start-Sleep -Seconds 1 } }; exit 1" > nul 2>&1
+if errorlevel 1 echo Voila did not answer within 90 s - check the QuantUI [native] WSL window.
start http://localhost:8867/?token=%QUANTUI_APP_TOKEN%
echo.
diff --git a/launchers/launch-native.command b/launchers/launch-native.command
index 19d4594b..b11b096b 100755
--- a/launchers/launch-native.command
+++ b/launchers/launch-native.command
@@ -36,8 +36,8 @@ for candidate in \
"$HOME/miniforge3/etc/profile.d/conda.sh" \
"/opt/miniforge3/etc/profile.d/conda.sh" \
"/opt/homebrew/Caskroom/miniforge/base/etc/profile.d/conda.sh" \
+ "/usr/local/Caskroom/miniforge/base/etc/profile.d/conda.sh" \
"/opt/miniconda3/etc/profile.d/conda.sh" \
- "/opt/miniconda3/condabin/conda" \
"$HOME/miniconda3/etc/profile.d/conda.sh" \
"$HOME/opt/miniconda3/etc/profile.d/conda.sh" \
"/opt/homebrew/Caskroom/miniconda/base/etc/profile.d/conda.sh" \
@@ -63,9 +63,13 @@ if [ -z "$CONDA_SH" ]; then
exit 1
fi
+# conda's activation scripts read unset variables, which `set -u` turns
+# into a fatal error, so nounset is off for these two lines only.
+set +u
# shellcheck disable=SC1090
source "$CONDA_SH"
conda activate quantui
+set -u
# pip install -e . is skipped when pyproject.toml has not changed since
# the last install (.dev_install_stamp). quantui/*.py changes are always
@@ -101,6 +105,22 @@ PORT=8867
TOKEN="${QUANTUI_APP_TOKEN:-$(python -c 'import secrets; print(secrets.token_urlsafe(24))')}"
URL="http://localhost:${PORT}/?token=${TOKEN}"
+# True when something answers on 127.0.0.1:$1 (python is the conda env's).
+port_open() {
+ python -c 'import socket, sys
+s = socket.socket()
+s.settimeout(0.5)
+sys.exit(0 if s.connect_ex(("127.0.0.1", int(sys.argv[1]))) == 0 else 1)' "$1"
+}
+
+# A server already on the port (an earlier run, another app) would be opened
+# in the browser instead of this one.
+if port_open "${PORT}"; then
+ echo "ERROR: port ${PORT} is already in use - is QuantUI already running?"
+ echo " Stop that server first, then run this again."
+ exit 1
+fi
+
echo "Starting Voilà on ${URL}..."
echo
@@ -114,9 +134,24 @@ voila notebooks/molecule_computations.ipynb \
--ServerApp.disable_check_xsrf=True &
VOILA_PID=$!
-# Give Voilà a moment to bind to the port before opening the browser.
-sleep 4
-open "${URL}"
+# Wait (up to 60 s) until Voilà answers on the port, rather than a fixed
+# sleep; stop early if it exited (e.g. a startup error).
+waited=0
+until port_open "${PORT}"; do
+ if ! kill -0 "${VOILA_PID}" 2>/dev/null; then
+ echo "ERROR: Voilà exited during startup - see the messages above."
+ wait "${VOILA_PID}" || true
+ exit 1
+ fi
+ if [ "${waited}" -ge 60 ]; then
+ echo "Voilà has not answered on port ${PORT} after 60 s; opening anyway."
+ break
+ fi
+ sleep 1
+ waited=$((waited + 1))
+done
+# Non-fatal under `set -e`: the URL is printed below regardless.
+open "${URL}" || true
echo
echo "Native dev server running at ${URL}"
diff --git a/launchers/launch-native.sh b/launchers/launch-native.sh
index 8df040e2..8b1b0f70 100755
--- a/launchers/launch-native.sh
+++ b/launchers/launch-native.sh
@@ -61,9 +61,13 @@ if [ -z "$CONDA_SH" ]; then
exit 1
fi
+# conda's activation scripts read unset variables, which `set -u` turns
+# into a fatal error, so nounset is off for these two lines only.
+set +u
# shellcheck disable=SC1090
source "$CONDA_SH"
conda activate quantui
+set -u
# pip install -e . is skipped when pyproject.toml has not changed since the
# last install (.dev_install_stamp). quantui/*.py changes are always live in
@@ -101,6 +105,22 @@ PORT=8867
TOKEN="${QUANTUI_APP_TOKEN:-$(python -c 'import secrets; print(secrets.token_urlsafe(24))')}"
URL="http://localhost:${PORT}/?token=${TOKEN}"
+# True when something answers on 127.0.0.1:$1 (python is the conda env's).
+port_open() {
+ python -c 'import socket, sys
+s = socket.socket()
+s.settimeout(0.5)
+sys.exit(0 if s.connect_ex(("127.0.0.1", int(sys.argv[1]))) == 0 else 1)' "$1"
+}
+
+# A server already on the port (an earlier run, another app) would be opened
+# in the browser instead of this one.
+if port_open "${PORT}"; then
+ echo "ERROR: port ${PORT} is already in use - is QuantUI already running?"
+ echo " Stop that server first, then run this again."
+ exit 1
+fi
+
echo "Starting Voilà on ${URL}..."
echo
@@ -114,10 +134,24 @@ voila notebooks/molecule_computations.ipynb \
--ServerApp.disable_check_xsrf=True &
VOILA_PID=$!
-# Give Voilà a moment to bind to the port before opening the browser. Try the
-# common openers in order; under WSL, wslview/cmd.exe hand off to the Windows
-# browser. All are non-fatal — the URL is printed regardless.
-sleep 4
+# Wait (up to 60 s) until Voilà answers on the port, rather than a fixed
+# sleep; stop early if it exited (e.g. a startup error).
+waited=0
+until port_open "${PORT}"; do
+ if ! kill -0 "${VOILA_PID}" 2>/dev/null; then
+ echo "ERROR: Voilà exited during startup - see the messages above."
+ wait "${VOILA_PID}" || true
+ exit 1
+ fi
+ if [ "${waited}" -ge 60 ]; then
+ echo "Voilà has not answered on port ${PORT} after 60 s; opening anyway."
+ break
+ fi
+ sleep 1
+ waited=$((waited + 1))
+done
+# Try the common openers in order; under WSL, wslview/cmd.exe hand off to the
+# Windows browser. All are non-fatal — the URL is printed regardless.
if command -v wslview >/dev/null 2>&1; then
wslview "${URL}" >/dev/null 2>&1 || true
elif command -v xdg-open >/dev/null 2>&1; then
diff --git a/tests/test_launcher_scripts.py b/tests/test_launcher_scripts.py
new file mode 100644
index 00000000..f1c1e595
--- /dev/null
+++ b/tests/test_launcher_scripts.py
@@ -0,0 +1,108 @@
+"""Native shell launchers (audit HPC-18): run them against fake conda/voila.
+
+The launchers are copied into a throwaway repo skeleton, so nothing here
+touches this checkout (they ``cd`` to their parent folder, clear
+``quantui/__pycache__`` and write ``.dev_install_stamp`` there).
+"""
+
+from __future__ import annotations
+
+import shutil
+import socket
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+REPO = Path(__file__).resolve().parent.parent
+
+pytestmark = pytest.mark.skipif(
+ sys.platform == "win32" or shutil.which("bash") is None, reason="runs bash"
+)
+
+PORT = 8867 # fixed in both native launchers
+
+
+def _skeleton(tmp_path: Path, launcher: str) -> tuple[Path, dict]:
+ root = tmp_path / "repo with 'apostrophe'"
+ (root / "launchers").mkdir(parents=True)
+ (root / "notebooks").mkdir()
+ (root / "pyproject.toml").write_text("[project]\nname = 'x'\n")
+ shutil.copy(REPO / "launchers" / launcher, root / "launchers" / launcher)
+
+ home = tmp_path / "home"
+ conda_sh = home / "miniforge3" / "etc" / "profile.d" / "conda.sh"
+ conda_sh.parent.mkdir(parents=True)
+ # Real conda activation scripts read unset variables; under `set -u`
+ # that used to abort the launch.
+ conda_sh.write_text(
+ ': "${QUANTUI_TEST_UNSET_AT_SOURCE}"\n'
+ 'conda() { : "${QUANTUI_TEST_UNSET_IN_ACTIVATE}"; }\n'
+ )
+ bindir = tmp_path / "bin"
+ bindir.mkdir()
+ for name, body in {
+ "pip": "exit 0",
+ # Exits at once, like a Voilà with a startup error.
+ "voila": 'echo "fake voila $*"; exit 3',
+ "open": 'echo "OPENED $*"',
+ "xdg-open": 'echo "OPENED $*"',
+ }.items():
+ exe = bindir / name
+ exe.write_text(f"#!/bin/sh\n{body}\n")
+ exe.chmod(0o755)
+ env = {
+ "HOME": str(home),
+ "PATH": f"{bindir}:{Path(sys.executable).parent}:/usr/bin:/bin",
+ "QUANTUI_APP_TOKEN": "tok",
+ }
+ return root / "launchers" / launcher, env
+
+
+def _run(script: Path, env: dict) -> subprocess.CompletedProcess:
+ return subprocess.run(
+ ["bash", str(script)],
+ env=env,
+ capture_output=True,
+ text=True,
+ timeout=60,
+ stdin=subprocess.DEVNULL,
+ )
+
+
+@pytest.mark.parametrize("launcher", ["launch-native.sh", "launch-native.command"])
+def test_native_launcher_startup_checks(tmp_path, launcher):
+ probe = socket.socket()
+ try:
+ probe.bind(("127.0.0.1", PORT))
+ except OSError:
+ probe.close()
+ pytest.skip(f"port {PORT} is in use on this machine")
+ script, env = _skeleton(tmp_path, launcher)
+
+ # 1. Something already listening on the port: refuse, never start Voilà.
+ probe.listen(1)
+ try:
+ busy = _run(script, env)
+ finally:
+ probe.close()
+ assert busy.returncode == 1
+ assert f"port {PORT} is already in use" in busy.stdout
+ assert "fake voila" not in busy.stdout
+ assert "unbound variable" not in busy.stderr # conda activation under set -u
+
+ # 2. Port free, Voilà dies at startup: say so instead of opening a URL
+ # nothing serves.
+ died = _run(script, env)
+ assert died.returncode == 1, died.stderr
+ assert "fake voila" in died.stdout
+ assert "exited during startup" in died.stdout
+ assert "OPENED" not in died.stdout
+
+
+def test_command_launcher_has_no_conda_executable_candidate():
+ # `source`-ing the conda *executable* (condabin/conda) is not conda.sh.
+ text = (REPO / "launchers" / "launch-native.command").read_text()
+ assert "condabin/conda" not in text
+ assert 'open "${URL}" || true' in text
From cb939041c32c4bdd4515588791b3b319a09bdc28 Mon Sep 17 00:00:00 2001
From: Claude
Date: Thu, 12 Nov 2026 20:29:12 +0000
Subject: [PATCH 14/64] Validate the SLURM partition before it reaches
submit.slurm (audit HPC-9)
`--partition` and QUANTUI_SLURM_PARTITION were pasted onto the
`#SBATCH --partition=` line unchecked, so a newline in the value added
#SBATCH directives or shell lines to the batch script, bypassing
validate_resources(). Account/QOS/GRES were already restricted to
[A-Za-z0-9_.:,=+-].
Add cluster_config.validate_partition() using the same pattern;
SlurmBackend._create_job() checks the partition together with the site
directives (SecurityError, before the job folder exists), and the
quantui-batch launcher's partition() port raises InputError, also before
its job folder is made.
Tests: tests/test_hpc_audit_low.py::TestPartitionValidation (package,
`quantui submit --prepare-only`, launcher).
Contributions:
- Claude (Opus 5.5): code edits, review, and conceptual discussion
- Jonathan Schultz: overall vision, planning, review, and orchestration
Co-authored-by: Jonathan Schultz
Co-authored-by: Claude Opus 5.5
---
quantui/backends/cluster_config.py | 16 +++
quantui/backends/slurm.py | 1 +
quantui/data/launcher/quantui_batch.py | 18 ++-
tests/test_hpc_audit_low.py | 145 +++++++++++++++++++++++++
4 files changed, 176 insertions(+), 4 deletions(-)
create mode 100644 tests/test_hpc_audit_low.py
diff --git a/quantui/backends/cluster_config.py b/quantui/backends/cluster_config.py
index ebe5fd59..11d69f1a 100644
--- a/quantui/backends/cluster_config.py
+++ b/quantui/backends/cluster_config.py
@@ -167,6 +167,22 @@ def site_directives() -> list[str]:
return lines
+def validate_partition(value: str) -> str:
+ """Return *value* if it is safe on the ``#SBATCH --partition`` line.
+
+ The partition (``--partition`` or ``QUANTUI_SLURM_PARTITION``) is pasted
+ into the batch script like the account/QOS/GRES values, so a newline
+ would add ``#SBATCH`` lines or shell. Raises ``ValueError`` otherwise.
+ """
+ text = str(value or "").strip()
+ if not _SITE_DIRECTIVE_VALUE_RE.match(text):
+ raise ValueError(
+ f"SLURM partition {text!r} has characters not allowed in an "
+ "#SBATCH value (use letters, digits and _ . : , = + -)"
+ )
+ return text
+
+
def gpu_requested() -> bool:
"""True when the worker should get ``apptainer exec --nv``.
diff --git a/quantui/backends/slurm.py b/quantui/backends/slurm.py
index b83e63d8..27e7362b 100644
--- a/quantui/backends/slurm.py
+++ b/quantui/backends/slurm.py
@@ -249,6 +249,7 @@ def _create_job(
# nothing behind.
try:
site_lines = cfg.site_directives()
+ self.partition = cfg.validate_partition(self.partition)
except ValueError as exc:
raise SecurityError(str(exc)) from exc
email = validate_email(email)
diff --git a/quantui/data/launcher/quantui_batch.py b/quantui/data/launcher/quantui_batch.py
index 5fa021c8..c7257dfd 100644
--- a/quantui/data/launcher/quantui_batch.py
+++ b/quantui/data/launcher/quantui_batch.py
@@ -128,10 +128,6 @@ def image():
return os.environ.get("QUANTUI_BATCH_IMAGE") or DEFAULT_IMAGE
-def partition():
- return os.environ.get("QUANTUI_SLURM_PARTITION") or SITE["default_partition"]
-
-
# Port of cluster_config.SITE_DIRECTIVE_ENV / site_directives() /
# gpu_requested(): optional account/QOS/GRES lines, read per job.
SITE_DIRECTIVE_ENV = (
@@ -157,6 +153,19 @@ def site_directives():
return lines
+def partition():
+ """Port of cluster_config.validate_partition(): it is pasted into the script."""
+ value = (
+ os.environ.get("QUANTUI_SLURM_PARTITION") or SITE["default_partition"]
+ ).strip()
+ if not _SITE_DIRECTIVE_VALUE_RE.match(value):
+ raise InputError(
+ f"SLURM partition {value!r} has characters not allowed in an "
+ "#SBATCH value (use letters, digits and _ . : , = + -)"
+ )
+ return value
+
+
def gpu_requested():
override = os.environ.get("QUANTUI_SLURM_NV", "").strip().lower()
if override in ("1", "true", "yes", "on"):
@@ -679,6 +688,7 @@ def unique_request(request):
def prepare_job(request, resources, job_name, email, image_path):
"""Write the job folder and its record, as SlurmBackend.prepare() does."""
site_directives() # a bad site setting fails before the job folder exists
+ partition()
unique_request(request)
root = staging_root()
name = sanitize_job_name(job_name or "") or default_job_name(request)
diff --git a/tests/test_hpc_audit_low.py b/tests/test_hpc_audit_low.py
new file mode 100644
index 00000000..e32b282d
--- /dev/null
+++ b/tests/test_hpc_audit_low.py
@@ -0,0 +1,145 @@
+"""
+Regression tests for the Low HPC findings of the 2026-11-10 audit
+(HPC-9 … HPC-22): batch-script injection via the partition, batch input
+validation, client-side limits, HTML escaping, the mock Slurm, the
+``quantui-batch`` launcher, polling and job-folder permissions.
+"""
+
+import io
+import sys
+from pathlib import Path
+
+import pytest
+
+from quantui import cli
+from quantui.backends.base import CalculationRequest
+from quantui.backends.registry import JobRegistry
+from quantui.security import SecurityError
+
+WATER_XYZ = """3
+water
+O 0.0000 0.0000 0.1173
+H 0.0000 0.7572 -0.4692
+H 0.0000 -0.7572 -0.4692
+"""
+
+
+def _request(rid: str = "low001", calc_type: str = "single_point"):
+ return CalculationRequest(
+ request_id=rid,
+ calc_type=calc_type,
+ method="RHF",
+ basis="STO-3G",
+ charge=0,
+ multiplicity=1,
+ molecule={"atoms": ["H", "H"], "coords": [[0, 0, 0], [0, 0, 0.74]]},
+ )
+
+
+def _capture(argv):
+ out, err = io.StringIO(), io.StringIO()
+ real_out, real_err = sys.stdout, sys.stderr
+ sys.stdout, sys.stderr = out, err
+ try:
+ rc = cli.main(argv)
+ finally:
+ sys.stdout, sys.stderr = real_out, real_err
+ return rc, out.getvalue(), err.getvalue()
+
+
+@pytest.fixture
+def registry(tmp_path):
+ return JobRegistry(jobs_root=tmp_path / "jobs", staging_root=tmp_path / "staging")
+
+
+@pytest.fixture
+def roots(tmp_path, monkeypatch):
+ monkeypatch.setenv("QUANTUI_JOBS_DIR", str(tmp_path / "jobs"))
+ monkeypatch.setenv("QUANTUI_STAGING_DIR", str(tmp_path / "staging"))
+ monkeypatch.delenv("QUANTUI_ENABLE_SLURM", raising=False)
+ for var in ("QUANTUI_SLURM_ACCOUNT", "QUANTUI_SLURM_QOS", "QUANTUI_SLURM_GRES"):
+ monkeypatch.delenv(var, raising=False)
+ return tmp_path
+
+
+@pytest.fixture
+def water(tmp_path):
+ path = tmp_path / "water.xyz"
+ path.write_text(WATER_XYZ)
+ return path
+
+
+def _import_launcher(path):
+ import importlib.machinery
+ import importlib.util
+
+ loader = importlib.machinery.SourceFileLoader("quantui_batch_low_test", str(path))
+ spec = importlib.util.spec_from_loader(loader.name, loader)
+ mod = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(mod)
+ return mod
+
+
+@pytest.fixture
+def launcher(tmp_path, roots):
+ from quantui.batch_launcher import render_launcher
+
+ image = tmp_path / "quantui.sif"
+ image.write_text("fake image")
+ path = tmp_path / "quantui_batch_rendered.py"
+ path.write_text(
+ render_launcher(str(image), sys.executable, "test"), encoding="utf-8"
+ )
+ mod = _import_launcher(path)
+ mod.TEST_IMAGE = str(image)
+ return mod
+
+
+# ---------------------------------------------------------------------------
+# HPC-9: the partition is validated like account/QOS/GRES
+# ---------------------------------------------------------------------------
+
+_INJECTED = "common\n#SBATCH --account=other\ntouch /tmp/pwned"
+
+
+class TestPartitionValidation:
+ def test_validate_partition(self):
+ from quantui.backends.cluster_config import validate_partition
+
+ assert validate_partition(" gpu ") == "gpu"
+ for bad in (_INJECTED, "a b", "", "x;y", "$(id)"):
+ with pytest.raises(ValueError):
+ validate_partition(bad)
+
+ def test_backend_rejects_injected_partition_before_job_dir(self, registry):
+ from quantui.backends.slurm import SlurmBackend
+
+ backend = SlurmBackend(registry, partition=_INJECTED, use_apptainer=False)
+ with pytest.raises(SecurityError, match="partition"):
+ backend.prepare(_request())
+ for root in (registry.staging_root, registry.jobs_root):
+ assert not root.exists() or not any(root.iterdir())
+
+ def test_backend_accepts_plain_partition(self, registry):
+ from quantui.backends.slurm import SlurmBackend
+
+ backend = SlurmBackend(registry, partition="gpu", use_apptainer=False)
+ record = backend.prepare(_request())
+ script = (Path(record.job_dir) / "submit.slurm").read_text()
+ assert "#SBATCH --partition=gpu\n" in script
+
+ def test_cli_prepare_only_rejects_bad_partition(self, roots, water):
+ rc, out, err = _capture(
+ ["submit", str(water), "--calc", "single_point", "--prepare-only"]
+ + ["--partition", "common\n#SBATCH --qos=x"]
+ )
+ assert rc == 1
+ assert "partition" in err
+ assert out == ""
+
+ def test_launcher_rejects_env_partition(self, launcher, monkeypatch):
+ monkeypatch.setenv("QUANTUI_SLURM_PARTITION", _INJECTED)
+ with pytest.raises(launcher.InputError, match="partition"):
+ launcher.partition()
+ monkeypatch.setenv("QUANTUI_SLURM_PARTITION", "gpu")
+ assert launcher.partition() == "gpu"
From ea41bc133f56a16ad40384f502287db104c98090 Mon Sep 17 00:00:00 2001
From: Claude
Date: Thu, 12 Nov 2026 20:29:44 +0000
Subject: [PATCH 15/64] Document the job limit for multi-file quantui submit
(audit HPC-10)
`quantui submit` with several input files waits out the submit cooldown
between them, but each dispatch still checks the concurrent-job limit
(QUANTUI_MAX_CONCURRENT_JOBS, default 2), so everything past the second
input was rejected. The code comment even cited a 30-job batch as the
motivating case.
Chaining the inputs would need a waiting/queueing loop, so document the
limit instead: `quantui submit --help` gets a description naming both
QUANTUI_MAX_CONCURRENT_JOBS and QUANTUI_SLURM_SUBMIT_COOLDOWN_S and the
two ways round the limit (raise it for the command, or --prepare-only +
sbatch); docs/CLI.md says the same in the submit section and lists both
variables in its environment table. The misleading comment is reworded.
Docs/help text only; no test.
Contributions:
- Claude (Opus 5.5): code edits, review, and conceptual discussion
- Jonathan Schultz: overall vision, planning, review, and orchestration
Co-authored-by: Jonathan Schultz
Co-authored-by: Claude Opus 5.5
---
docs/CLI.md | 12 ++++++++++++
quantui/cli.py | 17 ++++++++++++++---
2 files changed, 26 insertions(+), 3 deletions(-)
diff --git a/docs/CLI.md b/docs/CLI.md
index 5e279255..1d94d026 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -421,6 +421,16 @@ A real submission needs `sbatch` on PATH **and** `QUANTUI_ENABLE_SLURM` set
exits `1` with the reason. `--dry-run` and `--prepare-only` skip that check
and cannot be combined (exit `2`).
+A real submission counts toward the same limits as the app: at most
+`QUANTUI_MAX_CONCURRENT_JOBS` (default `2`) QuantUI jobs queued or running at
+once, and `QUANTUI_SLURM_SUBMIT_COOLDOWN_S` (default `30`) seconds between
+submits. With several input files the command waits out the cooldown between
+them, but an input that would exceed the job limit is rejected (exit `1`) and
+the rest still run. For a larger batch, raise `QUANTUI_MAX_CONCURRENT_JOBS`
+for that command (e.g. `QUANTUI_MAX_CONCURRENT_JOBS=30 quantui submit
+lab2/*.xyz --calc frequency`), or use `--prepare-only` and run `sbatch` on the
+printed scripts yourself.
+
---
## `quantui results`
@@ -492,6 +502,8 @@ chaining, `--queue-rest`, `check`):
| `QUANTUI_LOG_DIR` | Override the default `~/.quantui/logs/` location. The dashboard's default output (`~/.quantui/dashboard.html`) follows: it lives one level up from the active `QUANTUI_LOG_DIR`. |
| `QUANTUI_DISABLE_GPU` | Force CPU mode even when gpu4pyscf is installed. `quantui gpu check` reports this as the reason. Accepted truthy values: `1`, `true`, `True`. |
| `QUANTUI_ENABLE_SLURM` | Opt in to **SLURM batch (cluster)** on the System Settings → Execution backend dropdown. Requires `sbatch` on PATH. Off by default so student deployments stay in-kernel until an operator enables cluster mode in the Apptainer image, JupyterHub spawner, or shell. Accepted truthy values: `1`, `true`, `yes`, `on`. |
+| `QUANTUI_MAX_CONCURRENT_JOBS` | Most QuantUI SLURM jobs queued or running at once (app and `quantui submit`; default `2`). |
+| `QUANTUI_SLURM_SUBMIT_COOLDOWN_S` | Minimum seconds between SLURM submits (default `30`; `0` disables). `quantui submit` waits it out between input files. |
| `QUANTUI_FREQ_PARALLEL` | Opt in to parallel **CPU** workers for the IR/Raman finite-difference displacement loops in frequency calculations (`6N` displaced SCFs). Same effect as the **Parallelize IR/Raman displacements (CPU)** checkbox on the System Settings tab; when this env var is set it overrides the saved setting. Reference SCF and Hessian still use gpu4pyscf when available. Requires ≥4 cores and ≥2 atoms. Off by default. Accepted truthy values: `1`, `true`, `yes`, `on`. |
---
diff --git a/quantui/cli.py b/quantui/cli.py
index 1bdc74a6..b6f83021 100644
--- a/quantui/cli.py
+++ b/quantui/cli.py
@@ -427,9 +427,10 @@ def _cmd_submit(args: argparse.Namespace) -> int:
# interactive app from accidental rapid-fire submits). A batch of
# N requests submitted in one invocation would otherwise trip that
# cooldown between every pair and fail partway through a
- # legitimate scripted run — sleep it out proactively instead
- # (the motivating case for this command: an instructor running
- # a whole class's worth of jobs, e.g. Lab 2's 30, from one script).
+ # legitimate scripted run — sleep it out proactively instead.
+ # The concurrent-job limit still applies: a batch larger than
+ # QUANTUI_MAX_CONCURRENT_JOBS needs that raised (documented in
+ # --help and docs/CLI.md) or --prepare-only.
if submitted_count > 0:
cooldown = submit_cooldown_seconds()
if cooldown > 0:
@@ -707,6 +708,16 @@ def _build_parser() -> argparse.ArgumentParser:
"Submit CalculationRequest JSON file(s) to the SLURM batch "
"backend headlessly — no interactive app."
),
+ description=(
+ "Submit calculations to SLURM without the app. Submissions count "
+ "toward the same limits as the app: QUANTUI_MAX_CONCURRENT_JOBS "
+ "(default 2) jobs queued or running at once, and "
+ "QUANTUI_SLURM_SUBMIT_COOLDOWN_S (default 30) seconds between "
+ "submits. The cooldown is waited out between input files; inputs "
+ "past the job limit are rejected, so raise "
+ "QUANTUI_MAX_CONCURRENT_JOBS for a larger batch or use "
+ "--prepare-only and run sbatch yourself."
+ ),
)
submit_parser.add_argument(
"request",
From b018ad9a857ce3e7db5f1409af74e6901e570d49 Mon Sep 17 00:00:00 2001
From: Claude
Date: Thu, 12 Nov 2026 20:34:42 +0000
Subject: [PATCH 16/64] Check batch input at submit instead of in the job
(audit HPC-11)
`quantui submit` and `quantui-batch submit` accepted input that then failed
or was silently ignored on the compute node:
- the basis was never looked at (`--basis not-a-basis` prepared, exit 0);
- unknown `--option` keys were stored and ignored, and `scf_rescue=no`
arrived as the string "no", which the worker's bool() reads as True;
- `--cores 0` / `--memory-gb 0` fell back to the estimate (`or`);
- request JSON skipped the calc-type, atom/coordinate and
charge/multiplicity checks an .xyz input gets;
- a JSON request_id with `/` crashed with a traceback in registry.save;
an .xyz whose stem contains `..` was refused as a path component;
- `quantui submit --preopt` help named three calc types; it applies to five.
Fix, in batch_input and its port in the launcher (kept equal; the launcher
gets the option/basis tables through site_constants):
- check_basis(): normalise the spelling to QuantUI's list (incl. the
6-31G(d) spelling) and warn, not refuse, for anything else - the same
policy as calculator.py, since PySCF knows many more bases;
- check_options(): yes/no/on/off/true/false/1/0 -> bool for scf_rescue and
preopt_before_run (anything else refused); warn about keys the worker
does not read for that calc type (CALC_OPTION_KEYS, from worker.py);
- check_json_request(): request_id must match [A-Za-z0-9_][A-Za-z0-9_.-]{0,63}
without "..", known calc_type, atoms/coords as Molecule() checks them,
and the charge/multiplicity the worker will use (molecule first) must
fit the electron count;
- resource overrides use `is None`, so 0 is refused by the range check;
- file labels collapse runs of dots;
- --preopt help lists all PREOPT_CALC_TYPES.
Tests: tests/test_hpc_audit_low.py::TestBatchInputChecks (package and
launcher side by side).
Contributions:
- Claude (Opus 5.5): code edits, review, and conceptual discussion
- Jonathan Schultz: overall vision, planning, review, and orchestration
Co-authored-by: Jonathan Schultz
Co-authored-by: Claude Opus 5.5
---
quantui/backends/batch_input.py | 163 +++++++++++++++++++++-
quantui/backends/slurm.py | 6 +-
quantui/batch_launcher.py | 6 +
quantui/cli.py | 5 +-
quantui/data/launcher/quantui_batch.py | 118 +++++++++++++++-
tests/test_hpc_audit_low.py | 180 +++++++++++++++++++++++++
6 files changed, 471 insertions(+), 7 deletions(-)
diff --git a/quantui/backends/batch_input.py b/quantui/backends/batch_input.py
index e4b59dd8..f7ad618b 100644
--- a/quantui/backends/batch_input.py
+++ b/quantui/backends/batch_input.py
@@ -38,6 +38,38 @@
# Calc types driven by analytic gradients: a post-HF method (no gradients
# here) is refused before the job queues, not after it starts.
GRADIENT_CALC_TYPES = frozenset({"transition_state", "irc"})
+# The request options each calc type's worker runner reads
+# (backends/worker.py); any other key is stored in request.json and ignored,
+# so it gets a warning at submit. ``preopt_before_run`` is added for
+# PREOPT_CALC_TYPES below.
+CALC_OPTION_KEYS: Dict[str, frozenset] = {
+ "single_point": frozenset(),
+ "geometry_opt": frozenset({"fmax", "max_steps", "frozen_atoms"}),
+ "transition_state": frozenset({"fmax", "max_steps"}),
+ "irc": frozenset({"max_steps", "dx", "fmax"}),
+ "frequency": frozenset(),
+ "tddft": frozenset({"nstates"}),
+ "nmr": frozenset(),
+ "pes_scan": frozenset(
+ {
+ "scan_type",
+ "atom_indices",
+ "start",
+ "stop",
+ "steps",
+ "grid",
+ "fmax",
+ "max_opt_steps",
+ }
+ ),
+ "reorganization_energy": frozenset({"mode", "fmax", "max_steps"}),
+}
+# Options the worker reads with bool(): the string "no" would be True.
+BOOLEAN_OPTION_KEYS = frozenset({"scf_rescue", "preopt_before_run"})
+_TRUE_WORDS = frozenset({"true", "yes", "on", "1"})
+_FALSE_WORDS = frozenset({"false", "no", "off", "0"})
+# A request id names the job record file, so no path separators or "..".
+REQUEST_ID_RE = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}$")
class BatchInputError(ValueError):
@@ -66,7 +98,9 @@ def parse_option_pairs(pairs: Optional[Sequence[str]]) -> Dict[str, Any]:
def _file_label(path: Path) -> str:
"""The file's stem, made safe for ids and folder names."""
- return re.sub(r"[^A-Za-z0-9_.-]+", "_", path.stem).strip("_.-") or "molecule"
+ label = re.sub(r"[^A-Za-z0-9_.-]+", "_", path.stem)
+ # A ".." in the stem would be refused as a path component later.
+ return re.sub(r"\.{2,}", ".", label).strip("_.-") or "molecule"
def _request_id_for(path: Path) -> str:
@@ -242,6 +276,128 @@ def check_method(request: CalculationRequest) -> None:
)
+def option_keys_for(calc_type: str) -> frozenset:
+ """The request option keys the worker reads for *calc_type*."""
+ keys = {"scf_rescue"} | set(CALC_OPTION_KEYS.get(calc_type, ()))
+ if calc_type in PREOPT_CALC_TYPES:
+ keys.add("preopt_before_run")
+ return frozenset(keys)
+
+
+def check_options(request: CalculationRequest) -> List[str]:
+ """Normalise boolean options; return warnings for keys the job ignores.
+
+ ``scf_rescue=no`` arrives as the string ``"no"``, which the worker's
+ ``bool()`` reads as True, so yes/no/on/off/true/false/1/0 are turned into
+ booleans and anything else is refused.
+ """
+ for key in BOOLEAN_OPTION_KEYS:
+ if key not in request.options:
+ continue
+ value = request.options[key]
+ word = str(value).strip().lower()
+ if isinstance(value, bool):
+ continue
+ if word in _TRUE_WORDS:
+ request.options[key] = True
+ elif word in _FALSE_WORDS:
+ request.options[key] = False
+ else:
+ raise BatchInputError(
+ f"option {key}={value!r} must be true or false (yes/no also work)."
+ )
+ allowed = option_keys_for(request.calc_type)
+ unknown = sorted(k for k in request.options if k not in allowed)
+ if not unknown:
+ return []
+ return [
+ f"option(s) {', '.join(unknown)} are ignored by a {request.calc_type} "
+ f"job (it reads: {', '.join(sorted(allowed))})."
+ ]
+
+
+def known_basis_sets() -> List[str]:
+ """QuantUI's basis sets, plus the parenthesis spelling of starred Pople sets."""
+ from quantui import config
+
+ names = list(config.SUPPORTED_BASIS_SETS)
+ names += [config.pople_notation_alias(b) for b in config.SUPPORTED_BASIS_SETS]
+ return [n for n in names if n]
+
+
+def check_basis(request: CalculationRequest) -> List[str]:
+ """Normalise the basis spelling; warn about one QuantUI does not list.
+
+ Same policy as ``calculator``: a basis outside the list is allowed (PySCF
+ knows many more), but the job fails if PySCF does not know it, so the
+ user is told at submit rather than after the queue wait.
+ """
+ names = {b.lower(): b for b in known_basis_sets()}
+ given = str(request.basis or "").strip()
+ canonical = names.get(given.lower())
+ if canonical is not None:
+ request.basis = canonical
+ return []
+ if not given:
+ raise BatchInputError("the request has no basis set; give --basis.")
+ return [
+ f"basis {given!r} is not one of QuantUI's basis sets; the job fails "
+ "if PySCF does not know it (check the spelling)."
+ ]
+
+
+def check_json_request(request: CalculationRequest) -> None:
+ """The checks an ``.xyz`` input gets while it is parsed, for request JSON.
+
+ Request id (it names the job record file), calc type, atoms and
+ coordinates, and a charge/multiplicity that fit the electron count. The
+ worker takes charge and multiplicity from the molecule when it has
+ them, so those are the values checked.
+ """
+ from quantui.utils import validate_atom_symbol, validate_coordinates
+ from quantui.xyz_input import spin_compatibility_note
+
+ rid = request.request_id
+ if rid and (not isinstance(rid, str) or not REQUEST_ID_RE.match(rid)):
+ raise BatchInputError(
+ f"request_id {rid!r} may only use letters, digits and _ . - "
+ "(at most 64 characters)."
+ )
+ if rid and ".." in rid:
+ raise BatchInputError(f"request_id {rid!r} may not contain '..'.")
+ if request.calc_type not in CALC_TYPES:
+ raise BatchInputError(
+ f"unknown calc_type {request.calc_type!r}; choose one of "
+ f"{', '.join(CALC_TYPES)}."
+ )
+ mol = request.molecule
+ atoms = mol.get("atoms")
+ coords = mol.get("coords") or mol.get("coordinates")
+ if not isinstance(atoms, list) or not atoms:
+ raise BatchInputError("molecule.atoms must be a non-empty list.")
+ if not isinstance(coords, list) or len(coords) != len(atoms):
+ raise BatchInputError(
+ "molecule.coords must list one [x, y, z] per atom " f"({len(atoms)} atoms)."
+ )
+ # The worker's Molecule() rules (utils.validate_atom_symbol /
+ # validate_coordinates).
+ for i, (atom, row) in enumerate(zip(atoms, coords)):
+ if not isinstance(atom, str) or not validate_atom_symbol(atom):
+ raise BatchInputError(f"molecule.atoms[{i}]: unknown element {atom!r}.")
+ if not validate_coordinates(row):
+ raise BatchInputError(
+ f"molecule.coords[{i}] must be three finite numbers, got {row!r}."
+ )
+ charge = int(mol.get("charge", request.charge))
+ mult = int(mol.get("multiplicity", request.multiplicity))
+ note = spin_compatibility_note(atoms, charge, mult)
+ if note:
+ raise BatchInputError(
+ f"charge {charge} and multiplicity {mult} do not fit this "
+ f"molecule. {note}"
+ )
+
+
def load_request(
path: Path,
*,
@@ -276,6 +432,8 @@ def load_request(
)
check_solvent(request)
check_method(request)
+ warnings += check_basis(request)
+ warnings += check_options(request)
return request, warnings
data = json.loads(path.read_text())
@@ -303,6 +461,9 @@ def load_request(
request.options.update(options)
if preopt and request.calc_type in PREOPT_CALC_TYPES:
request.options["preopt_before_run"] = True
+ check_json_request(request)
check_solvent(request)
check_method(request)
+ warnings += check_basis(request)
+ warnings += check_options(request)
return request, warnings
diff --git a/quantui/backends/slurm.py b/quantui/backends/slurm.py
index 27e7362b..4658e851 100644
--- a/quantui/backends/slurm.py
+++ b/quantui/backends/slurm.py
@@ -239,8 +239,10 @@ def _create_job(
}
estimates = estimate_slurm_resources(request)
- cores = cores or estimates["cores"]
- memory_gb = memory_gb or estimates["memory_gb"]
+ # ``is None``: an explicit 0 is refused by validate_resources, not
+ # silently replaced by the estimate.
+ cores = estimates["cores"] if cores is None else cores
+ memory_gb = estimates["memory_gb"] if memory_gb is None else memory_gb
walltime = walltime or estimates["walltime"]
resources = validate_resources(cores, memory_gb, walltime)
diff --git a/quantui/batch_launcher.py b/quantui/batch_launcher.py
index d7ee679f..f0997095 100644
--- a/quantui/batch_launcher.py
+++ b/quantui/batch_launcher.py
@@ -50,9 +50,12 @@ def site_constants() -> Dict[str, Any]:
from quantui.backends import slurm_utils
from quantui.backends.base import CALC_TYPES
from quantui.backends.batch_input import (
+ BOOLEAN_OPTION_KEYS,
GRADIENT_CALC_TYPES,
PREOPT_CALC_TYPES,
SOLVENT_CALC_TYPES,
+ known_basis_sets,
+ option_keys_for,
)
from quantui.freq_ir_workers import freq_parallel_opt_in
@@ -85,6 +88,9 @@ def site_constants() -> Dict[str, Any]:
"solvent_calc_types": sorted(SOLVENT_CALC_TYPES),
"gradient_calc_types": sorted(GRADIENT_CALC_TYPES),
"post_hf_methods": sorted(config.POST_HF_METHODS),
+ "known_basis_sets": known_basis_sets(),
+ "calc_option_keys": {c: sorted(option_keys_for(c)) for c in CALC_TYPES},
+ "boolean_option_keys": sorted(BOOLEAN_OPTION_KEYS),
}
diff --git a/quantui/cli.py b/quantui/cli.py
index b6f83021..03cd8086 100644
--- a/quantui/cli.py
+++ b/quantui/cli.py
@@ -836,7 +836,10 @@ def _build_parser() -> argparse.ArgumentParser:
input_group.add_argument(
"--preopt",
action="store_true",
- help="Optimize the geometry first (frequency, tddft, pes_scan).",
+ help=(
+ "Optimize the geometry first (single_point, nmr, frequency, "
+ "tddft, pes_scan)."
+ ),
)
input_group.add_argument(
"--option",
diff --git a/quantui/data/launcher/quantui_batch.py b/quantui/data/launcher/quantui_batch.py
index c7257dfd..6d13c718 100644
--- a/quantui/data/launcher/quantui_batch.py
+++ b/quantui/data/launcher/quantui_batch.py
@@ -34,6 +34,7 @@
import argparse
import getpass
import json
+import math
import os
import re
import shlex
@@ -340,7 +341,113 @@ def parse_option_pairs(pairs):
def file_label(path):
- return re.sub(r"[^A-Za-z0-9_.-]+", "_", path.stem).strip("_.-") or "molecule"
+ label = re.sub(r"[^A-Za-z0-9_.-]+", "_", path.stem)
+ return re.sub(r"\.{2,}", ".", label).strip("_.-") or "molecule"
+
+
+# Port of batch_input.REQUEST_ID_RE: the id names the job record file.
+REQUEST_ID_RE = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}$")
+
+
+def _valid_atom(atom):
+ return isinstance(atom, str) and atom.strip() in SITE["atomic_numbers"]
+
+
+def _valid_coords(row):
+ """Port of utils.validate_coordinates."""
+ if isinstance(row, (str, bytes)):
+ return False
+ try:
+ if len(row) != 3:
+ return False
+ return all(math.isfinite(float(x)) for x in row)
+ except (ValueError, TypeError):
+ return False
+
+
+def check_json_request(request):
+ """Port of batch_input.check_json_request."""
+ rid = request["request_id"]
+ if not isinstance(rid, str) or not REQUEST_ID_RE.match(rid):
+ raise InputError(
+ f"request_id {rid!r} may only use letters, digits and _ . - "
+ "(at most 64 characters)."
+ )
+ if ".." in rid:
+ raise InputError(f"request_id {rid!r} may not contain '..'.")
+ if request["calc_type"] not in SITE["calc_types"]:
+ raise InputError(
+ f"unknown calc_type {request['calc_type']!r}; choose one of "
+ f"{', '.join(SITE['calc_types'])}."
+ )
+ mol = request["molecule"]
+ atoms = mol.get("atoms")
+ coords = mol.get("coords") or mol.get("coordinates")
+ if not isinstance(atoms, list) or not atoms:
+ raise InputError("molecule.atoms must be a non-empty list.")
+ if not isinstance(coords, list) or len(coords) != len(atoms):
+ raise InputError(
+ "molecule.coords must list one [x, y, z] per atom " f"({len(atoms)} atoms)."
+ )
+ for i, (atom, row) in enumerate(zip(atoms, coords)):
+ if not _valid_atom(atom):
+ raise InputError(f"molecule.atoms[{i}]: unknown element {atom!r}.")
+ if not _valid_coords(row):
+ raise InputError(
+ f"molecule.coords[{i}] must be three finite numbers, got {row!r}."
+ )
+ charge = int(mol.get("charge", request["charge"]))
+ mult = int(mol.get("multiplicity", request["multiplicity"]))
+ problem = charge_mult_problem([a.strip() for a in atoms], charge, mult)
+ if problem:
+ raise InputError(
+ f"charge {charge} and multiplicity {mult} do not fit this "
+ f"molecule: {problem}"
+ )
+
+
+def check_options(request):
+ """Port of batch_input.check_options: bool options, warn on ignored keys."""
+ options = request["options"]
+ for key in SITE["boolean_option_keys"]:
+ if key not in options:
+ continue
+ value = options[key]
+ if isinstance(value, bool):
+ continue
+ word = str(value).strip().lower()
+ if word in ("true", "yes", "on", "1"):
+ options[key] = True
+ elif word in ("false", "no", "off", "0"):
+ options[key] = False
+ else:
+ raise InputError(
+ f"option {key}={value!r} must be true or false (yes/no also work)."
+ )
+ allowed = SITE["calc_option_keys"].get(request["calc_type"], ["scf_rescue"])
+ unknown = sorted(k for k in options if k not in allowed)
+ if not unknown:
+ return []
+ return [
+ f"option(s) {', '.join(unknown)} are ignored by a {request['calc_type']} "
+ f"job (it reads: {', '.join(allowed)})."
+ ]
+
+
+def check_basis(request):
+ """Port of batch_input.check_basis: normalise spelling, warn if unlisted."""
+ names = {b.lower(): b for b in SITE["known_basis_sets"]}
+ given = str(request.get("basis") or "").strip()
+ canonical = names.get(given.lower())
+ if canonical is not None:
+ request["basis"] = canonical
+ return []
+ if not given:
+ raise InputError("the request has no basis set; give --basis.")
+ return [
+ f"basis {given!r} is not one of QuantUI's basis sets; the job fails "
+ "if PySCF does not know it (check the spelling)."
+ ]
def build_request(path, args, extra_options):
@@ -435,6 +542,9 @@ def build_request(path, args, extra_options):
request["options"].update(extra_options)
if args.preopt and request["calc_type"] in SITE["preopt_calc_types"]:
request["options"]["preopt_before_run"] = True
+ if not request["request_id"]:
+ request["request_id"] = uuid.uuid4().hex[:12]
+ check_json_request(request)
return request, warnings
@@ -555,8 +665,8 @@ def estimate(request):
def resolve_resources(request, args):
est = estimate(request)
- cores = args.cores or est["cores"]
- memory_gb = args.memory_gb or est["memory_gb"]
+ cores = est["cores"] if args.cores is None else args.cores
+ memory_gb = est["memory_gb"] if args.memory_gb is None else args.memory_gb
walltime = args.walltime or est["walltime"]
errors = []
if not SITE["min_cores"] <= cores <= SITE["max_cores"]:
@@ -1284,6 +1394,7 @@ def requests_from_args(args, extra, q):
request, warnings = chained_request(source_dir, source, args, extra)
check_solvent(request)
check_method(request)
+ warnings = warnings + check_basis(request) + check_options(request)
out.append((f"--from {source_dir.name}", request, warnings, dep))
except InputError as exc:
sys.stderr.write(f"--from {source_dir.name}: {exc}\n")
@@ -1294,6 +1405,7 @@ def requests_from_args(args, extra, q):
request, warnings = build_request(Path(name), args, extra)
check_solvent(request)
check_method(request)
+ warnings = warnings + check_basis(request) + check_options(request)
out.append((name, request, warnings, None))
except InputError as exc:
sys.stderr.write(f"{name}: {exc}\n")
diff --git a/tests/test_hpc_audit_low.py b/tests/test_hpc_audit_low.py
index e32b282d..2f7b6670 100644
--- a/tests/test_hpc_audit_low.py
+++ b/tests/test_hpc_audit_low.py
@@ -143,3 +143,183 @@ def test_launcher_rejects_env_partition(self, launcher, monkeypatch):
launcher.partition()
monkeypatch.setenv("QUANTUI_SLURM_PARTITION", "gpu")
assert launcher.partition() == "gpu"
+
+
+# ---------------------------------------------------------------------------
+# HPC-11: batch input is checked at submit, in the package and the launcher
+# ---------------------------------------------------------------------------
+
+
+def _write_json(path, **over):
+ import json
+
+ data = {
+ "request_id": "req1",
+ "calc_type": "single_point",
+ "method": "RHF",
+ "basis": "STO-3G",
+ "charge": 0,
+ "multiplicity": 1,
+ "molecule": {"atoms": ["H", "H"], "coords": [[0, 0, 0], [0, 0, 0.74]]},
+ }
+ data.update(over)
+ path.write_text(json.dumps(data))
+ return path
+
+
+def _launcher_args(launcher, argv):
+ return launcher.submit_parser("t").parse_args(argv)
+
+
+class TestBatchInputChecks:
+ @pytest.mark.parametrize(
+ "over, match",
+ [
+ ({"request_id": "x/y"}, "request_id"),
+ ({"request_id": "a..b"}, "request_id"),
+ ({"multiplicity": 2}, "multiplicity 2"),
+ ({"calc_type": "nope"}, "calc_type"),
+ (
+ {"molecule": {"atoms": ["H", "H"], "coords": [[0, 0, 0]]}},
+ "one \\[x, y, z\\] per atom",
+ ),
+ (
+ {"molecule": {"atoms": ["H", "Xx"], "coords": [[0, 0, 0]] * 2}},
+ "unknown element",
+ ),
+ (
+ {"molecule": {"atoms": ["H", "H"], "coords": [[0, 0], [0, 0, 1]]}},
+ "three finite numbers",
+ ),
+ (
+ {
+ "molecule": {
+ "atoms": ["H", "H"],
+ "coords": [[0, 0, 0], [0, 0, 0.74]],
+ "multiplicity": 2,
+ }
+ },
+ "multiplicity 2",
+ ),
+ ],
+ )
+ def test_json_request_is_checked_in_both(self, tmp_path, launcher, over, match):
+ from quantui.backends.batch_input import BatchInputError, load_request
+
+ path = _write_json(tmp_path / "r.json", **over)
+ with pytest.raises(BatchInputError, match=match):
+ load_request(path)
+ args = _launcher_args(launcher, [str(path)])
+ with pytest.raises(launcher.InputError, match=match):
+ launcher.build_request(path, args, {})
+
+ def test_valid_json_still_loads(self, tmp_path, launcher):
+ from quantui.backends.batch_input import load_request
+
+ path = _write_json(tmp_path / "r.json")
+ request, warnings = load_request(path)
+ assert warnings == [] and request.request_id == "req1"
+ ours, _ = launcher.build_request(
+ path, _launcher_args(launcher, [str(path)]), {}
+ )
+ assert ours["request_id"] == "req1"
+
+ @pytest.mark.parametrize(
+ "raw, expected", [("no", False), ("Off", False), ("yes", True), ("1", True)]
+ )
+ def test_string_booleans(self, tmp_path, launcher, raw, expected):
+ from quantui.backends.batch_input import load_request
+
+ path = _write_json(tmp_path / "r.json")
+ request, _ = load_request(path, options={"scf_rescue": raw})
+ assert request.options["scf_rescue"] is expected
+ req = {"calc_type": "single_point", "options": {"scf_rescue": raw}}
+ launcher.check_options(req)
+ assert req["options"]["scf_rescue"] is expected
+
+ def test_bad_boolean_is_refused(self, tmp_path, launcher):
+ from quantui.backends.batch_input import BatchInputError, load_request
+
+ path = _write_json(tmp_path / "r.json")
+ with pytest.raises(BatchInputError, match="true or false"):
+ load_request(path, options={"scf_rescue": "maybe"})
+ with pytest.raises(launcher.InputError, match="true or false"):
+ launcher.check_options(
+ {"calc_type": "single_point", "options": {"scf_rescue": "maybe"}}
+ )
+
+ def test_ignored_options_warn(self, water, launcher):
+ from quantui.backends.batch_input import load_request
+
+ _, warnings = load_request(
+ water, calc_type="tddft", options={"nstates": 5, "nstate": 5}
+ )
+ assert len(warnings) == 1 and "nstate " in warnings[0] + " "
+ assert "are ignored by a tddft job" in warnings[0]
+ ours = launcher.check_options(
+ {"calc_type": "tddft", "options": {"nstates": 5, "nstate": 5}}
+ )
+ assert ours == warnings
+
+ def test_option_keys_match_launcher(self, launcher):
+ from quantui.backends.base import CALC_TYPES
+ from quantui.backends.batch_input import option_keys_for
+
+ for calc in CALC_TYPES:
+ assert launcher.SITE["calc_option_keys"][calc] == sorted(
+ option_keys_for(calc)
+ )
+
+ def test_basis_is_normalised_or_warned(self, water, launcher):
+ from quantui.backends.batch_input import load_request
+
+ request, warnings = load_request(
+ water, calc_type="single_point", basis="def2-svp"
+ )
+ assert request.basis == "def2-SVP" and warnings == []
+ request, warnings = load_request(
+ water, calc_type="single_point", basis="6-31G(d)"
+ )
+ assert request.basis == "6-31G(d)" and warnings == []
+ _, warnings = load_request(water, calc_type="single_point", basis="not-a-basis")
+ assert len(warnings) == 1 and "not-a-basis" in warnings[0]
+ req = {"basis": "not-a-basis"}
+ assert launcher.check_basis(req) == warnings
+ req = {"basis": "def2-svp"}
+ assert launcher.check_basis(req) == [] and req["basis"] == "def2-SVP"
+
+ def test_zero_resources_are_refused_not_estimated(self, registry, launcher, water):
+ from quantui.backends.slurm import SlurmBackend
+
+ backend = SlurmBackend(registry, use_apptainer=False)
+ with pytest.raises(SecurityError, match="cores=0"):
+ backend.prepare(_request(), cores=0)
+ with pytest.raises(SecurityError, match="memory_gb=0"):
+ backend.prepare(_request("low002"), memory_gb=0)
+ args = _launcher_args(launcher, [str(water), "--calc", "single_point"])
+ req, _ = launcher.build_request(water, args, {})
+ args.cores = 0
+ with pytest.raises(launcher.InputError, match="cores=0"):
+ launcher.resolve_resources(req, args)
+
+ def test_dotdot_file_stem_is_accepted(self, tmp_path, roots, launcher):
+ from quantui.backends.batch_input import load_request
+
+ path = tmp_path / "a..b.xyz"
+ path.write_text(WATER_XYZ)
+ request, _ = load_request(path, calc_type="single_point")
+ assert ".." not in request.request_id
+ rc, out, err = _capture(
+ ["submit", str(path), "--calc", "single_point", "--prepare-only"]
+ )
+ assert rc == 0, err
+ assert launcher.file_label(path) == "a.b"
+
+ def test_preopt_help_lists_all_preopt_calc_types(self):
+ from quantui.backends.batch_input import PREOPT_CALC_TYPES
+
+ text = Path(cli.__file__).read_text(encoding="utf-8")
+ start = text.index('"--preopt"')
+ snippet = text[start : start + 300]
+ for calc in PREOPT_CALC_TYPES:
+ assert calc in snippet
From e8d1d117ccc792ef15638a759958d8f12dc52dab Mon Sep 17 00:00:00 2001
From: Claude
Date: Thu, 12 Nov 2026 20:35:54 +0000
Subject: [PATCH 17/64] Clamp quantui-batch rerun --more-memory/--more-time to
the limits (audit HPC-12)
`quantui-batch rerun --more-memory` doubled the memory with no ceiling and
`--more-time` past the last walltime option doubled the hours (48 h ->
96 h), so repeated reruns asked for far more than any submission may.
--more-memory is now clamped to the per-job memory limit the launcher
checks submissions against (SITE max_memory_gb) and refuses when the job
already had that much; --more-time moves to the next longer allowed time
limit (also from a hand-set value between options) and refuses past the
longest. Explicit sbatch flags still pass through unchanged.
The cluster_config comment called these "hard limits"; they are
client-side defaults read from the user's own environment, so it now says
so and points real enforcement at Slurm QOS/partition limits.
(apptainer/slurm/README.md has the same wording; not touched here.)
Tests: tests/test_batch_submit.py::TestRerunMore - the existing
--more-time test expected 96:00:00 (the old uncapped behaviour) and now
expects a refusal; new test_more_memory_stops_at_the_site_limit.
Contributions:
- Claude (Opus 5.5): code edits, review, and conceptual discussion
- Jonathan Schultz: overall vision, planning, review, and orchestration
Co-authored-by: Jonathan Schultz
Co-authored-by: Claude Opus 5.5
---
quantui/backends/cluster_config.py | 14 +++++++++-----
quantui/data/launcher/quantui_batch.py | 23 ++++++++++++++++++-----
tests/test_batch_submit.py | 26 ++++++++++++++++++++++++--
3 files changed, 51 insertions(+), 12 deletions(-)
diff --git a/quantui/backends/cluster_config.py b/quantui/backends/cluster_config.py
index 11d69f1a..f7b05433 100644
--- a/quantui/backends/cluster_config.py
+++ b/quantui/backends/cluster_config.py
@@ -33,15 +33,19 @@ def _env_positive_int(name: str, default: int) -> int:
return value if value > 0 else default
-# Hard limits for a submission, site-configurable: NCShare's
-# `common` nodes have 512 GB, but the default stays at the classroom policy.
-# Read at import, like QUANTUI_SLURM_PARTITION; `quantui install-launcher`
-# copies the values into the launcher, so set them in the image environment.
+# Per-job resource limits QuantUI checks before it submits, site-configurable:
+# NCShare's `common` nodes have 512 GB, but the default stays at the
+# classroom policy. These are client-side defaults, not enforcement: the
+# values come from the user's own environment and a hand-run `sbatch` skips
+# them, so a site that needs a real cap sets it in Slurm (QOS/partition
+# limits). Read at import, like QUANTUI_SLURM_PARTITION; `quantui
+# install-launcher` copies the values into the launcher, so set them in the
+# image environment.
MIN_CORES = 1
MAX_CORES = _env_positive_int("QUANTUI_SLURM_MAX_CORES", 32)
MIN_MEMORY_GB = 1
MAX_MEMORY_GB = _env_positive_int("QUANTUI_SLURM_MAX_MEMORY_GB", 128)
-# The estimate's own ceiling, separate from the hard limit: a site can allow
+# The estimate's own ceiling, separate from the per-job limit: a site can allow
# 512 GB on request while keeping automatic requests at 128 GB.
ESTIMATE_MAX_MEMORY_GB = min(
_env_positive_int("QUANTUI_SLURM_ESTIMATE_MAX_MEMORY_GB", MAX_MEMORY_GB),
diff --git a/quantui/data/launcher/quantui_batch.py b/quantui/data/launcher/quantui_batch.py
index 6d13c718..239d7458 100644
--- a/quantui/data/launcher/quantui_batch.py
+++ b/quantui/data/launcher/quantui_batch.py
@@ -1608,17 +1608,30 @@ def more_memory(job_dir, last_options, last_id):
candidates = [g for g in (current and current * 2, used and used * 1.5) if g]
if not candidates:
die(f"could not tell how much memory {job_dir.name} had; pass --mem=G")
- return f"--mem={int(-(-max(candidates) // 1))}G"
+ # Clamped to the same per-job limit a submission is checked against.
+ limit = SITE["max_memory_gb"]
+ wanted = min(int(-(-max(candidates) // 1)), limit)
+ if current and wanted <= current:
+ die(
+ f"{job_dir.name} already had {current:g} GB; QuantUI's limit is "
+ f"{limit} GB per job (QUANTUI_SLURM_MAX_MEMORY_GB)."
+ )
+ return f"--mem={wanted}G"
def more_time(job_dir, last_options):
current = _option_value(last_options, "--time") or _script_value(job_dir, "--time")
if not current:
die(f"could not tell {job_dir.name}'s time limit; pass --time=HH:MM:SS")
- options = SITE["walltime_options"]
- if current in options and options.index(current) + 1 < len(options):
- return "--time=" + options[options.index(current) + 1]
- return f"--time={int(_hours(current) * 2)}:00:00"
+ # The next longer of the time limits a submission may use, never past
+ # the longest one.
+ longer = [w for w in SITE["walltime_options"] if _hours(w) > _hours(current)]
+ if not longer:
+ die(
+ f"{job_dir.name} already had {current}, the longest time limit "
+ f"QuantUI uses ({SITE['walltime_options'][-1]})."
+ )
+ return "--time=" + longer[0]
def cmd_rerun(argv):
diff --git a/tests/test_batch_submit.py b/tests/test_batch_submit.py
index 4a6789f7..3b65ceea 100644
--- a/tests/test_batch_submit.py
+++ b/tests/test_batch_submit.py
@@ -1672,9 +1672,31 @@ def test_more_time_steps_up_and_keeps_earlier_overrides(self, cluster):
assert r.returncode == 0, r.stderr
last = cluster.log("sbatch.log").splitlines()[-1]
assert "--mem=20G" in last and "--time=01:00:00" in last # 00:30:00 -> next
- cluster.run("rerun", "slow", "--time=48:00:00")
+ cluster.run("rerun", "slow", "--time=05:00:00")
cluster.run("rerun", "slow", "--more-time")
- assert "--time=96:00:00" in cluster.log("sbatch.log").splitlines()[-1]
+ assert "--time=08:00:00" in cluster.log("sbatch.log").splitlines()[-1]
+ # Never past the longest time limit QuantUI uses (audit HPC-12).
+ cluster.run("rerun", "slow", "--time=48:00:00")
+ n = len(cluster.log("sbatch.log").splitlines())
+ r = cluster.run("rerun", "slow", "--more-time")
+ assert r.returncode == 1
+ assert "longest time limit" in r.stderr
+ assert len(cluster.log("sbatch.log").splitlines()) == n
+
+ def test_more_memory_stops_at_the_site_limit(self, cluster):
+ # audit HPC-12: --more-memory is clamped to QUANTUI_SLURM_MAX_MEMORY_GB.
+ from quantui.backends.cluster_config import MAX_MEMORY_GB as limit
+
+ assert cluster.submit_water("--job-name", "big").returncode == 0
+ assert cluster.run("rerun", "big", f"--mem={limit - 8}G").returncode == 0
+ r = cluster.run("rerun", "big", "--more-memory")
+ assert r.returncode == 0, r.stderr
+ assert f"--mem={limit}G" in cluster.log("sbatch.log").splitlines()[-1]
+ n = len(cluster.log("sbatch.log").splitlines())
+ r = cluster.run("rerun", "big", "--more-memory")
+ assert r.returncode == 1
+ assert f"limit is {limit} GB" in r.stderr
+ assert len(cluster.log("sbatch.log").splitlines()) == n
@needs_posix
From 569fc77eff31292b08fb7baff7c84c81882fe29c Mon Sep 17 00:00:00 2001
From: Claude
Date: Thu, 12 Nov 2026 20:36:59 +0000
Subject: [PATCH 18/64] Escape SLURM text in the app's error box and Cluster
Jobs table (audit HPC-13)
format_error_html() pasted Slurm stderr / exception text (translated
category, summary, advice, raw excerpt, or the untranslated first 500
characters) into HTML unescaped, and the Cluster Jobs table and the
startup "job still active" banner did the same with record fields
(status, SLURM id, method/basis, calc type, created, request id). Those
come from the job record JSON and request files, so a "<" in them broke
or injected markup. (The pending-jobs list and the error cell were
already escaped.)
Escape every interpolated value with html.escape(); the static markup is
unchanged.
Tests: tests/test_hpc_audit_low.py::TestSlurmHtmlEscaping.
Contributions:
- Claude (Opus 5.5): code edits, review, and conceptual discussion
- Jonathan Schultz: overall vision, planning, review, and orchestration
Co-authored-by: Jonathan Schultz
Co-authored-by: Claude Opus 5.5
---
quantui/app_slurm.py | 14 +++++-----
quantui/backends/slurm_errors.py | 13 ++++++---
tests/test_hpc_audit_low.py | 47 ++++++++++++++++++++++++++++++++
3 files changed, 63 insertions(+), 11 deletions(-)
diff --git a/quantui/app_slurm.py b/quantui/app_slurm.py
index 49ba2c97..471100cc 100644
--- a/quantui/app_slurm.py
+++ b/quantui/app_slurm.py
@@ -213,7 +213,7 @@ def startup_slurm_check(app: Any) -> None:
record = active[0]
_show_slurm_banner(
app,
- f"SLURM job still active (status: {record.status}). "
+ f"SLURM job still active (status: {html.escape(record.status)}). "
f"Click View progress to reconnect.",
request_id=record.request_id,
)
@@ -491,16 +491,16 @@ def refresh_slurm_jobs_tab(app: Any) -> None:
exit_code = acct.exit_code if acct and acct.exit_code else "—"
rows.append(
""
- f"| {record.status} | "
- f"{slurm_id} | "
+ f"{html.escape(record.status)} | "
+ f"{html.escape(str(slurm_id))} | "
f"{html.escape(slurm_state)} | "
f"{html.escape(elapsed)} | "
f"{html.escape(exit_code)} | "
- f"{req.method}/{req.basis} | "
- f"{record.calc_type} | "
- f"{created} | "
+ f"{html.escape(f'{req.method}/{req.basis}')} | "
+ f"{html.escape(record.calc_type)} | "
+ f"{html.escape(created)} | "
f"{_slurm_job_error_cell(record)} | "
- f"{record.request_id} | "
+ f"{html.escape(record.request_id)} | "
"
"
)
diff --git a/quantui/backends/slurm_errors.py b/quantui/backends/slurm_errors.py
index 4147b8aa..794dd04c 100644
--- a/quantui/backends/slurm_errors.py
+++ b/quantui/backends/slurm_errors.py
@@ -6,6 +6,7 @@
from __future__ import annotations
+import html
import re
from dataclasses import dataclass
from typing import List, Optional, Tuple
@@ -179,18 +180,22 @@ def format_error_html(stderr: str) -> str:
if not stderr or not stderr.strip():
return ""
+ # Every value is plain text (Slurm stderr, exception messages); escape
+ # it, or a "<" in a path or job name breaks the panel.
+ esc = html.escape
translation = translate_slurm_error(stderr)
if translation is not None:
return (
''
f'
'
- f"❌ {translation.category}: {translation.summary}
"
+ f"❌ {esc(translation.category)}: {esc(translation.summary)}
"
f''
- f"💡 What to do: {translation.advice}
"
+ f"💡 What to do: {esc(translation.advice)}"
f''
f"Technical details
"
- f"{translation.raw_excerpt}"
+ f""
+ f"{esc(translation.raw_excerpt)}"
f" "
)
@@ -201,5 +206,5 @@ def format_error_html(stderr: str) -> str:
''
"❌ Error encountered
"
f''
- f"{truncated}"
+ f"{esc(truncated)}"
)
diff --git a/tests/test_hpc_audit_low.py b/tests/test_hpc_audit_low.py
index 2f7b6670..a1470991 100644
--- a/tests/test_hpc_audit_low.py
+++ b/tests/test_hpc_audit_low.py
@@ -323,3 +323,50 @@ def test_preopt_help_lists_all_preopt_calc_types(self):
snippet = text[start : start + 300]
for calc in PREOPT_CALC_TYPES:
assert calc in snippet
+
+
+# ---------------------------------------------------------------------------
+# HPC-13: SLURM text is escaped in the app's HTML
+# ---------------------------------------------------------------------------
+
+
+class TestSlurmHtmlEscaping:
+ def test_format_error_html_escapes_untranslated_text(self):
+ from quantui.backends.slurm_errors import format_error_html
+
+ out = format_error_html("sbatch: error:
& co")
+ assert "
x"
+ )
+ assert ""
@@ -3921,6 +3935,7 @@ def build_trajectory_viewer_html(
ab_other="⇄ First step (input)",
scrub_title="Scrub the optimization steps",
extra_decls=f"var EABS={eabs}; var EREL={erel};",
+ register_goto=True, # the PES plot's click target
)
return _theme.frame_viewer_html(view_html, width=width, controls=controls)
diff --git a/quantui/orbital_visualization.py b/quantui/orbital_visualization.py
index 24ef45cb..dd4ee48c 100644
--- a/quantui/orbital_visualization.py
+++ b/quantui/orbital_visualization.py
@@ -1575,6 +1575,10 @@ def orbital_colors(scheme: str) -> tuple[str, str]:
// is exact; removeAllShapes() would also take out anything else ever added.
var shapes=[];
function surfaces(){
+ // The molecule placeholder (shown before the first Generate) carries XYZ
+ // text in DATA, not a cube: feeding that to addVolumetricData(...,"cube")
+ // when a slider moves would draw garbage or throw (audit VIZ-8).
+ if(!WITH_SURFACES){ return; }
var vw=v(); if(!vw){ return; }
for(var i=0;i str:
+ import re
+
+ for body in re.findall(r"", html, flags=re.S):
+ if "__quantuiIsoUpdate_" in body:
+ return body
+ raise AssertionError("iso viewer script not found")
+
+
+_FAKE_VIEWER_JS = """
+var window = globalThis; var volCalls = 0;
+globalThis.document = {getElementById: function(){ return null; },
+ querySelector: function(){ return null; }};
+globalThis.$3Dmol = {VolumeData: function(){}};
+var noop = function(){ return {}; };
+window.viewer___UID__ = new Proxy({}, {get: function(_t, name){
+ if(name === "addVolumetricData"){ return function(){ volCalls++; return {}; }; }
+ if(name === "getView"){ return function(){ return [0,0,0,0,0,0,0,1]; }; }
+ return noop;
+}});
+"""
+
+
+class TestPlaceholderIgnoresSurfaceUpdates:
+ """Before the first Generate the iso panel shows the molecule (XYZ). A
+ slider move used to rebuild 'surfaces' from that XYZ text as if it were a
+ cube."""
+
+ def _run(self, html: str, tmp_path) -> int:
+ import json
+ import re
+ import shutil
+ import subprocess
+
+ node = shutil.which("node")
+ if node is None:
+ pytest.skip("node not available")
+ uid = re.search(r"3dmolviewer_(\w+)", html).group(1)
+ script = (
+ _FAKE_VIEWER_JS.replace("__UID__", uid)
+ + _iso_script(html)
+ + "\nvar before = volCalls;"
+ + "\nwindow.__quantuiIsoUpdate({iso: 0.05, op: 0.5});"
+ + "\nconsole.log(JSON.stringify(volCalls - before));"
+ )
+ path = tmp_path / "iso.js"
+ path.write_text(script, encoding="utf-8")
+ out = subprocess.run([node, str(path)], capture_output=True, text=True)
+ assert out.returncode == 0, out.stderr
+ return int(json.loads(out.stdout.strip().splitlines()[-1]))
+
+ def test_update_on_placeholder_adds_no_volumetric_data(self, tmp_path):
+ pytest.importorskip("py3Dmol")
+ from quantui.orbital_visualization import render_molecule_placeholder_py3dmol
+
+ html = render_molecule_placeholder_py3dmol(_h2_molecule())
+ assert self._run(html, tmp_path) == 0
+
+ def test_update_on_a_real_cube_still_rebuilds(self, tmp_path):
+ # Guard against the harness passing for the wrong reason.
+ pytest.importorskip("py3Dmol")
+ from quantui.orbital_visualization import _build_iso_viewer
+
+ cube = (
+ "c\nc\n1 0.0 0.0 0.0\n2 1.0 0.0 0.0\n2 0.0 1.0 0.0\n2 0.0 0.0 1.0\n"
+ "1 0.0 0.0 0.0 0.0\n0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8\n"
+ )
+ html = _build_iso_viewer(
+ cube, data_format="cube", scene_key="k", with_surfaces=True
+ )
+ assert self._run(html, tmp_path) == 2 # + and - lobes
From 5ea54c1767f4da117f5f26afa85897ed0c3c118c Mon Sep 17 00:00:00 2001
From: Claude
Date: Thu, 12 Nov 2026 20:34:34 +0000
Subject: [PATCH 38/64] Isosurface Cancel ends its activity once, not twice
(audit VIZ-9)
on_iso_generate begins one "compute" activity and ends it through an
idempotent _finish_activity when the worker completes or times out.
on_iso_cancel called app._activity_end directly as well, so a cancelled
generation decremented the shared counter twice: once on Cancel and again
when the abandoned cubegen worker finished. With another operation running
(e.g. a calculation) the toolbar then showed Idle.
The generation now stores its _finish_activity on the app
(_iso_finish_activity) and Cancel calls that hook instead, so the late
completion is a no-op.
Tests: tests/test_viz_low_audit.py::TestIsoCancelBalancesActivity (counter
stays at the other operation's 1 after cancel + late completion; normal
completion still returns to 0).
Contributions:
- Claude (Opus 5.5): code edits, review, and conceptual discussion
- Jonathan Schultz: overall vision, planning, review, and orchestration
Co-authored-by: Jonathan Schultz
Co-authored-by: Claude Opus 5.5
---
quantui/app_visualization.py | 19 +++++++++---
tests/test_viz_low_audit.py | 56 ++++++++++++++++++++++++++++++++++++
2 files changed, 71 insertions(+), 4 deletions(-)
diff --git a/quantui/app_visualization.py b/quantui/app_visualization.py
index 2976206c..1251a4b6 100644
--- a/quantui/app_visualization.py
+++ b/quantui/app_visualization.py
@@ -1857,6 +1857,11 @@ def _finish_activity() -> None:
if _sp is not None:
_sp.layout.display = "none"
+ # Cancel ends the activity through this same idempotent hook, so the
+ # worker's later completion cannot decrement the counter a second time
+ # and leave the toolbar showing Idle while something else runs (VIZ-9).
+ app._iso_finish_activity = _finish_activity
+
def _reset_button() -> None:
_finish_activity()
if render_token != int(getattr(app, "_iso_render_token", 0)):
@@ -3114,10 +3119,16 @@ def on_iso_cancel(app: Any, btn: Any = None) -> None:
sp = getattr(app, "_iso_spinner", None)
if sp is not None:
sp.layout.display = "none"
- try:
- app._activity_end(kind="compute")
- except Exception: # noqa: BLE001 — cancelling must never raise
- pass
+ # End THIS generation's activity via its own once-only hook (set by
+ # on_iso_generate). Calling _activity_end directly decremented the
+ # counter here and again when the worker finished (audit VIZ-9).
+ finish = getattr(app, "_iso_finish_activity", None)
+ app._iso_finish_activity = None
+ if callable(finish):
+ try:
+ finish()
+ except Exception: # noqa: BLE001 — cancelling must never raise
+ pass
status = getattr(app, "_iso_export_status", None)
if status is not None:
status.value = 'Cancelled.'
diff --git a/tests/test_viz_low_audit.py b/tests/test_viz_low_audit.py
index 226ea42f..637654ce 100644
--- a/tests/test_viz_low_audit.py
+++ b/tests/test_viz_low_audit.py
@@ -159,3 +159,59 @@ def test_update_on_a_real_cube_still_rebuilds(self, tmp_path):
cube, data_format="cube", scene_key="k", with_surfaces=True
)
assert self._run(html, tmp_path) == 2 # + and - lobes
+
+
+# ── VIZ-9: Cancel must not double-decrement the activity counter ──────────
+
+
+class _CountingApp:
+ """Just enough of QuantUIApp for on_iso_generate / on_iso_cancel."""
+
+ def __init__(self):
+ from unittest.mock import Mock
+
+ self.count = 0
+ self._iso_render_token = 0
+ self._orb_toggle = Mock(value="HOMO")
+ self._iso_js_bridge = None
+ self._render_orbital_isosurface = Mock()
+
+ def _activity_begin(self, message="", kind="ui"):
+ self.count += 1
+
+ def _activity_end(self, kind="ui"):
+ self.count = max(0, self.count - 1)
+
+ def _queue_main_thread_callback(self, fn, *args):
+ fn(*args)
+
+
+class TestIsoCancelBalancesActivity:
+ def test_cancel_then_late_completion_ends_activity_once(self, monkeypatch):
+ from unittest.mock import Mock
+
+ from quantui import app_visualization as av
+
+ started = []
+ monkeypatch.setattr(av, "_start_daemon", lambda fn: started.append(fn) or True)
+ app = _CountingApp()
+ app._activity_begin("a calculation is running", kind="compute")
+
+ av.on_iso_generate(app, Mock())
+ assert app.count == 2
+ av.on_iso_cancel(app, None)
+ assert app.count == 1
+ started[0]() # the abandoned cubegen worker finishes later
+ assert app.count == 1, "toolbar would show Idle while the calc runs"
+
+ def test_normal_completion_still_ends_activity(self, monkeypatch):
+ from unittest.mock import Mock
+
+ from quantui import app_visualization as av
+
+ started = []
+ monkeypatch.setattr(av, "_start_daemon", lambda fn: started.append(fn) or True)
+ app = _CountingApp()
+ av.on_iso_generate(app, Mock())
+ started[0]()
+ assert app.count == 0
From d2f8a103a7ec740b25cb3513df6f4017916a41a3 Mon Sep 17 00:00:00 2001
From: Claude
Date: Thu, 12 Nov 2026 20:35:39 +0000
Subject: [PATCH 39/64] Isosurface viewer: placeholder and cube share a scene
key (audit VIZ-10)
The camera a user sets on the molecule placeholder (shown before the first
Generate) is meant to carry into the first isosurface; both viewers stash
and compare a SCENE key for that. The two keys hashed different things:
the cube key hashed the cube's atom records (Z plus Bohr coordinates), the
placeholder key hashed the XYZ element symbols. They could never match, so
the first surface always re-framed.
Both keys are now the element sequence as atomic numbers (cube: first
column of the atom records, which cubegen writes as the true Z; XYZ:
symbol -> Z via config.ATOMIC_NUMBERS). Switching orbitals still keeps the
view and switching molecules still re-frames; a re-optimised geometry of
the same molecule now also keeps the view.
Tests: tests/test_viz_low_audit.py::TestSceneKeysMatchAcrossPlaceholder-
AndCube (real cubegen water cube vs placeholder key, a different molecule
differs, and the SCENE emitted by both rendered viewers is identical).
Camera carry-over itself not checked in a browser.
Contributions:
- Claude (Opus 5.5): code edits, review, and conceptual discussion
- Jonathan Schultz: overall vision, planning, review, and orchestration
Co-authored-by: Jonathan Schultz
Co-authored-by: Claude Opus 5.5
---
quantui/orbital_visualization.py | 47 +++++++++++++++---------
tests/test_viz_low_audit.py | 61 ++++++++++++++++++++++++++++++++
2 files changed, 92 insertions(+), 16 deletions(-)
diff --git a/quantui/orbital_visualization.py b/quantui/orbital_visualization.py
index dd4ee48c..9c0ba6ea 100644
--- a/quantui/orbital_visualization.py
+++ b/quantui/orbital_visualization.py
@@ -1622,8 +1622,9 @@ def orbital_colors(scheme: str) -> tuple[str, str]:
__ORIENT__
// Restore the orientation the previous viewer had, but only for the same
// scene: carrying a camera onto a different molecule would frame it
- // arbitrarily. SCENE is the atom block, so switching ORBITALS keeps the
- // view (the common case) while switching MOLECULES re-frames.
+ // arbitrarily. SCENE is the element sequence, so switching ORBITALS (or
+ // going from the molecule placeholder to the first surface) keeps the
+ // view while switching MOLECULES re-frames.
// A freshly built viewer is never busy. Bumping the sequence invalidates
// any in-flight busy(true) from the previous viewer, so a stale retry can
// never land on this one and leave it dimmed with nothing to clear it.
@@ -1832,17 +1833,28 @@ def esp_legend_html(esp_range: float) -> str:
def _scene_key(cube_text: str) -> str:
"""Identity of the molecule in a cube, used to decide whether a saved
- camera still applies. The atom block only — a different orbital of the same
- molecule must keep the user's orientation, a different molecule must not."""
- import hashlib
-
+ camera still applies. A different orbital of the same molecule must keep
+ the user's orientation, a different molecule must not.
+
+ Keyed on the element sequence (atomic numbers in atom order), the one thing
+ a cube and the XYZ molecule placeholder share: cube atom records carry Bohr
+ coordinates, XYZ carries Angstrom, so hashing either form of the geometry
+ meant the placeholder's camera never carried into the first isosurface
+ (audit VIZ-10). See :func:`_scene_key_from_xyz`.
+ """
lines = cube_text.splitlines()
try:
n_atoms = abs(int(lines[2].split()[0]))
- block = "".join(lines[6 : 6 + n_atoms])
+ zs = [int(float(ln.split()[0])) for ln in lines[6 : 6 + n_atoms]]
except Exception: # noqa: BLE001 — a bad header only costs camera reuse
- block = "".join(lines[:8])
- return hashlib.sha1(block.encode()).hexdigest()[:16]
+ return _hash_key("".join(lines[:8]))
+ return _hash_key(",".join(str(z) for z in zs))
+
+
+def _hash_key(text: str) -> str:
+ import hashlib
+
+ return hashlib.sha1(text.encode()).hexdigest()[:16]
def render_molecule_placeholder_py3dmol(
@@ -1879,14 +1891,17 @@ def render_molecule_placeholder_py3dmol(
def _scene_key_from_xyz(xyz: str) -> str:
- import hashlib
+ """Same key as :func:`_scene_key` for an XYZ block: the element sequence
+ as atomic numbers, so a cube of this molecule matches it."""
+ from quantui.config import ATOMIC_NUMBERS
- lines = xyz.splitlines()[2:]
- # Cube atom records carry Z and Bohr coordinates while XYZ carries symbols
- # and Angstrom, so the two cannot hash to the same value. Element count and
- # ordering are enough to tell "same molecule" for camera reuse.
- block = "".join(ln.split()[0] for ln in lines if ln.strip())
- return hashlib.sha1(block.encode()).hexdigest()[:16]
+ zs = []
+ for ln in xyz.splitlines()[2:]:
+ if not ln.strip():
+ continue
+ sym = ln.split()[0]
+ zs.append(str(ATOMIC_NUMBERS.get(sym.capitalize(), sym)))
+ return _hash_key(",".join(zs))
def _build_iso_viewer(
diff --git a/tests/test_viz_low_audit.py b/tests/test_viz_low_audit.py
index 637654ce..2bfb2775 100644
--- a/tests/test_viz_low_audit.py
+++ b/tests/test_viz_low_audit.py
@@ -215,3 +215,64 @@ def test_normal_completion_still_ends_activity(self, monkeypatch):
av.on_iso_generate(app, Mock())
started[0]()
assert app.count == 0
+
+
+# ── VIZ-10: placeholder camera carries into the first isosurface ──────────
+
+
+def _water_molecule():
+ from quantui.molecule import Molecule
+
+ return Molecule(
+ ["O", "H", "H"],
+ [[0.0, 0.0, 0.0], [0.757, 0.587, 0.0], [-0.757, 0.587, 0.0]],
+ )
+
+
+def _cube_text_for(molecule, tmp_path) -> str:
+ gto = pytest.importorskip("pyscf.gto")
+ from pyscf import scf
+ from pyscf.tools import cubegen
+
+ mol = gto.M(
+ atom=[(s, c) for s, c in zip(molecule.atoms, molecule.coordinates)],
+ basis="sto-3g",
+ verbose=0,
+ )
+ mf = scf.RHF(mol).run()
+ path = tmp_path / "mo.cube"
+ cubegen.orbital(mol, str(path), mf.mo_coeff[:, 0], nx=4, ny=4, nz=4)
+ return path.read_text()
+
+
+class TestSceneKeysMatchAcrossPlaceholderAndCube:
+ def test_placeholder_and_cube_of_the_same_molecule_share_a_key(self, tmp_path):
+ from quantui.orbital_visualization import _scene_key, _scene_key_from_xyz
+
+ water = _water_molecule()
+ xyz = f"{len(water.atoms)}\n{water.get_formula()}\n{water.to_xyz_string()}"
+ assert _scene_key(_cube_text_for(water, tmp_path)) == _scene_key_from_xyz(xyz)
+
+ def test_a_different_molecule_does_not_match(self, tmp_path):
+ from quantui.orbital_visualization import _scene_key, _scene_key_from_xyz
+
+ assert _scene_key(_cube_text_for(_water_molecule(), tmp_path)) != (
+ _scene_key_from_xyz(_H2_XYZ)
+ )
+
+ def test_rendered_viewers_carry_the_same_scene(self, tmp_path):
+ pytest.importorskip("py3Dmol")
+ import re
+
+ from quantui.orbital_visualization import (
+ render_molecule_placeholder_py3dmol,
+ render_orbital_isosurface_py3dmol,
+ )
+
+ water = _water_molecule()
+ cube = tmp_path / "w.cube"
+ cube.write_text(_cube_text_for(water, tmp_path))
+ scene = re.compile(r"SCENE=(\"[0-9a-f]+\")")
+ a = scene.search(render_molecule_placeholder_py3dmol(water)).group(1)
+ b = scene.search(render_orbital_isosurface_py3dmol(cube)).group(1)
+ assert a == b
From 98189ba95753d469c27f52cad973a26f30cbdb4e Mon Sep 17 00:00:00 2001
From: Claude
Date: Thu, 12 Nov 2026 20:36:53 +0000
Subject: [PATCH 40/64] Analysis plots: a failed re-render shows an error
instead of the old figure (audit VIZ-11)
The IR, Raman, UV-Vis, ECD and NMR update paths, the orbital energy
diagram and the PES profile caught plotting exceptions, logged them and
nulled the stored figure, but left the Output widget untouched. The
previous molecule's (or previous setting's) plot then stayed on screen as
if it belonged to the current result.
New _show_plot_error(app, out, what, exc) swaps an inline, HTML-escaped
" could not be plotted: " message into that output. Used in
each of those except blocks; for the orbital diagram only when the
matplotlib fallback also fails (reporting the original Plotly error).
The live Y-range/core toggles of the orbital diagram are unchanged (same
result, so the figure on screen is not stale).
Tests: tests/test_viz_low_audit.py::TestFailedPlotsReplaceTheStaleFigure
(IR with an escaped message, NMR, PES).
Contributions:
- Claude (Opus 5.5): code edits, review, and conceptual discussion
- Jonathan Schultz: overall vision, planning, review, and orchestration
Co-authored-by: Jonathan Schultz
Co-authored-by: Claude Opus 5.5
---
quantui/app_visualization.py | 45 +++++++++++++++++++++++----
tests/test_viz_low_audit.py | 59 ++++++++++++++++++++++++++++++++++++
2 files changed, 98 insertions(+), 6 deletions(-)
diff --git a/quantui/app_visualization.py b/quantui/app_visualization.py
index 1251a4b6..cb004a7b 100644
--- a/quantui/app_visualization.py
+++ b/quantui/app_visualization.py
@@ -46,6 +46,26 @@ def _start_daemon(target: Any, *args: Any, **kwargs: Any) -> bool:
return True
+def _show_plot_error(app: Any, out: Any, what: str, exc: BaseException) -> None:
+ """Replace a plot that failed to rebuild with a visible error.
+
+ The ``except`` paths used to log and null the stored figure but leave the
+ Output widget alone, so the previous result's plot stayed on screen as if
+ it belonged to this one (audit VIZ-11).
+ """
+ if out is None:
+ return
+ detail = html.escape(f"{type(exc).__name__}: {exc}")
+ try:
+ app._set_html_output(
+ out,
+ f'⚠ {html.escape(what)} could '
+ f"not be plotted: {detail}
",
+ )
+ except Exception: # noqa: BLE001 — error display must never raise
+ pass
+
+
@contextmanager
def _viz_render_event(app: Any, task: Any, backend: Any, **extras: Any):
"""Lifecycle telemetry context manager for one render-path execution.
@@ -911,6 +931,7 @@ def update_ir_figure(app: Any, mode: str, fwhm: float) -> None:
_clog.log_event("ir_fig_error", f"{type(exc).__name__}: {exc}"[:300])
except Exception:
pass
+ _show_plot_error(app, getattr(app, "_ir_fig", None), "IR spectrum", exc)
def show_raman_spectrum(app: Any, freq_result: Any) -> bool:
@@ -1040,6 +1061,7 @@ def update_raman_figure(app: Any, mode: str, fwhm: float) -> None:
_clog.log_event("raman_fig_error", f"{type(exc).__name__}: {exc}"[:300])
except Exception:
pass
+ _show_plot_error(app, getattr(app, "_raman_fig", None), "Raman spectrum", exc)
def show_uv_vis_spectrum(
@@ -1294,6 +1316,7 @@ def update_uv_vis_figure(app: Any, mode: str, fwhm: float) -> None:
_clog.log_event("uv_fig_error", f"{type(exc).__name__}: {exc}"[:300])
except Exception:
pass
+ _show_plot_error(app, getattr(app, "_tddft_fig", None), "UV-Vis spectrum", exc)
# ── ECD (electronic circular dichroism) ─────────────────────────────────────
@@ -1454,6 +1477,7 @@ def update_ecd_figure(app: Any, mode: str, sigma_ev: float) -> None:
_clog.log_event("ecd_fig_error", f"{type(exc).__name__}: {exc}"[:300])
except Exception:
pass
+ _show_plot_error(app, getattr(app, "_ecd_fig", None), "ECD spectrum", exc)
def show_nmr_spectrum(
@@ -1591,6 +1615,7 @@ def update_nmr_figure(app: Any, nucleus: str) -> None:
_clog.log_event("nmr_fig_error", f"{type(exc).__name__}: {exc}"[:300])
except Exception:
pass
+ _show_plot_error(app, getattr(app, "_nmr_fig", None), "NMR spectrum", exc)
def _attach_mo_irreps(info: Any, result: Any) -> None:
@@ -1666,6 +1691,7 @@ def show_orbital_diagram(app: Any, result: Any) -> bool:
sync_iso_surface_controls(app)
plotly_rendered = False
+ plot_exc: Optional[BaseException] = None
try:
from quantui.orbital_visualization import plot_orbital_diagram_plotly
@@ -1681,8 +1707,8 @@ def show_orbital_diagram(app: Any, result: Any) -> bool:
app._last_orb_fig = fig
app._set_html_output(app._orb_diagram_html, _orb_screen_html(fig))
plotly_rendered = True
- except Exception:
- pass
+ except Exception as exc: # noqa: BLE001 — fall back to matplotlib below
+ plot_exc = exc
if not plotly_rendered:
app._last_orb_fig = None
@@ -1709,8 +1735,13 @@ def show_orbital_diagram(app: Any, result: Any) -> bool:
'style="max-width:100%;height:auto" />'
),
)
- except Exception:
- pass
+ except Exception as exc: # noqa: BLE001
+ _show_plot_error(
+ app,
+ getattr(app, "_orb_diagram_html", None),
+ "Orbital energy diagram",
+ plot_exc or exc,
+ )
if (
app._last_orb_mo_coeff is not None
@@ -4692,9 +4723,11 @@ def show_pes_scan_result(app: Any, result: Any) -> bool:
})();
"""
app._set_html_output(app._pes_plot_html, plot_html + (link_js if _link else ""))
- except Exception:
+ except Exception as exc: # noqa: BLE001
app._last_pes_fig = None
- pass
+ _show_plot_error(
+ app, getattr(app, "_pes_plot_html", None), "PES energy profile", exc
+ )
return True
diff --git a/tests/test_viz_low_audit.py b/tests/test_viz_low_audit.py
index 2bfb2775..eef3a8e7 100644
--- a/tests/test_viz_low_audit.py
+++ b/tests/test_viz_low_audit.py
@@ -276,3 +276,62 @@ def test_rendered_viewers_carry_the_same_scene(self, tmp_path):
a = scene.search(render_molecule_placeholder_py3dmol(water)).group(1)
b = scene.search(render_orbital_isosurface_py3dmol(cube)).group(1)
assert a == b
+
+
+# ── VIZ-11: a failed plot must not leave the previous figure on screen ────
+
+
+def _html_sink_app(**attrs):
+ from unittest.mock import Mock
+
+ app = Mock()
+ shown = {}
+ app._set_html_output.side_effect = lambda out, html: shown.__setitem__(
+ id(out), html
+ )
+ for k, v in attrs.items():
+ setattr(app, k, v)
+ return app, shown
+
+
+class TestFailedPlotsReplaceTheStaleFigure:
+ def test_ir_failure_shows_an_escaped_error(self, monkeypatch):
+ from quantui import app_visualization as av
+ from quantui import ir_plot
+
+ def boom(*a, **k):
+ raise ValueError("bad ")
+
+ monkeypatch.setattr(ir_plot, "plot_ir_spectrum", boom)
+ app, shown = _html_sink_app(_last_ir_freqs=[1.0], _last_ir_ints=[1.0])
+ av.update_ir_figure(app, "stick", 10.0)
+ html = shown[id(app._ir_fig)]
+ assert "IR spectrum could not be plotted" in html
+ assert "bad <data>" in html
+ assert app._last_ir_fig is None
+
+ def test_nmr_failure_shows_an_error(self, monkeypatch):
+ from quantui import app_visualization as av
+ from quantui import nmr_plot
+
+ def boom(*a, **k):
+ raise RuntimeError("nope")
+
+ monkeypatch.setattr(nmr_plot, "plot_nmr_spectrum", boom)
+ app, shown = _html_sink_app(
+ _last_nmr_atom_symbols=["O", "H", "H"],
+ _last_nmr_h_shifts=[(1, 1.0)],
+ )
+ av.update_nmr_figure(app, "¹H")
+ assert "NMR spectrum could not be plotted" in shown[id(app._nmr_fig)]
+
+ def test_pes_failure_shows_an_error(self):
+ from types import SimpleNamespace
+
+ from quantui import app_visualization as av
+
+ app, shown = _html_sink_app()
+ av.show_pes_scan_result(app, SimpleNamespace()) # no energies at all
+ assert (
+ "PES energy profile could not be plotted" in shown[id(app._pes_plot_html)]
+ )
From 8589c50adc75ff538e69ad82b323d05435abb570 Mon Sep 17 00:00:00 2001
From: Claude
Date: Thu, 12 Nov 2026 20:38:47 +0000
Subject: [PATCH 41/64] Viz: escape exception and path text before it reaches
HTML (audit VIZ-12)
Several error and status messages interpolated exception text, file
paths or a formula straight into HTML. Exception text can echo file
contents and a formula can come from a saved result, so markup in either
was rendered (or broke the message). Now escaped:
- app_visualization: trajectory render/viewer failures, the trajectory
export "Saved: " and "Export failed" lines, frame render failure,
the isosurface failure message, the density/ESP _show_msg helper and
_vib_err (both plain-text helpers now escape; the one _vib_err caller
that passed markup now passes plain text).
- visualization_py3dmol.render_molecule_html: "Visualization failed".
- viz_assets.standalone_html: the of exported files.
- orbital_visualization.orbital_summary_html: the formula.
Not repeated: the VIZ-1 fix (6404d2e) already escaped symmetry labels and
the script payloads; downloads.download_link_html already escapes names.
show_opt_trajectory has a local `html` string that shadows the module, so
its three messages use a module-level `_escape` alias instead.
Tests: tests/test_viz_low_audit.py::TestErrorTextIsEscaped (vib error,
export title, orbital summary formula, molecule viewer failure, and the
trajectory viewer failure inside show_opt_trajectory).
Contributions:
- Claude (Opus 5.5): code edits, review, and conceptual discussion
- Jonathan Schultz: overall vision, planning, review, and orchestration
Co-authored-by: Jonathan Schultz
Co-authored-by: Claude Opus 5.5
---
quantui/app_visualization.py | 31 +++++++-----
quantui/orbital_visualization.py | 3 +-
quantui/visualization_py3dmol.py | 3 +-
quantui/viz_assets.py | 4 +-
tests/test_viz_low_audit.py | 81 ++++++++++++++++++++++++++++++++
5 files changed, 108 insertions(+), 14 deletions(-)
diff --git a/quantui/app_visualization.py b/quantui/app_visualization.py
index cb004a7b..eb993541 100644
--- a/quantui/app_visualization.py
+++ b/quantui/app_visualization.py
@@ -7,6 +7,7 @@
import threading
import time
from contextlib import contextmanager
+from html import escape as _escape # for scopes where `html` is a local str
from pathlib import Path
from typing import Any, List, Optional, cast
@@ -281,7 +282,7 @@ def on_traj_expand(app: Any, change: dict[str, Any]) -> None:
widgets.HTML(
value=(
f''
- f"⚠ Trajectory rendering failed: {exc}
"
+ f"⚠ Trajectory rendering failed: {html.escape(str(exc))}
"
)
),
)
@@ -418,7 +419,7 @@ def _on_traj_png_captured(change: dict) -> None:
"data": {
"text/html": (
''
- f"Trajectory viewer failed: {exc}
"
+ f"Trajectory viewer failed: {_escape(str(exc))}"
)
},
"metadata": {},
@@ -475,7 +476,8 @@ def _do_export() -> None:
"value",
(
f''
- f"✓ Saved: {out_path} " + _download_link_html(out_path)
+ f"✓ Saved: {_escape(str(out_path))} "
+ + _download_link_html(out_path)
),
)
except Exception as exc:
@@ -483,7 +485,8 @@ def _do_export() -> None:
setattr,
export_status,
"value",
- f'Export failed: {exc}',
+ 'Export failed: '
+ f"{_escape(str(exc))}",
)
finally:
app._queue_main_thread_callback(setattr, _btn, "disabled", False)
@@ -595,7 +598,8 @@ def render_traj_frame(app: Any, molecule: Any, output_widget: Any) -> None:
with output_widget:
display(
HTML(
- f'Frame render failed: {exc}
'
+ 'Frame render failed: '
+ f"{html.escape(str(exc))}
"
)
)
@@ -2304,7 +2308,7 @@ def _show_err(msg: str = err_msg) -> None:
app._set_html_output(
app._orb_iso_output,
f''
- f"⚠ Orbital isosurface failed: {msg}
",
+ f"⚠ Orbital isosurface failed: {html.escape(msg)}",
)
app._queue_main_thread_callback(_show_err)
@@ -2377,7 +2381,8 @@ def _show_msg(msg: str) -> None:
app._queue_main_thread_callback(
app._set_html_output,
app._orb_iso_output,
- f'⚠ {msg}
',
+ # Plain text: messages carry exception text (audit VIZ-12).
+ f'⚠ {html.escape(msg)}
',
)
mo_coeff = getattr(app, "_last_orb_mo_coeff", None)
@@ -2547,8 +2552,12 @@ def _swap_vib_output(app: Any, html_str: str) -> None:
def _vib_err(app: Any, msg: str) -> None:
- """Show an error message in the vibrational animation output panel."""
- _swap_vib_output(app, f'⚠ {msg}
')
+ """Show a plain-text error message in the vibrational animation panel.
+
+ Escaped: callers pass exception text (audit VIZ-12)."""
+ _swap_vib_output(
+ app, f'⚠ {html.escape(msg)}
'
+ )
# JS snippet appended to every py3Dmol vib HTML payload. Patches
@@ -2930,8 +2939,8 @@ def _render_vib_mode_plotlymol(
if not _is_vib_stale(app, render_token):
_vib_err(
app,
- f"PlotlyMol vibrational animation requires plotlymol3d "
- f"(pip install plotlymol3d): {exc}",
+ "PlotlyMol vibrational animation requires plotlymol3d "
+ f"(pip install plotlymol3d): {exc}",
)
return
diff --git a/quantui/orbital_visualization.py b/quantui/orbital_visualization.py
index 9c0ba6ea..9925d355 100644
--- a/quantui/orbital_visualization.py
+++ b/quantui/orbital_visualization.py
@@ -19,6 +19,7 @@
import logging
import re
from dataclasses import dataclass
+from html import escape as _html_escape
from pathlib import Path
from typing import Any, List, Optional, Tuple
@@ -677,7 +678,7 @@ def orbital_summary_html(info: OrbitalInfo) -> str:
return (
''
- f"
Orbital Summary — {info.formula}"
+ f"
Orbital Summary — {_html_escape(info.formula)}"
f"Occupied MOs{a}: {info.n_occupied} | "
f"Virtual MOs{a}: {info.n_virtual} | "
f"Total{a}: {len(info.mo_energies_ev)}
"
diff --git a/quantui/visualization_py3dmol.py b/quantui/visualization_py3dmol.py
index e52f7398..9576df85 100644
--- a/quantui/visualization_py3dmol.py
+++ b/quantui/visualization_py3dmol.py
@@ -9,6 +9,7 @@
Created: 2026-02-17
"""
+import html as _html
import logging
import os
import tempfile
@@ -675,7 +676,7 @@ class in the whole page, not scoped to which button was clicked).
logger.error(f"Render failed for {molecule.get_formula()}: {e}")
parts.append(
'
'
- f"❌ Visualization failed: {e}
"
+ f"❌ Visualization failed: {_html.escape(str(e))}
"
)
# Frame the fragment at the viewer's own width — see theme.frame_viewer_html
# for why the border cannot live on the hosting Output widget's CSS class.
diff --git a/quantui/viz_assets.py b/quantui/viz_assets.py
index 16de36d3..a2709437 100644
--- a/quantui/viz_assets.py
+++ b/quantui/viz_assets.py
@@ -39,6 +39,7 @@
from __future__ import annotations
import base64
+import html
import logging
from functools import lru_cache
from pathlib import Path
@@ -114,7 +115,8 @@ def standalone_html(view_html: str, *, title: str = "QuantUI animation") -> str:
'\n\n'
'\n'
'\n'
- f"{title}\n"
+ # Escaped: titles carry formulas that can come from a saved result.
+ f"{html.escape(title)}\n"
"\n"
"\n\n" + view_html + "\n\n\n"
diff --git a/tests/test_viz_low_audit.py b/tests/test_viz_low_audit.py
index eef3a8e7..7cadf7d3 100644
--- a/tests/test_viz_low_audit.py
+++ b/tests/test_viz_low_audit.py
@@ -335,3 +335,84 @@ def test_pes_failure_shows_an_error(self):
assert (
"PES energy profile could not be plotted" in shown[id(app._pes_plot_html)]
)
+
+
+# ── VIZ-12: exception/path text is escaped before it reaches HTML ─────────
+
+_EVIL = "
"
+
+
+class TestErrorTextIsEscaped:
+ def test_vib_error_message(self, monkeypatch):
+ from unittest.mock import Mock
+
+ from quantui import app_visualization as av
+
+ seen = []
+ monkeypatch.setattr(av, "_swap_vib_output", lambda app, h: seen.append(h))
+ av._vib_err(Mock(), f"render failed: {_EVIL}")
+ assert _EVIL not in seen[0]
+ assert "<img" in seen[0]
+
+ def test_standalone_export_title(self):
+ from quantui.viz_assets import standalone_html
+
+ doc = standalone_html("", title=f"Geo Opt: {_EVIL}")
+ assert _EVIL not in doc
+ assert "" in doc # the body itself is not escaped
+
+ def test_orbital_summary_formula(self):
+ from quantui.orbital_visualization import OrbitalInfo, orbital_summary_html
+
+ info = OrbitalInfo(
+ mo_energies_ev=np.array([-10.0, 2.0]),
+ n_occupied=1,
+ homo_energy_ev=-10.0,
+ lumo_energy_ev=2.0,
+ homo_lumo_gap_ev=12.0,
+ formula=_EVIL,
+ )
+ assert _EVIL not in orbital_summary_html(info)
+
+ def test_molecule_viewer_failure(self, monkeypatch):
+ from quantui import visualization_py3dmol as vp
+
+ def boom(*a, **k):
+ raise RuntimeError(_EVIL)
+
+ monkeypatch.setattr(vp, "is_visualization_available", lambda: True)
+ monkeypatch.setattr(vp, "visualize_molecule", boom)
+ html = vp.render_molecule_html(_h2_molecule(), show_info=False)
+ assert "Visualization failed" in html
+ assert _EVIL not in html
+
+ def test_trajectory_viewer_failure(self, monkeypatch):
+ # Inside show_opt_trajectory a local ``html`` string shadows the
+ # module, so the message must not be built with html.escape there.
+ from types import SimpleNamespace
+ from unittest.mock import Mock
+
+ import ipywidgets as widgets
+
+ from quantui import app_visualization as av
+
+ def boom(*a, **k):
+ raise RuntimeError(_EVIL)
+
+ monkeypatch.setattr(av, "build_trajectory_viewer_html", boom)
+ app = Mock()
+ app._traj_render_token = 0
+ app._plotly_theme_colors.return_value = {"scene_bgcolor": "white"}
+ h2 = _h2_molecule()
+ result = SimpleNamespace(
+ trajectory=[h2, h2], energies_hartree=[-1.0, -1.1], formula="H2"
+ )
+ av.show_opt_trajectory(app, result, layout_fn=widgets.Layout)
+ outs = [
+ c
+ for c in app.traj_output.children
+ if isinstance(c, widgets.Output) and c.outputs
+ ]
+ page = " ".join(o.outputs[0]["data"]["text/html"] for o in outs)
+ assert "Trajectory viewer failed" in page
+ assert _EVIL not in page
From bafba7292985aa25f4baa420ebcf74a8feee7299 Mon Sep 17 00:00:00 2001
From: Claude
Date: Thu, 12 Nov 2026 20:40:31 +0000
Subject: [PATCH 42/64] Viewer packaging: smoke test loads the app, checksums,
isosurface docs (audit VIZ-13)
- smoke_launch.py fetched http://127.0.0.1: without the per-run
token. Voila answers that with its login page (HTTP 200), so the check
only proved a server was listening. It now reads the tokenised URL that
`quantui view` prints ("Starting QuantUI Viewer at ...?token=..."),
fetches it (no proxy, 120 s read timeout because Voila executes the
notebook before the page completes; overall deadline 120 -> 180 s) and
requires a rendered widget (nbconvert's lab template emits each widget
output as