From 5ec16f486cf16245f8d0095bbc046b27aa328a53 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 03:45:25 +0000 Subject: [PATCH 1/8] IRC: end a fallback branch at the minimized geometry (audit GEOM-1) When Sella's inner loop failed, the atoms were left at an inner-iteration geometry nothing had recorded. If the steepest descent found that point already converged it took no step, so the branch ended on the previous IRC point while reporting "reached a minimum": wrong end structure, end energy and barriers, with no warning (NH3 inversion, RHF/STO-3G: end fmax 0.82 eV/A, barrier 44.3 instead of 46.6 kJ/mol). Record that geometry before minimizing, and drop BFGS's repeated first frame at the index where BFGS started rather than assuming the descent took no step (it used to delete the first real descent point instead). tests/test_irc_endpoint.py drives run_irc with a harmonic stand-in for PySCF and Sella; the at-minimum case 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/irc.py | 19 +++++-- tests/test_irc_endpoint.py | 110 +++++++++++++++++++++++++++++++++++++ 2 files changed, 123 insertions(+), 6 deletions(-) create mode 100644 tests/test_irc_endpoint.py diff --git a/quantui/irc.py b/quantui/irc.py index 2e45cdf4..4223de96 100644 --- a/quantui/irc.py +++ b/quantui/irc.py @@ -388,21 +388,28 @@ def _record() -> None: f" Sella's IRC step did not converge after {irc_steps} steps; " "finishing this direction by descending from here.\n" ) + # Sella leaves the atoms at its last inner-loop geometry, which + # no observer recorded. Record it, so the branch's last frame is + # always the geometry the minimization below actually ends at + # (when the descent finds that point already converged, it takes + # no step and records nothing, and the branch used to end on the + # previous IRC point while reporting a minimum). + _record() # Steepest descent first: near the saddle a quasi-Newton step # can jump the ridge into the other valley (both directions then # end at the same minimum); descent steps only go downhill on # this side. BFGS with short steps finishes from the valley. converged = _steepest_descent(atoms, _record, fmax=fmax) if not converged: + n_before_bfgs = len(current["frames"]) opt = BFGS(atoms, logfile=io.StringIO(), maxstep=0.05) opt.attach(_record, interval=1) converged = bool(opt.run(fmax=fmax, steps=steps)) - # The minimization's first observer call repeats the last point. - if len(current["frames"]) > irc_steps + 1: - del current["frames"][irc_steps + 1] - del current["energies"][irc_steps + 1] - if len(current["frames"]) == irc_steps + 1: - irc_steps = None # it was already at the minimum + # BFGS's first observer call repeats the geometry it started + # from, which is already the last recorded frame. + if len(current["frames"]) > n_before_bfgs: + del current["frames"][n_before_bfgs] + del current["energies"][n_before_bfgs] if not current["frames"]: # nothing recorded: keep the start at least _record() branches[direction] = IRCBranch( diff --git a/tests/test_irc_endpoint.py b/tests/test_irc_endpoint.py new file mode 100644 index 00000000..46192a45 --- /dev/null +++ b/tests/test_irc_endpoint.py @@ -0,0 +1,110 @@ +"""IRC fallback after Sella's inner-loop failure: the stored end is the minimum. + +Sella can raise ``IRCInnerLoopConvergenceFailure`` after moving the atoms to +an inner-iteration geometry no observer recorded. The branch is then finished +by minimizing from where the atoms are; its last frame (end structure and +energy, which set the barriers) must be that minimized geometry, not the last +IRC point. Fast: a harmonic stand-in replaces PySCF and Sella's IRC. +""" + +from __future__ import annotations + +import io + +import numpy as np +import pytest + +from quantui.molecule import Molecule + +ATOMS = ["C", "N", "H"] +START = [[0.0, 0.0, 0.0], [0.0, 0.0, 1.18], [1.0, 0.0, 0.6]] +# The minimum the stand-in potential has on the "forward" side. +MINIMUM = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 1.18], [1.0, 0.0, -0.4]]) + + +def _harmonic_calc_class(): + from ase.calculators.calculator import Calculator, all_changes + + class Harmonic(Calculator): + implemented_properties = ["energy", "forces"] + + def __init__(self, **_kwargs): + super().__init__() + + def calculate(self, atoms=None, properties=None, system_changes=all_changes): + super().calculate(atoms, properties, system_changes) + d = self.atoms.get_positions() - MINIMUM + self.results = {"energy": float(0.5 * (d**2).sum()), "forces": -d} + + return Harmonic + + +def _fake_sella_irc(end_positions): + from sella.optimize.irc import IRCInnerLoopConvergenceFailure + + class FakeIRC: + """Records the start, moves to *end_positions* unrecorded, then fails.""" + + def __init__(self, atoms, **_kwargs): + self.atoms = atoms + self.observers = [] + self.nsteps = 0 + + def attach(self, fn, interval=1): + self.observers.append(fn) + + def run(self, fmax, steps, direction): + self.atoms.set_positions(np.array(START)) + for fn in self.observers: + fn() + self.atoms.set_positions(np.array(end_positions)) + raise IRCInnerLoopConvergenceFailure + + return FakeIRC + + +def _run(monkeypatch, end_positions): + pytest.importorskip("sella") + import sella + + import quantui.optimizer as optimizer + import quantui.ts_search as ts_search + from quantui.irc import run_irc + + monkeypatch.setattr(optimizer, "_QuantUIPySCFCalc", _harmonic_calc_class()) + monkeypatch.setattr(ts_search, "_analytic_hessian_fn", lambda calc: None) + monkeypatch.setattr(sella, "IRC", _fake_sella_irc(end_positions)) + return run_irc( + Molecule(ATOMS, START, validate_spin=False), + "RHF", + "STO-3G", + fmax=0.05, + progress_stream=io.StringIO(), + ) + + +def _end_force(branch) -> float: + d = np.asarray(branch.trajectory[-1].coordinates) - MINIMUM + return float(np.sqrt((d**2).sum(axis=1)).max()) + + +def test_failure_at_the_minimum_stores_the_minimum(monkeypatch): + # Sella's failed inner loop already sits at the minimum: the descent + # takes no step. The branch used to end on the previous IRC point (here + # the start) while reporting "reached a minimum". + r = _run(monkeypatch, MINIMUM) + for branch in (r.forward, r.reverse): + assert branch.converged + assert _end_force(branch) < 0.05 + assert branch.end_energy_hartree == pytest.approx(0.0, abs=1e-12) + + +def test_failure_near_the_minimum_ends_converged_without_duplicates(monkeypatch): + near = MINIMUM + np.array([[0, 0, 0], [0, 0, 0], [0.3, 0.0, 0.2]]) + r = _run(monkeypatch, near) + for branch in (r.forward, r.reverse): + 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" From 789cd2bc7ac738be1e1c2d13795c700e7a0666d9 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 03:52:26 +0000 Subject: [PATCH 2/8] SLURM: recognise "CANCELLED by " and other final states (audit HPC-1) sacct reports a cancelled job as "CANCELLED by ". The parser kept the whole string and every consumer compared against bare state names, so a cancelled job fell through to "submitted": Cancel reported failure after a successful scancel, and once the job left squeue the record stayed active for good, holding one of the two job slots. Preempted, boot-failed and deadline-killed jobs did the same. - normalize_slurm_state() reduces sacct/squeue states to the bare name (drops "by " and a trailing "+"); used by the sacct parser and both squeue paths. - PREEMPTED, BOOT_FAIL, DEADLINE, REVOKED are terminal (error); COMPLETING/SUSPENDED map to running and REQUEUED to pending instead of "submitted". - The cancel confirmation loop waits through non-final states instead of giving up on the first one that is not PENDING/RUNNING. - The mock sacct prints "CANCELLED by " like real Slurm, so the existing cancel test now exercises the real string. New tests fail on the old code; still to confirm on NCShare. 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/slurm.py | 30 ++++++++++++++------- quantui/backends/slurm_utils.py | 14 +++++++++- testing/mock-slurm/mock_slurm_cli.py | 3 +++ tests/test_backends_registry.py | 7 +++++ tests/test_backends_slurm.py | 40 ++++++++++++++++++++++++++++ 5 files changed, 84 insertions(+), 10 deletions(-) diff --git a/quantui/backends/slurm.py b/quantui/backends/slurm.py index b1e5569b..0a6d48df 100644 --- a/quantui/backends/slurm.py +++ b/quantui/backends/slurm.py @@ -38,6 +38,7 @@ SlurmJobAccounting, default_job_name, estimate_slurm_resources, + normalize_slurm_state, parse_sacct_accounting, parse_sacct_states, parse_slurm_job_id, @@ -54,8 +55,19 @@ "TIMEOUT", "NODE_FAIL", "OUT_OF_MEMORY", + # Also final for this job id: a preempted job is not requeued + # under it unless the site requeues (then squeue reports it again). + "PREEMPTED", + "BOOT_FAIL", + "DEADLINE", + "REVOKED", } ) +# Non-terminal states that are not literally PENDING/RUNNING. +_RUNNING_LIKE_SLURM = frozenset({"COMPLETING", "SUSPENDED", "STOPPED", "RESIZING"}) +_PENDING_LIKE_SLURM = frozenset( + {"PENDING", "CONFIGURING", "REQUEUED", "REQUEUE_HOLD", "REQUEUE_FED"} +) _TERMINAL_RECORD = frozenset({"success", "error", "cancelled"}) _ACTIVE_RECORD = frozenset({"queued", "pending", "running", "submitted"}) # A request id (uuid hex / job-name style) or a numeric SLURM job id. @@ -463,8 +475,8 @@ def _squeue_status(self, slurm_job_id: str) -> str | None: ): return None - status = result.stdout.strip() - return status.upper() if status else None + status = normalize_slurm_state(result.stdout) + return status or None def _sacct_status(self, slurm_job_id: str) -> str | None: batch = self._batch_sacct([slurm_job_id]) @@ -566,8 +578,8 @@ def _batch_squeue(self, slurm_job_ids: List[str]) -> Dict[str, str]: ) for line in result.stdout.splitlines(): parts = line.strip().split() - if len(parts) == 2: - statuses[parts[0]] = parts[1] + if len(parts) >= 2: + statuses[parts[0]] = normalize_slurm_state(" ".join(parts[1:])) except ( subprocess.TimeoutExpired, FileNotFoundError, @@ -746,8 +758,8 @@ def cancel(self, request_id: str) -> bool: ) if status in _TERMINAL_SLURM: return self._finalize_cancel_from_slurm_state(record, status) - if status and status not in ("PENDING", "RUNNING", "CONFIGURING"): - return self._finalize_cancel_from_slurm_state(record, status) + # Anything else (PENDING, RUNNING, COMPLETING, ...) is still on + # its way to CANCELLED: keep waiting until the deadline. time.sleep(cfg.CANCEL_POLL_INTERVAL_SECONDS) self._record_cancel_failure( @@ -812,10 +824,10 @@ def _is_within(path: Path, parent: Path) -> bool: def _map_slurm_status(slurm_status: str) -> str: - upper = slurm_status.upper() - if upper in ("PENDING", "CONFIGURING"): + upper = normalize_slurm_state(slurm_status) + if upper in _PENDING_LIKE_SLURM: return "pending" - if upper == "RUNNING": + if upper == "RUNNING" or upper in _RUNNING_LIKE_SLURM: return "running" if upper in _TERMINAL_SLURM: if upper == "COMPLETED": diff --git a/quantui/backends/slurm_utils.py b/quantui/backends/slurm_utils.py index eaf85776..484bba02 100644 --- a/quantui/backends/slurm_utils.py +++ b/quantui/backends/slurm_utils.py @@ -105,6 +105,18 @@ def parse_slurm_job_id(sbatch_output: str) -> Optional[str]: return None +def normalize_slurm_state(state: str) -> str: + """Reduce a SLURM state string to its bare upper-case state name. + + ``sacct`` reports a cancel as ``CANCELLED by `` and may append ``+`` + to a state (``CANCELLED+``); ``squeue`` long forms can carry a reason in + the same way. Every consumer compares against bare names + (``CANCELLED``, ``COMPLETED``, ...), so the extra text is dropped here. + """ + parts = str(state or "").strip().upper().split() + return parts[0].rstrip("+") if parts else "" + + def parse_sacct_accounting(sacct_output: str) -> Dict[str, SlurmJobAccounting]: """Parse ``sacct -P --format=JobID,State,ExitCode,Elapsed`` output.""" rows: Dict[str, SlurmJobAccounting] = {} @@ -116,7 +128,7 @@ def parse_sacct_accounting(sacct_output: str) -> Dict[str, SlurmJobAccounting]: if len(parts) < 2: continue job_id = parts[0].strip() - state = parts[1].strip().upper() + state = normalize_slurm_state(parts[1]) if not job_id or not state or "." in job_id: continue exit_code = parts[2].strip() if len(parts) > 2 else "" diff --git a/testing/mock-slurm/mock_slurm_cli.py b/testing/mock-slurm/mock_slurm_cli.py index 981c8f77..445d4d65 100644 --- a/testing/mock-slurm/mock_slurm_cli.py +++ b/testing/mock-slurm/mock_slurm_cli.py @@ -72,6 +72,9 @@ def cmd_sacct(argv: list[str]) -> int: state_dir = _state_dir() for job_id, data, _path in _iter_jobs(state_dir, ids): status = str(data.get("status", "PENDING")).upper() + if status == "CANCELLED": + # Real sacct names who cancelled the job. + status = f"CANCELLED by {os.getuid() if hasattr(os, 'getuid') else 0}" exit_code = str(data.get("exit_code", "0:0")) elapsed = str(data.get("elapsed", "00:00:01")) print(f"{job_id}|{status}|{exit_code}|{elapsed}") diff --git a/tests/test_backends_registry.py b/tests/test_backends_registry.py index d1ca3e1f..56dcbfa5 100644 --- a/tests/test_backends_registry.py +++ b/tests/test_backends_registry.py @@ -87,6 +87,13 @@ def test_parse_sacct_states(self): states = parse_sacct_states(output) assert states == {"123456": "COMPLETED", "789": "CANCELLED"} + def test_parse_sacct_states_drops_who_cancelled(self): + # Real sacct output for a cancelled job names the canceller; a + # trailing ``+`` can follow a truncated state. + output = "789|CANCELLED by 1000|0:15|00:00:04\n790|CANCELLED+|0:15|00:00:01\n" + states = parse_sacct_states(output) + assert states == {"789": "CANCELLED", "790": "CANCELLED"} + def test_parse_sacct_accounting(self): output = "123456|FAILED|1:0|00:00:42\n" rows = parse_sacct_accounting(output) diff --git a/tests/test_backends_slurm.py b/tests/test_backends_slurm.py index db183c90..d11dc355 100644 --- a/tests/test_backends_slurm.py +++ b/tests/test_backends_slurm.py @@ -596,6 +596,46 @@ def _fake_run(args, **_kwargs): assert record.status == "cancelled" +class TestRealSlurmStateStrings: + """sacct reports ``CANCELLED by ``; finished states beyond the + common six must end a job instead of leaving it ``submitted``.""" + + @pytest.mark.parametrize( + "state, expected", + [ + ("CANCELLED by 1000", "cancelled"), + ("CANCELLED+", "cancelled"), + ("PREEMPTED", "error"), + ("BOOT_FAIL", "error"), + ("DEADLINE", "error"), + ("COMPLETING", "running"), + ("SUSPENDED", "running"), + ("REQUEUED", "pending"), + ], + ) + def test_map_slurm_status(self, state, expected): + from quantui.backends.slurm import _map_slurm_status + + assert _map_slurm_status(state) == expected + + def test_cancelled_job_out_of_squeue_leaves_the_active_count(self, slurm_backend): + slurm_backend.registry.create(_request("gone"), "cluster_slurm") + slurm_backend.registry.update_status("gone", "submitted", slurm_job_id="900077") + + def _fake_run(args, **_kwargs): + from unittest.mock import MagicMock + + res = MagicMock(returncode=0, stderr="") + res.stdout = ( + "900077|CANCELLED by 1000|0:15|00:00:04\n" if args[0] == "sacct" else "" + ) + return res + + with patch("quantui.backends.slurm.subprocess.run", side_effect=_fake_run): + slurm_backend.refresh_registry_statuses() + assert slurm_backend.registry.load("gone").status == "cancelled" + + class TestDependsOn: """``--depends-on`` accepts a request id or a SLURM job id, nothing else.""" From 649a9c5491b039cfff769a5bf77b518984f58b31 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 03:52:39 +0000 Subject: [PATCH 3/8] Run: one run at a time, inputs read once (audit APP-2, APP-3, APP-4, APP-6) APP-4: on_run_clicked never checked _calc_running, and the worker thread set it (and disabled Run) only after it started, so a double-click started two runs sharing the cancel flag, live log and checkpoint directory; loading a molecule mid-run also re-enabled Run. The run is now claimed on the main thread before the worker starts, a click while one is in flight is ignored, and _set_molecule leaves Run disabled while a run is going. APP-2: _do_run read method, basis, solvent, fmax, step limit and the pre-opt flag from the live widgets at every stage, and used the active molecule object the Charge/Multiplicity fields write into. Changing the basis during a Geometry Opt gave a final single point at the new basis saved under the old label. They are now read once when the run starts and the molecule is copied; the Calculation Setup controls (plus charge, multiplicity and calculation type) are disabled for the run and restored to their previous state afterwards (help buttons stay usable). APP-6: an exception before _do_run's own try/finally (e.g. an unwritable log directory) left Run disabled for the session. The worker entry point now releases the run and reports the error if _do_run did not. APP-3: every seed path (Geometry Opt, TD-DFT, NMR, PES, and Frequency / IRC / TS via resolve_seed_geometry, which batch submission also uses) took the seed trajectory's last frame with that run's charge and multiplicity, so "the cation at the neutral's optimized geometry" recomputed the neutral and saved it as the cation's method. seed_with_run_charge() keeps the seed geometry and the current run's charge and multiplicity. tests/test_run_lock.py covers a seeded cation run, the click guard, freeze/restore, an early error, and a mid-run basis/charge change during Geometry Opt. 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.py | 260 +++++++++++++++++++++++++++++------------ quantui/app_runflow.py | 37 +++++- tests/test_run_lock.py | 155 ++++++++++++++++++++++++ 3 files changed, 376 insertions(+), 76 deletions(-) create mode 100644 tests/test_run_lock.py diff --git a/quantui/app.py b/quantui/app.py index 580fc77f..59195b3f 100644 --- a/quantui/app.py +++ b/quantui/app.py @@ -14,8 +14,10 @@ from __future__ import annotations import asyncio +import copy import html as _html import io +import logging import re import threading import time @@ -424,6 +426,9 @@ from quantui.app_runflow import ( resolve_ts_product as _run_resolve_ts_product, ) +from quantui.app_runflow import ( + seed_with_run_charge as _run_seed_with_run_charge, +) from quantui.app_runflow import ( update_estimate as _run_update_estimate, ) @@ -681,6 +686,8 @@ select_backend, ) +logger = logging.getLogger(__name__) + # ── Availability flags (computed once at import, not per-instantiation) ─────── try: from quantui.ase_bridge import ASE_AVAILABLE @@ -5932,7 +5939,8 @@ def _set_molecule( ) -> None: """Update shared state and refresh dependent widgets.""" self._molecule = mol - self.run_btn.disabled = False + # Loading a molecule mid-run must not re-arm Run (audit APP-4). + self.run_btn.disabled = bool(getattr(self, "_calc_running", False)) self.export_btn.disabled = False self.export_xyz_btn.disabled = False self.export_mol_btn.disabled = not _RDKIT_AVAILABLE @@ -6388,12 +6396,121 @@ def _on_vib_next_clicked(self, _btn) -> None: self.vib_mode_dd.value = opts[i + 1][1] return + # ── Run lock: one calculation at a time, setup frozen while it runs ── + + def _run_input_widgets(self) -> List[Any]: + """Every control whose value a run reads (the Calculation Setup panel, + the molecule's charge/multiplicity, the calculation type).""" + found: List[Any] = [] + seen: set = set() + help_buttons = { + id(w) + for name, w in vars(self).items() + if name.endswith("_help_btn") and w is not None + } + + def _walk(w: Any) -> None: + if w is None or id(w) in seen: + return + seen.add(id(w)) + children = getattr(w, "children", None) + if children: + for child in children: + _walk(child) + return + if hasattr(w, "disabled") and id(w) not in help_buttons: + found.append(w) + + _walk(getattr(self, "calc_setup_panel", None)) + for name in ("charge_si", "mult_si", "calc_type_dd"): + _walk(getattr(self, name, None)) + return found + + def _freeze_run_inputs(self) -> None: + """Disable the run's input controls, remembering their prior state.""" + frozen = getattr(self, "_frozen_run_inputs", None) or {} + for w in self._run_input_widgets(): + if id(w) in frozen: + continue + try: + frozen[id(w)] = (w, bool(w.disabled)) + w.disabled = True + except Exception: # noqa: BLE001 — a widget without the trait + frozen.pop(id(w), None) + self._frozen_run_inputs = frozen + + def _restore_run_inputs(self) -> None: + """Re-enable what :meth:`_freeze_run_inputs` disabled.""" + frozen = getattr(self, "_frozen_run_inputs", None) or {} + self._frozen_run_inputs = {} + for w, was_disabled in frozen.values(): + try: + w.disabled = was_disabled + except Exception: # noqa: BLE001 — closed widget + pass + + def _begin_run_lock(self) -> None: + """Mark a run in flight (main thread, before the worker starts).""" + self._calc_running = True + self.run_btn.disabled = True + self._freeze_run_inputs() + + def _end_run_lock(self) -> None: + """Release the run lock taken by :meth:`_begin_run_lock`.""" + self._calc_running = False + self.run_btn.disabled = False + self._restore_run_inputs() + + def _run_in_thread(self) -> None: + """Worker-thread entry: :meth:`_do_run`, plus a guaranteed unlock. + + ``_do_run`` releases the run state in its own ``finally``, but that + block starts after its setup; an error before it (an unwritable log + directory, say) used to leave Run disabled for the session. + """ + error: Optional[BaseException] = None + try: + self._do_run() + except Exception as exc: # noqa: BLE001 — reported below + logger.exception("Calculation run failed before it started") + error = exc + finally: + if getattr(self, "_calc_running", False): + self._cancel_event.clear() + self.cancel_btn.disabled = True + self.log_clear_btn.disabled = False + try: + self._stop_elapsed_ticker() + self._activity_end(kind="compute") + except Exception: # noqa: BLE001 — teardown is best-effort + pass + self._end_run_lock() + self.run_status.value = ( + f"The run could not start: {error}" + if error is not None + else "The run stopped unexpectedly." + ) + else: + self._restore_run_inputs() + def _do_run(self) -> None: """Main calculation dispatch — runs in a background thread.""" - mol = self._molecule - if mol is None: + if self._molecule is None: self.run_status.value = "Load a molecule first." + self._end_run_lock() return + # Everything the run depends on is read once, here. The run lasts + # minutes and the setup widgets (and the active molecule, whose + # charge/multiplicity the Charge/Multiplicity fields write into) + # stay live: a later read would mix two levels of theory in one + # saved result (audit APP-2). + mol = copy.deepcopy(self._molecule) + _run_method = self.method_dd.value + _run_basis = self.basis_dd.value + _run_solvent_opt = self.solvent_dd.value if self.solvent_cb.value else None + _run_fmax = self.fmax_fi.value + _run_max_steps = self.max_steps_si.value + _run_preopt = bool(self._freq_preopt_cb.value) self._activity_begin( "Running compute operations...", kind="compute", @@ -6412,7 +6529,7 @@ def _do_run(self) -> None: _calc_log.log_event( "calc_start", - f"{self.method_dd.value}/{self.basis_dd.value} on {mol.get_formula()}", + f"{_run_method}/{_run_basis} on {mol.get_formula()}", n_atoms=len(mol.atoms), ) _run_wall_t = time.perf_counter() @@ -6432,9 +6549,7 @@ def _do_run(self) -> None: _predicted_run_confidence: str = "unknown" try: _ct_for_est = _run_calc_type_key(self) - _nb_for_est = _calc_log.count_basis_functions( - mol.atoms, self.basis_dd.value - ) + _nb_for_est = _calc_log.count_basis_functions(mol.atoms, _run_basis) # Match _update_estimate's GPU-prediction logic so the # recorded predicted_s is what the user SAW in the UI # before they hit Run. @@ -6448,7 +6563,7 @@ def _do_run(self) -> None: ) _gpu_avail, _ = is_gpu_available() - if _gpu_avail and self.method_dd.value.upper() not in _GPU_NO: + if _gpu_avail and _run_method.upper() not in _GPU_NO: _predicted_gpu_used = True else: _predicted_gpu_used = False @@ -6460,7 +6575,7 @@ def _do_run(self) -> None: # references are never fitted, so predict False for them. _predicted_density_fit: Optional[bool] = None try: - if self.method_dd.value.upper() in ("MP2", "CCSD", "CCSD(T)"): + if _run_method.upper() in ("MP2", "CCSD", "CCSD(T)"): _predicted_density_fit = False else: _predicted_density_fit = bool( @@ -6472,8 +6587,8 @@ def _do_run(self) -> None: _est = _calc_log.estimate_time( n_atoms=len(mol.atoms), n_electrons=mol.get_electron_count(), - method=self.method_dd.value, - basis=self.basis_dd.value, + method=_run_method, + basis=_run_basis, n_basis=_nb_for_est, calc_type=_ct_for_est, gpu_used=_predicted_gpu_used, @@ -6516,7 +6631,7 @@ def _run_required_final_single_point(target_mol, reason: str): """Run a required post-optimization single point on target geometry.""" from quantui.engines import EnginePreference, EngineRequest, run_calc - _solvent = self.solvent_dd.value if self.solvent_cb.value else None + _solvent = _run_solvent_opt self.run_status.value = ( "Running required single-point on optimized geometry..." ) @@ -6528,8 +6643,8 @@ def _run_required_final_single_point(target_mol, reason: str): EngineRequest( request_id=_uuid.uuid4().hex, calc_type="single_point", - method=self.method_dd.value, - basis=self.basis_dd.value, + method=_run_method, + basis=_run_basis, charge=int(target_mol.charge), multiplicity=int(target_mol.multiplicity), molecule={ @@ -6621,7 +6736,7 @@ def _run_required_final_single_point(target_mol, reason: str): ct = self.calc_type_dd.value # PCM solvent for this run (None = gas phase). The checkbox is # disabled for calc types without solvent support. - _run_solvent = self.solvent_dd.value if self.solvent_cb.value else None + _run_solvent = _run_solvent_opt result: Any = None result_html: str = "" save_spectra: dict = {} @@ -6632,7 +6747,7 @@ def _run_required_final_single_point(target_mol, reason: str): # Frequency and UV-Vis (TD-DFT) both have dedicated seed/pre-opt # handling in their own branches so they can layer a seed # geometry under the pre-opt step. - if self._freq_preopt_cb.value and ct not in ( + if _run_preopt and ct not in ( "Geometry Opt", "Frequency", "UV-Vis (TD-DFT)", @@ -6656,8 +6771,8 @@ def _run_required_final_single_point(target_mol, reason: str): try: _pre_opt = optimize_geometry( molecule=calc_mol, - method=self.method_dd.value, - basis=self.basis_dd.value, + method=_run_method, + basis=_run_basis, progress_stream=log, # type: ignore[arg-type] solvent=_run_solvent, ) @@ -6697,7 +6812,7 @@ def _run_required_final_single_point(target_mol, reason: str): self.run_status.value = "Loading seed geometry from history…" _geo_seed_traj, _ = load_trajectory(Path(_geo_seed_path)) - calc_mol = _geo_seed_traj[-1] + calc_mol = _run_seed_with_run_charge(_geo_seed_traj[-1], mol) log.write( f"\nSeed geometry loaded from: " f"{Path(_geo_seed_path).name}\n" @@ -6711,20 +6826,18 @@ def _run_required_final_single_point(target_mol, reason: str): # History-based expected step count → "step k/~N" + a floor # for the live progress fraction. None on cold history. - _expected_steps = _calc_log.estimate_opt_steps( - self.method_dd.value, self.basis_dd.value - ) + _expected_steps = _calc_log.estimate_opt_steps(_run_method, _run_basis) log.opt_expected_steps = ( int(round(_expected_steps)) if _expected_steps else None ) - log.opt_fmax_target = float(self.fmax_fi.value) + log.opt_fmax_target = float(_run_fmax) log.opt_fmax0 = None result = run_calc( EngineRequest( request_id=_uuid.uuid4().hex, calc_type="geometry_opt", - method=self.method_dd.value, - basis=self.basis_dd.value, + method=_run_method, + basis=_run_basis, charge=int(calc_mol.charge), multiplicity=int(calc_mol.multiplicity), molecule={ @@ -6732,8 +6845,8 @@ def _run_required_final_single_point(target_mol, reason: str): "coordinates": [list(c) for c in calc_mol.coordinates], }, options={ - "fmax": self.fmax_fi.value, - "steps": self.max_steps_si.value, + "fmax": _run_fmax, + "steps": _run_max_steps, "expected_steps": ( int(round(_expected_steps)) if _expected_steps else None ), @@ -6816,15 +6929,15 @@ def _run_required_final_single_point(target_mol, reason: str): check_search_possible, ) - check_search_possible(self.method_dd.value) + check_search_possible(_run_method) self.run_status.value = ( "Building a transition-state guess from reactant + product…" ) _ts_guess = build_ts_guess( calc_mol, _ts_product, - self.method_dd.value, - self.basis_dd.value, + _run_method, + _run_basis, n_images=int(self._ts_n_images_si.value), solvent=_run_solvent, progress_stream=log, # type: ignore[arg-type] @@ -6835,10 +6948,10 @@ def _run_required_final_single_point(target_mol, reason: str): self.run_status.value = "Searching for a transition state…" result = run_ts_search( calc_mol, - self.method_dd.value, - self.basis_dd.value, + _run_method, + _run_basis, fmax=float(self._ts_fmax_fi.value), - steps=int(self.max_steps_si.value), + steps=int(_run_max_steps), progress_stream=log, # type: ignore[arg-type] solvent=_run_solvent, cancel_check=self._cancel_event.is_set, @@ -6886,9 +6999,9 @@ def _run_required_final_single_point(target_mol, reason: str): self.run_status.value = "Following the reaction path…" result = run_irc( calc_mol, - self.method_dd.value, - self.basis_dd.value, - steps=int(self.max_steps_si.value), + _run_method, + _run_basis, + steps=int(_run_max_steps), progress_stream=log, # type: ignore[arg-type] solvent=_run_solvent, cancel_check=self._cancel_event.is_set, @@ -6917,7 +7030,7 @@ def _run_required_final_single_point(target_mol, reason: str): # any failure log to the user log, keep ``calc_mol`` as # the input geometry, and proceed to the freq analysis — # the user can iterate if their input was actually wrong. - if self._freq_preopt_cb.value: + if _run_preopt: from quantui import optimize_geometry from quantui.optimizer import FREQ_PREOPT_FMAX @@ -6930,8 +7043,8 @@ def _run_required_final_single_point(target_mol, reason: str): try: _pre_opt = optimize_geometry( molecule=calc_mol, - method=self.method_dd.value, - basis=self.basis_dd.value, + method=_run_method, + basis=_run_basis, fmax=FREQ_PREOPT_FMAX, progress_stream=log, # type: ignore[arg-type] solvent=_run_solvent, @@ -6964,7 +7077,7 @@ def _run_required_final_single_point(target_mol, reason: str): ) # ── Step 3: frequency analysis ──────────────────────────────── - if _run_solvent and not self._freq_preopt_cb.value: + if _run_solvent and not _run_preopt: log.write( f"\nNote: PCM ({_run_solvent}) frequencies are only " "meaningful at a geometry optimized in the same " @@ -6976,8 +7089,8 @@ def _run_required_final_single_point(target_mol, reason: str): self.run_status.value = "Computing frequencies (SCF + Hessian)…" result = run_freq_calc( molecule=calc_mol, - method=self.method_dd.value, - basis=self.basis_dd.value, + method=_run_method, + basis=_run_basis, progress_stream=log, # type: ignore[arg-type] # The app opens _ckpt and resolves _resume # above (used by Geometry Opt / PES Scan / Reorganization @@ -7009,8 +7122,8 @@ def _run_required_final_single_point(target_mol, reason: str): _retried = retry_frequency_off_saddle( calc_mol, result, - method=self.method_dd.value, - basis=self.basis_dd.value, + method=_run_method, + basis=_run_basis, solvent=_run_solvent, progress_stream=log, # type: ignore[arg-type] ) @@ -7037,7 +7150,7 @@ def _run_required_final_single_point(target_mol, reason: str): self.run_status.value = "Loading seed geometry from history…" _seed_traj, _ = load_trajectory(Path(_tddft_seed_path)) - calc_mol = _seed_traj[-1] + calc_mol = _run_seed_with_run_charge(_seed_traj[-1], mol) log.write( f"\nSeed geometry loaded from: {Path(_tddft_seed_path).name}\n" f" Formula: {calc_mol.get_formula()} " @@ -7047,7 +7160,7 @@ def _run_required_final_single_point(target_mol, reason: str): # ── Step 2: optional geometry optimization ──────────────────── # Renamed from # "pre-optimisation" — DFT geom-opt is just geom-opt. - if self._freq_preopt_cb.value: + if _run_preopt: from quantui import optimize_geometry self.run_status.value = ( @@ -7063,8 +7176,8 @@ def _run_required_final_single_point(target_mol, reason: str): try: _pre_opt = optimize_geometry( molecule=calc_mol, - method=self.method_dd.value, - basis=self.basis_dd.value, + method=_run_method, + basis=_run_basis, progress_stream=log, # type: ignore[arg-type] solvent=_run_solvent, ) @@ -7097,8 +7210,8 @@ def _run_required_final_single_point(target_mol, reason: str): self.run_status.value = "Running TD-DFT excited states..." result = run_tddft_calc( molecule=calc_mol, - method=self.method_dd.value, - basis=self.basis_dd.value, + method=_run_method, + basis=_run_basis, nstates=self.nstates_si.value, progress_stream=log, # type: ignore[arg-type] solvent=_run_solvent, @@ -7127,7 +7240,7 @@ def _run_required_final_single_point(target_mol, reason: str): self.run_status.value = "Loading seed geometry from history…" _nmr_seed_traj, _ = load_trajectory(Path(_nmr_seed_path)) - calc_mol = _nmr_seed_traj[-1] + calc_mol = _run_seed_with_run_charge(_nmr_seed_traj[-1], mol) log.write( f"\nSeed geometry loaded from: {Path(_nmr_seed_path).name}\n" f" Formula: {calc_mol.get_formula()} " @@ -7139,8 +7252,8 @@ def _run_required_final_single_point(target_mol, reason: str): result = run_nmr_calc( molecule=calc_mol, - method=self.method_dd.value, - basis=self.basis_dd.value, + method=_run_method, + basis=_run_basis, progress_stream=log, # type: ignore[arg-type] ) result_html = self._format_nmr_result(result) @@ -7179,7 +7292,7 @@ def _run_required_final_single_point(target_mol, reason: str): self.run_status.value = "Loading seed geometry from history…" _seed_traj, _ = load_trajectory(Path(_scan_seed.value)) if _seed_traj: - calc_mol = _seed_traj[-1] + calc_mol = _run_seed_with_run_charge(_seed_traj[-1], mol) log.write( f"\nSeed geometry loaded from: " f"{Path(_scan_seed.value).name}\n" @@ -7199,16 +7312,16 @@ def _run_required_final_single_point(target_mol, reason: str): result = run_pes_scan( molecule=calc_mol, - method=self.method_dd.value, - basis=self.basis_dd.value, + method=_run_method, + basis=_run_basis, scan_type=_st, atom_indices=_atom_idx, start=self._scan_start.value, stop=self._scan_stop.value, steps=self._scan_steps.value, grid=str(getattr(self._scan_grid_dd, "value", "linear")), - fmax=self.fmax_fi.value, - max_opt_steps=self.max_steps_si.value, + fmax=_run_fmax, + max_opt_steps=_run_max_steps, progress_stream=log, # type: ignore[arg-type] checkpoint=_ckpt, resume=_resume, @@ -7229,14 +7342,14 @@ def _run_required_final_single_point(target_mol, reason: str): run_reorganization_energy, ) - _solvent = self.solvent_dd.value if self.solvent_cb.value else None + _solvent = _run_solvent_opt result = run_reorganization_energy( molecule=calc_mol, mode=self._reorg_mode_dd.value, - method=self.method_dd.value, - basis=self.basis_dd.value, - fmax=self.fmax_fi.value, - steps=self.max_steps_si.value, + method=_run_method, + basis=_run_basis, + fmax=_run_fmax, + steps=_run_max_steps, progress_stream=log, # type: ignore[arg-type] solvent=_solvent, checkpoint=_ckpt, @@ -7250,7 +7363,7 @@ def _run_required_final_single_point(target_mol, reason: str): from quantui.engines import EnginePreference, EngineRequest, run_calc # MP2 heavy-atom warning - if self.method_dd.value.upper() == "MP2": + if _run_method.upper() == "MP2": _n_heavy = sum(1 for a in calc_mol.atoms if a != "H") if _n_heavy > 20: self.result_output.append_display_data( @@ -7262,13 +7375,13 @@ def _run_required_final_single_point(target_mol, reason: str): ) ) - _solvent = self.solvent_dd.value if self.solvent_cb.value else None + _solvent = _run_solvent_opt engine_result = run_calc( EngineRequest( request_id=_uuid.uuid4().hex, calc_type="single_point", - method=self.method_dd.value, - basis=self.basis_dd.value, + method=_run_method, + basis=_run_basis, charge=int(calc_mol.charge), multiplicity=int(calc_mol.multiplicity), molecule={ @@ -7345,8 +7458,8 @@ def _run_required_final_single_point(target_mol, reason: str): _ana_ctx = _AnalysisContext( calc_type=save_type, formula=result.formula, - method=self.method_dd.value, - basis=self.basis_dd.value, + method=_run_method, + basis=_run_basis, live_result=result, molecule=calc_mol, spectra_data=save_spectra, @@ -7507,7 +7620,7 @@ def _run_required_final_single_point(target_mol, reason: str): self._queue_main_thread_callback( self._update_log_panel, log.getvalue(), - f"{result.formula} {self.method_dd.value}/{self.basis_dd.value}", + f"{result.formula} {_run_method}/{_run_basis}", ) self._queue_main_thread_callback( self._show_result_log, @@ -7680,7 +7793,7 @@ def _run_required_final_single_point(target_mol, reason: str): try: _calc_log.log_event( "calc_cancelled", - f"{mol.get_formula()} {self.method_dd.value}/{self.basis_dd.value}", + f"{mol.get_formula()} {_run_method}/{_run_basis}", elapsed_s=round(_elapsed, 2), ) except OSError: @@ -7723,8 +7836,8 @@ def _run_required_final_single_point(target_mol, reason: str): _log_dir.mkdir(parents=True, exist_ok=True) _ts = _dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S") _formula = mol.get_formula() if mol is not None else "unknown" - _method = self.method_dd.value - _basis = self.basis_dd.value + _method = _run_method + _basis = _run_basis with open(_log_dir / "error_log.txt", "a") as _ef: _ef.write( f"\n{'='*60}\n" @@ -7755,6 +7868,7 @@ def _run_required_final_single_point(target_mol, reason: str): finally: self.run_btn.disabled = False + self._restore_run_inputs() # Disarm Cancel, re-enable Clear, clear run-in-flight state. self._calc_running = False self._cancel_event.clear() diff --git a/quantui/app_runflow.py b/quantui/app_runflow.py index c314f4a0..d2ce6825 100644 --- a/quantui/app_runflow.py +++ b/quantui/app_runflow.py @@ -126,6 +126,12 @@ def _set_run_output(app: Any, outputs: tuple) -> None: def on_run_clicked(app: Any, btn: Any) -> None: """Reset result panes and start the background run thread.""" + # One run at a time. The button is disabled while a run is in flight, + # but a double-click (or a click queued before the disable reached the + # browser) still lands here; two runs would share the cancel flag, the + # live log and the checkpoint directory (audit APP-4). + if getattr(app, "_calc_running", False): + return # Pre-run guard: catch a basis with no parameters for an # element (e.g. 6-31G on Pt) or a charge/multiplicity inconsistent with the # electron count, and explain it here — on the main thread, before anything @@ -220,7 +226,10 @@ def on_run_clicked(app: Any, btn: Any) -> None: submit_slurm_run(app) return - threading.Thread(target=app._do_run, daemon=True).start() + # Claim the run on this (main) thread, before the worker starts: the + # worker used to set the flag itself, leaving a window for a second run. + app._begin_run_lock() + threading.Thread(target=app._run_in_thread, daemon=True).start() _FREQ_PREOPT_DESC_DEFAULT = "Geometry optimization before calculation (QM, slower)" @@ -1134,8 +1143,29 @@ def _update_freq_perturb_seed_ui(app: Any, path_str: str) -> None: box.layout.display = "none" +def seed_with_run_charge(seed_mol: Any, base_mol: Any) -> Any: + """*seed_mol*'s geometry with *base_mol*'s charge and multiplicity. + + A seed is a saved result's geometry, and its ``trajectory.json`` carries + the charge and multiplicity of *that* run. The run being set up decides + the electronic state: the classic "cation at the neutral's optimized + geometry" must not silently recompute the neutral (audit APP-3). + """ + from quantui.molecule import Molecule + + return Molecule( + list(seed_mol.atoms), + [list(map(float, c)) for c in seed_mol.coordinates], + charge=int(base_mol.charge), + multiplicity=int(base_mol.multiplicity), + ) + + def resolve_seed_geometry(app: Any, base_mol: Any, *, log: Any | None = None) -> Any: - """Apply seed geometry (geo-opt final frame or freq mode perturbation).""" + """Apply seed geometry (geo-opt final frame or freq mode perturbation). + + The returned molecule keeps *base_mol*'s charge and multiplicity. + """ from quantui.backends.dispatch import load_seed_molecule, seed_path_from_app from quantui.freq_calc import ( VIB_MODE_DISPLAY_AMPLITUDE_ANGSTROM, @@ -1157,6 +1187,7 @@ def resolve_seed_geometry(app: Any, base_mol: Any, *, log: Any | None = None) -> mode_number, fraction=fraction, ) + mol = seed_with_run_charge(mol, base_mol) if log is not None: freq_raw = meta.get("frequency_cm1") freq_val = float(freq_raw) if isinstance(freq_raw, (int, float)) else None @@ -1170,7 +1201,7 @@ def resolve_seed_geometry(app: Any, base_mol: Any, *, log: Any | None = None) -> ) return mol - mol = load_seed_molecule(seed_path) + mol = seed_with_run_charge(load_seed_molecule(seed_path), base_mol) if log is not None: log.write( f"\nSeed geometry loaded from: {Path(seed_path).name}\n" diff --git a/tests/test_run_lock.py b/tests/test_run_lock.py new file mode 100644 index 00000000..dea18ca0 --- /dev/null +++ b/tests/test_run_lock.py @@ -0,0 +1,155 @@ +"""One run at a time, read once (audit APP-2, APP-3, APP-4, APP-6). + +- A second Run click while a run is in flight is ignored, and loading a + molecule mid-run does not re-arm Run. +- The run's inputs are frozen while it runs and restored afterwards. +- Everything a run depends on is read when it starts: a widget change or a + Charge-field edit mid-run cannot reach its later stages. +- A seed geometry keeps the charge/multiplicity of the run being set up. +- An error before ``_do_run``'s own cleanup still releases the run. +""" + +from __future__ import annotations + +from unittest.mock import MagicMock, patch + +import pytest + +from quantui.app import QuantUIApp +from quantui.molecule import Molecule + + +def _water(charge: int = 0, mult: int = 1) -> Molecule: + return Molecule( + ["O", "H", "H"], + [[0.0, 0.0, 0.117], [0.0, 0.757, -0.469], [0.0, -0.757, -0.469]], + charge=charge, + multiplicity=mult, + ) + + +@pytest.fixture +def app(): + a = QuantUIApp() + a._set_molecule(_water()) + a.method_dd.value = "RHF" + a.basis_dd.value = "STO-3G" + return a + + +def test_second_click_while_running_is_ignored(app): + # The worker is a stub that never finishes, so the run stays in flight. + with patch.object(app, "_run_in_thread") as worker: + app._on_run_clicked(None) + app._on_run_clicked(None) + assert worker.call_count == 1 + assert app._calc_running and app.run_btn.disabled + + +def test_inputs_frozen_while_running_and_restored_after(app): + app.solvent_cb.disabled = True # a control that was already off stays off + with patch.object(app, "_run_in_thread"): + app._on_run_clicked(None) + for w in (app.method_dd, app.basis_dd, app.charge_si, app.mult_si): + assert w.disabled, w + assert app.calc_type_dd.disabled + assert not app.method_help_btn.disabled + app._end_run_lock() + for w in (app.method_dd, app.basis_dd, app.charge_si, app.mult_si): + assert not w.disabled, w + assert app.solvent_cb.disabled + assert not app._calc_running and not app.run_btn.disabled + + +def test_loading_a_molecule_mid_run_keeps_run_disabled(app): + with patch.object(app, "_run_in_thread"): + app._on_run_clicked(None) + app._set_molecule(_water()) + assert app.run_btn.disabled + + +def test_error_before_the_run_starts_releases_the_lock(app): + app._begin_run_lock() + with patch.object(app, "_do_run", side_effect=OSError(28, "No space left")): + app._run_in_thread() + assert not app._calc_running + assert not app.run_btn.disabled + assert not app.method_dd.disabled + assert "could not start" in app.run_status.value + + +def _opt_mocks(final_mol: Molecule): + opt = MagicMock() + opt.energy_hartree = -75.0 + opt.converged = True + opt.n_iterations = 3 + opt.energies_hartree = [-75.0] + opt.trajectory = [] + opt.formula = "H2O" + opt.method = "RHF" + opt.basis = "STO-3G" + opt.molecule = final_mol + opt.mo_energy_hartree = opt.mo_occ = opt.mo_coeff = None + opt.pyscf_mol_atom = opt.pyscf_mol_basis = None + sp = MagicMock() + sp.converged = True + sp.energy_hartree = -75.1 + sp.mo_energy_hartree = [0.0] + sp.mo_occ = [2.0] + sp.mo_coeff = [[0.0]] + sp.pyscf_mol_atom = [("O", [0.0, 0.0, 0.0])] + sp.pyscf_mol_basis = "STO-3G" + e_opt, e_sp = MagicMock(), MagicMock() + e_opt.to_session_result.return_value = opt + e_sp.to_session_result.return_value = sp + return e_opt, e_sp + + +def test_mid_run_edits_do_not_reach_later_stages(app): + # Geometry Opt, then its required final single point. Between the two, + # the basis dropdown and the active molecule's charge change (a molecule + # load or the Charge field). The final single point used to read both. + app.calc_type_dd.value = "Geometry Opt" + e_opt, e_sp = _opt_mocks(_water()) + + def _engine(request, *a, **kw): + if request.calc_type == "geometry_opt": + app.basis_dd.value = "3-21G" + app._molecule.charge = 1 + return e_opt + return e_sp + + with patch("quantui.engines.run_calc", side_effect=_engine) as run: + with patch("quantui.save_result"): + app._begin_run_lock() + app._run_in_thread() + requests = [c.args[0] for c in run.call_args_list] + assert [r.calc_type for r in requests] == ["geometry_opt", "single_point"] + assert {r.basis for r in requests} == {"STO-3G"} + assert {r.charge for r in requests} == {0} + + +def test_seed_keeps_the_runs_charge_and_multiplicity(app, tmp_path): + # A neutral optimization's final geometry as the seed for a cation run. + from quantui.app_runflow import seed_with_run_charge + + seeded = seed_with_run_charge(_water(0, 1), _water(1, 2)) + assert (seeded.charge, seeded.multiplicity) == (1, 2) + + app._set_molecule(_water(1, 2)) + app.charge_si.value, app.mult_si.value = 1, 2 + app.method_dd.value = "UHF" + app.calc_type_dd.value = "Geometry Opt" + app._geo_seed_dd.options = [("—", ""), ("neutral opt", str(tmp_path))] + app._geo_seed_dd.value = str(tmp_path) + e_opt, e_sp = _opt_mocks(_water(1, 2)) + with patch( + "quantui.results_storage.load_trajectory", + return_value=([_water(0, 1)], [-75.0]), + ): + with patch("quantui.engines.run_calc", side_effect=[e_opt, e_sp]) as run: + with patch("quantui.save_result"): + app._begin_run_lock() + app._run_in_thread() + opt_request = run.call_args_list[0].args[0] + assert (opt_request.charge, opt_request.multiplicity) == (1, 2) From 5968568617c2c2b47a5e54635d0af8cfce50da35 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 03:53:05 +0000 Subject: [PATCH 4/8] Search: keep the resolver's charge and multiplicity (audit DATA-1) The structure search rebuilt the molecule from the resolved XYZ text alone, so it always loaded as a neutral singlet: sulfate, acetate or ammonium with an even electron count loaded as the wrong species with no warning, and odd-electron ions and radicals ([OH-], [CH3], NO2) failed as "Not found: Multiplicity Error". 26 bundled library entries (O2 triplet, charged complexes, ...) were affected the same way. - The resolvers' metadata now carries a multiplicity (radical electrons RDKit perceives + 1) next to the formal charge, and ResolvedStructure keeps it. - resolve_structure_with_details() returns the full ResolvedStructure; resolve_structure_with_message() is a wrapper over it (unchanged API). - molecule_from_resolved() builds the Molecule with that charge and multiplicity, falling back to the lowest multiplicity consistent with the electron count when a resolver knows the charge but not the spin. - The resolve message states a non-default charge/multiplicity. tests/test_search_charge_multiplicity.py drives the app's search handler offline for [NH4+], [OH-], sulfate, [CH3] and library O2. 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.py | 26 +++++--- quantui/pubchem.py | 17 ++++++ quantui/structure_providers.py | 76 +++++++++++++++++++----- tests/test_search_charge_multiplicity.py | 71 ++++++++++++++++++++++ 4 files changed, 166 insertions(+), 24 deletions(-) create mode 100644 tests/test_search_charge_multiplicity.py diff --git a/quantui/app.py b/quantui/app.py index 59195b3f..9e46d078 100644 --- a/quantui/app.py +++ b/quantui/app.py @@ -674,7 +674,7 @@ freq_parallel_opt_in, ) from quantui.help_content import HELP_TOPICS, VIEWER_HELP_TOPICS -from quantui.molecule import Molecule, parse_xyz_input +from quantui.molecule import Molecule from quantui.progress import StepProgress from quantui.user_settings import UserSettings from quantui.utils import get_session_resources @@ -748,7 +748,10 @@ RDKIT_AVAILABLE as _PUBCHEM_RDKIT_AVAILABLE, ) from quantui.structure_providers import ( - resolve_structure_with_message as _resolve_structure_with_message, + molecule_from_resolved as _molecule_from_resolved, + ) + from quantui.structure_providers import ( + resolve_structure_with_details as _resolve_structure_with_details, ) from quantui.structure_providers import ( search_candidates as _struct_search_candidates, @@ -761,7 +764,8 @@ except ImportError: PUBCHEM_AVAILABLE = False _student_friendly_resolve = None # type: ignore[assignment] - _resolve_structure_with_message = None # type: ignore[assignment] + _resolve_structure_with_details = None # type: ignore[assignment] + _molecule_from_resolved = None # type: ignore[assignment] _struct_search_candidates = None # type: ignore[assignment] @@ -4836,13 +4840,19 @@ def _apply_pubchem_search_result( def _resolve_and_apply(self, query: str, loop) -> None: """Resolve a single query (background thread) and apply on the main loop.""" try: - xyz_str, _msg, source, _is_offline = _resolve_structure_with_message(query) - if xyz_str is None: + resolved, _msg = _resolve_structure_with_details(query) + if resolved is None: raise ValueError(_msg) - atoms, coords = parse_xyz_input(xyz_str) - mol = Molecule(atoms=atoms, coordinates=coords) + # Keep the resolver's charge and multiplicity: rebuilt from the + # coordinates alone, an ion or radical loaded as a neutral + # singlet or failed the electron-count check (audit DATA-1). + mol = _molecule_from_resolved(resolved) loop.call_soon_threadsafe( - self._apply_pubchem_search_result, query, mol, None, source + self._apply_pubchem_search_result, + query, + mol, + None, + resolved.source, ) except Exception as exc: loop.call_soon_threadsafe( diff --git a/quantui/pubchem.py b/quantui/pubchem.py index 37eb952c..d5841c42 100644 --- a/quantui/pubchem.py +++ b/quantui/pubchem.py @@ -40,6 +40,20 @@ _last_request_time = 0.0 +def _multiplicity_from_radicals(mol: Any) -> int: + """Spin multiplicity implied by the structure's radical electrons. + + Each unpaired (radical) electron RDKit perceives counts toward a + high-spin multiplicity ``n_unpaired + 1``; a structure with none is a + singlet. Formal charges are carried separately (``charge``). + """ + try: + n = sum(int(a.GetNumRadicalElectrons()) for a in mol.GetAtoms()) + except Exception: # noqa: BLE001 — metadata is best-effort + n = 0 + return n + 1 + + def _throttle() -> None: """Block just long enough to honor the client-side minimum request gap.""" global _last_request_time @@ -425,6 +439,7 @@ def sdf_to_xyz(sdf_content: str) -> Tuple[str, Dict[str, Any]]: "formula": formula, "molecular_weight": Descriptors.MolWt(mol), "charge": Chem.GetFormalCharge(mol), + "multiplicity": _multiplicity_from_radicals(mol), "num_atoms": mol.GetNumAtoms(), "num_heavy_atoms": mol.GetNumHeavyAtoms(), "coords_embedded": coords_embedded, @@ -669,6 +684,7 @@ def smiles_to_xyz(smiles: str, optimize_3d: bool = True) -> Tuple[str, Dict[str, "formula": formula, "molecular_weight": Descriptors.MolWt(mol), "charge": Chem.GetFormalCharge(mol), + "multiplicity": _multiplicity_from_radicals(mol), "num_atoms": mol.GetNumAtoms(), "num_heavy_atoms": mol.GetNumHeavyAtoms(), "smiles": smiles, @@ -726,6 +742,7 @@ def inchi_to_xyz(inchi: str, optimize_3d: bool = True) -> Tuple[str, Dict[str, A "formula": formula, "molecular_weight": Descriptors.MolWt(mol), "charge": Chem.GetFormalCharge(mol), + "multiplicity": _multiplicity_from_radicals(mol), "num_atoms": mol.GetNumAtoms(), "num_heavy_atoms": mol.GetNumHeavyAtoms(), "inchi": inchi, diff --git a/quantui/structure_providers.py b/quantui/structure_providers.py index 68d3faf1..d49b442f 100644 --- a/quantui/structure_providers.py +++ b/quantui/structure_providers.py @@ -77,6 +77,7 @@ def _from_metadata(xyz: str, meta: Dict[str, Any], *, source: str) -> ResolvedSt num_atoms=int(meta.get("num_atoms", 0) or 0), num_heavy_atoms=int(meta.get("num_heavy_atoms", 0) or 0), charge=int(meta.get("charge", 0) or 0), + multiplicity=int(meta.get("multiplicity", 1) or 1), molecular_weight=meta.get("molecular_weight"), conformer_origin=meta.get("conformer_origin", meta.get("source", "")), identifiers=identifiers, @@ -209,19 +210,15 @@ def search_candidates(query: str) -> List[Dict[str, Any]]: return [] -def resolve_structure_with_message( +def resolve_structure_with_details( query: str, -) -> Tuple[Optional[str], str, Optional[str], bool]: - """Chain-backed resolve that also reports provenance. +) -> Tuple[Optional[ResolvedStructure], str]: + """Chain-backed resolve returning the full :class:`ResolvedStructure`. - Returns ``(xyz_or_None, message, source_or_None, is_offline)``. ``source`` - is the raw provider key (``"pubchem"`` / ``"cactus"`` / ``"library"`` / - ``"library-offline-fallback"`` / ``"rdkit-smiles"`` / ``"rdkit-inchi"``) so - the UI can label the loaded molecule by where it *actually* came from - rather than always saying "PubChem". ``is_offline`` is True when the - structure was produced without a network call (local RDKit or the bundled - library) — the UI surfaces a no-network note for the offline *fallback* - (network was attempted and failed). + Returns ``(structure_or_None, message)``. Unlike the XYZ text alone, the + structure carries the resolver's charge and multiplicity, which the + caller must keep: an ion or radical rebuilt from coordinates alone + loads as a neutral singlet, or fails the electron-count check. """ try: result = resolve_structure(query, conformer_3d=True) @@ -235,13 +232,14 @@ def resolve_structure_with_message( f"number, or check spelling.\n" f" Search manually at: https://pubchem.ncbi.nlm.nih.gov/" ), - None, - False, ) except Exception as exc: # pragma: no cover - unexpected logger.error(f"Unexpected error resolving '{query}': {exc}", exc_info=True) - return None, f"❌ Error resolving '{query}': {exc}", None, False + return None, f"❌ Error resolving '{query}': {exc}" + return result, _resolved_message(query, result) + +def _resolved_message(query: str, result: ResolvedStructure) -> str: source_label = { "rdkit-smiles": "generated locally from SMILES", "rdkit-inchi": "generated locally from InChI", @@ -258,12 +256,58 @@ def resolve_structure_with_message( else "" ) mw = f"{result.molecular_weight:.2f} g/mol" if result.molecular_weight else "—" - message = ( + state = "" + if result.charge or result.multiplicity != 1: + state = ( + f"\n Charge {result.charge:+d}, multiplicity {result.multiplicity}" + if result.charge + else f"\n Multiplicity {result.multiplicity}" + ) + return ( f"✓ Resolved '{query}' via {source_label}.\n" f" Formula: {result.formula}\n" f" Atoms: {result.num_atoms} ({result.num_heavy_atoms} heavy)\n" - f" Molecular weight: {mw}{embedded}" + f" Molecular weight: {mw}{embedded}{state}" ) + + +def molecule_from_resolved(result: ResolvedStructure) -> Any: + """A :class:`~quantui.molecule.Molecule` with the resolver's charge and spin. + + The multiplicity comes from the resolver (bundled-library entry, or the + radical electrons RDKit perceives). If it is impossible for the electron + count (a resolver that knows the charge but not the spin), the lowest + consistent multiplicity is used instead: 1 for an even electron count, + 2 for an odd one. + """ + from .molecule import Molecule, parse_xyz_input + + atoms, coords = parse_xyz_input(result.xyz) + charge = int(result.charge) + mult = max(1, int(result.multiplicity)) + n_electrons = config.electron_count(atoms, charge) + if (n_electrons - (mult - 1)) % 2 != 0 or mult - 1 > n_electrons: + mult = 2 if n_electrons % 2 else 1 + return Molecule(atoms=atoms, coordinates=coords, charge=charge, multiplicity=mult) + + +def resolve_structure_with_message( + query: str, +) -> Tuple[Optional[str], str, Optional[str], bool]: + """Chain-backed resolve that also reports provenance. + + Returns ``(xyz_or_None, message, source_or_None, is_offline)``. ``source`` + is the raw provider key (``"pubchem"`` / ``"cactus"`` / ``"library"`` / + ``"library-offline-fallback"`` / ``"rdkit-smiles"`` / ``"rdkit-inchi"``) so + the UI can label the loaded molecule by where it *actually* came from + rather than always saying "PubChem". ``is_offline`` is True when the + structure was produced without a network call (local RDKit or the bundled + library) — the UI surfaces a no-network note for the offline *fallback* + (network was attempted and failed). + """ + result, message = resolve_structure_with_details(query) + if result is None: + return None, message, None, False return result.xyz, message, result.source, result.is_offline diff --git a/tests/test_search_charge_multiplicity.py b/tests/test_search_charge_multiplicity.py new file mode 100644 index 00000000..a50d0d50 --- /dev/null +++ b/tests/test_search_charge_multiplicity.py @@ -0,0 +1,71 @@ +"""Structure search keeps the resolver's charge and multiplicity (audit DATA-1). + +The search handler used to rebuild the molecule from the XYZ text alone, so +ions and radicals loaded as neutral singlets (even electron counts) or failed +as "Not found" (odd electron counts). +""" + +from __future__ import annotations + +from unittest.mock import patch + +import pytest + +pytest.importorskip("rdkit") + +import requests # noqa: E402 + +from quantui.app import QuantUIApp # noqa: E402 +from quantui.structure_providers import ( # noqa: E402 + ResolvedStructure, + molecule_from_resolved, + resolve_structure_with_details, +) + + +class _ImmediateLoop: + def call_soon_threadsafe(self, fn, *args): + fn(*args) + + +@pytest.fixture(autouse=True) +def _offline(): + with patch("requests.get", side_effect=requests.ConnectionError("offline")): + yield + + +@pytest.mark.parametrize( + "query, charge, mult", + [ + ("[NH4+]", 1, 1), + ("[OH-]", -1, 1), + ("[O-]S(=O)(=O)[O-]", -2, 1), + ("[CH3]", 0, 2), + ("O2", 0, 3), # bundled library entry: triplet oxygen + ], +) +def test_search_loads_the_resolved_charge_and_multiplicity(query, charge, mult): + app = QuantUIApp() + app._resolve_and_apply(query, _ImmediateLoop()) + mol = app._molecule + assert mol is not None, app.pubchem_msg.value + assert (mol.charge, mol.multiplicity) == (charge, mult) + assert (app.charge_si.value, app.mult_si.value) == (charge, mult) + + +def test_resolved_message_states_a_non_default_charge(): + result, message = resolve_structure_with_details("[NH4+]") + assert result is not None and result.charge == 1 + assert "Charge +1" in message + + +def test_impossible_resolver_spin_falls_back_to_a_consistent_one(): + # A resolver that knows the charge but reports no radical: NH4 neutral + # has 11 electrons, so multiplicity 1 is impossible -> doublet. + xyz = ( + "5\n\nN 0 0 0\nH 0.6 0.6 0.6\nH -0.6 -0.6 0.6\nH -0.6 0.6 -0.6\nH 0.6 -0.6 -0.6" + ) + mol = molecule_from_resolved( + ResolvedStructure(xyz=xyz, source="pubchem", charge=0, multiplicity=1) + ) + assert (mol.charge, mol.multiplicity) == (0, 2) From e174102bd446252db68fca46c5ec2210526ec001 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 03:56:58 +0000 Subject: [PATCH 5/8] Frequency resume: never reuse displacements from another geometry (audit APP-1) Banked IR dipoles and Raman polarizabilities were keyed only by (atom, axis, sign). The app's resume key is built from the input molecule, but the finite differences are taken around the geometry actually used: after an optional pre-optimization, a seed, or a mode displacement. Cancel a Frequency run, tick "Geometry optimization before calculation", Run again with Resume (ticked by default): the old geometry's dipoles were spliced into the new derivative and the result saved as normal (water: 12632 / 22014 / 17598 km/mol instead of 7 / 44 / 30). Changing density fitting had the same effect. The item set is now named "_displacements-", the digest covering the reference geometry (Bohr, 1e-6), atoms, charge, spin, basis, ECP, functional, density fitting, solvent, step size and restricted/unrestricted. Results banked for anything else are not found, so those displacements are recomputed; an unchanged resume still reuses them. Parallel workers get the directory from the parent, unchanged. New test resumes at a moved geometry and compares with a clean run; it fails on the old code. Existing checkpoint tests find the set by prefix. 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 | 13 ++++++- quantui/freq_displacement_ids.py | 51 +++++++++++++++++++++++- quantui/raman_calc.py | 14 ++++++- tests/test_freq_calc.py | 66 +++++++++++++++++++++++++++----- tests/test_raman_calc.py | 15 +++++++- 5 files changed, 145 insertions(+), 14 deletions(-) diff --git a/quantui/freq_calc.py b/quantui/freq_calc.py index 4cc0c488..013282c6 100644 --- a/quantui/freq_calc.py +++ b/quantui/freq_calc.py @@ -800,6 +800,7 @@ def _status(msg: str) -> None: from .config import BOHR_TO_ANGSTROM as _BOHR_TO_ANG from .freq_displacement_ids import ( displacement_id, + displacement_set_name, parse_displacement_id, ) @@ -835,7 +836,17 @@ def _status(msg: str) -> None: # assembly step itself a proper gate: it only runs # once every required id is present here, regardless of how # it got there. - _ITEM_SET_NAME = "freq_displacements" + # Named for this reference geometry and SCF setup, so a + # resume never reuses dipoles displaced from anything else. + _ITEM_SET_NAME = displacement_set_name( + "freq_displacements", + mol, + xc=_xc, + density_fit=_density_fit_used, + solvent=_pcm_solvent, + delta_bohr=_DELTA, + unrestricted=_dm0_is_unrestricted, + ) _dipoles: dict = {} if checkpoint is not None and resume: for _item_id, _payload in checkpoint.completed_items( diff --git a/quantui/freq_displacement_ids.py b/quantui/freq_displacement_ids.py index 61a52764..3fb50eba 100644 --- a/quantui/freq_displacement_ids.py +++ b/quantui/freq_displacement_ids.py @@ -20,7 +20,9 @@ from __future__ import annotations -from typing import List, Tuple +import hashlib +import json +from typing import Any, List, Optional, Tuple _AXIS_LABELS = ("x", "y", "z") _SIGN_LABELS = {1: "+", -1: "-"} @@ -76,3 +78,50 @@ def required_displacement_ids(n_atoms: int) -> List[str]: ids.append(displacement_id(atom_index, axis, 1)) ids.append(displacement_id(atom_index, axis, -1)) return ids + + +def displacement_set_name( + prefix: str, + mol: Any, + *, + xc: Optional[str], + density_fit: bool, + solvent: Optional[str], + delta_bohr: float, + unrestricted: bool, +) -> str: + """Checkpoint item-set name for one reference geometry and setup. + + The ids above say *which* displacement a banked result is, not *what it + was displaced from*. A resumed Frequency run whose reference geometry + changed (pre-optimization ticked on the second attempt, a different + seed or mode displacement) or whose SCF setup changed (density fitting, + functional, solvent) used to splice the old geometry's dipoles into the + new finite difference, giving wrong IR intensities with no warning. The + set name now carries a digest of everything a displaced SCF depends on, + so results banked for anything else are simply not found. + + *mol* is the PySCF ``Mole`` of the reference SCF. + """ + coords = [ + [round(float(v), 6) + 0.0 for v in row] for row in mol.atom_coords().tolist() + ] + basis = mol.basis if isinstance(mol.basis, str) else repr(mol.basis) + ecp = mol.ecp if isinstance(mol.ecp, str) else repr(sorted(dict(mol.ecp or {}))) + key = { + "atoms": [mol.atom_symbol(i) for i in range(mol.natm)], + "coords_bohr": coords, + "charge": int(mol.charge), + "spin": int(mol.spin), + "basis": basis, + "ecp": ecp, + "xc": xc, + "density_fit": bool(density_fit), + "solvent": solvent, + "delta_bohr": float(delta_bohr), + "unrestricted": bool(unrestricted), + } + digest = hashlib.sha256( + json.dumps(key, sort_keys=True, default=str).encode("utf-8") + ).hexdigest()[:16] + return f"{prefix}-{digest}" diff --git a/quantui/raman_calc.py b/quantui/raman_calc.py index b30aa828..98ef0653 100644 --- a/quantui/raman_calc.py +++ b/quantui/raman_calc.py @@ -176,8 +176,20 @@ def _cpu_raman_activities_fd( ) from quantui.gpu_offload import try_to_gpu as _try_to_gpu_inner - _ITEM_SET_NAME = "raman_displacements" _xc = getattr(mf, "xc", None) + # Named for this reference geometry and SCF setup, so a resume never + # reuses polarizabilities displaced from anything else. + from quantui.freq_displacement_ids import displacement_set_name + + _ITEM_SET_NAME = displacement_set_name( + "raman_displacements", + mol, + xc=_xc, + density_fit=density_fit_used, + solvent=None, # Raman is skipped for solvated runs + delta_bohr=_DELTA_BOHR, + unrestricted=dm0_is_unrestricted, + ) _n_atoms = mol.natm _coords0 = mol.atom_coords().copy() _total = _n_atoms * 3 * 2 diff --git a/tests/test_freq_calc.py b/tests/test_freq_calc.py index fe958d12..28462b2e 100644 --- a/tests/test_freq_calc.py +++ b/tests/test_freq_calc.py @@ -78,6 +78,17 @@ def _water(): # ============================================================================ +def _item_set(ckpt, prefix): + """The one item set named ``-`` in *ckpt*.""" + names = [ + p.name + for p in (ckpt.dir / "items").iterdir() + if p.name.startswith(prefix + "-") + ] + assert len(names) == 1, names + return names[0] + + class TestThermoData: def test_fields_stored(self): td = _make_thermo() @@ -797,7 +808,7 @@ def test_every_displacement_is_recorded(self, tmp_path, monkeypatch): ckpt = self._checkpoint(tmp_path, molecule) run_freq_calc(molecule, method="RHF", basis="STO-3G", checkpoint=ckpt) # 3 atoms x 3 axes x 2 signs = 18. - assert len(ckpt.completed_item_ids("freq_displacements")) == 18 + assert len(ckpt.completed_item_ids(_item_set(ckpt, "freq_displacements"))) == 18 def test_successful_run_marks_the_checkpoint_complete(self, tmp_path, monkeypatch): """A successful frequency run must not linger forever in the @@ -861,15 +872,17 @@ def test_partial_resume_recomputes_only_the_missing_displacements( molecule, method="RHF", basis="STO-3G", checkpoint=ckpt ) all_ids = required_displacement_ids(3) - assert ckpt.completed_item_ids("freq_displacements") == set(all_ids) + assert ckpt.completed_item_ids(_item_set(ckpt, "freq_displacements")) == set( + all_ids + ) # Simulate an interrupted run: keep only the first 3 banked. keep = set(all_ids[:3]) - items_dir = ckpt.items_dir("freq_displacements") + items_dir = ckpt.items_dir(_item_set(ckpt, "freq_displacements")) for item_id in all_ids: if item_id not in keep: (items_dir / f"{item_id}.json").unlink() - assert ckpt.completed_item_ids("freq_displacements") == keep + assert ckpt.completed_item_ids(_item_set(ckpt, "freq_displacements")) == keep ckpt.begin() # a real resubmission calls .begin() again — must not erase items calls = self._count_rescue_calls(monkeypatch) @@ -878,11 +891,42 @@ def test_partial_resume_recomputes_only_the_missing_displacements( ) # reference SCF + the 15 displacements that were NOT kept. assert len(calls) == 1 + (len(all_ids) - len(keep)) - assert ckpt.completed_item_ids("freq_displacements") == set(all_ids) + assert ckpt.completed_item_ids(_item_set(ckpt, "freq_displacements")) == set( + all_ids + ) assert resumed.ir_intensities == pytest.approx( baseline.ir_intensities, abs=1e-6 ) + @pyscf_only + def test_resume_at_a_different_geometry_does_not_reuse_dipoles( + self, tmp_path, monkeypatch + ): + """Audit APP-1: the app's resume key is the *input* geometry, but the + displacements are taken around the geometry actually used (after an + optional pre-optimization or seed). Resuming after that changed used + to splice the old geometry's dipoles into the new finite difference + (water: IR 12632 / 22014 / 17598 km/mol instead of 7 / 44 / 30).""" + from quantui.freq_calc import run_freq_calc + from quantui.molecule import Molecule + + monkeypatch.setenv("QUANTUI_RAMAN", "0") + monkeypatch.setenv("QUANTUI_FREQ_PARALLEL", "0") + start = _water() + ckpt = self._checkpoint(tmp_path, start) + run_freq_calc(start, method="RHF", basis="STO-3G", checkpoint=ckpt) + + moved = Molecule( + start.atoms, + [[0.0, 0.0, 0.0], [0.80, 0.62, 0.0], [-0.80, 0.62, 0.0]], + ) + clean = run_freq_calc(moved, method="RHF", basis="STO-3G") + ckpt.begin() + resumed = run_freq_calc( + moved, method="RHF", basis="STO-3G", checkpoint=ckpt, resume=True + ) + assert resumed.ir_intensities == pytest.approx(clean.ir_intensities, abs=1e-6) + def test_resume_false_ignores_a_populated_checkpoint(self, tmp_path, monkeypatch): """resume=False must behave like no checkpoint was ever passed for *reading* progress — even though the run still writes into it, so a @@ -895,7 +939,7 @@ def test_resume_false_ignores_a_populated_checkpoint(self, tmp_path, monkeypatch molecule = _water() ckpt = self._checkpoint(tmp_path, molecule) run_freq_calc(molecule, method="RHF", basis="STO-3G", checkpoint=ckpt) - assert len(ckpt.completed_item_ids("freq_displacements")) == 18 + assert len(ckpt.completed_item_ids(_item_set(ckpt, "freq_displacements"))) == 18 ckpt.begin() calls = self._count_rescue_calls(monkeypatch) @@ -920,10 +964,12 @@ def test_a_corrupt_banked_item_is_recomputed_not_trusted( run_freq_calc(molecule, method="RHF", basis="STO-3G", checkpoint=ckpt) all_ids = required_displacement_ids(3) - items_dir = ckpt.items_dir("freq_displacements") + items_dir = ckpt.items_dir(_item_set(ckpt, "freq_displacements")) corrupt_id = all_ids[0] (items_dir / f"{corrupt_id}.json").write_text("{not json", encoding="utf-8") - assert corrupt_id not in ckpt.completed_item_ids("freq_displacements") + assert corrupt_id not in ckpt.completed_item_ids( + _item_set(ckpt, "freq_displacements") + ) ckpt.begin() calls = self._count_rescue_calls(monkeypatch) @@ -933,7 +979,9 @@ def test_a_corrupt_banked_item_is_recomputed_not_trusted( # reference SCF + the one corrupted (and therefore recomputed) displacement. assert len(calls) == 2 assert resumed.ir_intensities, "must still produce a usable result" - assert corrupt_id in ckpt.completed_item_ids("freq_displacements") + assert corrupt_id in ckpt.completed_item_ids( + _item_set(ckpt, "freq_displacements") + ) if __name__ == "__main__": diff --git a/tests/test_raman_calc.py b/tests/test_raman_calc.py index fc6cba15..11bd794e 100644 --- a/tests/test_raman_calc.py +++ b/tests/test_raman_calc.py @@ -13,6 +13,17 @@ ) +def _item_set(ckpt, prefix): + """The one item set named ``-`` in *ckpt*.""" + names = [ + p.name + for p in (ckpt.dir / "items").iterdir() + if p.name.startswith(prefix + "-") + ] + assert len(names) == 1, names + return names[0] + + class TestRamanInvariants: def test_isotropic_mode_gives_45_alpha_bar_squared(self): # ∂α/∂Q proportional to identity → γ² = 0 @@ -375,8 +386,8 @@ def test_raman_displacements_recorded_under_their_own_item_set( ckpt = self._checkpoint(tmp_path, molecule) run_freq_calc(molecule, method="RHF", basis="STO-3G", checkpoint=ckpt) - ir_ids = ckpt.completed_item_ids("freq_displacements") - raman_ids = ckpt.completed_item_ids("raman_displacements") + ir_ids = ckpt.completed_item_ids(_item_set(ckpt, "freq_displacements")) + raman_ids = ckpt.completed_item_ids(_item_set(ckpt, "raman_displacements")) assert len(ir_ids) == 18 assert len(raman_ids) == 18 # Same displacement grid, but the two sets never collide — reading From 6404d2e2deb3edac6b7eec4ee6fb7cefeb045823 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 03:59:56 +0000 Subject: [PATCH 6/8] Treat a results folder as data, not page code (audit VIZ-1) The Viewer opens other people's result folders and zips, and History replays from disk; three paths pasted folder content into the page, which has a live kernel connection: - Cached vibrational-animation HTML (vib_frames/mode_NNN.html) was served verbatim, and index.json's "file" was joined unchecked ("../x.html" or an absolute path was read). Each entry now carries an HMAC-SHA256 of the HTML under a per-user key (vib_cache.key next to the settings file, created 0600); a file is served only if its name is a plain mode_NNN.html and the MAC verifies. Foreign, altered and older caches are misses and get re-rendered. - The saved HOMO/LUMO cube's index "file" was joined unchecked, and cube text was embedded in a " intact. The file must now be a plain name, and every value pasted into an inline script in the viewer builders goes through viz_assets.script_json(), which escapes "; label escaping). 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/app_visualization.py | 38 ++++----- quantui/orbital_visualization.py | 38 +++++---- quantui/symmetry.py | 18 ++-- quantui/vib_cache.py | 88 ++++++++++++++++++-- quantui/visualization_py3dmol.py | 4 +- quantui/viz_assets.py | 13 +++ tests/test_results_folder_trust.py | 129 +++++++++++++++++++++++++++++ 7 files changed, 274 insertions(+), 54 deletions(-) create mode 100644 tests/test_results_folder_trust.py diff --git a/quantui/app_visualization.py b/quantui/app_visualization.py index 5a838fca..d1d4444f 100644 --- a/quantui/app_visualization.py +++ b/quantui/app_visualization.py @@ -25,6 +25,7 @@ from quantui.orbital_visualization import _GENERIC_CAPTURE_JS, _png_capture_controls from quantui.symmetry import html_irrep from quantui.viz_assets import orient_js, orient_view +from quantui.viz_assets import script_json as _script_json logger = logging.getLogger(__name__) @@ -3116,11 +3117,10 @@ def iso_bridge_update(app: Any, **opts: Any) -> None: bridge = getattr(app, "_iso_js_bridge", None) if bridge is None: return - import json from IPython.display import Javascript, display - payload = json.dumps(opts) + payload = _script_json(opts) # Retry-until-present mirrors _vib_bridge_set_mode: at the moment a slider # fires, the viewer may still be loading its async 3Dmol bundle. js = ( @@ -3446,7 +3446,6 @@ def _frame_stepper_controls( (e.g. per-frame energy arrays). ``loop`` makes Play cycle forever, else it runs once and stops on the last frame. """ - import json btn = _STEPPER_BTN_STYLE start = (n - 1) if start_index is None else start_index @@ -3483,8 +3482,8 @@ def _frame_stepper_controls( .replace("__IV__", str(interval_ms)) .replace("__LOOP__", "1" if loop else "0") .replace("__START__", str(start)) - .replace("__AB_START__", json.dumps(ab_at_start or "")) - .replace("__AB_OTHER__", json.dumps(ab_other or "")) + .replace("__AB_START__", _script_json(ab_at_start or "")) + .replace("__AB_OTHER__", _script_json(ab_other or "")) .replace("__EXTRA__", extra_decls) .replace("__LABEL_BODY__", label_js) ) @@ -3520,7 +3519,6 @@ def build_reorg_geometry_viewer_html( the isosurface viewer's capture bridge but with a uid-scoped capture function — see ``_GENERIC_CAPTURE_JS``. Empty omits the button. """ - import json import re from quantui.viz_assets import make_view @@ -3549,7 +3547,7 @@ def build_reorg_geometry_viewer_html( return _theme.frame_viewer_html(view_html, width=width) uid = m.group(1) - slugs = json.dumps( + slugs = _script_json( [ g.get("label", f"geometry_{i + 1}").split(" — ")[0] for i, g in enumerate(geometries) @@ -3561,7 +3559,7 @@ def build_reorg_geometry_viewer_html( capture_js = ( _GENERIC_CAPTURE_JS.replace("__UID__", uid) .replace("__CAPFN__", capture_fn) - .replace("__BG__", json.dumps(bgcolor)) + .replace("__BG__", _script_json(bgcolor)) ) bridge_js = ( _REORG_PNG_BRIDGE_JS.replace("__UID__", uid) @@ -3583,10 +3581,10 @@ def build_reorg_geometry_viewer_html( if len(geometries) < 2: return _theme.frame_viewer_html(view_html, width=width) - labels = json.dumps( + labels = _script_json( [g.get("label", f"Geometry {i + 1}") for i, g in enumerate(geometries)] ) - notes = json.dumps([g.get("note", "") for g in geometries]) + notes = _script_json([g.get("note", "") for g in geometries]) controls = _frame_stepper_controls( uid, len(geometries), @@ -3826,7 +3824,6 @@ def build_trajectory_viewer_html( displayed in it — nothing trajectory-specific needed). Empty omits the button. """ - import json import re from quantui.viz_assets import make_view @@ -3850,7 +3847,7 @@ def build_trajectory_viewer_html( capture_js = ( _GENERIC_CAPTURE_JS.replace("__UID__", uid) .replace("__CAPFN__", capture_fn) - .replace("__BG__", json.dumps(bgcolor)) + .replace("__BG__", _script_json(bgcolor)) ) view_html = ( view_html @@ -3864,9 +3861,9 @@ def build_trajectory_viewer_html( return _theme.frame_viewer_html(view_html, width=width) interval_ms = max(1, int(round(1000.0 / max(1, fps)))) - eabs = json.dumps([float(e) for e in energies]) if energies else "null" - erel = json.dumps([float(e) for e in rel_e]) if rel_e else "null" - fjs = json.dumps(formula or "") + eabs = _script_json([float(e) for e in energies]) if energies else "null" + erel = _script_json([float(e) for e in rel_e]) if rel_e else "null" + fjs = _script_json(formula or "") label_js = ( 'var s="Step "+i+" / "+(N-1);' f'if({fjs}) s+=" \\u00b7 "+{fjs};' @@ -4022,7 +4019,6 @@ def build_vib_viewer_html( equivalent client-side capture global, same reasoning as the main molecule viewer. """ - import json import re import numpy as np @@ -4056,14 +4052,14 @@ def build_vib_viewer_html( interval_ms = max(1, int(round(1000.0 / max(1, fps)))) js = ( _VIB_VIEWER_JS.replace("__UID__", uid) - .replace("__SYM__", json.dumps(atoms)) - .replace("__BASE__", json.dumps(base.tolist())) - .replace("__DISPL__", json.dumps(displ_map)) + .replace("__SYM__", _script_json(atoms)) + .replace("__BASE__", _script_json(base.tolist())) + .replace("__DISPL__", _script_json(displ_map)) .replace("__NAT__", str(n_atoms)) .replace("__NF__", str(int(n_frames))) .replace("__AMP__", repr(float(amplitude))) .replace("__IV__", str(interval_ms)) - .replace("__BG__", json.dumps(bgcolor)) + .replace("__BG__", _script_json(bgcolor)) .replace("__INIT__", str(int(initial_mode))) .replace("__ARROWS__", "true" if arrows else "false") .replace("__ORIENT__", orient_js("v", base)) @@ -4074,7 +4070,7 @@ def build_vib_viewer_html( capture_js = ( _GENERIC_CAPTURE_JS.replace("__UID__", uid) .replace("__CAPFN__", capture_fn) - .replace("__BG__", json.dumps(bgcolor)) + .replace("__BG__", _script_json(bgcolor)) ) body = ( body diff --git a/quantui/orbital_visualization.py b/quantui/orbital_visualization.py index 617fd809..49859f79 100644 --- a/quantui/orbital_visualization.py +++ b/quantui/orbital_visualization.py @@ -25,6 +25,7 @@ import numpy as np from quantui import theme as _theme +from quantui.viz_assets import script_json as _script_json logger = logging.getLogger(__name__) @@ -1801,7 +1802,6 @@ def _build_iso_viewer( voldata_text: Optional[str] = None, vol_range: float = 0.05, ) -> str: - import json from quantui.viz_assets import coords_from_model_text, make_view, orient_js @@ -1818,19 +1818,19 @@ def _build_iso_viewer( js = ( _ISO_VIEWER_JS.replace("__UID__", uid) - .replace("__DATA__", json.dumps(data_text)) - .replace("__FMT__", json.dumps(data_format)) + .replace("__DATA__", _script_json(data_text)) + .replace("__FMT__", _script_json(data_format)) .replace("__WITH_SURFACES__", "true" if with_surfaces else "false") - .replace("__SCENE__", json.dumps(scene_key)) + .replace("__SCENE__", _script_json(scene_key)) .replace("__ISO__", repr(float(isovalue))) .replace("__OP__", repr(float(opacity))) .replace("__WF__", "true" if wireframe else "false") - .replace("__POS__", json.dumps(pos_color)) - .replace("__NEG__", json.dumps(neg_color)) - .replace("__BG__", json.dumps(bgcolor)) + .replace("__POS__", _script_json(pos_color)) + .replace("__NEG__", _script_json(neg_color)) + .replace("__BG__", _script_json(bgcolor)) .replace("__STYLE__", style) - .replace("__MODE__", json.dumps(mode)) - .replace("__VOL__", json.dumps(voldata_text)) + .replace("__MODE__", _script_json(mode)) + .replace("__VOL__", _script_json(voldata_text)) .replace("__RANGE__", repr(float(vol_range))) .replace( "__ORIENT__", @@ -2299,7 +2299,6 @@ def build_orbital_gallery_html( even split), at most four. """ import html as _html - import json import uuid from quantui.viz_assets import coords_from_model_text, make_view, orient_js @@ -2327,17 +2326,17 @@ def build_orbital_gallery_html( f'
' + _GALLERY_VIEWER_JS.replace("__UID__", uid).replace( - "__BG__", json.dumps(bgcolor) + "__BG__", _script_json(bgcolor) ) ) js = ( _GALLERY_TILE_JS.replace("__UID__", uid) .replace("__GROUP__", group) - .replace("__DATA__", json.dumps(tile.cube_text)) + .replace("__DATA__", _script_json(tile.cube_text)) .replace("__ISO__", repr(float(isovalue))) - .replace("__POS__", json.dumps(pos)) - .replace("__NEG__", json.dumps(neg)) - .replace("__BG__", json.dumps(bgcolor)) + .replace("__POS__", _script_json(pos)) + .replace("__NEG__", _script_json(neg)) + .replace("__BG__", _script_json(bgcolor)) .replace( "__ORIENT__", orient_js("vw", coords_from_model_text(tile.cube_text, "cube")), @@ -2488,10 +2487,13 @@ def load_frontier_cube( continue if entry.get("spin", "") not in spins: continue + name = str(entry.get("file", "")) + if not name or Path(name).name != name or name in (".", ".."): + # index.json comes with the results folder; a path in it must + # not reach outside frontier_cubes/. + return False try: - raw = ( - Path(result_dir) / FRONTIER_CUBES_DIR / str(entry["file"]) - ).read_bytes() + raw = (Path(result_dir) / FRONTIER_CUBES_DIR / name).read_bytes() Path(dest).write_text(gzip.decompress(raw).decode()) except (OSError, KeyError, ValueError): return False diff --git a/quantui/symmetry.py b/quantui/symmetry.py index 1361ff74..09f170ba 100644 --- a/quantui/symmetry.py +++ b/quantui/symmetry.py @@ -29,6 +29,7 @@ from __future__ import annotations +import html as _html import logging import re import threading @@ -140,7 +141,8 @@ def pretty_group(name: str) -> str: def html_group(name: str) -> str: """Schoenflies symbol with the subscript as HTML (``C2v``).""" - pretty = pretty_group(name) + # Escaped: the name can come from a saved result.json. + pretty = _html.escape(pretty_group(name)) if len(pretty) <= 1 or pretty.startswith("SO"): return pretty return f"{pretty[0]}{pretty[1:]}" @@ -694,13 +696,19 @@ def html_irrep(label: str) -> str: Primes (Cs) and ⁺/⁻ (Σ) follow the subscript; joined labels (``"b1+b2"``) are rendered per part. """ + # Labels come from saved results (a shared results folder too), so + # every piece is escaped; only the tags added here are markup. out = [] for part in label.split("+"): - m = re.fullmatch(r"(.)([0-9gu]*)(.*)", part) + m = re.fullmatch(r"(.)([0-9gu]*)(.*)", part, flags=re.DOTALL) if not m: - return label + return _html.escape(label) head, sub, rest = m.groups() - out.append(head + (f"{sub}" if sub else "") + rest) + out.append( + _html.escape(head) + + (f"{sub}" if sub else "") + + _html.escape(rest) + ) return "+".join(out) @@ -708,7 +716,7 @@ def html_gamma(gamma: str) -> str: """``"2A1 + 2E"`` with HTML subscripts.""" terms = [] for term in gamma.split(" + "): - m = re.fullmatch(r"(\d*)(\(?)(.*?)(\)?)", term) + m = re.fullmatch(r"(\d*)(\(?)(.*?)(\)?)", term, flags=re.DOTALL) count, lp, body, rp = m.groups() if m else ("", "", term, "") terms.append(f"{count}{lp}{html_irrep(body)}{rp}") return " + ".join(terms) diff --git a/quantui/vib_cache.py b/quantui/vib_cache.py index 2af574a7..781ca361 100644 --- a/quantui/vib_cache.py +++ b/quantui/vib_cache.py @@ -35,6 +35,16 @@ parameter changes between save and read (e.g. user customises amplitude later), the cache is treated as stale and a miss is returned. +Trust +----- +A result directory can come from someone else (a shared folder, a zip opened +in the Viewer), and a cached file is pasted into the page as HTML. So each +entry carries ``"mac"``: an HMAC-SHA256 of the HTML under a per-user secret +(``vib_cache.key`` next to the settings file, created 0600 on first use). +A cached file is served only when its name is a plain ``mode_NNN.html`` in +``vib_frames/`` and the MAC verifies; anything else, including every cache +written by another user or an older QuantUI, is a miss and is re-rendered. + Robustness ---------- - Atomic writes (write-to-`.tmp` then `os.replace`) so a crash mid-write @@ -48,11 +58,15 @@ from __future__ import annotations +import hashlib +import hmac import json import logging import os +import re +import secrets from pathlib import Path -from typing import cast +from typing import Optional, cast _SCHEMA_VERSION = 1 _LOG = logging.getLogger(__name__) @@ -62,6 +76,55 @@ _AMPLITUDE_TOL = 1e-6 +_FILE_RE = re.compile(r"mode_\d{3,}\.html") +_KEY_BYTES = 32 + + +def _key_path() -> Path: + from .user_settings import UserSettings + + return UserSettings._resolve_path(None).parent / "vib_cache.key" + + +def _cache_key() -> Optional[bytes]: + """This user's secret for signing cached HTML (created on first use).""" + path = _key_path() + try: + key = path.read_bytes() + if len(key) == _KEY_BYTES: + return key + except OSError: + pass + try: + path.parent.mkdir(parents=True, exist_ok=True) + key = secrets.token_bytes(_KEY_BYTES) + tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp") + fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "wb") as fh: + fh.write(key) + os.replace(tmp, path) + # Another process may have won the race; use what is on disk. + key = path.read_bytes() + return key if len(key) == _KEY_BYTES else None + except OSError as exc: + _LOG.warning("No vib cache key at %s (%s); cache disabled", path, exc) + return None + + +def _mac(html: str) -> Optional[str]: + key = _cache_key() + if key is None: + return None + return hmac.new(key, html.encode("utf-8"), hashlib.sha256).hexdigest() + + +def _safe_file_name(fname: object) -> Optional[str]: + """*fname* if it is a plain ``mode_NNN.html`` name, else ``None``.""" + if isinstance(fname, str) and _FILE_RE.fullmatch(fname): + return fname + return None + + def cache_dir(result_dir: Path) -> Path: """Return the `vib_frames/` directory inside a result directory.""" return Path(result_dir) / "vib_frames" @@ -109,8 +172,8 @@ def has_cached( entry = modes.get(str(mode_number)) if not isinstance(entry, dict) or not entry.get("cached"): return False - fname = entry.get("file") - if not isinstance(fname, str): + fname = _safe_file_name(entry.get("file")) + if fname is None or not isinstance(entry.get("mac"), str): return False return (cache_dir(result_dir) / fname).exists() @@ -136,12 +199,10 @@ def get_cached_html( return None idx = load_index(result_dir) entry = idx["modes"][str(mode_number)] - html_path = cache_dir(result_dir) / entry["file"] + fname = cast(str, _safe_file_name(entry.get("file"))) + html_path = cache_dir(result_dir) / fname try: - # html_path is Any: load_index()'s bare `dict` return (untyped JSON) - # propagates through entry["file"] and the / operator. read_text() - # genuinely returns str; the cast documents that, not a runtime check. - return cast(str, html_path.read_text(encoding="utf-8")) + html = html_path.read_text(encoding="utf-8") except OSError as exc: _LOG.warning( "Failed to read cached html at %s (%s)", @@ -149,6 +210,13 @@ def get_cached_html( exc, ) return None + expected = _mac(html) + if expected is None or not hmac.compare_digest(expected, str(entry["mac"])): + # Not written by this user (or altered since): never paste it into + # the page. The caller re-renders from the result's data instead. + _LOG.info("Ignoring unsigned or foreign vib cache file %s", html_path) + return None + return html def save_cached_html( @@ -216,10 +284,14 @@ def save_cached_html( 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, } diff --git a/quantui/visualization_py3dmol.py b/quantui/visualization_py3dmol.py index 64dbc28a..6ba31b0f 100644 --- a/quantui/visualization_py3dmol.py +++ b/quantui/visualization_py3dmol.py @@ -15,6 +15,7 @@ from typing import Literal, Sequence, cast from quantui import theme as _theme +from quantui.viz_assets import script_json as _script_json logger = logging.getLogger(__name__) @@ -635,7 +636,6 @@ class in the whole page, not scoped to which button was clicked). if callable(make_html): view_html = viz._make_html() if capture_class: - import json import re from quantui.orbital_visualization import ( @@ -650,7 +650,7 @@ class in the whole page, not scoped to which button was clicked). capture_js = ( _GENERIC_CAPTURE_JS.replace("__UID__", uid) .replace("__CAPFN__", capture_fn) - .replace("__BG__", json.dumps(bgcolor)) + .replace("__BG__", _script_json(bgcolor)) ) view_html = ( view_html diff --git a/quantui/viz_assets.py b/quantui/viz_assets.py index 34dbe428..8a824172 100644 --- a/quantui/viz_assets.py +++ b/quantui/viz_assets.py @@ -223,3 +223,16 @@ def plotly_camera(coords: Any, distance: float = 1.8) -> Optional[dict]: "eye": {k: float(v) * distance for k, v in zip("xyz", toward)}, "up": {k: float(v) for k, v in zip("xyz", up)}, } + + +def script_json(value: object) -> str: + """``json.dumps(value)`` safe to paste inside an inline ```` and ``