diff --git a/.claude/hooks/session-start.sh b/.claude/hooks/session-start.sh index b277e500..a3492c58 100755 --- a/.claude/hooks/session-start.sh +++ b/.claude/hooks/session-start.sh @@ -16,15 +16,50 @@ fi cd "${CLAUDE_PROJECT_DIR:-$(dirname "$0")/../..}" +# QuantUI supports Python 3.9-3.11 only; on 3.12+ the install fails +# (pyscf-properties does not build). The cloud image's default `python` can be +# newer (3.13 at the time of audit INFRA-11), which left sessions with nothing +# installed. In that case build a 3.11 venv in .venv (uv preferred, else a +# system python3.11) and install there instead. +PY="python" +_supported() { + "$1" -c 'import sys; sys.exit(0 if (3, 9) <= sys.version_info[:2] <= (3, 11) else 1)' \ + >/dev/null 2>&1 +} +if ! _supported "$PY"; then + if [ -x .venv/bin/python ] && _supported .venv/bin/python; then + echo "Reusing existing .venv ($(.venv/bin/python --version 2>&1))." >&2 + elif command -v uv >/dev/null 2>&1; then + echo "Default python is outside 3.9-3.11; creating .venv with uv (3.11)." >&2 + # --seed puts pip into the venv so the `-m pip` calls below work unchanged. + uv venv --seed -p python3.11 .venv + elif command -v python3.11 >/dev/null 2>&1; then + echo "Default python is outside 3.9-3.11; creating .venv with python3.11." >&2 + python3.11 -m venv .venv + else + echo "WARNING: default python is outside 3.9-3.11 and neither uv nor python3.11 is available; the install below will probably fail." >&2 + fi + if [ -x .venv/bin/python ] && _supported .venv/bin/python; then + PY="$PWD/.venv/bin/python" + # Make the venv the session's interpreter for every later Bash call. + if [ -n "${CLAUDE_ENV_FILE:-}" ]; then + { + echo "export VIRTUAL_ENV=\"$PWD/.venv\"" + echo "export PATH=\"$PWD/.venv/bin:\$PATH\"" + } >> "$CLAUDE_ENV_FILE" + fi + fi +fi + # Best-effort: a newer pip resolves faster, but some base images ship a # distro-managed pip that can't self-upgrade — don't let that abort setup. -python -m pip install --upgrade pip || true +"$PY" -m pip install --upgrade pip || true # Ensure a modern setuptools/wheel. Some base images ship a distro-patched # setuptools that breaks source builds of pyscf-properties with # "AttributeError: install_layout". --ignore-installed sidesteps the # distro-managed copy (which has no RECORD and so can't be uninstalled). -python -m pip install --upgrade --ignore-installed setuptools wheel || true +"$PY" -m pip install --upgrade --ignore-installed setuptools wheel || true # Editable install with the same extras CI uses. Editable + plain `install` # (not `ci`-style clean installs) so the resolved deps are cached in the @@ -34,8 +69,9 @@ python -m pip install --upgrade --ignore-installed setuptools wheel || true # (the distro Python) while `python` is /usr/local/bin/python. The setuptools # upgrade above targets `python`, so a bare `pip` install used the distro # setuptools and failed to build pyscf-properties, which left the session -# with nothing installed. -python -m pip install -e ".[pyscf,ase,dev,xtb,ts]" +# with nothing installed. ($PY is the venv interpreter when one was created +# above.) +"$PY" -m pip install -e ".[pyscf,ase,dev,xtb,ts]" echo "QuantUI cloud env ready: package + [pyscf,ase,dev,xtb,ts] installed." >&2 diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index b69b18a2..a1c071de 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -86,7 +86,7 @@ QuantUI/ ├── notebooks/ │ ├── molecule_computations.ipynb ← Student-facing Voilà app (thin launcher) │ └── tutorials/ ← 01–05 step-by-step tutorial notebooks -├── tests/ ← pytest suite (~4,100 tests; PySCF-gated tests skip on native Windows) +├── tests/ ← pytest suite (~4,700 tests; PySCF-gated tests skip on native Windows) ├── .github/ │ └── copilot-instructions.md ← This file ├── apptainer/ @@ -224,7 +224,8 @@ _PANEL_REGISTRY = { "single_point": [Energies, Isosurface, Populations], "geometry_opt": [Energies(False), Isosurface(True), Trajectory(True), Populations], "frequency": [Vibrational, IR Spectrum, Raman Spectrum, Trajectory (pre-opt), Energies, Isosurface, Populations], - "transition_state": [Vibrational, IR Spectrum, Trajectory, Energies, Isosurface, Populations], + "transition_state": [Vibrational, IR Spectrum, Trajectory, Energies, Isosurface, Populations, + PES Scan (_pop_ts_guess_profile — reactant+product searches only)], "irc": [PES Scan (energy profile via _pop_irc_profile), Trajectory], "tddft": [UV-Vis, ECD, Energies, Isosurface, Populations], "nmr": [NMR], @@ -399,8 +400,6 @@ Unavailable panels show a "Not available — run a X calculation first" placehol `_activate_ana_panel()` swaps the placeholder for real content and expands the accordion. `_deactivate_all_ana_panels()` restores placeholders and collapses — never hides. -| Panel | Accordion attr | Activated by calc types | -|---|---|---| Source of truth: `_PANEL_META` / `_PANEL_REGISTRY` in `app.py`. | Panel | Accordion attr | Activated by calc types | @@ -411,7 +410,7 @@ Source of truth: `_PANEL_META` / `_PANEL_REGISTRY` in `app.py`. | Vibrational | `vib_accordion` | Frequency, Transition State | | IR Spectrum | `_ir_accordion` | Frequency, Transition State | | Raman Spectrum | `_raman_accordion` | Frequency | -| PES Scan | `_pes_scan_accordion` | PES Scan, IRC (energy profile) | +| PES Scan | `_pes_scan_accordion` | PES Scan, IRC (energy profile), Transition State (interpolated-path profile, reactant + product searches only) | | Isosurface | `_iso_accordion` | Single Point, Geometry Opt, Frequency, Transition State, UV-Vis, Reorganization Energy (Linux/WSL) | | Geometries | `_reorg_geom_accordion` | Reorganization Energy | | UV-Vis | `_tddft_accordion` | UV-Vis (TD-DFT) | @@ -482,8 +481,10 @@ Source of truth: `_PANEL_META` / `_PANEL_REGISTRY` in `app.py`. It loads the installed package's plotly.js once per page and embeds each figure with `include_plotlyjs=False`. Never use `"cdn"` (fails silently offline) or `"require"` (plotly ≥ 6 has no such mode: it inlines the full - ~4.8 MB bundle per figure). Standalone exported HTML files keep - `include_plotlyjs=True` so they work on their own. Enforced by + ~4.8 MB bundle per figure). Inlining plotly.js (`include_plotlyjs=True`) + is allowed **only** for standalone exported files (which must work on + their own) and `plotly_embed`'s own no-app fallback — the same rule as + `CLAUDE.md` (DEC-010 as amended 2026-11-12). Enforced by `tests/test_code_quality.py`. 9. **All `.observe()` callbacks must be wrapped with `_safe_cb`.** Exceptions in @@ -687,8 +688,9 @@ jupyter lab notebooks/molecule_computations.ipynb # Run tests python -m pytest tests/ -q --no-cov -# Install/update package -pip install -e ".[dev]" +# Install/update package (same extras as CI; without pyscf/xtb/ts the PySCF, +# GFN-FF and Sella tests skip silently) +pip install -e ".[pyscf,ase,dev,xtb,ts]" # Verify app.py import python -c "from quantui.app import QuantUIApp; print('OK')" @@ -742,32 +744,31 @@ The table above lists the core files only; `tests/` has many more (one per feature area, e.g. `test_backends_worker.py`, `test_checkpoint_*.py`, `test_ts_search.py`, `test_irc.py`, `test_cli.py`). -**Baseline (Linux, Python 3.11, 2026-11; `pytest -m "not network"`):** ~4120 -passed, 24 skipped. +**Baseline (Linux, Python 3.11, 2026-11; `pytest -m "not network"`):** ~4680 +passed, 11 skipped. --- ## Dependency Groups -| Group | Packages | Notes | -| --- | --- | --- | Source of truth: `pyproject.toml`. | Group | Packages | Notes | | --- | --- | --- | -| Core (always installed) | `jupyter`, `ipywidgets`, `notebook`, `numpy`, `requests`, `matplotlib`, `plotly`, `plotlymol`, `kaleido`, `py3Dmol` | Base UI + visualization stack | +| Core (always installed) | `jupyter`, `ipywidgets`, `notebook`, `numpy`, `requests`, `matplotlib`, `plotly`, `plotlymol`, `kaleido`, `py3Dmol<2.6`, `rdkit`, `psutil` | Base UI + visualization stack; py3Dmol capped at the vendored 3Dmol.js minor | | `pyscf` extra | `pyscf>=2.13.0`, `pyscf-properties`, `pyscf-dispersion` | SCF/frequency/TDDFT/NMR/PES backends; NMR + Raman; PBE-D3 | | `pyfock` extra | `pyfock>=0.1.7,<0.3` (+ ase, scipy, numba) | Native-Windows PBE subset | | `ase` extra | `ase>=3.22.0` | Geometry optimization and structure I/O | -| `xtb` extra | `xtb` | GFN-FF pre-optimization for metals (Linux wheels) | -| `ts` extra | `sella>=2.6`, `ase>=3.26` | Transition State and IRC | +| `xtb` extra | `xtb>=22.1,<23`, `ase` | GFN-FF pre-optimization for metals (Linux wheels) | +| `ts` extra | `sella>=2.6,<3`, `ase>=3.26` | Transition State and IRC | | `app` extra | `voila>=0.5.0,<0.6`, `ipykernel>=6.0.0` | Student-facing Voilà deployment | | `gpu-cuda12x` / `gpu-cuda13x` | gpu4pyscf + cupy + cutensor | GPU offload (match the driver's CUDA version) | | `pyfock-gpu-cuda12x` / `-cuda13x` | cupy | PyFock GPU path | | `notebook` extra | `nbmake>=1.4.0`, `ipykernel>=6.0.0` | Notebook smoke-testing support | -| `dev` extra | `pytest`, `pytest-cov`, `pytest-mock`, `pytest-xdist`, `build`, `mypy`, `types-requests`, `ruff`, `black`, `pre-commit` | Development tooling | +| `dev` extra | `pytest`, `pytest-cov`, `pytest-mock`, `pytest-xdist`, `build`, `setuptools>=77`, `mypy~=1.10.0`, `types-requests`, `ruff`, `black`, `pre-commit` | Development tooling | -Install all runtime + dev extras: `pip install -e ".[pyscf,ase,app,notebook,dev]"` +CI / cloud install (what the SessionStart hook runs): `pip install -e ".[pyscf,ase,dev,xtb,ts]"`. +Everything incl. the app server and notebook smoke tests: `pip install -e ".[pyscf,ase,xtb,ts,app,notebook,dev]"`. --- diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7ff9bead..4f8da495 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -107,9 +107,10 @@ jobs: - name: Run non-PySCF tests # PySCF tests are skipped automatically via skipif guards when pyscf - # is not installed. network tests also skipped. + # is not installed (no --ignore needed: every test file must skip + # cleanly without PySCF). network tests also skipped. # Single line: PowerShell does not support backslash line continuation. - run: pytest -m "not network" --ignore=tests/test_session_calc.py --ignore=tests/test_optimizer.py --ignore=tests/test_preopt.py --no-cov --no-header -q + run: pytest -m "not network" --no-cov --no-header -q # ── Windows: real PyFock calculation ─────────────────────────────────────── test-windows-pyfock: diff --git a/.github/workflows/network-tests.yml b/.github/workflows/network-tests.yml new file mode 100644 index 00000000..259dd84f --- /dev/null +++ b/.github/workflows/network-tests.yml @@ -0,0 +1,39 @@ +name: Network tests + +# The `network`-marked tests (live PubChem lookups, installing the built wheel +# from PyPI into a fresh venv) are deselected by every job in ci.yml, so +# without this workflow they ran nowhere (audit INFRA-12). They depend on +# outside services, so they run on a weekly schedule (and on demand) instead of +# gating pull requests: a red run here means "PubChem/PyPI changed or broke", +# not "this PR broke something". + +on: + schedule: + # Mondays 06:41 UTC (off the hour to dodge the scheduler's top-of-hour rush). + - cron: "41 6 * * 1" + workflow_dispatch: + +permissions: + contents: read + +jobs: + test-network: + name: Network tests (ubuntu-24.04, Python 3.11) + runs-on: ubuntu-24.04 + + steps: + - uses: actions/checkout@v7 + + - name: Set up Python 3.11 + uses: actions/setup-python@v7 + with: + python-version: "3.11" + cache: pip + + - name: Install package and dev dependencies + run: | + python -m pip install --upgrade pip + pip install -e ".[pyscf,ase,dev]" + + - name: Run network tests + run: pytest -m network --no-header -q -n0 diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index 299d71a0..15964972 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -20,10 +20,12 @@ on: types: [published] workflow_dispatch: +# Least privilege: the default is read-only. Only the deploy job, which does +# nothing but publish the uploaded artifact, gets the Pages-write and OIDC +# permissions; the build job (which runs third-party build tooling) does not +# (audit INFRA-12). permissions: contents: read - pages: write - id-token: write # Only one deployment at a time; don't cancel in-progress runs. concurrency: @@ -72,6 +74,9 @@ jobs: deploy: name: Deploy to GitHub Pages + permissions: + pages: write + id-token: write environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} diff --git a/.github/workflows/viewer-builds.yml b/.github/workflows/viewer-builds.yml index 18fe169a..fda320ae 100644 --- a/.github/workflows/viewer-builds.yml +++ b/.github/workflows/viewer-builds.yml @@ -168,5 +168,8 @@ jobs: TAG: ${{ github.event.release.tag_name }} run: | ls -la installers - gh release upload "$TAG" installers/QuantUI-Viewer-* \ + # Unsigned installers: publish checksums so a download can at least + # be checked against what CI built. + (cd installers && sha256sum QuantUI-Viewer-* > SHA256SUMS.txt && cat SHA256SUMS.txt) + gh release upload "$TAG" installers/QuantUI-Viewer-* installers/SHA256SUMS.txt \ --repo "$GITHUB_REPOSITORY" --clobber diff --git a/.gitignore b/.gitignore index 024482ee..94a16af0 100644 --- a/.gitignore +++ b/.gitignore @@ -65,3 +65,7 @@ nul .claudeignore .apptainer-build-tmp/ quantui-gpu.sif + +# Local symlink to the private planning repo (see CLAUDE.md / DEV-ENVIRONMENT); +# never commit it — `git add -A` would otherwise add the symlink (audit INFRA-20). +.plans diff --git a/CLAUDE.md b/CLAUDE.md index dd6dc9be..f1f449d9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -43,8 +43,9 @@ pip install -e ".[pyscf,ase,dev,xtb,ts]" This mirrors the Linux job in `.github/workflows/ci.yml`. A `SessionStart` hook (`.claude/hooks/`) does this automatically on cloud sessions so the suite and linters are runnable immediately. If the container's default `python` is -outside 3.9–3.11 (e.g. 3.13), that install can fail (`pyscf-properties` does -not build); create a 3.11 env instead, e.g. +outside 3.9–3.11 (e.g. 3.13), a plain install fails (`pyscf-properties` does +not build), so the hook creates a 3.11 venv in `.venv` (via `uv`, else +`python3.11`), installs there and puts it on `PATH` for the session. By hand: `uv venv -p python3.11 .venv && . .venv/bin/activate` and install as above. **Local (conda):** use [`local-setup/environment.yml`](local-setup/environment.yml) @@ -62,7 +63,7 @@ pytest tests/test_foo.py -n0 # one test, serial (breakpoints work; -n=auto is o pre-commit run --all-files # file hygiene + nbstripout + black (26.5.1) + ruff (v0.16.0); mypy runs on pre-push and in CI ``` -Test baseline (see STATUS): **~4120 passed / 24 skipped** for +Test baseline (see STATUS): **~4680 passed / 11 skipped** for `pytest -m "not network"` (cloud, Python 3.11, 2026-11). `network`-marked tests need internet (live PubChem) — skip them in the cloud. diff --git a/README.md b/README.md index 9baff0ed..4d74740b 100644 --- a/README.md +++ b/README.md @@ -561,9 +561,11 @@ switch to def2-SVP before the calculation starts. ## Running tests ```bash -pip install -e ".[dev]" +# Same extras as CI. With only ".[dev]" there is no PySCF/ASE/xtb/Sella, and +# the numerical suite skips silently instead of running. +pip install -e ".[pyscf,ase,dev,xtb,ts]" -# All tests (Linux/macOS — PySCF available) +# All tests (Linux/macOS — needs the extras above) pytest -m "not network" # Skip PySCF-dependent tests (Windows without container) @@ -627,7 +629,7 @@ quantui/ Main package notebooks/ molecule_computations.ipynb Main user-facing interface (3-cell launcher) tutorials/ Step-by-step guided notebooks (01–05) -tests/ pytest test suite (~4,100 tests; run in parallel via pytest-xdist) +tests/ pytest test suite (~4,700 tests; run in parallel via pytest-xdist) apptainer/ Container definition for reproducible deployment local-setup/ Conda environment definition pyproject.toml Package metadata and tool config diff --git a/SECURITY.md b/SECURITY.md index 10d90b26..8f611513 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,8 +2,8 @@ QuantUI is an educational teaching tool designed for classroom and local research use. By default it runs calculations inside your own Python session — -there is no hosted server and no user accounts, and results stay on the -machine (or cluster account) you run it on. The optional SLURM batch mode +there is no hosted server and no user accounts, and results, logs, settings +and checkpoints stay on the machine (or cluster account) you run it on. The optional SLURM batch mode writes job folders under your own cluster home and submits them with your own `sbatch`. @@ -41,10 +41,35 @@ within **30 days** for confirmed vulnerabilities. ## Scope This project is a local teaching tool. The threat model is limited — there is -no multi-user server, no authentication layer, and no persistent user data. +no multi-user server and no user accounts. It does keep **persistent data in +the user's own account**, protected only by its file permissions: saved +results (`./results/` by default, `QUANTUI_RESULTS_DIR` in the Apptainer +image and Viewer), and under `~/.quantui/` logs (`logs/perf_log.jsonl`, +`logs/event_log.jsonl`), user settings (`settings.json`), calculation +checkpoints (`checkpoints/`), SLURM job folders and staging (`jobs/`, +`staging/`) and the generated launcher notebook. The log, settings and +checkpoint paths can be redirected with `QUANTUI_LOG_DIR`, +`QUANTUI_SETTINGS_PATH` and `QUANTUI_CHECKPOINT_DIR`. + The primary security concerns are: -- **Path traversal** in file I/O (molecule XYZ parsing, script export) +- **Access to the running app.** `quantui run app`, `quantui view`, the native + launchers and the Apptainer image's `app` runscript bind Voilà to + `127.0.0.1` and require a per-run token (`QUANTUI_APP_TOKEN` when set, + otherwise a fresh random one); the printed/opened URL carries it + (`?token=...`). Standalone Voilà reads no token from the environment, so on + a shared host the token is visible to other local users in the process + list (`ps`). `launch-native-jupyter.sh` uses `JUPYTER_TOKEN` (off the + command line). The Apptainer image's default JupyterLab mode keeps + Jupyter's own token handling. Anyone holding the token can drive the + session as you — read History, submit SLURM jobs with your account. +- **Untrusted files the app reads:** the Viewer's `.zip` upload of a results + folder (`quantui/app_viewer.py`), structure-file upload + (`quantui/structure_upload.py`: XYZ/PDB/CIF/MOL/SDF/MOL2/Gaussian), and + ingestion of SLURM job folders and result data written outside the session + (`quantui/backends/slurm_ingest.py`, `quantui/results_storage.py`). +- **Path traversal** in file I/O (the uploads/ingest above, molecule XYZ + parsing, script and bundle export) - **Unsafe subprocess calls** — PySCF runs in-process via the Python API, but `subprocess` is used for SLURM (`sbatch`, `squeue`, `sacct`, `scancel`; see `quantui/backends/slurm.py` and the `quantui-batch` launcher), for starting 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/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/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/local-setup/environment.yml b/local-setup/environment.yml index a4ecf973..53ed5f12 100644 --- a/local-setup/environment.yml +++ b/local-setup/environment.yml @@ -8,42 +8,50 @@ dependencies: - python=3.11 # Core Jupyter and widgets - - jupyter>=1.0.0 - - ipywidgets>=8.0.0 - - notebook>=7.0.0 - - ipykernel>=6.0.0 + # Version ranges mirror pyproject.toml (runtime deps carry the same MAJOR caps; + # dev tools the same pins) — tests/test_environment_yml.py keeps them in step. + - jupyter>=1.0.0,<2 + - ipywidgets>=8.0.0,<9 + - notebook>=7.0.0,<8 + - ipykernel>=6.0.0,<8 # Scientific computing - - numpy>=1.24.0 - - ase>=3.26.0 # Structure I/O, molecule library, geometry optimisation (Sella needs 3.26) + - numpy>=1.24.0,<3 + - psutil>=5.0,<8 # CPU/RAM detection (log_utils, utils) + - ase>=3.26.0,<4 # Structure I/O, molecule library, geometry optimisation (Sella needs 3.26) - rdkit>=2022.03.1 # PubChem SDF→XYZ conversion, SMILES input - xtb-python>=20.2 # GFN-FF metal-capable pre-optimization (the Python API + # ASE calculator; conda-forge has Windows/macOS builds, # whereas the PyPI `xtb` wheel is Linux-only) # Visualization - - py3dmol>=2.0.0 # Primary 3D molecular viewer - - matplotlib>=3.7.0 - - plotly>=5.0.0 # Orbital diagrams and comparison plots - - kaleido>=0.2.1 # Static PNG export for Plotly figures + - py3dmol>=2.0.0,<2.6 # Primary 3D molecular viewer (minor = vendored 3Dmol.js) + - matplotlib>=3.7.0,<4 + - plotly>=5.0.0,<8 # Orbital diagrams and comparison plots + - kaleido>=0.2.1,<2 # Static PNG export for Plotly figures # Web APIs (PubChem integration) - - requests>=2.28.0 + - requests>=2.28.0,<3 # Testing and development - pytest>=7.0.0 - pytest-cov>=4.0.0 - pytest-mock>=3.10.0 - - mypy>=1.0.0 + - pytest-xdist>=3.0.0 # pyproject addopts has -n=auto; bare `pytest` fails without it + - mypy>=1.10.0,<1.11 # = pyproject's mypy~=1.10.0 / CI's pinned mypy step + - types-requests>=2.28.0 + - python-build>=1.0.0 # PyPI `build`; used by tests/test_packaging.py + - setuptools>=77 # --no-isolation wheel build: bdist_wheel + PEP 639 license - nbstripout>=0.7.0 # Strip notebook outputs before git commits - - pre-commit>=3.0.0 + - pre-commit>=3.7.0 # Package manager for pip dependencies - pip>=23.0 - pip: # Voilà app server — clean widget-only UI for classroom demos - - voila>=0.5.0 + # Capped like pyproject's [app] extra (Voila 0.6 is untested). + - voila>=0.5.0,<0.6 # Notebook smoke testing - nbmake>=1.4.0 # Code formatting and linting (not on conda-forge). Pinned to a compatible @@ -60,7 +68,7 @@ dependencies: # from GitHub source until a new release lands on PyPI. - pyscf-properties @ git+https://github.com/pyscf/properties.git # Grimme D3 for PBE-D3 (PySCF mf.disp); Linux/macOS wheels on PyPI. - - pyscf-dispersion + - pyscf-dispersion>=1.0,<2 # Transition-state search (M-TS, DEC-024); pulls in jax (~380 MB). - - sella>=2.6 + - sella>=2.6,<3 - -e .. diff --git a/packaging/viewer/README.md b/packaging/viewer/README.md index 3045e01a..0e8a7721 100644 --- a/packaging/viewer/README.md +++ b/packaging/viewer/README.md @@ -30,7 +30,7 @@ Where students get them: | Results folder | Any folder on disk (type the path, **Open**) | Upload a `.zip` of it (**Upload .zip**) | | Offline | Yes | Only if Pyodide is self-hosted (see below) | | Size | Installer download ~185–225 MB (CI build 2026-11-08: Windows 208, Linux 223, macOS 185 MB; was 338 / 247 / 213 MB in v0.11.1) | ~20–60 MB first load from CDN; ~550 MB site if self-hosted | -| Isosurfaces | Not available (needs PySCF) | Not available (needs PySCF) | +| Isosurfaces | HOMO/LUMO saved with the result (QuantUI 0.11.0+); others need PySCF | Same as the installer | | Signing | **Unsigned** — see below | None needed | ## Desktop installer @@ -53,6 +53,11 @@ The installers are **not code-signed**. First run: without a further prompt (not yet confirmed on a real Mac). - **Linux** — `bash QuantUI-Viewer-*.sh` (needs a terminal once). +Each release also carries `SHA256SUMS.txt` for the installers; check a +download with `sha256sum -c SHA256SUMS.txt --ignore-missing` (Linux), +`shasum -a 256 -c SHA256SUMS.txt --ignore-missing` (macOS) or +`Get-FileHash` (Windows). + Free signing for the Windows installer is available to open-source projects through the [SignPath Foundation](https://signpath.org/); macOS notarization has no free route. @@ -91,10 +96,10 @@ load under `voici` 0.10.0 (built against a newer JupyterLab); 0.7.0 does. ## Known gaps -- Orbital isosurfaces need PySCF to compute the cube file, so they are not - available in either build yet (the panel says so). Fix: have the full app - save HOMO/LUMO cubes at calculation time, or evaluate orbitals on a grid - with numpy alone. +- Only the HOMO and LUMO isosurfaces the full app saved with the result + (`frontier_cubes/`, QuantUI 0.11.0 or later) can be drawn. Other orbitals, + density and ESP surfaces need PySCF to compute the cube, so neither build + offers them (the panel says so). - Thermochemistry is shown as saved with the result; recomputing at another T / P needs PySCF. Mode symmetry labels are likewise saved at calc time. - The **Upload .zip** button shows a file count, e.g. "(0)": ipywidgets' diff --git a/packaging/viewer/installer/smoke_launch.py b/packaging/viewer/installer/smoke_launch.py index d8c2fa78..877cdc9a 100644 --- a/packaging/viewer/installer/smoke_launch.py +++ b/packaging/viewer/installer/smoke_launch.py @@ -1,5 +1,5 @@ """CI smoke test: start the installed viewer the way a shortcut does and -check that it serves a page. +check that it serves the app. python smoke_launch.py PATH/TO/quantui[.exe] @@ -7,17 +7,30 @@ catches anything that only works when its folders are on PATH (the first Windows build failed exactly that way: "Voila is not installed or not on PATH" from a Start-menu shortcut). + +The page is fetched with the per-run token that ``quantui view`` prints, and +must contain a rendered widget. Without the token Voila answers 200 with its +login page, so a bare HTTP 200 proved only that a server was listening. """ from __future__ import annotations import os +import re import socket import subprocess import sys +import threading import time import urllib.request +# nbconvert's lab template (which Voila renders with) emits every widget +# output as " @@ -3921,6 +3927,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) @@ -4666,9 +4673,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/quantui/app_xyz_input.py b/quantui/app_xyz_input.py index 5d02792d..2b200646 100644 --- a/quantui/app_xyz_input.py +++ b/quantui/app_xyz_input.py @@ -8,7 +8,7 @@ import ipywidgets as widgets from quantui import theme as _theme -from quantui.molecule import parse_xyz_input +from quantui.molecule import ISOTOPE_NOTE, has_isotope_labels, parse_xyz_input from quantui.xyz_input import ( format_xyz_body, load_molecule_from_xyz_text, @@ -264,6 +264,8 @@ def on_load_xyz(app: Any, _btn: Any = None) -> None: ) else: app.xyz_msg.value = f"Loaded {mol.get_formula()} ({len(mol.atoms)} atoms)." + if has_isotope_labels(text): + app.xyz_msg.value += f" {ISOTOPE_NOTE}" except Exception as exc: app.xyz_msg.value = f"Parse error: {exc}" 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/cluster_config.py b/quantui/backends/cluster_config.py index ab63aebb..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), @@ -167,6 +171,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``. @@ -315,6 +335,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/quantui/backends/dispatch.py b/quantui/backends/dispatch.py index a154d0f8..3b961136 100644 --- a/quantui/backends/dispatch.py +++ b/quantui/backends/dispatch.py @@ -7,7 +7,7 @@ import os import shutil from pathlib import Path -from typing import Any +from typing import Any, cast from uuid import uuid4 from .base import CalculationRequest @@ -210,6 +210,20 @@ def build_calculation_request( def slurm_backend_for_app(app: Any) -> SlurmBackend: - """Construct a :class:`SlurmBackend` sharing the app's job registry.""" + """The app's :class:`SlurmBackend`, sharing the app's job registry. + + One backend per app (kept on ``app._slurm_backend`` while the registry + is the same), so its short-lived squeue/sacct status cache is reused + across refreshes instead of starting empty on every call. + """ registry = getattr(app, "_job_registry", None) - return SlurmBackend(registry=registry) + cached = getattr(app, "_slurm_backend", None) + if registry is not None and getattr(cached, "registry", None) is registry: + return cast(SlurmBackend, cached) + backend = SlurmBackend(registry=registry) + if registry is not None: + try: + app._slurm_backend = backend + except AttributeError: # an object that takes no new attributes + pass + return backend diff --git a/quantui/backends/registry.py b/quantui/backends/registry.py index 658d03c8..29486f56 100644 --- a/quantui/backends/registry.py +++ b/quantui/backends/registry.py @@ -177,6 +177,10 @@ def progress_path(self) -> Path: return self.staging_path / "progress.json" +# Mode for the job/staging roots and job folders QuantUI creates. +JOB_DIR_MODE = 0o700 + + class JobRegistry: """JSON-backed registry of submitted backend jobs.""" @@ -187,15 +191,18 @@ def __init__( ) -> None: self.jobs_root = (jobs_root or cfg.default_jobs_root()).expanduser() self.staging_root = (staging_root or cfg.default_staging_root()).expanduser() - self.jobs_root.mkdir(parents=True, exist_ok=True) - self.staging_root.mkdir(parents=True, exist_ok=True) + # Owner-only (0o700) when QuantUI creates them: on shared scratch + # with umask 022 other users could otherwise read graded work. An + # existing folder keeps its mode (a course may share one on purpose). + self.jobs_root.mkdir(mode=JOB_DIR_MODE, parents=True, exist_ok=True) + self.staging_root.mkdir(mode=JOB_DIR_MODE, parents=True, exist_ok=True) def _record_path(self, request_id: str) -> Path: return safe_join(self.jobs_root, f"{request_id}.json") def staging_dir_for(self, request_id: str) -> Path: path = safe_join(self.staging_root, request_id) - path.mkdir(parents=True, exist_ok=True) + path.mkdir(mode=JOB_DIR_MODE, parents=True, exist_ok=True) return path def new_job_dir(self, name: str) -> Path: @@ -208,7 +215,7 @@ def new_job_dir(self, name: str) -> Path: candidate = name if n == 1 else f"{name}_{n}" path = safe_join(self.staging_root, candidate) try: - path.mkdir(parents=True, exist_ok=False) + path.mkdir(mode=JOB_DIR_MODE, parents=True, exist_ok=False) except FileExistsError: n += 1 continue diff --git a/quantui/backends/slurm.py b/quantui/backends/slurm.py index b83e63d8..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) @@ -249,6 +251,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/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/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/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/benchmarks.py b/quantui/benchmarks.py index 2e5bbf46..becd8999 100644 --- a/quantui/benchmarks.py +++ b/quantui/benchmarks.py @@ -52,6 +52,8 @@ from __future__ import annotations +import atexit +import functools import time from dataclasses import dataclass, field from datetime import datetime, timezone @@ -963,6 +965,7 @@ def _calibration_worker( import os as _os import time as _t from datetime import datetime as _dt + from datetime import timezone as _tz from pathlib import Path as _P # Must run BEFORE any quantui / pyscf / gpu4pyscf import so @@ -982,7 +985,7 @@ def _calibration_worker( # result dir's pyscf.log. with open(log_path, "a", encoding="utf-8", buffering=1) as log_fh: log_fh.write( - f"\n========= {_dt.utcnow().isoformat()} :: {label} =========\n" + f"\n========= {_dt.now(_tz.utc).isoformat()} :: {label} =========\n" ) per_calc_buf = _io.StringIO() # _TeeStream implements only .write() — the one method any of @@ -1003,6 +1006,8 @@ def _calibration_worker( # (_save_calibration_step) takes it untyped. Annotate Any so mypy # doesn't pin the variable to whichever branch it sees first. res: Any + n_iterations: Optional[int] + n_steps: Optional[int] = None if calc_type == "geometry_opt": from quantui.optimizer import optimize_geometry as _opt @@ -1015,7 +1020,11 @@ def _calibration_worker( ) formula = res.molecule.get_formula() converged = bool(res.converged) - n_iterations = int(getattr(res, "n_steps", -1)) + # Optimizer steps are n_steps, not SCF iterations: logged + # under the same key the app uses, so calibration records + # feed estimate_opt_steps (audit DATA-14). + n_iterations = None + n_steps = int(getattr(res, "n_steps", -1)) elif calc_type == "frequency": from quantui.freq_calc import run_freq_calc as _freq @@ -1073,12 +1082,16 @@ def _calibration_worker( mol=mol, ) + from quantui import calc_log as _calc_log_mod + result_queue.put( { "status": "ok", "formula": formula, "converged": converged, "n_iterations": n_iterations, + "n_steps": n_steps, + "n_threads": _calc_log_mod.current_thread_count(), "elapsed_s": elapsed, "import_s": import_s, # Device / DF provenance, so GPU and forced-CPU probe @@ -1101,6 +1114,46 @@ def _calibration_worker( ) +def _calibration_worker_main(*args) -> None: + """Spawn target: lead a fresh process group, then run the worker. + + The worker is not daemonic (so a frequency step can start its parallel + IR-intensity pool — audit DATA-10), and that pool's processes would + survive a plain ``terminate()`` of the worker. Leading its own process + group lets :func:`_terminate_worker_tree` signal the worker and every + process it started in one go (POSIX only; elsewhere it degrades to a + plain ``terminate()``). Skipped when not in a child process, so tests + that drive the worker inline never re-group the test runner. + """ + import multiprocessing as _mp + import os as _os + + if _mp.parent_process() is not None and hasattr(_os, "setpgrp"): + try: + _os.setpgrp() + except OSError: + pass + _calibration_worker(*args) + + +def _terminate_worker_tree(worker) -> None: + """Terminate a calibration worker and any processes it spawned.""" + if not worker.is_alive(): + return + import os as _os + import signal as _signal + + pid = getattr(worker, "pid", None) + if pid and hasattr(_os, "killpg"): + try: + if _os.getpgid(pid) == pid: + _os.killpg(pid, _signal.SIGTERM) + return + except OSError: + pass + worker.terminate() + + def _tail_last_status_line(log_path) -> str: """Return the last meaningful progress line from the calibration log. @@ -1400,7 +1453,7 @@ def _emit_progress(*args, live_message=None, step=None) -> None: # Spawn the worker. result_queue = _ctx.Queue() worker = _ctx.Process( - target=_calibration_worker, + target=_calibration_worker_main, args=( atoms, coords, @@ -1414,10 +1467,19 @@ def _emit_progress(*args, live_message=None, step=None) -> None: timestamp, # calibration_run_id — the parent's run timestamp force_cpu, # cross-device probe flag ), - daemon=True, + # NOT daemonic: a daemonic process may not have children, so a + # frequency step's parallel IR-intensity ProcessPoolExecutor + # always fell back to serial and the tier-4 "parallel-IR" entry + # measured the serial path (audit DATA-10). Every exit path of + # the poll loop below terminates the worker, and an atexit hook + # covers interpreter shutdown mid-step — multiprocessing would + # otherwise *join* a live non-daemonic child at exit. + daemon=False, ) t_start = time.perf_counter() worker.start() + _reap = functools.partial(_terminate_worker_tree, worker) + atexit.register(_reap) # Poll loop — finish naturally OR hit timeout OR stop OR skip. poll_interval = 0.5 @@ -1434,7 +1496,7 @@ def _emit_progress(*args, live_message=None, step=None) -> None: # cut off a near-finishing benzene freq). # ``None`` means "user controls; never auto-kill". if timeout_per_step is not None and elapsed > timeout_per_step: - worker.terminate() + _terminate_worker_tree(worker) worker.join(timeout=5) step.status = _STATUS_TIMEOUT step.elapsed_s = elapsed @@ -1442,7 +1504,7 @@ def _emit_progress(*args, live_message=None, step=None) -> None: break if stop_event is not None and stop_event.is_set(): - worker.terminate() + _terminate_worker_tree(worker) worker.join(timeout=5) step.status = _STATUS_STOPPED step.elapsed_s = elapsed @@ -1456,7 +1518,7 @@ def _emit_progress(*args, live_message=None, step=None) -> None: # Skip again. (Replaces the hard timeout that was cutting # off near-finishing calcs.) if skip_event is not None and skip_event.is_set(): - worker.terminate() + _terminate_worker_tree(worker) worker.join(timeout=5) step.status = _STATUS_SKIPPED step.elapsed_s = elapsed @@ -1470,6 +1532,8 @@ def _emit_progress(*args, live_message=None, step=None) -> None: step_n, total, label, "running", elapsed, live_message=live_msg ) + atexit.unregister(_reap) + if worker_done_normally: try: msg = result_queue.get(timeout=2.0) @@ -1515,11 +1579,12 @@ def _emit_progress(*args, live_message=None, step=None) -> None: n_electrons=step.n_electrons, method=method, basis=basis, - n_iterations=int(msg.get("n_iterations", -1)), + n_iterations=msg.get("n_iterations"), elapsed_s=float(msg["elapsed_s"]), converged=bool(msg["converged"]), n_basis=step.n_basis, - n_cores=1, + n_threads=msg.get("n_threads"), + n_steps=msg.get("n_steps"), calc_type=calc_type, source="calibration", import_s=msg.get("import_s"), diff --git a/quantui/calc_log.py b/quantui/calc_log.py index 208d94dd..5b5be60d 100644 --- a/quantui/calc_log.py +++ b/quantui/calc_log.py @@ -366,9 +366,37 @@ def _prediction_log_path() -> Path: return _log_dir() / "prediction_log.jsonl" +def _json_default(obj: object) -> object: + """``json.dumps`` fallback: numpy scalars/arrays -> plain data, else str. + + A numpy int/bool or a ``Path`` in a record used to raise TypeError out + of the logger (audit DATA-13). + """ + tolist = getattr(obj, "tolist", None) + if callable(tolist): + try: + return tolist() + except Exception: # noqa: BLE001 — fall back to str below + pass + return str(obj) + + +def _dumps_record(record: dict) -> str: + return json.dumps(record, ensure_ascii=False, default=_json_default) + + +def _parse_jsonl_line(raw: str) -> Optional[dict]: + """Parse one JSONL line; ``None`` for malformed or non-object lines.""" + try: + rec = json.loads(raw) + except (ValueError, RecursionError): + return None + return rec if isinstance(rec, dict) else None + + def _append(path: Path, record: dict) -> None: path.parent.mkdir(parents=True, exist_ok=True) - line = json.dumps(record, ensure_ascii=False) + "\n" + line = _dumps_record(record) + "\n" with _LOCK: with open(path, "a", encoding="utf-8") as fh: fh.write(line) @@ -399,23 +427,26 @@ def _read_all(path: Path) -> list[dict]: and cached[0] == stat.st_mtime and cached[1] == stat.st_size ): - return list(cached[2]) + # Copy each record, not just the list: a caller that mutates a + # returned dict must not poison the cache (audit DATA-13). + return [dict(r) for r in cached[2]] records: list[dict] = [] # errors="replace": a concurrent/interrupted append can leave a partial # multibyte UTF-8 sequence at EOF; strict decoding would raise # UnicodeDecodeError and abort the whole read. Replacing the bad bytes # lets that one line fail json.loads and be skipped, matching the # deliberate malformed-entry tolerance below (and under pytest -n=auto). + # Non-object lines (e.g. a stray ``42``) are skipped too: callers + # index every record as a dict (audit DATA-13). with open(path, encoding="utf-8", errors="replace") as fh: for raw in fh: raw = raw.strip() if raw: - try: - records.append(json.loads(raw)) - except json.JSONDecodeError: - pass + rec = _parse_jsonl_line(raw) + if rec is not None: + records.append(rec) _READ_ALL_CACHE[key] = (stat.st_mtime, stat.st_size, records) - return list(records) + return [dict(r) for r in records] # --------------------------------------------------------------------------- @@ -551,6 +582,7 @@ def log_calculation( import_s: Optional[float] = None, stages: Optional[dict] = None, density_fit: Optional[bool] = None, + n_threads: Optional[int] = None, ) -> None: """Append one performance record to ``perf_log.jsonl``. @@ -585,6 +617,13 @@ def log_calculation( partitioned in :func:`estimate_time` exactly as ``gpu_used`` is — mixing fitted and unfitted runs of the same chemistry under one key would give the estimator a bimodal distribution it cannot see. + + ``n_threads`` (audit DATA-14) is the BLAS/OpenMP thread count the + calculation actually ran with (:func:`current_thread_count`). It is + provenance only — the estimator does not read it. ``n_cores`` is the + estimator's normalisation input; callers used to hard-code it to 1, so + they now leave it unset (read back as 1, same estimate) rather than + record a value that was never measured. """ record: dict = { "timestamp": datetime.now(timezone.utc).isoformat(), @@ -609,6 +648,8 @@ def log_calculation( record["gpu_name"] = gpu_name if density_fit is not None: record["density_fit"] = bool(density_fit) + if n_threads is not None: + record["n_threads"] = int(n_threads) # Outer-loop step count (geom-opt BFGS steps / PES scan points). Enables # a history-based "step k / ~N" prior for the live progress fraction. if n_steps is not None: @@ -624,6 +665,16 @@ def log_calculation( _append(_perf_path(), record) +def current_thread_count() -> Optional[int]: + """BLAS/OpenMP threads PySCF will use in this process, or ``None``.""" + try: + from pyscf import lib as _pyscf_lib + + return int(_pyscf_lib.num_threads()) + except Exception: # noqa: BLE001 — provenance only; never fail a log + return None + + #: Hessian-cost multipliers used by the frequency cost model. #: PySCF's analytical Hessian for HF/DFT runs in ~2-3× SCF time; for #: post-HF methods it falls back to numerical Hessian which is much @@ -639,6 +690,12 @@ def log_calculation( # Minimum tagged frequency records carrying ``stages`` before learned stage # ratios replace the fixed Hessian / IR multipliers. _MIN_FREQ_STAGE_SAMPLES: int = 2 +# Records faster than this are kept out of the n_basis^β power-law fit +# (strategies 1 and 3 of estimate_time_from_records): sub-second runs are +# dominated by fixed per-calc overhead, so extrapolating them by n_basis^β +# grossly over-predicts larger systems. They still feed the electron-count +# strategies, which scale far more gently. +_MIN_POWER_LAW_ELAPSED_S: float = 1.0 def _bucket_freq_stages(stages: dict[str, float]) -> dict[str, float]: @@ -734,6 +791,7 @@ def _estimate_frequency_cost( n_cores: Optional[int] = None, gpu_used: Optional[bool] = None, source: Optional[str] = None, + density_fit: Optional[bool] = None, ) -> Optional[dict]: """Structured frequency-time estimate from an SP anchor. @@ -784,6 +842,7 @@ def _estimate_frequency_cost( calc_type="single_point", gpu_used=gpu_used, source=source, + density_fit=density_fit, ) if sp_est is None: return None @@ -1061,14 +1120,24 @@ def _maybe_downgrade(conf: str) -> str: n_cores_current = n_cores if n_cores is not None else 1 def _eff(r: dict) -> Optional[float]: - """Normalised efficiency: elapsed_s × n_cores / n_basis^β.""" + """Normalised efficiency: elapsed_s × n_cores / n_basis^β. + + ``None`` (record left out of the power-law fit) for records under + :data:`_MIN_POWER_LAW_ELAPSED_S`: their wall time is mostly fixed + overhead, not the n_basis^β work, so scaling them up by n_basis^β + wildly over-predicts large systems (audit DATA-14: four sub-0.1 s + STO-3G runs predicted 51 min for n_basis = 200). When too few + records survive, the electron-count strategies below take over. + """ nb: float = float(r.get("n_basis") or 0) if not nb: return None + elapsed: float = float(r["elapsed_s"]) + if elapsed < _MIN_POWER_LAW_ELAPSED_S: + return None rc: float = float(r.get("n_cores") or 1) r_method: str = str(r.get("method") or method) beta: float = _METHOD_SCALE_EXP.get(r_method, 3.5) - elapsed: float = float(r["elapsed_s"]) return float(elapsed * rc / (nb**beta)) # ── Strategy 1: exact method + basis, basis-function efficiency ────────── @@ -1179,6 +1248,7 @@ def _eff(r: dict) -> Optional[float]: n_cores=n_cores, gpu_used=gpu_used, source=source, + density_fit=density_fit, ) if cost_est is not None: return cost_est @@ -1428,35 +1498,49 @@ def prune_events(days: int = 7) -> None: with _LOCK: if not path.exists(): return - records: list[dict] = [] # errors="replace" for the same reason as _read_all: tolerate a partial # multibyte sequence from a concurrent/interrupted append rather than # abort the prune. - with open(path, encoding="utf-8", errors="replace") as fh: - for raw in fh: - raw = raw.strip() - if raw: - try: - records.append(json.loads(raw)) - except json.JSONDecodeError: - pass - - kept: list[dict] = [] - for r in records: + with open(path, "rb") as fh: + data = fh.read() + read_size = len(data) + + kept: list[str] = [] + for raw in data.decode("utf-8", errors="replace").splitlines(): + raw = raw.strip() + if not raw: + continue + r = _parse_jsonl_line(raw) + if r is None: + continue # junk line / non-object JSON (e.g. ``123``) try: ts = datetime.fromisoformat(r["timestamp"]) # fromisoformat on Python < 3.11 doesn't handle 'Z' suffix if ts.tzinfo is None: ts = ts.replace(tzinfo=timezone.utc) if ts >= cutoff: - kept.append(r) - except (KeyError, ValueError): - kept.append(r) # keep malformed entries rather than silently drop - - path.parent.mkdir(parents=True, exist_ok=True) - with open(path, "w", encoding="utf-8") as fh: - for r in kept: - fh.write(json.dumps(r, ensure_ascii=False) + "\n") + kept.append(raw) + except (KeyError, ValueError, TypeError): + kept.append(raw) # keep malformed entries rather than silently drop + + # _LOCK is per-process: another kernel / worker process may have + # appended since the read. Carry those bytes over, then swap the + # file in atomically, so the window in which a foreign append can be + # lost shrinks from "the whole prune" to the final rename. + tmp = path.with_name(path.name + ".tmp") + try: + with open(path, "rb") as fh: + fh.seek(read_size) + tail = fh.read() + with open(tmp, "wb") as out: + out.write("".join(line + "\n" for line in kept).encode("utf-8")) + out.write(tail) + os.replace(tmp, path) + except OSError: + try: + tmp.unlink() + except OSError: + pass def get_recent_events(n: int = 100) -> list[dict]: diff --git a/quantui/checklist_widget.py b/quantui/checklist_widget.py index 21faf479..b96ad895 100644 --- a/quantui/checklist_widget.py +++ b/quantui/checklist_widget.py @@ -8,6 +8,7 @@ from __future__ import annotations +import html from typing import Any, List, Sequence, Tuple import ipywidgets as widgets @@ -37,7 +38,7 @@ def options(self, options: Sequence[Tuple[str, Any]]) -> None: self._boxes = [] for label, value in self._options: if value in ("", None): - rows.append(widgets.HTML(f"{label}")) + rows.append(widgets.HTML(f"{html.escape(label)}")) continue box = widgets.Checkbox( value=False, diff --git a/quantui/checkpoint.py b/quantui/checkpoint.py index 92d487fb..64d3cf1c 100644 --- a/quantui/checkpoint.py +++ b/quantui/checkpoint.py @@ -52,6 +52,7 @@ import json import logging import os +import re import shutil import time import uuid @@ -121,7 +122,9 @@ def _coords_digest(coords: Optional[Sequence[Sequence[float]]]) -> str: """ if not coords: return "" - rounded = [[round(float(v), 6) for v in row] for row in coords] + # ``+ 0.0`` folds -0.0 (and values that round to it) into 0.0, so a + # sign-of-zero difference cannot change the resume key (audit DATA-15). + rounded = [[round(float(v), 6) + 0.0 for v in row] for row in coords] return hashlib.sha256( json.dumps(rounded, separators=(",", ":")).encode("utf-8") ).hexdigest()[:16] @@ -883,4 +886,34 @@ def prune( for state in survivors[max_checkpoints:]: shutil.rmtree(state["dir"], ignore_errors=True) removed += 1 + + # Checkpoint dirs load_all() skipped (meta.json missing, corrupt, or an + # old schema) used to be kept forever (audit DATA-15). Age them out by + # their newest file mtime instead. Only names shaped like a resume key + # are touched, so a checkpoint root pointed at a shared directory never + # loses anything that is not a checkpoint. + readable = {str(state["dir"]) for state in states} + for path in _iter_checkpoint_dirs(root): + if str(path) in readable or not _RESUME_KEY_RE.match(path.name): + continue + if _newest_mtime(path) < cutoff: + shutil.rmtree(path, ignore_errors=True) + removed += 1 return removed + + +_RESUME_KEY_RE = re.compile(r"^[0-9a-f]{16}$") + + +def _newest_mtime(path: Path) -> float: + """Newest mtime of *path* and its direct children (0.0 if unreadable).""" + try: + newest = path.stat().st_mtime + for child in path.iterdir(): + try: + newest = max(newest, child.stat().st_mtime) + except OSError: + continue + except OSError: + return 0.0 + return newest diff --git a/quantui/cli.py b/quantui/cli.py index 1bdc74a6..03cd8086 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", @@ -825,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/config.py b/quantui/config.py index d270112b..2211b35d 100644 --- a/quantui/config.py +++ b/quantui/config.py @@ -146,7 +146,8 @@ "type": "dft", "label": "PBE-D3 — PBE + D3 Dispersion Correction", "description": ( - "PBE GGA functional with Grimme's D3BJ empirical dispersion correction. " + "PBE GGA functional with Grimme's D3 empirical dispersion correction " + "(zero damping, as Gaussian's EmpiricalDispersion=GD3). " "Dramatically improves non-covalent interaction energies over plain PBE " "at negligible extra cost." ), @@ -167,9 +168,9 @@ "label": "CCSD — Coupled Cluster with Singles and Doubles", "description": ( "Post-HF coupled-cluster method that includes all single and double " - "excitations from the HF reference. Often called the gold standard for " - "single-reference systems — significantly more accurate than MP2 — but " - "scales as O(N⁶). Memory and runtime both grow steeply with basis size; " + "excitations from the HF reference. Usually more accurate than MP2 for " + "single-reference systems, but without the perturbative triples that " + "make CCSD(T) the 'gold standard'. Scales as O(N⁶). Memory and runtime both grow steeply with basis size; " "expect very small molecules (~10 heavy atoms or fewer) only." ), "use_for": "High-accuracy benchmarks for small closed-shell molecules.", diff --git a/quantui/data/js/PROVENANCE.md b/quantui/data/js/PROVENANCE.md index 0a362851..c042f159 100644 --- a/quantui/data/js/PROVENANCE.md +++ b/quantui/data/js/PROVENANCE.md @@ -18,4 +18,8 @@ To update: download the matching `3dmol@/build/3Dmol-min.js`, bump `THREEDMOL_VERSION` in `viz_assets.py`, and confirm the version still matches py3Dmol's `view()` constructor default `js=` URL (so the generated viewer -calls stay API-compatible). +calls stay API-compatible). Patch-level skew is tolerated (py3Dmol 2.5.5 +targets 3Dmol.js 2.5.5 while 2.5.4 is vendored); `pyproject.toml` caps py3Dmol +below the next minor, and `tests/test_viz_assets_version.py` fails when the +installed py3Dmol targets a different major.minor than the vendored bundle — +re-vendor and raise that cap together. diff --git a/quantui/data/launcher/quantui_batch.py b/quantui/data/launcher/quantui_batch.py index 5fa021c8..233995d4 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 @@ -55,8 +56,19 @@ JOB_LOG = ".quantui-batch-jobs" ATTEMPT_RE = re.compile(r"^attempt-(\d+)_job(\w+)$") ACTIVE_STATES = ("PENDING", "RUNNING", "CONFIGURING", "COMPLETING", "SUSPENDED") -FAILED_STATES = ("FAILED", "OUT_OF_MEMORY", "TIMEOUT", "CANCELLED", "NODE_FAIL") +FAILED_STATES = ( + "FAILED", + "OUT_OF_MEMORY", + "TIMEOUT", + "CANCELLED", + "NODE_FAIL", + "PREEMPTED", + "BOOT_FAIL", + "DEADLINE", +) BACKEND_ID = "cluster_slurm" +# Port of registry.JOB_DIR_MODE: folders QuantUI creates are owner-only. +JOB_DIR_MODE = 0o700 HELP = """\ quantui-batch: run QuantUI calculations as Slurm batch jobs. @@ -128,10 +140,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 +165,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"): @@ -331,7 +352,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): @@ -426,6 +553,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 @@ -546,8 +676,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"]: @@ -601,11 +731,13 @@ def safe(text): def new_job_dir(root, name): + # The root first: parents=True would create it with the default mode. + root.mkdir(mode=JOB_DIR_MODE, parents=True, exist_ok=True) n = 1 while True: candidate = root / (name if n == 1 else f"{name}_{n}") try: - candidate.mkdir(parents=True, exist_ok=False) + candidate.mkdir(mode=JOB_DIR_MODE, parents=True, exist_ok=False) except FileExistsError: n += 1 continue @@ -660,6 +792,18 @@ def utc_now(): return datetime.now(timezone.utc).replace(microsecond=0).isoformat() +def record_path(request_id): + """The job record file for *request_id*, which must stay in jobs_root(). + + Port of registry._record_path / safe_join: a "/" or ".." in the id + would write the record somewhere else. + """ + rid = str(request_id or "") + if not REQUEST_ID_RE.match(rid) or ".." in rid: + raise InputError(f"request_id {rid!r} cannot name a job record file") + return jobs_root() / (rid + ".json") + + def unique_request(request): """Give *request* a fresh id when a job record already uses its id. @@ -667,9 +811,8 @@ def unique_request(request): request .json submitted twice must not overwrite the record of a job that may still be running. The original id is kept in run_context. """ - jobs = jobs_root() original = request["request_id"] - if (jobs / (original + ".json")).exists(): + if record_path(original).exists(): request["request_id"] = f"{original[:40]}-{uuid.uuid4().hex[:8]}" request["run_context"] = dict( request.get("run_context") or {}, source_request_id=original @@ -679,6 +822,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) @@ -707,9 +851,9 @@ def prepare_job(request, resources, job_name, email, image_path): "unknown_since": None, "unknown_polls": 0, } - jobs = jobs_root() - jobs.mkdir(parents=True, exist_ok=True) - with open(str(jobs / (request["request_id"] + ".json")), "w") as fh: + path = record_path(request["request_id"]) + path.parent.mkdir(mode=JOB_DIR_MODE, parents=True, exist_ok=True) + with open(str(path), "w") as fh: json.dump(record, fh, indent=2) return script @@ -801,6 +945,25 @@ def job_ids(job_dir): return [jid for jid, _opts in job_log(job_dir)] +def all_job_ids(job_dir, q): + """Every Slurm id known for *job_dir*, oldest first. + + JOB_LOG holds only what quantui-batch submitted; a job the app (or a + bare sbatch) queued shows up as an attempt folder once it starts, and + in the queue, with this folder's submit.slurm, before that. + """ + ids = job_ids(job_dir) + ids += [jid for _n, jid, _p in attempts(job_dir) if jid.isdigit()] + script = job_dir / "submit.slurm" + for jid, (_state, path, _reason) in q.items(): + try: + if path and Path(path).resolve() == script.resolve(): + ids.append(jid) + except OSError: + continue + return list(dict.fromkeys(ids)) # unique, first-seen order + + def record_job(job_dir, job_id, options=()): stamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) with open(str(job_dir / JOB_LOG), "a") as fh: @@ -1274,6 +1437,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") @@ -1284,6 +1448,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") @@ -1332,7 +1497,14 @@ def cmd_submit(argv): # `limit` of them ever run at once. waits_for = slots.pop(0) deps.append(f"afterany:{waits_for}") - script = prepare_job(request, resources, args.job_name, args.email, image_path) + try: + script = prepare_job( + request, resources, args.job_name, args.email, image_path + ) + except InputError as exc: # a bad site setting or record id + sys.stderr.write(f"{label}: {exc}\n") + code = 1 + continue job_dir = script.parent options = [] if deps: @@ -1486,17 +1658,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): @@ -1509,7 +1694,7 @@ def cmd_rerun(argv): rest = argv[1:] q = queue() log = job_log(job_dir) - for jid, _opts in log: + for jid in all_job_ids(job_dir, q): if jid in q and q[jid][0] in ACTIVE_STATES: die( f"{job_dir.name} is still {q[jid][0].lower()} (job {jid}); " @@ -1521,7 +1706,11 @@ def cmd_rerun(argv): f"you already have {active} QuantUI job(s) queued or running " f"(limit {max_jobs()})." ) - last_id, last_options = log[-1] if log else (None, []) + if log: + last_id, last_options = log[-1] + else: # queued by the app or a bare sbatch: its attempt folders say which + tried = [jid for _n, jid, _p in attempts(job_dir) if jid.isdigit()] + last_id, last_options = (tried[-1] if tried else None), [] # Carry the previous attempt's resource overrides forward, then apply new ones. options = [ o for o in last_options if o.startswith("--mem") or o.startswith("--time") @@ -1560,7 +1749,7 @@ def cmd_cancel(argv): die("usage: quantui-batch cancel JOB", 2) job_dir = resolve_job(argv[0]) q = queue() - live = [jid for jid in job_ids(job_dir) if jid in q] + live = [jid for jid in all_job_ids(job_dir, q) if jid in q] if not live: print(f"{job_dir.name} has no queued or running job.") return 0 @@ -1768,7 +1957,7 @@ def report(ok, text, fix=""): ) root = staging_root() try: - root.mkdir(parents=True, exist_ok=True) + root.mkdir(mode=JOB_DIR_MODE, parents=True, exist_ok=True) writable = os.access(str(root), os.W_OK) except OSError: writable = False @@ -1785,7 +1974,7 @@ def report(ok, text, fix=""): ), ) try: - jobs_root().mkdir(parents=True, exist_ok=True) + jobs_root().mkdir(mode=JOB_DIR_MODE, parents=True, exist_ok=True) report(os.access(str(jobs_root()), os.W_OK), f"job records: {jobs_root()}") except OSError: report(False, f"job records: {jobs_root()}", "the folder must be writable") 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/quantui/estimator_eval.py b/quantui/estimator_eval.py index 33769535..576c472c 100644 --- a/quantui/estimator_eval.py +++ b/quantui/estimator_eval.py @@ -185,6 +185,7 @@ def replay( calc_type=record.get("calc_type"), gpu_used=record.get("gpu_used"), source=record.get("source") if use_source else None, + density_fit=record.get("density_fit"), ) history.append(record) if predicted is None or float(predicted["seconds"]) <= 0: 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/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/help_content.py b/quantui/help_content.py index 07fb435e..7b8590d8 100644 --- a/quantui/help_content.py +++ b/quantui/help_content.py @@ -256,8 +256,9 @@ "not cover most heavier metals, so a calculation on, say, a " "platinum or palladium complex will stop with a message asking you " "to switch. " - "Use def2-SVP or def2-TZVP — these carry effective " - "core potentials that cover the whole periodic table (or " + "Use def2-SVP or def2-TZVP — these cover hydrogen to " + "radon (except the lanthanides Ce–Lu), with effective core " + "potentials from rubidium on (or " "LANL2DZ, an ECP basis for the heaviest centres). Remember to " "set the charge and multiplicity from the metal's oxidation " "state, and for a reliable starting geometry load one of the " @@ -333,7 +334,7 @@ "" "

How much accuracy do you lose? On a real test case " "(aspirin, B3LYP/6-31G*), the total energy changed by about " - "0.008 kcal/mol — hundreds of times smaller than " + "0.008 kcal/mol — more than 100 times smaller than " "‘chemical accuracy’ (1 kcal/mol), and far below the " "error of the functional itself. For most purposes it is " "invisible.

" @@ -722,10 +723,10 @@ "viewer; Clear resets the selection.

" "

Note: this needs the py3Dmol viewer — if the " "panel shows a message instead of the picker, switch backends " - "with the toggle above the viewer (or in Settings). Switching " - "molecules or leaving the Analysis tab clears the current " - "selection, so a measurement is never shown against the wrong " - "structure.

" + "with the toggle above the viewer (or in Settings). Whenever the " + "Analysis viewer is redrawn — a new result loaded, or the viewer " + "backend switched — the current selection is cleared, so a " + "measurement is never shown against the wrong structure.

" "

If four picked atoms include three that fall in a straight " "line, the dihedral has no defined plane — the panel reports " "this rather than showing a number.

" @@ -812,6 +813,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/inorganic_guards.py b/quantui/inorganic_guards.py index 2db2cf79..39bb83c3 100644 --- a/quantui/inorganic_guards.py +++ b/quantui/inorganic_guards.py @@ -21,7 +21,8 @@ from typing import Iterable, List, Optional # def2 basis sets QuantUI ships that carry effective core potentials for heavy -# elements (so they cover the whole periodic table, unlike the Pople / cc sets). +# elements: H–Rn except the lanthanides Ce–Lu (ECPs from Rb on), far wider +# than the Pople / cc sets. No def2 set covers the actinides. _ECP_BASIS_SUGGESTION = "def2-SVP or def2-TZVP" @@ -94,8 +95,9 @@ def check_basis_coverage(elements: Iterable[str], basis: str) -> Optional[str]: return ( f"The basis set '{basis}' has no parameters for {els}. " f"Transition metals and other heavy elements need an ECP basis — switch " - f"to {_ECP_BASIS_SUGGESTION} (these cover the whole periodic table via " - f"effective core potentials) and run again." + f"to {_ECP_BASIS_SUGGESTION} (these cover hydrogen to radon, except the " + f"lanthanides Ce–Lu, using effective core potentials from rubidium on) " + f"and run again." ) 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/issue_tracker.py b/quantui/issue_tracker.py index 0324c901..b5b551cf 100644 --- a/quantui/issue_tracker.py +++ b/quantui/issue_tracker.py @@ -29,9 +29,10 @@ import os import sqlite3 import threading +from contextlib import contextmanager from datetime import datetime, timezone from pathlib import Path -from typing import Optional +from typing import Iterator, Optional _LOCK = threading.Lock() @@ -64,10 +65,25 @@ def _db_path() -> Path: """ +@contextmanager +def _connect(path: Path) -> Iterator[sqlite3.Connection]: + """Open *path*, commit on success, and always CLOSE the connection. + + ``sqlite3.connect`` used as a context manager only commits/rolls back; + it never closes, so every call leaked a connection (audit DATA-17). + """ + conn = sqlite3.connect(str(path)) + try: + with conn: + yield conn + finally: + conn.close() + + def _init_db() -> None: db = _db_path() db.parent.mkdir(parents=True, exist_ok=True) - with sqlite3.connect(str(db)) as conn: + with _connect(db) as conn: conn.execute(_CREATE_TABLE) conn.commit() @@ -98,7 +114,7 @@ def log_issue( ts = datetime.now(timezone.utc).isoformat() ctx_json = json.dumps(context or {}, ensure_ascii=False) with _LOCK: - with sqlite3.connect(str(_db_path())) as conn: + with _connect(_db_path()) as conn: cursor = conn.execute( "INSERT INTO issues (timestamp, description, session_id, context_json)" " VALUES (?, ?, ?, ?)", @@ -136,7 +152,7 @@ def get_issues(n: int = 50) -> list[dict]: db = _db_path() if not db.exists(): return [] - with sqlite3.connect(str(db)) as conn: + with _connect(db) as conn: rows = conn.execute( "SELECT id, timestamp, description, session_id, context_json" " FROM issues ORDER BY id DESC LIMIT ?", @@ -164,7 +180,7 @@ def clear_issues() -> None: if not db.exists(): return with _LOCK: - with sqlite3.connect(str(db)) as conn: + with _connect(db) as conn: conn.execute("DROP TABLE IF EXISTS issues") conn.execute(_CREATE_TABLE) conn.commit() diff --git a/quantui/log_utils.py b/quantui/log_utils.py index 1b77a62b..f3507d73 100644 --- a/quantui/log_utils.py +++ b/quantui/log_utils.py @@ -10,6 +10,7 @@ import os import platform +import re import socket import subprocess import uuid @@ -417,10 +418,7 @@ def _extract_warnings( if not stripped: continue lower = stripped.lower() - if any( - kw in lower - for kw in ("warn", "error", "failed", "not converge", "imaginary") - ): + if _DIGEST_KEYWORDS.search(lower): if drop_degeneracy and _is_homo_lumo_degeneracy_warning(lower): continue if stripped not in seen: @@ -429,6 +427,15 @@ def _extract_warnings( return found +# Whole-word keywords for the warnings digest. A bare substring test also +# flagged identifiers that merely contain the letters ("error_tol", +# "terror", "unfailed") — audit DATA-17. "warn" stays a prefix so "warning", +# "warnings.warn" and "UserWarning" still match. +_DIGEST_KEYWORDS = re.compile( + r"warn|\berrors?\b|\bfailed\b|\bnot converge|\bimaginary\b" +) + + def format_log_footer( *, result: Any, diff --git a/quantui/measurement.py b/quantui/measurement.py index 2322beb9..91c06b9e 100644 --- a/quantui/measurement.py +++ b/quantui/measurement.py @@ -66,8 +66,16 @@ def describe_picks(molecule: Molecule, picks: Sequence[int]) -> str: d = distance(molecule, picks[0], picks[1]) parts.append(f"{atom_label(molecule, picks[1])} ({d:.3f} Å)") if len(picks) >= 3: - a = angle(molecule, picks[0], picks[1], picks[2]) - parts.append(f"{atom_label(molecule, picks[2])} ({a:.1f}°)") + try: + a = angle(molecule, picks[0], picks[1], picks[2]) + parts.append(f"{atom_label(molecule, picks[2])} ({a:.1f}°)") + except ZeroDivisionError: + # ASE: "Undefined angle" when the vertex coincides with a + # neighbour (zero-length bond vector). + parts.append( + f"{atom_label(molecule, picks[2])} " + "(angle undefined — two atoms coincide)" + ) if len(picks) >= 4: try: dh = dihedral(molecule, picks[0], picks[1], picks[2], picks[3]) diff --git a/quantui/molecule.py b/quantui/molecule.py index dad159d2..7c653c0a 100644 --- a/quantui/molecule.py +++ b/quantui/molecule.py @@ -8,6 +8,7 @@ import logging import math import numbers +import re from typing import Any, Dict, List, Optional, Tuple from . import config, utils @@ -250,14 +251,16 @@ def count_electrons(self) -> int: """ return self.get_electron_count() - def get_spin(self) -> int: + def get_spin(self) -> float: """ Get spin quantum number S from multiplicity (2S+1). Returns: - int: Number of unpaired electrons / 2 + float: S = (multiplicity - 1) / 2 — 0.5 for a doublet. (Integer + division used to return 0 for a doublet; audit DATA-17.) PySCF's + ``mol.spin`` is 2S, i.e. ``multiplicity - 1``. """ - return (self.multiplicity - 1) // 2 + return (self.multiplicity - 1) / 2 def to_dict(self) -> Dict[str, Any]: """ @@ -329,15 +332,57 @@ def _count_xyz_frames(lines: List[str], count_idx: int, n_atoms: int) -> int: return max(frames, 1) +#: Hydrogen isotope labels read as plain H (audit DATA-16). +_ISOTOPE_LABELS = frozenset({"D", "T"}) +ISOTOPE_NOTE = ( + "Hydrogen isotope labels (D/T) were read as H. QuantUI uses standard " + "isotope masses, so vibrational frequencies are those of the ordinary-H " + "molecule." +) +# Fortran double-precision exponent: 1.17D-01 -> 1.17e-01. +_FORTRAN_EXP = re.compile(r"(?<=[\d.])[dD](?=[+-]?\d)") + + +def normalize_xyz_text(text: str) -> str: + """Undo common text-encoding quirks in coordinate text (audit DATA-16). + + Strips a UTF-8 byte-order mark (Windows Notepad), converts CRLF and + old-Mac CR line endings to LF, and turns the Unicode minus sign (U+2212, + from word processors and web pages) into an ASCII hyphen-minus. + """ + text = text.lstrip("\ufeff") + text = text.replace("\r\n", "\n").replace("\r", "\n") + return text.replace("\u2212", "-") + + +def _xyz_float(token: str) -> float: + """``float`` that also accepts Fortran ``D`` exponents.""" + return float(_FORTRAN_EXP.sub("e", token)) + + +def _xyz_symbol(symbol: str) -> str: + """Element symbol with the D/T isotope labels mapped to H.""" + return "H" if symbol in _ISOTOPE_LABELS else symbol + + +def has_isotope_labels(xyz_text: str) -> bool: + """Whether any coordinate row of *xyz_text* uses a D or T label.""" + for line in normalize_xyz_text(xyz_text).split("\n"): + parts = line.split() + if len(parts) >= 4 and parts[0] in _ISOTOPE_LABELS and _is_atom_row(line): + return True + return False + + def _is_atom_row(line: str) -> bool: """True if *line* reads as ``SYMBOL X Y Z`` (inline comments ignored).""" for comment_char in ("#", "!"): line = line.split(comment_char)[0] parts = line.split() - if len(parts) < 4 or not utils.validate_atom_symbol(parts[0]): + if len(parts) < 4 or not utils.validate_atom_symbol(_xyz_symbol(parts[0])): return False try: - float(parts[1]), float(parts[2]), float(parts[3]) + _xyz_float(parts[1]), _xyz_float(parts[2]), _xyz_float(parts[3]) except ValueError: return False return True @@ -399,6 +444,8 @@ def parse_xyz_input(xyz_text: str) -> Tuple[List[str], List[List[float]]]: Raises: ValueError: If input format is invalid """ + if xyz_text: + xyz_text = normalize_xyz_text(xyz_text) if not xyz_text or not xyz_text.strip(): raise ValueError( "❌ Empty Input: Please provide XYZ coordinates.\n\n" @@ -514,7 +561,7 @@ def parse_xyz_input(xyz_text: str) -> Tuple[List[str], List[List[float]]]: f" 2. Three coordinate values (X, Y, Z)" ) - atom_symbol = parts[0] + atom_symbol = _xyz_symbol(parts[0]) # Validate atom symbol with helpful suggestions if not utils.validate_atom_symbol(atom_symbol): @@ -581,7 +628,7 @@ def parse_xyz_input(xyz_text: str) -> Tuple[List[str], List[List[float]]]: # Parse coordinates try: - x, y, z = float(parts[1]), float(parts[2]), float(parts[3]) + x, y, z = _xyz_float(parts[1]), _xyz_float(parts[2]), _xyz_float(parts[3]) except ValueError as e: raise ValueError( f"❌ Line {orig_line_num}: Could not parse coordinates as numbers.\n\n" diff --git a/quantui/molecule_library.py b/quantui/molecule_library.py index a4624e00..1a0e6b3c 100644 --- a/quantui/molecule_library.py +++ b/quantui/molecule_library.py @@ -374,14 +374,22 @@ def search( materialize the chosen entry. Empty ``query`` lists entries (optionally filtered by ``category``). """ - q = f"%{query.strip().lower()}%" + # Escape LIKE wildcards: a "%" or "_" typed by the user is a literal + # character, not "match anything" (audit DATA-17). + _needle = query.strip().lower() + q = ( + "%" + + _needle.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + + "%" + ) con = _connect_ro() if con is not None: try: sql = ( "SELECT id, name, formula, category, n_heavy, n_atoms, charge, " "multiplicity, source FROM molecule WHERE " - "(lower(name) LIKE ? OR lower(formula) LIKE ? OR lower(synonyms) LIKE ?)" + "(lower(name) LIKE ? ESCAPE '\\' OR lower(formula) LIKE ? ESCAPE '\\' " + "OR lower(synonyms) LIKE ? ESCAPE '\\')" ) params: List[Any] = [q, q, q] if category: diff --git a/quantui/nmr_plot.py b/quantui/nmr_plot.py index 9659bf0a..f8c6cc32 100644 --- a/quantui/nmr_plot.py +++ b/quantui/nmr_plot.py @@ -16,6 +16,15 @@ "¹³C": (0.0, 220.0), } +# Shifts closer than this (ppm) are drawn as one stick (equivalent nuclei). +# Scaled with each nucleus's shift range: ¹H shifts are quoted to 0.01 ppm, +# ¹³C to 0.1 ppm, and symmetry-equivalent carbons in an unsymmetrised +# geometry differ by more than ¹H's 0.05 ppm window (audit VIZ-14). +_MERGE_WINDOW_PPM = { + "¹H": 0.05, + "¹³C": 0.5, +} + def plot_nmr_spectrum( shifts: Sequence[Tuple[int, float]], @@ -23,6 +32,7 @@ def plot_nmr_spectrum( *, nucleus_label: str = "¹H", x_range: Optional[Tuple[float, float]] = None, + descending: bool = True, ) -> go.Figure: """Return a stick Plotly figure for isotropic chemical shifts (δ, ppm). @@ -31,6 +41,8 @@ def plot_nmr_spectrum( atom_symbols: Full molecule atom list (for peak labels). nucleus_label: Display label (``"¹H"`` or ``"¹³C"``). x_range: Optional fixed ``(xmin, xmax)`` in ppm. + descending: Draw δ high → low, left to right (the NMR convention, + default); ``False`` gives an ascending axis. """ pairs = [(int(i), float(d)) for i, d in shifts if i < len(atom_symbols)] pairs.sort(key=lambda p: p[1]) @@ -54,7 +66,7 @@ def plot_nmr_spectrum( layout=dict( xaxis=dict( title="Chemical shift δ (ppm)", - range=[xmin, xmax], + range=[xmax, xmin] if descending else [xmin, xmax], showgrid=True, gridcolor="#e5e7eb", ), @@ -76,13 +88,14 @@ def plot_nmr_spectrum( if not pairs: return fig - # Equivalent nuclei (same δ within 0.05 ppm) share one stick, labelled - # with every atom and as tall as their count — the integration a student - # reads off a real spectrum. Separate labels used to print on top of - # each other. + # Equivalent nuclei (same δ within the nucleus's merge window) share one + # stick, labelled with every atom and as tall as their count — the + # integration a student reads off a real spectrum. Separate labels used to + # print on top of each other. + window = _MERGE_WINDOW_PPM.get(nucleus_label, 0.05) groups: List[List[Tuple[int, float]]] = [] for idx, delta in pairs: - if groups and abs(groups[-1][-1][1] - delta) < 0.05: + if groups and abs(groups[-1][-1][1] - delta) < window: groups[-1].append((idx, delta)) else: groups.append([(idx, delta)]) 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/quantui/orbital_visualization.py b/quantui/orbital_visualization.py index 38408ee7..909175a6 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)}
    " @@ -903,7 +904,10 @@ def generate_cube_file( " conda install -c conda-forge pyscf" ) from exc - data = np.load(results_path, allow_pickle=True) + # allow_pickle=False: results.npz may come from someone else's folder, and + # unpickling an object array runs arbitrary code. Every key read here is a + # plain numeric or string array (mol_atom/mol_basis are saved as str). + data = np.load(results_path, allow_pickle=False) mo_coeff = data["mo_coeff"] mo_occ = data["mo_occ"] if "mo_occ" in data else None if mo_coeff.ndim == 3: @@ -1572,6 +1576,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 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. @@ -1825,17 +1834,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( @@ -1872,14 +1892,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( @@ -2586,7 +2609,11 @@ def load_frontier_cube( spins = ("beta",) if beta else ("alpha", "") for entry in _frontier_index(result_dir): - if int(entry.get("index", -1)) != int(orbital_index): + try: + entry_index = int(entry.get("index", -1)) + except (TypeError, ValueError): # malformed index.json entry + continue + if entry_index != int(orbital_index): continue if entry.get("spin", "") not in spins: continue 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/quantui/pubchem.py b/quantui/pubchem.py index d5841c42..7ccbc88f 100644 --- a/quantui/pubchem.py +++ b/quantui/pubchem.py @@ -615,6 +615,21 @@ def check_pubchem_availability() -> bool: # ============================================================================ +#: Largest molecule (atoms incl. H) embedded locally from SMILES/InChI. RDKit +#: embedding + UFF of a protein-sized string can tie up the kernel for +#: minutes, far beyond anything QuantUI can then compute (audit DATA-17). +MAX_LOCAL_EMBED_ATOMS = 500 + + +def _check_embed_size(mol: Any) -> None: + n = mol.GetNumAtoms() + if n > MAX_LOCAL_EMBED_ATOMS: + raise ValueError( + f"Structure has {n} atoms (with hydrogens); the limit for building " + f"3-D coordinates here is {MAX_LOCAL_EMBED_ATOMS}." + ) + + def smiles_to_xyz(smiles: str, optimize_3d: bool = True) -> Tuple[str, Dict[str, Any]]: """ Convert SMILES string to XYZ coordinates with 3D structure generation. @@ -643,22 +658,24 @@ def smiles_to_xyz(smiles: str, optimize_3d: bool = True) -> Tuple[str, Dict[str, # Add hydrogens mol = Chem.AddHs(mol) + _check_embed_size(mol) - # Generate 3D coordinates - if optimize_3d: - # Generate conformer - result = AllChem.EmbedMolecule(mol, randomSeed=42) - if result != 0: - # Try with random coords if embedding fails - AllChem.EmbedMolecule(mol, randomSeed=42, useRandomCoords=True) + # Generate 3D coordinates. Always embed — the XYZ needs a conformer; + # ``optimize_3d=False`` only skips the UFF clean-up (it used to skip + # the embedding too, so it always raised — audit DATA-17). + result = AllChem.EmbedMolecule(mol, randomSeed=42) + if result != 0: + # Try with random coords if embedding fails + AllChem.EmbedMolecule(mol, randomSeed=42, useRandomCoords=True) + if optimize_3d: # Optimize with UFF force field try: AllChem.UFFOptimizeMolecule(mol) except Exception: logger.warning("UFF optimization failed, using unoptimized coordinates") - _separate_fragments(mol) # keep salt counterions apart + _separate_fragments(mol) # keep salt counterions apart # Extract coordinates if mol.GetNumConformers() == 0: @@ -715,16 +732,17 @@ def inchi_to_xyz(inchi: str, optimize_3d: bool = True) -> Tuple[str, Dict[str, A raise ValueError(f"Invalid InChI string: {inchi}") mol = Chem.AddHs(mol) + _check_embed_size(mol) + result = AllChem.EmbedMolecule(mol, randomSeed=42) + if result != 0: + AllChem.EmbedMolecule(mol, randomSeed=42, useRandomCoords=True) if optimize_3d: - result = AllChem.EmbedMolecule(mol, randomSeed=42) - if result != 0: - AllChem.EmbedMolecule(mol, randomSeed=42, useRandomCoords=True) try: AllChem.UFFOptimizeMolecule(mol) except Exception: logger.warning("UFF optimization failed, using unoptimized coordinates") - _separate_fragments(mol) # keep salt counterions apart + _separate_fragments(mol) # keep salt counterions apart if mol.GetNumConformers() == 0: raise ValueError("Failed to generate 3D coordinates") 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/reorganization_energy.py b/quantui/reorganization_energy.py index 851289c5..004e4baf 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``. @@ -681,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/quantui/results_storage.py b/quantui/results_storage.py index b82a7f82..32e8fbe7 100644 --- a/quantui/results_storage.py +++ b/quantui/results_storage.py @@ -24,6 +24,7 @@ from __future__ import annotations import json +import math import os import re from datetime import datetime @@ -131,6 +132,58 @@ def _safe_name(s: str) -> str: return re.sub(r"[^\w\-]", "x", s) +# Cap on each formula/method/basis component of a result directory name: a +# long custom basis string otherwise pushed the name past the 255-byte +# filename limit and save_result raised OSError (audit DATA-11). +_MAX_NAME_COMPONENT = 48 + + +def _json_safe(obj: Any) -> Any: + """Recursively convert *obj* into strict-JSON-serialisable plain data. + + numpy scalars/arrays become Python numbers/lists, ``Path`` becomes + ``str``, and non-finite floats (NaN/inf) become ``None`` — ``json.dumps`` + would otherwise write bare ``NaN``, which strict JSON readers reject. + Anything else unknown is left for ``json.dumps(default=str)``. + """ + if isinstance(obj, dict): + return {str(k): _json_safe(v) for k, v in obj.items()} + if isinstance(obj, (list, tuple)): + return [_json_safe(v) for v in obj] + if isinstance(obj, bool) or obj is None or isinstance(obj, str): + return obj + if isinstance(obj, Path): + return str(obj) + if hasattr(obj, "tolist") and callable(obj.tolist): + # numpy ndarray or numpy scalar (np.bool_, np.int64, np.float32, ...) + try: + return _json_safe(obj.tolist()) + except Exception: # noqa: BLE001 — fall through to default=str + return obj + if isinstance(obj, float): + return obj if math.isfinite(obj) else None + return obj + + +def _dumps_json_safe(data: Any, **kwargs: Any) -> str: + """``json.dumps`` after :func:`_json_safe`; raises nothing for odd values.""" + return json.dumps(_json_safe(data), allow_nan=False, default=str, **kwargs) + + +def _atomic_write_text(path: Path, text: str) -> None: + """Write *text* to *path* via a sibling temp file + ``os.replace``.""" + tmp = path.with_name(path.name + ".tmp") + try: + tmp.write_text(text) + os.replace(tmp, path) + except BaseException: + try: + tmp.unlink() + except OSError: + pass + raise + + def _opt_float(x: object) -> Optional[float]: """Coerce an optional (possibly numpy) scalar to a JSON-safe float or None.""" if x is None: @@ -333,19 +386,13 @@ def save_result( dirname = "_".join( [ ts, - _safe_name(getattr(result, "formula", "unknown")), - _safe_name(getattr(result, "method", "unknown")), - _safe_name(getattr(result, "basis", "unknown")), + _safe_name(str(getattr(result, "formula", "unknown")))[ + :_MAX_NAME_COMPONENT + ], + _safe_name(str(getattr(result, "method", "unknown")))[:_MAX_NAME_COMPONENT], + _safe_name(str(getattr(result, "basis", "unknown")))[:_MAX_NAME_COMPONENT], ] ) - dest = base / dirname - # Windows timer resolution can produce identical microsecond timestamps for - # back-to-back calls; append a counter to guarantee a unique directory. - _collision = 1 - while dest.exists(): - dest = base / f"{dirname}_{_collision}" - _collision += 1 - dest.mkdir(parents=True) _e_ha_raw = getattr(result, "energy_hartree", float("nan")) _e_ha = _opt_float(_e_ha_raw) @@ -439,7 +486,27 @@ def save_result( data["geometry"] = _geom if extras: data.update(extras) - (dest / "result.json").write_text(json.dumps(data, indent=2)) + # Serialise BEFORE creating the directory: a numpy bool/array or other + # non-JSON value used to raise TypeError after mkdir, leaving an empty + # result directory and losing the save (audit DATA-11). + payload = _dumps_json_safe(data, indent=2) + + dest = base / dirname + # Windows timer resolution can produce identical microsecond timestamps for + # back-to-back calls; append a counter to guarantee a unique directory. + _collision = 1 + while dest.exists(): + dest = base / f"{dirname}_{_collision}" + _collision += 1 + dest.mkdir(parents=True) + try: + _atomic_write_text(dest / "result.json", payload) + except BaseException: + try: + dest.rmdir() + except OSError: + pass + raise if pyscf_log: (dest / "pyscf.log").write_text(pyscf_log) @@ -1037,7 +1104,8 @@ def save_trajectory( for i, mol in enumerate(trajectory) ], } - (result_dir / filename).write_text(json.dumps(data)) + # numpy float32 coordinates/energies are not JSON-serialisable as-is. + (result_dir / filename).write_text(_dumps_json_safe(data)) def load_trajectory(result_dir: Path, filename: str = "trajectory.json"): @@ -1080,21 +1148,35 @@ def save_thumbnail(result_dir: Path, data: dict) -> None: Silently skips if matplotlib is unavailable or any error occurs. """ try: - import matplotlib - - matplotlib.use("Agg") - import matplotlib.pyplot as plt + from matplotlib.backends.backend_agg import FigureCanvasAgg + from matplotlib.figure import Figure except ImportError: return + class _AggOnly: + """The one ``plt`` call the builder makes, without pyplot. + + ``matplotlib.use("Agg")`` here switched the backend for the whole + kernel, breaking a student's inline/widget plots after the first + saved result (audit DATA-17). A bare Figure on its own Agg canvas + renders the PNG without touching pyplot's global state. + """ + + @staticmethod + def figure(**kwargs: Any) -> Any: + fig = Figure(**kwargs) + FigureCanvasAgg(fig) + return fig + + plt = _AggOnly + # Fix (2026-07-14): only the matplotlib import itself was # guarded — figure construction, text rendering, and fig.savefig() (a # real filesystem write, so it can hit disk-full / permission errors) # could all raise past this function despite the docstring's promise # to silently skip "any error". Wrap the whole body so that promise - # actually holds; fig.close() still runs via finally regardless of - # where in the body a failure happened. - fig = None + # actually holds. (The figure is not registered with pyplot, so there + # is nothing to close.) try: fig = _build_thumbnail_figure(plt, data) fig.savefig( @@ -1106,9 +1188,6 @@ def save_thumbnail(result_dir: Path, data: dict) -> None: ) except Exception: pass - finally: - if fig is not None: - plt.close(fig) def _build_thumbnail_figure(plt: Any, data: dict) -> Any: 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 d7c76e73..090af966 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 @@ -1079,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/structure_edit.py b/quantui/structure_edit.py index 433afb6c..fbcc5dd2 100644 --- a/quantui/structure_edit.py +++ b/quantui/structure_edit.py @@ -255,16 +255,44 @@ def add_hydrogen(mol: Molecule, i: int) -> Tuple[Molecule, str]: ) +#: Ceiling for a range when the atom count is unknown (no molecule loaded). +_MAX_ATOM_NUMBER = 100_000 + + +class _RangeError(Exception): + """An in-range check failed in parse_atom_list (kept apart from int()).""" + + def parse_atom_list(text: str, n_atoms: Optional[int] = None) -> List[int]: """'1, 3 5-7' (1-based, ranges allowed) → sorted 0-based indices.""" out: Set[int] = set() for token in text.replace(",", " ").split(): - if "-" in token: - lo, hi = token.split("-", 1) - a, b = int(lo), int(hi) - out.update(range(min(a, b), max(a, b) + 1)) - else: - out.add(int(token)) + try: + if "-" in token: + lo, hi = token.split("-", 1) + a, b = sorted((int(lo), int(hi))) + # Bounds-check BEFORE expanding: "1-30000000" used to build + # the whole set first (seconds; larger ranges exhausted + # memory) only to be rejected afterwards (audit DATA-17). + if a < 1: + raise _RangeError("Atom numbers start at 1.") + limit = n_atoms if n_atoms is not None else _MAX_ATOM_NUMBER + if b > limit: + raise _RangeError( + f"This structure has only {n_atoms} atoms." + if n_atoms is not None + else f"Atom number {b} is out of range." + ) + out.update(range(a, b + 1)) + else: + out.add(int(token)) + except _RangeError as exc: + raise ValueError(str(exc)) from None + except ValueError: + # int() alone said "invalid literal for int() with base 10". + raise ValueError( + f"'{token}' is not an atom number or range (e.g. 1, 3, 5-7)." + ) from None if any(n < 1 for n in out): raise ValueError("Atom numbers start at 1.") if n_atoms is not None and any(n > n_atoms for n in out): diff --git a/quantui/structure_upload.py b/quantui/structure_upload.py index 0a62dbbb..6ec9cbe2 100644 --- a/quantui/structure_upload.py +++ b/quantui/structure_upload.py @@ -23,7 +23,15 @@ from pathlib import Path from typing import List, Optional, Tuple -from .molecule import Molecule +from .molecule import ( + _FORTRAN_EXP, + _ISOTOPE_LABELS, + ISOTOPE_NOTE, + Molecule, + _is_atom_row, + normalize_xyz_text, + parse_xyz_input, +) SUPPORTED_SUFFIXES = ( ".xyz", @@ -53,9 +61,111 @@ class UploadedStructure: notes: List[str] +#: Longest stem kept from an uploaded filename (the temp file is named after +#: it; an over-long name used to raise a raw OSError — audit DATA-16). +_MAX_STEM_CHARS = 100 + + def _safe_filename(name: str) -> str: stem = re.sub(r"[^A-Za-z0-9_.-]+", "_", Path(str(name)).name).strip("._") - return stem or "upload" + if not stem: + return "upload" + suffix = Path(stem).suffix[:16] + base = stem[: len(stem) - len(Path(stem).suffix)] if Path(stem).suffix else stem + return (base[:_MAX_STEM_CHARS] or "upload") + suffix + + +def _decode_upload_text(content: bytes) -> str: + """Decode an uploaded text file: UTF-16 (BOM) or UTF-8, normalised. + + Every supported format is text. UTF-16 files (some Windows exports) used + to fail with a raw decode error and a UTF-8 BOM broke the XYZ count line + (audit DATA-16); line endings and the Unicode minus are normalised too. + """ + if content.startswith((b"\xff\xfe", b"\xfe\xff")): + text = content.decode("utf-16", errors="replace") + else: + text = content.decode("utf-8", errors="replace") + return normalize_xyz_text(text) + + +def _prepare_xyz(text: str, notes: List[str]) -> str: + """Map D/T labels to H and Fortran D exponents to E on XYZ atom rows.""" + out: List[str] = [] + mapped = False + for line in text.split("\n"): + if _is_atom_row(line): + m = re.match(r"(\s*)(\S+)(.*)", line) + assert m is not None # an atom row has a symbol + lead, symbol, rest = m.groups() + if symbol in _ISOTOPE_LABELS: + symbol, mapped = "H", True + line = lead + symbol + _FORTRAN_EXP.sub("e", rest) + out.append(line) + if mapped: + notes.append(ISOTOPE_NOTE) + return "\n".join(out) + + +def _xyz_is_headerless(text: str) -> bool: + """True when the first content line is not an XYZ atom-count line.""" + for line in text.split("\n"): + if line.strip(): + try: + int(line.strip()) + except ValueError: + return True + return False + return False + + +def _last_xyz_comment(text: str) -> Optional[str]: + """Comment line of the LAST frame of a (multi-frame) XYZ file.""" + lines = text.split("\n") + idx, comment = 0, None + while idx < len(lines): + stripped = lines[idx].strip() + if not stripped: + idx += 1 + continue + try: + n = int(stripped) + except ValueError: + break + if idx + 1 < len(lines): + comment = lines[idx + 1] + idx += n + 2 + return comment + + +def _drop_pdb_altlocs(text: str, notes: List[str]) -> str: + """Keep one alternate location per atom (``A``, else the first seen). + + ASE loads every altLoc record, so a water with two conformers of O came + out as H2O2 (audit DATA-16). + """ + lines = text.split("\n") + alts = [ + ln[16] + for ln in lines + if ln.startswith(("ATOM", "HETATM")) and len(ln) > 16 and ln[16] != " " + ] + if not alts: + return text + keep = "A" if "A" in alts else alts[0] + kept = [ + ln + for ln in lines + if not ( + ln.startswith(("ATOM", "HETATM")) + and len(ln) > 16 + and ln[16] not in (" ", keep) + ) + ] + notes.append( + f"The PDB file has alternate atom locations; loaded altLoc '{keep}' only." + ) + return "\n".join(kept) def _gaussian_input_charge_mult(text: str) -> Optional[Tuple[int, int]]: @@ -168,9 +278,11 @@ def _from_ase( from_file = True notes.append("Loaded the last geometry in the Gaussian output.") elif suffix == ".xyz": - lines = text.splitlines() - if len(lines) > 1: - m = _CHARGE_MULT_COMMENT.search(lines[1]) + # The geometry comes from the LAST frame, so its comment line is the + # one that describes it (was: always frame 1's — audit DATA-16). + comment = _last_xyz_comment(text) + if comment is not None: + m = _CHARGE_MULT_COMMENT.search(comment) if m: charge, multiplicity = int(m.group(1)), int(m.group(2)) from_file = True @@ -217,11 +329,29 @@ def read_uploaded_structure( if len(content) > MAX_UPLOAD_BYTES: raise ValueError("File is too large for a structure upload (limit 20 MB).") notes: List[str] = [] + text = _decode_upload_text(content) + if suffix == ".xyz": + text = _prepare_xyz(text, notes) + elif suffix == ".pdb": + text = _drop_pdb_altlocs(text, notes) with tempfile.TemporaryDirectory(prefix="quantui-upload-") as tmp: path = Path(tmp) / safe - path.write_bytes(content) try: - if suffix in (".mol", ".sdf", ".mol2"): + path.write_text(text, encoding="utf-8") + if suffix == ".xyz" and _xyz_is_headerless(text): + # Bare "SYMBOL X Y Z" rows, as the paste box accepts. + atoms, coords = parse_xyz_input(text) + mol, from_file = ( + Molecule( + atoms, + coords, + charge=int(charge), + multiplicity=int(multiplicity), + validate_spin=False, + ), + False, + ) + elif suffix in (".mol", ".sdf", ".mol2"): mol, from_file = _from_rdkit(path, suffix, charge, multiplicity, notes) else: mol, from_file = _from_ase(path, suffix, charge, multiplicity, notes) 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 c3f35489..7191a06f 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 " @@ -254,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( @@ -391,6 +408,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/quantui/user_settings.py b/quantui/user_settings.py index 0517cd1c..d90010b2 100644 --- a/quantui/user_settings.py +++ b/quantui/user_settings.py @@ -165,7 +165,11 @@ def load(cls, path: Path | None = None) -> UserSettings: return cls() try: data = json.loads(resolved.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError) as exc: + except (OSError, ValueError, RecursionError) as exc: + # ValueError covers JSONDecodeError AND UnicodeDecodeError + # (non-UTF-8 bytes); RecursionError a pathologically nested + # file. Any of them used to escape and crash app construction + # (audit DATA-12). _LOG.warning( "Failed to read settings at %s (%s); using defaults", resolved, @@ -390,10 +394,11 @@ def save(self, path: Path | None = None) -> None: ) return + payload = self._merge_unknown(self._read_existing(resolved), self.to_dict()) tmp = resolved.with_suffix(resolved.suffix + ".tmp") try: tmp.write_text( - json.dumps(self.to_dict(), indent=2) + "\n", + json.dumps(payload, indent=2) + "\n", encoding="utf-8", ) os.replace(tmp, resolved) @@ -409,6 +414,35 @@ def save(self, path: Path | None = None) -> None: except OSError: pass + @staticmethod + def _read_existing(resolved: Path) -> dict: + """Return the settings file's current JSON object, or ``{}``.""" + try: + data = json.loads(resolved.read_text(encoding="utf-8")) + except (OSError, ValueError, RecursionError): + return {} + return data if isinstance(data, dict) else {} + + @staticmethod + def _merge_unknown(existing: dict, ours: dict) -> dict: + """Carry sections/keys this version does not know into *ours*. + + A save used to rewrite the file from the three known sections only, + erasing anything a newer QuantUI (or a hand edit) had added (audit + DATA-12). Only a same-schema-version file is merged; known keys + always take this instance's values. + """ + if existing.get("_schema_version") != ours.get("_schema_version"): + return ours + merged = dict(existing) + for key, value in ours.items(): + old = existing.get(key) + if isinstance(value, dict) and isinstance(old, dict): + merged[key] = {**old, **value} + else: + merged[key] = value + return merged + @classmethod def _resolve_path(cls, path: Path | None) -> Path: if path is not None: diff --git a/quantui/vib_cache.py b/quantui/vib_cache.py index 2f7a58ef..ac43ac50 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} } } @@ -67,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 @@ -256,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/quantui/visualization_py3dmol.py b/quantui/visualization_py3dmol.py index e52f7398..c6069466 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 @@ -467,10 +468,13 @@ def visualize_molecule( """ # Determine backend if backend == "auto": - if PLOTLYMOL_AVAILABLE: - backend = "plotlymol" - elif PY3DMOL_AVAILABLE: + # py3Dmol first, as documented above and as the info box reports + # (get_available_backends()[0]); this used to pick PlotlyMol whenever + # it was installed (audit VIZ-14). + if PY3DMOL_AVAILABLE: backend = "py3dmol" + elif PLOTLYMOL_AVAILABLE: + backend = "plotlymol" else: raise ImportError( "No visualization backend available. Install one of:\n" @@ -675,7 +679,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. @@ -774,27 +778,6 @@ def display_molecule( logger.error(f"Display failed for {molecule.get_formula()}: {e}") -def get_installation_message() -> str: - """ - Get installation instructions for visualization backends. - - Returns: - Formatted string with installation instructions - """ - return """ -To enable 3D molecular visualization: - -Option 1 (Recommended): py3Dmol - pip install py3dmol - -Option 2 (Optional): PlotlyMol - conda install -c conda-forge rdkit plotly kaleido - pip install plotlymol - -For most users, py3Dmol is sufficient and more stable. -""" - - # Module-level check and logging available = get_available_backends() if available: diff --git a/quantui/viz_assets.py b/quantui/viz_assets.py index 8a824172..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 @@ -50,6 +51,10 @@ # at, so the API the py3Dmol-generated JS calls (createViewer, addModel, # addVolumetricData, addModelsAsFrames, animate, ...) is guaranteed present. # Provenance + license: data/js/PROVENANCE.md, data/js/3Dmol-LICENSE.txt. +# py3Dmol's own default may be a later PATCH of the same minor (py3Dmol 2.5.5 +# targets 3Dmol.js 2.5.5) — tolerated; pyproject caps py3Dmol below the next +# minor and tests/test_viz_assets_version.py fails on a minor mismatch +# (audit INFRA-16). THREEDMOL_VERSION = "2.5.4" _JS_PATH = Path(__file__).parent / "data" / "js" / "3Dmol-min.js" @@ -110,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/testing/mock-slurm/mock_slurm_cli.py b/testing/mock-slurm/mock_slurm_cli.py index 445d4d65..534effc3 100644 --- a/testing/mock-slurm/mock_slurm_cli.py +++ b/testing/mock-slurm/mock_slurm_cli.py @@ -7,9 +7,27 @@ import json import os import re +import shutil +import subprocess import sys from pathlib import Path +# Real squeue lists only jobs that have not finished. +TERMINAL_STATES = frozenset( + { + "COMPLETED", + "CANCELLED", + "FAILED", + "TIMEOUT", + "OUT_OF_MEMORY", + "NODE_FAIL", + "PREEMPTED", + "BOOT_FAIL", + "DEADLINE", + "REVOKED", + } +) + def _state_dir() -> Path: raw = os.environ.get("MOCK_SLURM_STATE") @@ -49,7 +67,7 @@ def cmd_squeue(argv: list[str]) -> int: state_dir = _state_dir() for job_id, data, _path in _iter_jobs(state_dir, ids): status = data.get("status", "PENDING") - if status == "COMPLETED": + if str(status).upper() in TERMINAL_STATES: continue if "%i" in fmt and "%T" in fmt: print(f"{job_id} {status}") @@ -88,7 +106,13 @@ def cmd_scancel(argv: list[str]) -> int: job_id = argv[0] path = _state_dir() / f"{job_id}.json" if not path.exists(): - return 0 + # Real scancel fails for a job id it does not know. + print( + f"scancel: error: Kill job error on job id {job_id}: " + "Invalid job id specified", + file=sys.stderr, + ) + return 1 data = json.loads(path.read_text(encoding="utf-8")) data["status"] = "CANCELLED" path.write_text(json.dumps(data), encoding="utf-8") @@ -109,18 +133,36 @@ def cmd_sbatch(argv: list[str]) -> int: return 1 job_id = str(10000 + len(list(state_dir.glob("*.json")))) + # A script bash cannot parse would fail on the compute node; catch it here. + bash = shutil.which("bash") + if bash: + check = subprocess.run( + [bash, "-n", script_path], capture_output=True, text=True, timeout=30 + ) + if check.returncode != 0: + print( + f"sbatch: error: batch script is not valid bash:\n{check.stderr}", + file=sys.stderr, + ) + return 1 + content = Path(script_path).read_text(encoding="utf-8") - cores = memory = walltime = None + ntasks = cpus_per_task = memory = None for line in content.splitlines(): m = re.search(r"#SBATCH\s+--ntasks=(\d+)", line) if m: - cores = int(m.group(1)) + ntasks = int(m.group(1)) + m = re.search(r"#SBATCH\s+--cpus-per-task=(\d+)", line) + if m: + cpus_per_task = int(m.group(1)) m = re.search(r"#SBATCH\s+--mem=(\d+)G", line) if m: memory = int(m.group(1)) - m = re.search(r"#SBATCH\s+--time=(\S+)", line) - if m: - walltime = m.group(1) + + # Cores the job asks for: tasks x CPUs per task (QuantUI uses 1 x N). + cores = None + if ntasks is not None or cpus_per_task is not None: + cores = (ntasks or 1) * (cpus_per_task or 1) limits_path = state_dir / "config.json" max_cores = 32 diff --git a/testing/mock-slurm/sacct.sh b/testing/mock-slurm/sacct.sh index 2364490b..5f11514c 100755 --- a/testing/mock-slurm/sacct.sh +++ b/testing/mock-slurm/sacct.sh @@ -1,42 +1,5 @@ #!/usr/bin/env bash -# Mock SLURM sacct for QuantUI backend tests. +# Mock SLURM sacct for QuantUI backend tests: same behaviour as the .cmd shim, +# from the one implementation in mock_slurm_cli.py. set -euo pipefail - -STATE_DIR="${MOCK_SLURM_STATE:?MOCK_SLURM_STATE must be set}" - -job_filter="" - -args=("$@") -i=0 -while [[ $i -lt ${#args[@]} ]]; do - case "${args[$i]}" in - -j) - i=$((i + 1)) - job_filter="${args[$i]}" - ;; - esac - i=$((i + 1)) -done - -python3 - "$STATE_DIR" "$job_filter" <<'PY' -import json -import sys -from pathlib import Path - -state_dir, job_filter = sys.argv[1:3] -ids = [] -if job_filter: - ids = [j.strip() for j in job_filter.split(",") if j.strip()] - -for path in sorted(Path(state_dir).glob("*.json")): - if path.name == "config.json": - continue - data = json.loads(path.read_text()) - job_id = str(data.get("job_id", path.stem)) - if ids and job_id not in ids: - continue - status = str(data.get("status", "PENDING")).upper() - 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}") -PY +exec python3 "$(dirname "$0")/mock_slurm_cli.py" sacct "$@" diff --git a/testing/mock-slurm/sbatch.sh b/testing/mock-slurm/sbatch.sh index 227d4361..67096046 100755 --- a/testing/mock-slurm/sbatch.sh +++ b/testing/mock-slurm/sbatch.sh @@ -1,82 +1,5 @@ #!/usr/bin/env bash -# Mock SLURM sbatch for QuantUI backend tests (Linux CI). +# Mock SLURM sbatch for QuantUI backend tests: same behaviour as the .cmd shim, +# from the one implementation in mock_slurm_cli.py. set -euo pipefail - -STATE_DIR="${MOCK_SLURM_STATE:?MOCK_SLURM_STATE must be set}" -mkdir -p "$STATE_DIR" - -script_path="" -for arg in "$@"; do - if [[ -f "$arg" ]]; then - script_path="$arg" - break - fi -done - -if [[ -z "$script_path" ]]; then - echo "sbatch: error: No job script specified" >&2 - exit 1 -fi - -job_id="$((10000 + $(find "$STATE_DIR" -maxdepth 1 -name '*.json' 2>/dev/null | wc -l)))" -out_file="$STATE_DIR/${job_id}.json" - -python3 - "$STATE_DIR" "$job_id" "$script_path" <<'PY' -import json -import os -import re -import sys -from pathlib import Path - -state_dir, job_id, script_path = sys.argv[1:4] -content = Path(script_path).read_text() -cores = memory = walltime = None -for line in content.splitlines(): - m = re.search(r"#SBATCH\s+--ntasks=(\d+)", line) - if m: - cores = int(m.group(1)) - m = re.search(r"#SBATCH\s+--mem=(\d+)G", line) - if m: - memory = int(m.group(1)) - m = re.search(r"#SBATCH\s+--time=(\S+)", line) - if m: - walltime = m.group(1) - -limits_path = Path(state_dir) / "config.json" -max_cores = 32 -max_mem = 128 -if limits_path.exists(): - cfg = json.loads(limits_path.read_text()) - max_cores = cfg.get("max_cores", max_cores) - max_mem = cfg.get("max_memory_gb", max_mem) - -if cores is not None and cores > max_cores: - print(f"sbatch: error: CPU count {cores} exceeds limit", file=sys.stderr) - sys.exit(1) -if memory is not None and memory > max_mem: - print(f"sbatch: error: Memory {memory}G exceeds limit", file=sys.stderr) - sys.exit(1) - -payload = { - "job_id": job_id, - "status": "PENDING", - "script": script_path, - "submitted_at": os.environ.get("MOCK_SLURM_NOW", "0"), -} -Path(state_dir, f"{job_id}.json").write_text(json.dumps(payload)) -PY - -echo "Submitted batch job ${job_id}" - -# Optionally transition to RUNNING then COMPLETED for squeue tests. -if [[ "${MOCK_SLURM_AUTO_COMPLETE:-0}" == "1" ]]; then - python3 - "$STATE_DIR" "$job_id" <<'PY' -import json, sys -from pathlib import Path -state_dir, job_id = sys.argv[1:3] -path = Path(state_dir) / f"{job_id}.json" -data = json.loads(path.read_text()) -data["status"] = "COMPLETED" -path.write_text(json.dumps(data)) -PY -fi +exec python3 "$(dirname "$0")/mock_slurm_cli.py" sbatch "$@" diff --git a/testing/mock-slurm/scancel.sh b/testing/mock-slurm/scancel.sh index e9b2dc05..b401f662 100755 --- a/testing/mock-slurm/scancel.sh +++ b/testing/mock-slurm/scancel.sh @@ -1,25 +1,5 @@ #!/usr/bin/env bash -# Mock SLURM scancel for QuantUI backend tests. +# Mock SLURM scancel for QuantUI backend tests: same behaviour as the .cmd shim, +# from the one implementation in mock_slurm_cli.py. set -euo pipefail - -STATE_DIR="${MOCK_SLURM_STATE:?MOCK_SLURM_STATE must be set}" - -job_id="${1:-}" -if [[ -z "$job_id" ]]; then - echo "scancel: error: job id required" >&2 - exit 1 -fi - -python3 - "$STATE_DIR" "$job_id" <<'PY' -import json -import sys -from pathlib import Path - -state_dir, job_id = sys.argv[1:3] -path = Path(state_dir) / f"{job_id}.json" -if not path.exists(): - sys.exit(0) -data = json.loads(path.read_text()) -data["status"] = "CANCELLED" -path.write_text(json.dumps(data)) -PY +exec python3 "$(dirname "$0")/mock_slurm_cli.py" scancel "$@" diff --git a/testing/mock-slurm/squeue.sh b/testing/mock-slurm/squeue.sh index 41024532..28d14f53 100755 --- a/testing/mock-slurm/squeue.sh +++ b/testing/mock-slurm/squeue.sh @@ -1,50 +1,5 @@ #!/usr/bin/env bash -# Mock SLURM squeue for QuantUI backend tests. +# Mock SLURM squeue for QuantUI backend tests: same behaviour as the .cmd shim, +# from the one implementation in mock_slurm_cli.py. set -euo pipefail - -STATE_DIR="${MOCK_SLURM_STATE:?MOCK_SLURM_STATE must be set}" - -format="%T" -job_filter="" - -args=("$@") -i=0 -while [[ $i -lt ${#args[@]} ]]; do - case "${args[$i]}" in - -o) - i=$((i + 1)) - format="${args[$i]}" - ;; - -j) - i=$((i + 1)) - job_filter="${args[$i]}" - ;; - esac - i=$((i + 1)) -done - -python3 - "$STATE_DIR" "$format" "$job_filter" <<'PY' -import json -import sys -from pathlib import Path - -state_dir, fmt, job_filter = sys.argv[1:4] -ids = [] -if job_filter: - ids = [j.strip() for j in job_filter.split(",") if j.strip()] - -for path in sorted(Path(state_dir).glob("*.json")): - if path.name == "config.json": - continue - data = json.loads(path.read_text()) - job_id = str(data.get("job_id", path.stem)) - if ids and job_id not in ids: - continue - status = data.get("status", "PENDING") - if status == "COMPLETED": - continue - if "%i" in fmt and "%T" in fmt: - print(f"{job_id} {status}") - else: - print(status) -PY +exec python3 "$(dirname "$0")/mock_slurm_cli.py" squeue "$@" diff --git a/tests/conftest.py b/tests/conftest.py index 96d07bea..37fdde6e 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -9,6 +9,16 @@ import pytest +# Cap BLAS/OpenMP threads per xdist worker (audit INFRA-12). ``-n=auto`` (see +# ``addopts``) starts one worker per core, and every worker's NumPy/PySCF +# would otherwise start one OpenMP thread per core as well: N x N threads on +# N cores, which thrashes and makes timing-sensitive tests flaky. xdist sets +# ``PYTEST_XDIST_WORKER`` before the worker loads this conftest, and nothing +# here has imported NumPy yet, so the cap takes effect. An explicit +# ``OMP_NUM_THREADS`` from the caller still wins; ``-n0`` runs are untouched. +if os.environ.get("PYTEST_XDIST_WORKER"): + os.environ.setdefault("OMP_NUM_THREADS", "1") + @pytest.fixture(autouse=True, scope="session") def _isolate_results_dir(): diff --git a/tests/test_app.py b/tests/test_app.py index d22ee33f..64163a19 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -100,11 +100,6 @@ def test_export_btn_initially_disabled(self): app = QuantUIApp() assert app.export_btn.disabled is True - def test_scroll_guard_installer_method_exists(self): - app = QuantUIApp() - assert hasattr(app, "_install_run_output_scroll_guard") - assert callable(app._install_run_output_scroll_guard) - # --------------------------------------------------------------------------- # Default widget values @@ -632,12 +627,6 @@ def test_pyscf_flag_mirrors_module_level(self): app = QuantUIApp() assert app._pyscf_available == _PYSCF_AVAILABLE - def test_preopt_flag_mirrors_module_level(self): - from quantui.app import _PREOPT_AVAILABLE - - app = QuantUIApp() - assert app._preopt_available == _PREOPT_AVAILABLE - class TestQuantumEngineGating: def test_pyfock_limits_setup_to_validated_subset(self): diff --git a/tests/test_app_formatters.py b/tests/test_app_formatters.py index a6e8ca2a..37e8b807 100644 --- a/tests/test_app_formatters.py +++ b/tests/test_app_formatters.py @@ -630,6 +630,29 @@ def test_format_tddft_result_labels_uks(): assert "(UKS)" in html +def test_format_tddft_states_are_not_called_singlets_for_open_shell(): + # Audit UI-13: states from a UKS/UHF reference were labelled S1, S2, ... + from quantui.app_formatters import tddft_state_prefix + + kw = dict( + converged=True, + energy_hartree=-1600.0, + excitation_energies_ev=[3.0, 3.5], + oscillator_strengths=[0.1, 0.0], + formula="Co(H2O)6", + method="B3LYP", + basis="def2-SVP", + ) + html = format_tddft_result(_TDDFTStub(scf_variant="UKS", **kw)) + assert "S1" not in html and "S2" not in html + assert ">1" in html + assert "S1" in format_tddft_result(_TDDFTStub(scf_variant="RKS", **kw)) + assert tddft_state_prefix(_TDDFTStub(scf_variant="ROHF", **kw)) == "" + # Older saved results: no scf_variant; is saved only when open shell. + assert tddft_state_prefix(_TDDFTStub(spin_square=0.76, **kw)) == "" + assert tddft_state_prefix(_TDDFTStub(**kw)) == "S" + + def test_format_nmr_result_labels_uks(): result = _NMRStub( converged=True, diff --git a/tests/test_app_pes_pick.py b/tests/test_app_pes_pick.py new file mode 100644 index 00000000..d8ece281 --- /dev/null +++ b/tests/test_app_pes_pick.py @@ -0,0 +1,198 @@ +"""Click-to-pick atoms for PES Scan setup (quantui.app_pes_pick). + +Audit INFRA-22: this module had no tests. Driven with a duck-typed app +(plain value holders for the widgets), so no front end, PySCF or py3Dmol is +needed; the JS transport itself is covered in test_ui_display_audit.py. +""" + +from __future__ import annotations + +from types import SimpleNamespace +from unittest.mock import patch + +import pytest + +from quantui import app_pes_pick as pp +from quantui.molecule import Molecule + + +def _w(value): + return SimpleNamespace(value=value) + + +@pytest.fixture +def app(): + return SimpleNamespace( + _molecule=Molecule( + ["O", "H", "H", "H"], + [[0.0, 0.0, 0.0], [0.96, 0.0, 0.0], [-0.24, 0.93, 0.0], [0, 0, 1.0]], + charge=1, + ), + _scan_type_dd=_w("Bond"), + _scan_atom1=_w(1), + _scan_atom2=_w(2), + _scan_atom3=_w(3), + _scan_atom4=_w(4), + _scan_pick_inbox=_w(""), + _scan_pick_readout=_w(""), + _scan_pick_buffer=[], + calc_type_dd=_w("PES Scan"), + ) + + +@pytest.fixture +def summary(): + """Record the scan-coordinate summary refresh a completed pick triggers.""" + with patch("quantui.app_runflow._update_scan_coord_summary") as fn: + yield fn + + +def _click(app, idx): + app._scan_pick_inbox.value = str(idx) + pp.on_pes_pick_inbox_changed(app, {"new": str(idx)}) + + +class TestNeededPicks: + @pytest.mark.parametrize( + "scan_type, n", + [("Bond", 2), ("angle", 3), ("DIHEDRAL", 4), ("something else", 2)], + ) + def test_atoms_per_coordinate(self, scan_type, n): + assert pp._needed_picks(scan_type) == n + + +class TestScanPickIndices: + def test_dropdowns_are_one_based_indices_zero_based(self, app): + app._scan_type_dd.value = "Dihedral" + assert pp._scan_pick_indices(app) == [0, 1, 2, 3] + app._scan_type_dd.value = "Angle" + assert pp._scan_pick_indices(app) == [0, 1, 2] + app._scan_type_dd.value = "Bond" + app._scan_atom1.value, app._scan_atom2.value = 3, 1 + assert pp._scan_pick_indices(app) == [2, 0] + + +class TestSequentialClicks: + def test_two_clicks_fill_a_bond(self, app, summary): + _click(app, 0) + assert app._scan_atom1.value == 1 + assert app._scan_pick_buffer == [0] + assert "1 more" in app._scan_pick_readout.value + summary.assert_not_called() + + _click(app, 2) + assert (app._scan_atom1.value, app._scan_atom2.value) == (1, 3) + assert app._scan_pick_buffer == [] # complete: next click starts over + assert "Picked O1 → H3" in app._scan_pick_readout.value + summary.assert_called_once_with(app) + assert app._scan_pick_inbox.value == "" # inbox drained each click + + def test_dihedral_needs_four(self, app, summary): + app._scan_type_dd.value = "Dihedral" + for i in (3, 0, 1): + _click(app, i) + summary.assert_not_called() + _click(app, 2) + summary.assert_called_once() + assert [ + w.value + for w in ( + app._scan_atom1, + app._scan_atom2, + app._scan_atom3, + app._scan_atom4, + ) + ] == [4, 1, 2, 3] + + def test_clicking_the_same_atom_twice_is_ignored(self, app, summary): + _click(app, 1) + _click(app, 1) + assert app._scan_pick_buffer == [1] + assert app._scan_pick_inbox.value == "" + summary.assert_not_called() + + def test_a_shorter_coordinate_restarts_a_longer_pick(self, app, summary): + # Three atoms picked for a dihedral, then the user switches to Bond: + # the stale buffer must not overflow into atom3/atom4. + app._scan_pick_buffer = [0, 1, 2] + _click(app, 3) + assert app._scan_pick_buffer == [3] + assert app._scan_atom1.value == 4 + summary.assert_not_called() + + @pytest.mark.parametrize("raw", ["7", "-1", "x", "1.5"]) + def test_out_of_range_or_garbage_clears_the_inbox(self, app, raw, summary): + app._scan_pick_inbox.value = raw + pp.on_pes_pick_inbox_changed(app, {"new": raw}) + assert app._scan_pick_inbox.value == "" + assert app._scan_pick_buffer == [] + assert app._scan_atom1.value == 1 # untouched + + def test_no_molecule_ignores_clicks(self, app, summary): + app._molecule = None + _click(app, 0) + assert app._scan_pick_buffer == [] + assert app._scan_pick_inbox.value == "" + + def test_empty_change_is_a_no_op(self, app, summary): + pp.on_pes_pick_inbox_changed(app, {"new": ""}) + pp.on_pes_pick_inbox_changed(app, {}) + assert app._scan_pick_buffer == [] + + def test_each_click_pushes_the_highlight(self, app, summary): + with patch.object(pp, "push_scan_highlight") as push: + _click(app, 0) + _click(app, 2) + assert [c.args[1] for c in push.call_args_list] == [[0], [0, 2]] + + +class TestHighlightAndHtml: + def test_push_is_a_no_op_without_a_bridge(self, app): + with patch.object(pp, "push_highlight") as ph: + pp.push_scan_highlight(app, [0, 1]) + ph.assert_not_called() + + def test_push_targets_the_scan_bridge_without_touching_measure(self, app): + # The highlight is sent through the scan viewer's own bridge; the + # measure bridge is never swapped (audit LEAD-4), even on error. + app._scan_pick_bridge = "scan-bridge" + app._measure_js_bridge = "measure-bridge" + seen = [] + + def _boom(a, indices, *, slot, bridge): + seen.append((a._measure_js_bridge, list(indices), slot, bridge)) + raise RuntimeError("display failed") + + with patch.object(pp, "push_highlight", side_effect=_boom): + with pytest.raises(RuntimeError): + pp.push_scan_highlight(app, [0, 1]) + assert seen == [ + ("measure-bridge", [0, 1], pp.PES_PICK_INBOX_CLASS, "scan-bridge") + ] + assert app._measure_js_bridge == "measure-bridge" + + def test_finalize_wires_clicks_only_for_a_py3dmol_pes_scan(self, app): + inject_p = patch.object(pp, "inject_click_js", return_value="wired") + push_p = patch.object(pp, "push_scan_highlight") + with inject_p as inject, push_p as push: + assert pp.finalize_pes_calc_html(app, "html", "plotlymol") == "html" + app.calc_type_dd.value = "Single Point" + assert pp.finalize_pes_calc_html(app, "html", "py3dmol") == "html" + inject.assert_not_called() + + app.calc_type_dd.value = "PES Scan" + assert pp.finalize_pes_calc_html(app, "html", "py3dmol") == "wired" + assert inject.call_args.kwargs["inbox_class"] == pp.PES_PICK_INBOX_CLASS + push.assert_called_once_with(app, [0, 1]) + + def test_finalize_without_a_calc_type_dropdown(self, app): + app.calc_type_dd = None + assert pp.finalize_pes_calc_html(app, "html", "py3dmol") == "html" + + def test_clear_resets_buffer_and_readout(self, app): + app._scan_pick_buffer = [2] + with patch.object(pp, "push_scan_highlight") as push: + pp.clear_pes_pick(app) + assert app._scan_pick_buffer == [] + assert "Click atoms" in app._scan_pick_readout.value + push.assert_called_once_with(app, [0, 1]) diff --git a/tests/test_appui_audit_low.py b/tests/test_appui_audit_low.py new file mode 100644 index 00000000..de866b77 --- /dev/null +++ b/tests/test_appui_audit_low.py @@ -0,0 +1,351 @@ +"""App/UI fixes from the 2026-11 audit (Low findings). + +- APP-14: the in-session comparison shows its chart and closes the figure. +- APP-15: calc-type switching leaks no widgets; Cancel during error + handling; TS/IRC badges and History chips; Files-tab default selection; + platform-specific dependency hint. +- UI-10: a reloaded PES/IRC profile whose first point failed is plotted. +- UI-12: "unavailable" panel messages carry no escaped markup. +- UI-14: MOL/PDB bond-perception warning; readable Freeze-list errors; + local strings escaped in HTML. +- LEAD-4: PES-pick / Edit highlights pass their own JS bridge. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from quantui.app import QuantUIApp +from quantui.session_calc import SessionResult + +pytest.importorskip("matplotlib") + + +@pytest.fixture +def app(): + return QuantUIApp() + + +@pytest.fixture +def shown(monkeypatch): + """Collect what app_runflow passes to ``display`` (no kernel in tests).""" + items: list = [] + monkeypatch.setattr("quantui.app_runflow.display", lambda *a, **k: items.extend(a)) + return items + + +def _html(items) -> str: + return "\n".join(str(getattr(o, "data", "")) for o in items) + + +def _sr(energy: float, method: str = "RHF") -> SessionResult: + return SessionResult( + energy_hartree=energy, + homo_lumo_gap_ev=10.0, + converged=True, + n_iterations=5, + method=method, + basis="STO-3G", + formula="H2", + ) + + +# ── APP-14 ──────────────────────────────────────────────────────────────── + + +def test_in_session_comparison_shows_chart_and_closes_figure(app, shown): + import matplotlib.pyplot as plt + + plt.close("all") + app._results.extend([_sr(-1.11), _sr(-1.12, "B3LYP")]) + app._refresh_comparison() + html = _html(shown) + assert "Comparison chart" in html + assert "data:image/png;base64," in html + assert plt.get_fignums() == [] + + +def test_saved_result_comparison_still_shows_chart(app, shown, monkeypatch): + import matplotlib.pyplot as plt + + from quantui.comparison import summary_from_session_result + + plt.close("all") + rows = {"/a": _sr(-1.11), "/b": _sr(-1.12, "B3LYP")} + # Key by the path as given: str(Path("/a")) is "\\a" on Windows. + monkeypatch.setattr( + "quantui.results_storage.load_result", lambda p: {"key": Path(p).as_posix()} + ) + monkeypatch.setattr( + "quantui.summary_from_saved_result", + lambda d: summary_from_session_result(rows[d["key"]]), + ) + app.compare_select.options = [("a", "/a"), ("b", "/b")] + app.compare_select.value = ("/a", "/b") + app._on_compare(None) + assert "Comparison chart" in _html(shown) + assert plt.get_fignums() == [] + + +# ── APP-15 ──────────────────────────────────────────────────────────────── + + +def _calc_types(app) -> list: + return [o if isinstance(o, str) else o[1] for o in app.calc_type_dd.options] + + +def test_calc_type_switching_does_not_leak_widgets(app): + import ipywidgets as widgets + + reg = widgets.widgets.widget._instances + types = _calc_types(app) + for ct in types: # warm up lazily built persistent widgets + app.calc_type_dd.value = ct + app.calc_type_dd.value = types[0] + before = len(reg) + for _ in range(3): + for ct in types: + app.calc_type_dd.value = ct + app.calc_type_dd.value = types[0] + assert len(reg) - before == 0 + + # Everything shown after a switch is still a live widget. + def _alive(w): + assert w.comm is not None, w + assert w.layout.comm is not None, w + for c in getattr(w, "children", None) or (): + _alive(c) + + for ct in types: + app.calc_type_dd.value = ct + for child in app.calc_extra_opts.children: + _alive(child) + + +def _result_html(app) -> str: + return "\n".join( + str(o.get("data", {}).get("text/html", "")) for o in app.result_output.outputs + ) + + +@pytest.mark.parametrize("exc", [RuntimeError("boom"), ImportError("no pyscf")]) +def test_cancel_clicked_as_the_calculation_fails_still_reports_it(app, exc): + from unittest.mock import patch + + from quantui.molecule import Molecule + + pytest.importorskip("pyscf") + app._set_molecule(Molecule(["H", "H"], [[0, 0, 0], [0, 0, 0.74]])) + app.method_dd.value = "RHF" + app.basis_dd.value = "STO-3G" + app.calc_type_dd.value = "Single Point" + + def _fail(*a, **k): + app._on_cancel(None) # click lands just before the error surfaces + raise exc + + with patch("quantui.engines.run_calc", side_effect=_fail): + app._begin_run_lock() + app._run_in_thread() + assert app.run_status.value in ("Calculation failed.", "Dependency unavailable.") + html = _result_html(app) + assert "Calculation Failed" in html or "Dependency Not Available" in html + assert "Calculation cancelled" not in html + + +def test_ts_and_irc_have_badges_and_history_chips(app): + from quantui.app_runflow import _calc_type_badge + + assert _calc_type_badge("transition_state") == "TS" + assert _calc_type_badge("irc") == "IRC" + assert {"transition_state", "irc"} <= set(app._history_calc_chips) + + +def test_files_tab_defaults_to_the_first_listed_entry(app, tmp_path, monkeypatch): + names = [f"{c}.txt" for c in "abcdefghijklmnop"] + for n in names: + (tmp_path / n).write_text("x") + monkeypatch.setattr(app, "_files_allowed_roots", lambda: [tmp_path]) + app._files_current_dir = tmp_path + app._update_files_entries() + assert app._files_entries.value == str(tmp_path / "a.txt") + + +def test_dependency_hint_is_platform_specific(): + from quantui.app import _dependency_hint + + assert "Apptainer" in _dependency_hint("win32") + assert "WSL" in _dependency_hint("win32") + linux = _dependency_hint("linux") + assert "Windows" not in linux and "Apptainer" not in linux + assert "pip install" in linux + + +# ── UI-10 ───────────────────────────────────────────────────────────────── + + +def _capture_pes(app, monkeypatch) -> list: + shown_results: list = [] + monkeypatch.setattr( + app, + "_show_pes_scan_result", + lambda r: shown_results.append(r) or True, + ) + return shown_results + + +@pytest.mark.parametrize("failed", [float("nan"), None]) +def test_reloaded_pes_scan_with_failed_first_point_is_plotted(app, monkeypatch, failed): + import math + from types import SimpleNamespace + + from quantui.app_analysis import pop_pes_plot + + got = _capture_pes(app, monkeypatch) + ctx = SimpleNamespace( + live_result=None, + result_dir=None, + spectra_data={ + "pes_scan": { + "scan_type": "bond", + "atom_indices": [0, 1], + "scan_parameter_values": [0.6, 0.7, 0.8], + "energies_hartree": [failed, -1.10, -1.11], + } + }, + ) + assert pop_pes_plot(app, ctx) + rel = got[0].energies_relative_kcal + assert math.isnan(rel[0]) + assert rel[2] == pytest.approx(0.0) + assert rel[1] == pytest.approx(0.01 * 627.5094740631) + + +def test_reloaded_irc_with_failed_first_point_is_plotted(app, monkeypatch): + import math + from types import SimpleNamespace + + from quantui.app_analysis import pop_irc_profile + + got = _capture_pes(app, monkeypatch) + ctx = SimpleNamespace( + live_result=None, + result_dir=None, + spectra_data={ + "irc": { + "energies_hartree": [float("nan"), -1.0, -1.02], + "reaction_coordinate": [-1.0, 0.0, 1.0], + } + }, + ) + assert pop_irc_profile(app, ctx) + rel = got[0].energies_relative_kcal + assert math.isnan(rel[0]) + assert rel[2] == pytest.approx(0.0) + + +# ── UI-12 ───────────────────────────────────────────────────────────────── + + +@pytest.mark.parametrize( + "calc_type", + ["single_point", "geometry_opt", "frequency", "tddft", "nmr", "pes_scan"], +) +def test_unavailable_panel_messages_show_no_escaped_markup(app, calc_type): + from types import SimpleNamespace + + from quantui.app_analysis import _reset_unavailable_messages_for_context + + _reset_unavailable_messages_for_context(app, SimpleNamespace(calc_type=calc_type)) + for name, msg in app._ana_unavail_msgs.items(): + assert "<" not in msg.value, (name, msg.value) + if calc_type == "frequency": + assert "Geometry optimization before calculation" in ( + app._ana_unavail_msgs["Trajectory"].value + ) + + +# ── UI-14 ───────────────────────────────────────────────────────────────── + + +def _no_radical(): + from quantui.molecule import Molecule + + return Molecule(["N", "O"], [[0, 0, 0], [0, 0, 1.15]], multiplicity=2) + + +def test_mol_export_warns_when_bond_orders_cannot_be_determined( + app, tmp_path, monkeypatch +): + pytest.importorskip("rdkit") + monkeypatch.chdir(tmp_path) + app._set_molecule(_no_radical()) + app._on_export_mol(None) + status = app.struct_export_status.value + assert status.startswith("Saved:"), status + assert "bond orders could not be determined" in status + # Connectivity is still written. + block = next(tmp_path.glob("*.mol")).read_text() + counts = block.splitlines()[3] + assert int(counts[3:6]) == 1 # one bond + + +def test_mol_export_of_a_closed_shell_molecule_has_no_warning(app): + pytest.importorskip("rdkit") + from quantui.app_exports import _saved_status, molecule_to_rdkit + from quantui.molecule import Molecule + + water = Molecule( + ["O", "H", "H"], [[0, 0, 0.117], [0, 0.757, -0.467], [0, -0.757, -0.467]] + ) + rd = molecule_to_rdkit(water) + assert rd.GetNumBonds() == 2 + assert _saved_status("w.mol", rd) == "Saved: w.mol" + + +def test_freeze_list_typo_gets_a_readable_message(): + from quantui.structure_edit import parse_atom_list + + with pytest.raises(ValueError, match="'1-' is not an atom number or range"): + parse_atom_list("1-") + + +def test_local_strings_are_escaped_in_html(app): + from quantui.checklist_widget import CheckList + + cl = CheckList(options=[("none", "")]) + assert "<b>none" in cl.children[0].value + + html = app._render_status_html((False, None, "import raised ")) + assert "<libcublas>" in html and "" not in html + html = app._render_status_html((True, "Card ", "")) + assert "Card <X>" in html + + +# ── LEAD-4 ──────────────────────────────────────────────────────────────── + + +def test_scan_and_edit_highlights_do_not_swap_the_measure_bridge(): + from types import SimpleNamespace + from unittest.mock import patch + + from quantui import app_pes_pick, app_structure_edit + + measure, scan, edit = object(), object(), object() + app = SimpleNamespace( + _measure_js_bridge=measure, _scan_pick_bridge=scan, _edit_pick_bridge=edit + ) + seen: list = [] + + def _ph(a, indices, *, slot, bridge=None): + seen.append((a._measure_js_bridge, bridge)) + + for mod, fn in ( + (app_pes_pick, "push_scan_highlight"), + (app_structure_edit, "_push_edit_highlight"), + ): + with patch.object(mod, "push_highlight", side_effect=_ph): + getattr(mod, fn)(app, [0]) + assert seen == [(measure, scan), (measure, edit)] diff --git a/tests/test_audit_defects_issue19.py b/tests/test_audit_defects_issue19.py index 41a13164..18b7942c 100644 --- a/tests/test_audit_defects_issue19.py +++ b/tests/test_audit_defects_issue19.py @@ -137,10 +137,14 @@ def _fake_calc(**kw): req = CalculationRequest.from_dict(data) runner = _run_single_point if calc_type == "single_point" else _run_nmr + # The worker's required single point after the pre-opt (audit + # HPC-14) also goes through run_in_session: stub it for both calc + # types so the test stays PySCF-free. with patch("quantui.optimizer.optimize_geometry", return_value=opt) as m_opt: - with patch(target, side_effect=_fake_calc): - with open(staging / "live.log", "w") as log: - runner(req, staging, log) + with patch("quantui.session_calc.run_in_session", side_effect=_fake_calc): + with patch(target, side_effect=_fake_calc): + with open(staging / "live.log", "w") as log: + runner(req, staging, log) m_opt.assert_called_once() assert seen["z"] == pytest.approx(0.71) # B2.5 tightens only the frequency pre-opt. diff --git a/tests/test_audit_low_data.py b/tests/test_audit_low_data.py new file mode 100644 index 00000000..9e2d7f0f --- /dev/null +++ b/tests/test_audit_low_data.py @@ -0,0 +1,769 @@ +"""Regression tests for the Low-priority data-layer audit findings (DATA-10..17).""" + +from __future__ import annotations + +import os +import queue +import subprocess +import sys +import time + +import pytest + +from quantui import benchmarks + +# --------------------------------------------------------------------------- +# DATA-10 — calibration worker must be able to start the parallel IR pool +# --------------------------------------------------------------------------- + + +class _RecordingProcess: + created: list = [] + + def __init__(self, target, args, daemon=None): + self.target, self.args, self.daemon = target, args, daemon + self.exitcode = 0 + self.pid = None + _RecordingProcess.created.append(self) + + def start(self): + self.args[8].put( + { + "status": "ok", + "formula": "H2", + "converged": True, + "n_iterations": 3, + "elapsed_s": 0.5, + "result_dir": None, + } + ) + + def join(self, timeout=None): + return None + + def is_alive(self): + return False + + def terminate(self): + return None + + +class _RecordingCtx: + Process = _RecordingProcess + + @staticmethod + def Queue(): + return queue.Queue() + + +def test_calibration_worker_is_not_daemonic(monkeypatch, tmp_path): + """A daemonic worker cannot have children, so freq steps never got the + parallel IR pool (audit DATA-10).""" + pytest.importorskip("pyscf") + import multiprocessing + + entry = benchmarks._MODE_TO_SUITE["tier1"][0] + monkeypatch.setitem(benchmarks._MODE_TO_SUITE, "tier1", [entry]) + monkeypatch.setattr(multiprocessing, "get_context", lambda *_a: _RecordingCtx()) + monkeypatch.setattr( + benchmarks, "_calibration_log_path", lambda ts: tmp_path / "cal.log" + ) + monkeypatch.setattr(benchmarks, "_save_calibration_json", lambda *a, **k: None) + monkeypatch.setattr("quantui.calc_log.log_calculation", lambda **kw: None) + monkeypatch.setattr( + "quantui.gpu_offload.is_gpu_available", lambda: (False, None), raising=False + ) + _RecordingProcess.created = [] + + result = benchmarks.run_calibration(mode="tier1") + + assert [s.status for s in result.steps] == ["ok"] + (proc,) = _RecordingProcess.created + assert proc.daemon is False + + +def _group_leader_with_child(pids): # pragma: no cover - runs in a fork child + os.setpgrp() + child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"]) + pids.put(child.pid) + time.sleep(60) + + +@pytest.mark.skipif(not hasattr(os, "killpg"), reason="POSIX process groups") +def test_terminate_worker_tree_kills_grandchildren(): + """Stop/Skip/timeout must not orphan the worker's pool processes.""" + import multiprocessing + + ctx = multiprocessing.get_context("fork") + pids = ctx.Queue() + worker = ctx.Process(target=_group_leader_with_child, args=(pids,)) + worker.start() + try: + kids = [pids.get(timeout=20)] + benchmarks._terminate_worker_tree(worker) + worker.join(10) + assert not worker.is_alive() + deadline = time.time() + 10 + while time.time() < deadline: + alive = [ + k + for k in kids + if os.path.exists(f"/proc/{k}") + and "Z" not in open(f"/proc/{k}/stat").read().split()[2] + ] + if not alive: + break + time.sleep(0.1) + assert not alive + finally: + if worker.is_alive(): + os.killpg(worker.pid, 9) + + +# --------------------------------------------------------------------------- +# DATA-11 — save_result / save_trajectory robustness +# --------------------------------------------------------------------------- + + +def _fake_result(**kw): + from types import SimpleNamespace + + base = dict( + formula="H2", + method="RHF", + basis="STO-3G", + energy_hartree=-1.117, + converged=True, + n_iterations=5, + ) + base.update(kw) + return SimpleNamespace(**base) + + +def test_save_result_numpy_fields_are_serialised(tmp_path): + import json + + import numpy as np + + from quantui.results_storage import save_result + + res = _fake_result(cc_converged=np.bool_(True), solvent=np.str_("water")) + d = save_result( + res, + results_dir=tmp_path, + spectra={"ir": {"freqs": np.array([1.0, 2.0], dtype=np.float32)}}, + extras={"flag": np.bool_(False), "where": tmp_path}, + ) + data = json.loads((d / "result.json").read_text()) + assert data["cc_converged"] is True + assert data["spectra"]["ir"]["freqs"] == [1.0, 2.0] + assert data["flag"] is False + assert data["where"] == str(tmp_path) + + +def test_save_result_failure_leaves_no_empty_dir(tmp_path, monkeypatch): + from quantui import results_storage + + def _boom(*_a, **_k): + raise TypeError("unserialisable") + + monkeypatch.setattr(results_storage, "_dumps_json_safe", _boom) + with pytest.raises(TypeError): + results_storage.save_result(_fake_result(), results_dir=tmp_path) + assert list(tmp_path.iterdir()) == [] + + +def test_save_result_nan_written_as_null(tmp_path): + import json + + from quantui.results_storage import save_result + + res = _fake_result(energy_hartree=float("nan"), homo_lumo_gap_ev=float("inf")) + d = save_result(res, results_dir=tmp_path) + text = (d / "result.json").read_text() + assert "NaN" not in text and "Infinity" not in text + data = json.loads(text) + assert data["energy_hartree"] is None + assert data["homo_lumo_gap_ev"] is None + + +def test_save_result_truncates_long_basis_name(tmp_path): + from quantui.results_storage import save_result + + d = save_result(_fake_result(basis="x" * 300), results_dir=tmp_path) + assert len(d.name) < 255 + assert (d / "result.json").is_file() + assert not list(d.glob("*.tmp")) + + +def test_save_trajectory_float32(tmp_path): + import numpy as np + + from quantui.molecule import Molecule + from quantui.results_storage import load_trajectory, save_trajectory + + mol = Molecule(["H", "H"], [[0.0, 0.0, 0.0], [0.0, 0.0, 0.74]]) + mol.coordinates = np.asarray(mol.coordinates, dtype=np.float32) + save_trajectory(tmp_path, [mol, mol], [np.float32(-1.1), np.float32(-1.12)]) + mols, energies = load_trajectory(tmp_path) + assert len(mols) == 2 + assert energies[1] == pytest.approx(-1.12, abs=1e-6) + + +# --------------------------------------------------------------------------- +# DATA-12 — corrupt settings.json must not crash; unknown sections survive +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "raw", + [b"\xff\xfe\x00garbage\x80", b"[" * 100000], + ids=["non-utf8", "deeply-nested"], +) +def test_corrupt_settings_fall_back_to_defaults(tmp_path, raw): + from quantui.user_settings import UserSettings + + p = tmp_path / "settings.json" + p.write_bytes(raw) + assert UserSettings.load(p) == UserSettings() + + +def test_settings_save_preserves_unknown_sections(tmp_path): + import json + + from quantui.user_settings import UserSettings + + p = tmp_path / "settings.json" + data = UserSettings().to_dict() + data["future_section"] = {"x": 1} + data["compute"]["future_key"] = "keep" + p.write_text(json.dumps(data), encoding="utf-8") + + s = UserSettings.load(p) + s.compute.density_fit = True + s.save(p) + + saved = json.loads(p.read_text(encoding="utf-8")) + assert saved["future_section"] == {"x": 1} + assert saved["compute"]["future_key"] == "keep" + assert saved["compute"]["density_fit"] is True + + +# --------------------------------------------------------------------------- +# DATA-13 — calc_log writers/readers robustness +# --------------------------------------------------------------------------- + + +@pytest.fixture +def _calc_log_dir(tmp_path, monkeypatch): + from quantui import calc_log + + monkeypatch.setenv("QUANTUI_LOG_DIR", str(tmp_path)) + calc_log._READ_ALL_CACHE.clear() + yield tmp_path + calc_log._READ_ALL_CACHE.clear() + + +def test_log_event_accepts_numpy_and_path(_calc_log_dir): + import numpy as np + + from quantui import calc_log + + calc_log.log_event( + "x", "msg", n=np.int64(3), ok=np.bool_(True), where=_calc_log_dir + ) + (rec,) = calc_log.get_recent_events() + assert rec["n"] == 3 and rec["ok"] is True + assert rec["where"] == str(_calc_log_dir) + + +def test_non_object_lines_are_skipped(_calc_log_dir): + from quantui import calc_log + + calc_log.log_event("a", "first") + with open(calc_log._event_path(), "a", encoding="utf-8") as fh: + fh.write("123\n") + calc_log.prune_events() # used to raise TypeError on the ``123`` line + events = calc_log.get_recent_events() + assert [e["event"] for e in events] == ["a"] + + with open(calc_log._perf_path(), "a", encoding="utf-8") as fh: + fh.write("42\n") + assert calc_log.get_perf_history() == [] + calc_log.estimate_time(n_atoms=2, n_electrons=2, method="RHF", basis="STO-3G") + + +def test_prune_keeps_bytes_appended_after_read(_calc_log_dir, monkeypatch): + """An append from another process between read and rewrite survives.""" + from quantui import calc_log + + calc_log.log_event("a", "first") + path = calc_log._event_path() + real_open = open + state = {"n": 0} + + def _open(file, mode="r", *a, **k): + fh = real_open(file, mode, *a, **k) + if str(file) == str(path) and mode == "rb": + state["n"] += 1 + if state["n"] == 1: # after the prune's first read + with real_open(path, "a", encoding="utf-8") as other: + other.write( + '{"timestamp": "2999-01-01T00:00:00+00:00",' + ' "event": "foreign", "message": ""}\n' + ) + return fh + + monkeypatch.setattr(calc_log, "open", _open, raising=False) + calc_log.prune_events() + monkeypatch.delattr(calc_log, "open") + calc_log._READ_ALL_CACHE.clear() + assert [e["event"] for e in calc_log.get_recent_events()] == ["a", "foreign"] + + +def test_read_all_cache_not_poisoned_by_caller_mutation(_calc_log_dir): + from quantui import calc_log + + calc_log.log_event("a", "first") + calc_log.get_recent_events()[0]["event"] = "mutated" + assert calc_log.get_recent_events()[0]["event"] == "a" + + +# --------------------------------------------------------------------------- +# DATA-14 — time estimator +# --------------------------------------------------------------------------- + + +def _perf(**kw): + rec = dict( + converged=True, + method="RHF", + basis="STO-3G", + n_atoms=3, + n_electrons=10, + n_basis=7, + calc_type="single_point", + source="app", + gpu_used=False, + ) + rec.update(kw) + return rec + + +def test_frequency_cost_model_partitions_by_density_fit(): + from quantui import calc_log + + records = [_perf(elapsed_s=2.0, density_fit=True) for _ in range(3)] + [ + _perf(elapsed_s=200.0, density_fit=False) for _ in range(3) + ] + kw = dict( + n_atoms=3, + n_electrons=10, + method="RHF", + basis="STO-3G", + n_basis=7, + calc_type="frequency", + gpu_used=False, + source="app", + ) + fast = calc_log.estimate_time_from_records(records, density_fit=True, **kw) + slow = calc_log.estimate_time_from_records(records, density_fit=False, **kw) + assert fast is not None and slow is not None + assert slow["seconds"] > 50 * fast["seconds"] + + +def test_replay_passes_density_fit(monkeypatch): + from quantui import calc_log, estimator_eval + + seen = [] + + def _spy(history, **kw): + seen.append(kw.get("density_fit")) + return None + + monkeypatch.setattr(calc_log, "estimate_time_from_records", _spy) + estimator_eval.replay( + [_perf(elapsed_s=3.0, density_fit=True, timestamp="2026-01-01")] + ) + assert seen == [True] + + +def test_sub_second_records_do_not_drive_power_law(): + """Overhead-dominated runs must not be extrapolated by n_basis^3.5.""" + from quantui import calc_log + + records = [ + _perf(elapsed_s=0.05, n_basis=2, n_electrons=2), + _perf(elapsed_s=0.06, n_basis=7, n_electrons=10), + _perf(elapsed_s=0.07, n_basis=7, n_electrons=10), + _perf(elapsed_s=0.08, n_basis=2, n_electrons=2), + ] + est = calc_log.estimate_time_from_records( + records, + n_atoms=40, + n_electrons=160, + method="RHF", + basis="STO-3G", + n_basis=200, + calc_type="single_point", + ) + assert est is not None + # Power law gave ~51 min here; electron-count scaling is minutes at most. + assert est["seconds"] < 600 + + +def test_log_calculation_records_n_threads(tmp_path, monkeypatch): + from quantui import calc_log + + monkeypatch.setenv("QUANTUI_LOG_DIR", str(tmp_path)) + calc_log._READ_ALL_CACHE.clear() + calc_log.log_calculation( + formula="H2", + n_atoms=2, + n_electrons=2, + method="RHF", + basis="STO-3G", + n_iterations=3, + elapsed_s=1.0, + converged=True, + n_threads=4, + ) + (rec,) = calc_log.get_perf_history() + assert rec["n_threads"] == 4 + assert "n_cores" not in rec + calc_log._READ_ALL_CACHE.clear() + + +def test_calibration_logs_opt_steps_and_threads(monkeypatch, tmp_path): + pytest.importorskip("pyscf") + import multiprocessing + + entry = tuple(benchmarks._MODE_TO_SUITE["tier1"][0]) + ("geometry_opt",) + monkeypatch.setitem(benchmarks._MODE_TO_SUITE, "tier1", [entry]) + + class _Proc(_RecordingProcess): + def start(self): + self.args[8].put( + { + "status": "ok", + "formula": "H2", + "converged": True, + "n_iterations": None, + "n_steps": 4, + "n_threads": 2, + "elapsed_s": 1.5, + "result_dir": None, + } + ) + + class _Ctx(_RecordingCtx): + Process = _Proc + + monkeypatch.setattr(multiprocessing, "get_context", lambda *_a: _Ctx()) + monkeypatch.setattr( + benchmarks, "_calibration_log_path", lambda ts: tmp_path / "cal.log" + ) + monkeypatch.setattr(benchmarks, "_save_calibration_json", lambda *a, **k: None) + monkeypatch.setattr( + "quantui.gpu_offload.is_gpu_available", lambda: (False, None), raising=False + ) + logged = [] + monkeypatch.setattr( + "quantui.calc_log.log_calculation", lambda **kw: logged.append(kw) + ) + benchmarks.run_calibration(mode="tier1") + (rec,) = logged + assert rec["n_steps"] == 4 + assert rec["n_iterations"] is None + assert rec["n_threads"] == 2 + assert "n_cores" not in rec + + +def test_calibration_worker_reports_opt_steps(monkeypatch, tmp_path): + from types import SimpleNamespace + + fake = SimpleNamespace( + molecule=SimpleNamespace(get_formula=lambda: "H2"), + converged=True, + n_steps=5, + ) + monkeypatch.setattr("quantui.optimizer.optimize_geometry", lambda **k: fake) + monkeypatch.setattr(benchmarks, "_save_calibration_step", lambda *a, **k: None) + log = tmp_path / "cal.log" + log.write_text("") + + class _Q: + items: list = [] + + def put(self, item): + self.items.append(item) + + q = _Q() + benchmarks._calibration_worker( + ["H", "H"], + [[0.0, 0.0, 0.0], [0.0, 0.0, 0.74]], + 0, + 1, + "RHF", + "STO-3G", + "geometry_opt", + str(log), + q, + "rid", + False, + ) + (msg,) = q.items + assert msg["status"] == "ok", msg + assert msg["n_steps"] == 5 + assert msg["n_iterations"] is None + + +# --------------------------------------------------------------------------- +# DATA-15 — checkpoint retention / resume key +# --------------------------------------------------------------------------- + + +def test_coords_digest_ignores_sign_of_zero(): + from quantui.checkpoint import _coords_digest + + a = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.74]] + b = [[-0.0, 0.0, -0.0], [0.0, -0.0000001, 0.74]] + assert _coords_digest(a) == _coords_digest(b) + assert _coords_digest(a) != _coords_digest([[0.0, 0.0, 0.0], [0.0, 0.0, 0.75]]) + + +def test_prune_removes_old_unreadable_checkpoint_dirs(tmp_path): + from quantui import checkpoint as C + + old = time.time() - 60 * 86400 + missing = tmp_path / ("a" * 16) + missing.mkdir() + corrupt = tmp_path / ("b" * 16) + corrupt.mkdir() + (corrupt / "meta.json").write_text("{not json") + fresh = tmp_path / ("c" * 16) + fresh.mkdir() # e.g. a checkpoint being created right now + foreign = tmp_path / "not-a-checkpoint" + foreign.mkdir() + for p in (missing, corrupt / "meta.json", corrupt, foreign): + os.utime(p, (old, old)) + + assert C.prune(tmp_path, max_age_days=14) == 2 + assert not missing.exists() and not corrupt.exists() + assert fresh.exists() and foreign.exists() + + +# --------------------------------------------------------------------------- +# DATA-16 — parser gaps for real-world files +# --------------------------------------------------------------------------- + +_WATER = "3\nwater\nO 0 0 0.117\nH 0 0.757 -0.467\nH 0 -0.757 -0.467\n" + + +@pytest.mark.parametrize( + "text", + [ + "" + _WATER, + _WATER.replace("\n", "\r"), + _WATER.replace("0.117", "1.17D-01"), + _WATER.replace("-0.467", "−0.467"), + "O 0 0 0.117\nD 0 0.757 -0.467\nT 0 -0.757 -0.467\n", + ], + ids=["bom", "old-mac-cr", "fortran-d", "unicode-minus", "isotopes"], +) +def test_paste_parser_accepts_real_world_quirks(text): + from quantui.molecule import parse_xyz_input + + atoms, coords = parse_xyz_input(text) + assert atoms == ["O", "H", "H"] + assert coords[0][2] == pytest.approx(0.117) + assert coords[1][2] == pytest.approx(-0.467) + + +def test_has_isotope_labels(): + from quantui.molecule import has_isotope_labels + + assert has_isotope_labels("O 0 0 0\nD 0 0 1\n") + assert not has_isotope_labels(_WATER) + + +@pytest.mark.parametrize( + "content", + [ + b"\xef\xbb\xbf" + _WATER.encode(), + _WATER.encode("utf-16"), + _WATER.replace("\n", "\r").encode(), + _WATER.replace("0.117", "1.17D-01").encode(), + _WATER.replace("-0.467", "−0.467").encode(), + b"O 0 0 0.117\nH 0 0.757 -0.467\nH 0 -0.757 -0.467\n", + ], + ids=["bom", "utf16", "old-mac-cr", "fortran-d", "unicode-minus", "headerless"], +) +def test_upload_xyz_accepts_real_world_quirks(content): + pytest.importorskip("ase") + from quantui.structure_upload import read_uploaded_structure + + up = read_uploaded_structure("water.xyz", content) + assert up.molecule.atoms == ["O", "H", "H"] + assert up.molecule.coordinates[0][2] == pytest.approx(0.117) + + +def test_upload_xyz_isotopes_mapped_with_note(): + pytest.importorskip("ase") + from quantui.molecule import ISOTOPE_NOTE + from quantui.structure_upload import read_uploaded_structure + + up = read_uploaded_structure( + "d2o.xyz", _WATER.replace("H 0 0.757", "D 0 0.757").encode() + ) + assert up.molecule.atoms == ["O", "H", "H"] + assert ISOTOPE_NOTE in up.notes + + +def test_upload_xyz_charge_comment_from_last_frame(): + pytest.importorskip("ase") + from quantui.structure_upload import read_uploaded_structure + + content = ( + b"2\ncharge=0 multiplicity=1\nH 0 0 0\nH 0 0 0.74\n" + b"2\ncharge=1 multiplicity=2\nH 0 0 0\nH 0 0 1.0\n" + ) + up = read_uploaded_structure("traj.xyz", content) + assert up.molecule.coordinates[1][2] == pytest.approx(1.0) + assert (up.molecule.charge, up.molecule.multiplicity) == (1, 2) + + +def test_upload_pdb_altlocs_keep_one_conformer(): + pytest.importorskip("ase") + from quantui.structure_upload import read_uploaded_structure + + pdb = ( + "ATOM 1 O AHOH A 1 0.000 0.000 0.117 0.50 0.00" + " O\n" + "ATOM 2 O BHOH A 1 0.100 0.000 0.117 0.50 0.00" + " O\n" + "ATOM 3 H1 HOH A 1 0.000 0.757 -0.467 1.00 0.00" + " H\n" + "ATOM 4 H2 HOH A 1 0.000 -0.757 -0.467 1.00 0.00" + " H\n" + "END\n" + ) + up = read_uploaded_structure("w.pdb", pdb.encode()) + assert sorted(up.molecule.atoms) == ["H", "H", "O"] + assert any("alternate" in n for n in up.notes) + + +def test_upload_overlong_filename(): + pytest.importorskip("ase") + from quantui.structure_upload import read_uploaded_structure + + up = read_uploaded_structure("x" * 300 + ".xyz", _WATER.encode()) + assert up.molecule.atoms == ["O", "H", "H"] + + +# --------------------------------------------------------------------------- +# DATA-17 — smaller items +# --------------------------------------------------------------------------- + + +def test_package_exports(): + import quantui + + assert quantui.student_friendly_resolve.__module__ == ( + "quantui.structure_providers" + ) + assert "run_pes_scan" in quantui.__all__ + assert "PESScanResult" in quantui.__all__ + + +def test_get_spin_doublet_is_half(): + from quantui.molecule import Molecule + + assert Molecule(["H"], [[0, 0, 0]], multiplicity=2).get_spin() == 0.5 + + +def test_parse_atom_list_bounds_checked_before_expanding(): + from quantui.structure_edit import parse_atom_list + + t0 = time.perf_counter() + with pytest.raises(ValueError, match="only 3 atoms"): + parse_atom_list("1-30000000", 3) + with pytest.raises(ValueError): + parse_atom_list("1-300000000000") + with pytest.raises(ValueError, match="start at 1"): + parse_atom_list("0-2", 3) + assert time.perf_counter() - t0 < 1.0 + assert parse_atom_list("3-1, 5", 5) == [0, 1, 2, 4] + + +def test_smiles_without_optimisation_and_atom_cap(): + pytest.importorskip("rdkit") + from quantui.pubchem import MAX_LOCAL_EMBED_ATOMS, smiles_to_xyz + + xyz, meta = smiles_to_xyz("CCO", optimize_3d=False) + assert xyz.splitlines()[0] == "9" + with pytest.raises(ValueError, match=str(MAX_LOCAL_EMBED_ATOMS)): + smiles_to_xyz("C" * 200) + + +def test_issue_tracker_closes_connections(tmp_path, monkeypatch): + import sqlite3 + + from quantui import issue_tracker + + monkeypatch.setenv("QUANTUI_LOG_DIR", str(tmp_path)) + opened = [] + real_connect = sqlite3.connect + + def _connect(*a, **k): + conn = real_connect(*a, **k) + opened.append(conn) + return conn + + monkeypatch.setattr(issue_tracker.sqlite3, "connect", _connect) + issue_tracker.log_issue("x") + assert issue_tracker.get_issues()[0]["description"] == "x" + issue_tracker.clear_issues() + assert opened + for conn in opened: + with pytest.raises(sqlite3.ProgrammingError): + conn.execute("SELECT 1") + + +def test_save_thumbnail_keeps_matplotlib_backend(tmp_path): + matplotlib = pytest.importorskip("matplotlib") + from quantui.results_storage import save_thumbnail + + orig = matplotlib.get_backend() + matplotlib.use("svg") + try: + save_thumbnail(tmp_path, {"calc_type": "single_point", "formula": "H2"}) + assert matplotlib.get_backend() == "svg" + assert (tmp_path / "thumbnail.png").stat().st_size > 0 + finally: + matplotlib.use(orig) + + +def test_warnings_digest_matches_whole_words(): + from quantui.log_utils import _extract_warnings + + log = "\n".join( + [ + "conv_tol = 1e-09 error_tol = 1e-05", + "WARN: HOMO-LUMO gap small", + "SCF not converged.", + "Error in DIIS", + "UserWarning: Module EFG is under testing", + ] + ) + found = _extract_warnings(log) + assert "conv_tol = 1e-09 error_tol = 1e-05" not in found + assert len(found) == 4 + + +def test_library_search_treats_wildcards_literally(): + from quantui import molecule_library + + assert molecule_library.search("%") == [] + assert molecule_library.search("_") == [] + assert molecule_library.search("water") diff --git a/tests/test_backends_local.py b/tests/test_backends_local.py new file mode 100644 index 00000000..fc1fb042 --- /dev/null +++ b/tests/test_backends_local.py @@ -0,0 +1,74 @@ +"""quantui.backends.local.LocalBackend (audit INFRA-22: had no tests).""" + +from __future__ import annotations + +import pytest + +from quantui import config +from quantui.backends.base import CALC_TYPES, CalculationRequest, ComputeBackend +from quantui.backends.local import LocalBackend +from quantui.backends.registry import JobRegistry + + +@pytest.fixture +def registry(tmp_path): + return JobRegistry(jobs_root=tmp_path / "jobs", staging_root=tmp_path / "staging") + + +def _request(request_id="req-1"): + return CalculationRequest( + request_id=request_id, + calc_type="single_point", + method="RHF", + basis="STO-3G", + charge=0, + multiplicity=1, + molecule={"atoms": ["H", "H"], "coordinates": [[0, 0, 0], [0, 0, 0.74]]}, + ) + + +def test_capabilities_describe_the_local_backend(registry): + caps = LocalBackend(registry).capabilities() + assert caps.backend_id == LocalBackend.backend_id == "local_pyscf" + assert caps.supported_calc_types == CALC_TYPES + assert caps.supported_methods == tuple(config.SUPPORTED_METHODS) + assert caps.supports_solvent and caps.supports_cancellation + assert caps.supports_live_progress and caps.supports_history_artifacts + + +def test_register_local_run_records_a_running_job(registry): + backend = LocalBackend(registry) + req = _request() + assert backend.register_local_run(req) == "req-1" + rec = registry.load("req-1") + assert rec is not None + assert rec.status == "running" + assert rec.backend_id == "local_pyscf" + assert rec.calc_type == "single_point" + assert rec.request_obj.method == "RHF" + + +def test_dispatch_registers_without_running_anything(registry): + backend = LocalBackend(registry) + assert backend.dispatch(_request("req-2")) == "req-2" + assert registry.load("req-2").status == "running" + + +def test_a_request_id_is_never_registered_twice(registry): + backend = LocalBackend(registry) + backend.register_local_run(_request()) + with pytest.raises(FileExistsError): + backend.register_local_run(_request()) + + +def test_default_registry_follows_the_env_roots(tmp_path, monkeypatch): + monkeypatch.setenv("QUANTUI_JOBS_DIR", str(tmp_path / "j")) + monkeypatch.setenv("QUANTUI_HOME", str(tmp_path / "home")) + monkeypatch.delenv("QUANTUI_STAGING_DIR", raising=False) + backend = LocalBackend() + assert backend.registry.jobs_root == tmp_path / "j" + assert str(backend.registry.staging_root).startswith(str(tmp_path / "home")) + + +def test_satisfies_the_compute_backend_protocol(registry): + assert isinstance(LocalBackend(registry), ComputeBackend) 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 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_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 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_calc_log.py b/tests/test_calc_log.py index 3b0ccbfe..166ebb06 100644 --- a/tests/test_calc_log.py +++ b/tests/test_calc_log.py @@ -2,18 +2,23 @@ from __future__ import annotations -import importlib - import pytest @pytest.fixture(autouse=True) def isolated_log_dir(tmp_path, monkeypatch): - """Point QUANTUI_LOG_DIR at a fresh temp directory for every test.""" + """Point QUANTUI_LOG_DIR at a fresh temp directory for every test. + + ``calc_log._log_dir()`` reads the env var on every call, so no + ``importlib.reload`` is needed (audit INFRA-18: reloading replaced the + module's globals under every other module holding a reference to it). + The one piece of per-process state a test depends on, the prune + throttle counter, is reset explicitly. + """ monkeypatch.setenv("QUANTUI_LOG_DIR", str(tmp_path)) import quantui.calc_log as clog - importlib.reload(clog) + monkeypatch.setattr(clog, "_events_since_prune", 0) yield tmp_path diff --git a/tests/test_calculator.py b/tests/test_calculator.py index 02aa96be..0b46ba47 100644 --- a/tests/test_calculator.py +++ b/tests/test_calculator.py @@ -306,7 +306,7 @@ def test_exported_npz_has_fields_the_cube_helper_needs(self, tmp_path): ) assert proc.returncode == 0, proc.stdout + proc.stderr - npz = np.load(tmp_path / "results.npz", allow_pickle=True) + npz = np.load(tmp_path / "results.npz", allow_pickle=False) assert "mol_atom" in npz.files assert "mol_basis" in npz.files assert "mo_occ" in npz.files @@ -367,7 +367,7 @@ def test_exported_post_hf_script_runs_successfully(self, tmp_path, method): import numpy as np - npz = np.load(tmp_path / "results.npz", allow_pickle=True) + npz = np.load(tmp_path / "results.npz", allow_pickle=False) # RHF/STO-3G water energy is ~-74.963; any real correlation energy # must make the total more negative than that. assert float(npz["energy"]) < -74.97 diff --git a/tests/test_calibration_save_results.py b/tests/test_calibration_save_results.py index 753597ac..43886cd1 100644 --- a/tests/test_calibration_save_results.py +++ b/tests/test_calibration_save_results.py @@ -275,13 +275,38 @@ def test_worker_source_calls_save_calibration_step(self): # And the queue payload now carries result_dir. assert "result_dir" in src - def test_save_calibration_json_includes_result_dir(self): + def test_save_calibration_json_includes_result_dir(self, tmp_path, monkeypatch): # The persisted calibration.json should expose result_dir per - # step so future tooling can find the saved results. + # step so future tooling can find the saved results. Write one and + # read it back (audit INFRA-19: was a source-text check). from quantui import benchmarks - src = inspect.getsource(benchmarks._save_calibration_json) - assert '"result_dir"' in src or "'result_dir'" in src + cal_path = tmp_path / "calibration.json" + monkeypatch.setenv("QUANTUI_CALIBRATION_PATH", str(cal_path)) + step = benchmarks.BenchmarkStep( + label="H2O RHF/STO-3G", + method="RHF", + basis="STO-3G", + n_atoms=3, + n_electrons=10, + status=benchmarks._STATUS_OK, + elapsed_s=1.0, + result_dir=str(tmp_path / "results" / "h2o"), + ) + failed = benchmarks.BenchmarkStep( + label="H2O B3LYP/STO-3G", + method="B3LYP", + basis="STO-3G", + n_atoms=3, + n_electrons=10, + status=benchmarks._STATUS_ERROR, + ) + result = benchmarks.CalibrationResult( + timestamp="2026-11-12T00:00:00Z", steps=[step, failed] + ) + benchmarks._save_calibration_json(result, tmp_path / "cal.log") + steps = json.loads(cal_path.read_text(encoding="utf-8"))["steps"] + assert [s["result_dir"] for s in steps] == [step.result_dir, None] class TestHistoryLabelMarker: diff --git a/tests/test_checkpoint_wiring.py b/tests/test_checkpoint_wiring.py index d71fdbb3..7698c1d6 100644 --- a/tests/test_checkpoint_wiring.py +++ b/tests/test_checkpoint_wiring.py @@ -1087,15 +1087,17 @@ class TestResumedRunsGetTheirOwnResultDirectory: def test_directory_name_is_timestamped(self): import quantui.results_storage as R - src = Path(R.__file__).read_text(encoding="utf-8") - body = src[src.index("def save_result") :][:4000] + # Whole function: since audit DATA-11 the mkdir comes after the + # payload is serialised, past the first few thousand characters. + body = inspect.getsource(R.save_result) assert "%Y-%m-%d_%H-%M-%S-%f" in body def test_a_collision_never_reuses_an_existing_directory(self): import quantui.results_storage as R - src = Path(R.__file__).read_text(encoding="utf-8") - body = src[src.index("def save_result") :][:4000] + # Whole function: since audit DATA-11 the mkdir comes after the + # payload is serialised, past the first few thousand characters. + body = inspect.getsource(R.save_result) assert "while dest.exists():" in body assert "dest.mkdir(parents=True)" in body assert "exist_ok" not in body.split("dest.mkdir(parents=True)")[0][-200:] diff --git a/tests/test_ci_gating.py b/tests/test_ci_gating.py new file mode 100644 index 00000000..b51bfbcc --- /dev/null +++ b/tests/test_ci_gating.py @@ -0,0 +1,92 @@ +"""Audit INFRA-12 — CI gating guards. + +Line-based checks on the workflow files and the test harness (no PyYAML, same +reasoning as ``test_ci_hook_reachability.py``): + +* the ``network``-marked tests run somewhere (a scheduled workflow), since + every ``ci.yml`` job deselects them; +* ``pages.yml`` grants ``pages: write`` / ``id-token: write`` to the deploy + job only, not workflow-wide (where the build job would inherit them); +* the Windows job runs the whole non-PySCF suite — every test file must skip + cleanly without PySCF rather than being ``--ignore``\\ d; +* xdist workers cap ``OMP_NUM_THREADS`` (conftest). +""" + +from __future__ import annotations + +import os +import re +from pathlib import Path + +import pytest + +_ROOT = Path(__file__).resolve().parent.parent +_WORKFLOWS = _ROOT / ".github" / "workflows" + + +def _read(path: Path) -> str: + return path.read_text(encoding="utf-8") + + +def _top_level_block(text: str, key: str) -> str: + """Return the indented body under a top-level ``key:`` line ('' if absent).""" + lines = text.splitlines() + for i, line in enumerate(lines): + if line.rstrip() == f"{key}:": + body = [] + for nxt in lines[i + 1 :]: + if nxt and not nxt[0].isspace() and not nxt.startswith("#"): + break + body.append(nxt) + return "\n".join(body) + return "" + + +def test_network_tests_run_on_a_schedule(): + runners = [] + for wf in sorted(_WORKFLOWS.glob("*.yml")): + text = _read(wf) + if re.search(r'pytest[^\n]*-m\s+"?network"?(\s|$)', text): + runners.append((wf.name, text)) + assert runners, "no workflow runs `pytest -m network`" + assert any( + "schedule:" in text and "cron:" in text for _, text in runners + ), "the workflow running `-m network` has no schedule" + + +def test_pages_write_permissions_are_job_scoped(): + text = _read(_WORKFLOWS / "pages.yml") + top = _top_level_block(text, "permissions") + assert "contents: read" in top + assert "pages: write" not in top + assert "id-token: write" not in top + deploy = text.split("\n deploy:", 1) + assert len(deploy) == 2, "pages.yml has no deploy job" + build = deploy[0].split("\n build:", 1)[1] + assert "pages: write" not in build and "id-token: write" not in build + assert "pages: write" in deploy[1] and "id-token: write" in deploy[1] + + +def test_windows_job_does_not_ignore_test_files(): + text = _read(_WORKFLOWS / "ci.yml") + job = text.split("\n test-windows:", 1)[1].split("\n test-windows-pyfock:")[0] + runs = [ln for ln in job.splitlines() if ln.strip().startswith("run:")] + assert any("pytest" in ln for ln in runs) + assert not any("--ignore" in ln for ln in runs), ( + "the Windows job --ignores a test file; give it a PySCF skip guard " + "instead so it runs (and skips cleanly) without PySCF" + ) + + +@pytest.mark.skipif( + not os.environ.get("PYTEST_XDIST_WORKER"), reason="only meaningful under xdist" +) +def test_xdist_workers_cap_omp_threads(): + assert os.environ.get("OMP_NUM_THREADS") + + +def test_conftest_caps_omp_threads_for_xdist_workers(): + # -n0 runs can't observe the worker env, so also pin the conftest logic. + text = _read(_ROOT / "tests" / "conftest.py") + assert 'os.environ.get("PYTEST_XDIST_WORKER")' in text + assert 'os.environ.setdefault("OMP_NUM_THREADS", "1")' in text diff --git a/tests/test_code_quality.py b/tests/test_code_quality.py index 23eb0676..6ff1bf67 100644 --- a/tests/test_code_quality.py +++ b/tests/test_code_quality.py @@ -1,34 +1,96 @@ """Static analysis guards for patterns that fail silently at runtime.""" +import ast import re from pathlib import Path SRC = Path(__file__).parent.parent / "quantui" -# Files where silent failure is most dangerous — numeric/data extraction -# paths where a swallowed exception ships subtly-wrong results downstream -# (bug-A class: cupy TypeError swallow in session_calc.py, session 55). -# -# Every broad-except + pass in these files must EITHER: -# - have a log call (logger.*, calc_log.log_event, _clog.log_event) -# within 10 lines after the ``except`` (window allows for multi-line -# log messages — see session_calc.py:455 MO-extract for an example), OR -# - carry a ``# noqa: BLE001 — `` comment on the ``except`` line +# Silent broad-excepts (audit INFRA-15). Every ``except Exception`` / bare +# ``except`` in the package must EITHER: +# - have a log call (logger.*, calc_log.log_event, _clog.log_event, +# warnings.warn) or a ``raise`` inside the handler body, OR +# - carry a ``# noqa: BLE001 — `` comment on the ``except`` header # justifying the silence (cleanup, telemetry self-guard, optional probe). # +# The guard used to cover only eight hand-picked numerics files. It now covers +# the whole package: a module not listed below must have no silent +# broad-excepts (so every new module, numerics or not, is guarded from day +# one), and a listed legacy module may not gain more than it had when the +# guard was widened (2026-11-12). Lower a count when you fix some; drop the +# entry at zero. The original high-risk numerics files (session_calc, +# freq_calc, raman_calc, tddft_calc, nmr_calc, optimizer, gpu_offload, +# analytics) and the newer numerics modules (scf_robust, symmetry, +# reorganization_energy, ts_search, ts_guess, population_analysis, the +# engines, ...) are all at zero. +# # See reflections/03-error-surfacing.md Rule 1 for the categorization rubric # and BARE-EXCEPT-AUDIT-2026-05-25.md for the originating audit. -_HIGH_RISK_FILES = { - "session_calc.py", - "freq_calc.py", - "raman_calc.py", - "tddft_calc.py", - "nmr_calc.py", - "optimizer.py", - "gpu_offload.py", - "analytics.py", +_SILENT_BROAD_EXCEPT_BASELINE = { + "app.py": 51, + "app_analysis.py": 9, + "app_builders.py": 1, + "app_exports.py": 7, + "app_history.py": 21, + "app_launcher.py": 1, + "app_runflow.py": 38, + "app_slurm.py": 4, + "app_visualization.py": 51, + "app_xyz_input.py": 5, + "benchmarks.py": 2, + "c_stderr.py": 5, + "calc_log.py": 2, + "cli.py": 2, + "density_fitting.py": 1, + "inorganic_guards.py": 1, + "issue_tracker.py": 1, + "log_utils.py": 5, + "orbital_visualization.py": 2, + "pes_scan.py": 1, + "pubchem.py": 4, + "results_storage.py": 14, + "slurm_ingest.py": 1, + "worker.py": 2, + "worker_payload.py": 3, + "xyz_input.py": 1, } +_LOG_CALL_RE = re.compile( + r"\b(logger\.|_clog\.|calc_log\.log_event|log_event\(|" + r"_log_event|warnings\.warn)" +) + + +def _silent_broad_excepts(source: str) -> list[int]: + """Line numbers of silent broad ``except`` handlers in *source*. + + AST-based: the handler body is exactly the ``except`` block, so a log + call that merely follows the block (the old 10-line text window counted + those) does not excuse it, and a black-wrapped + ``except (\n Exception\n): # noqa: BLE001 — ...`` header is seen. + """ + lines = source.splitlines() + hits = [] + for node in ast.walk(ast.parse(source)): + if not isinstance(node, ast.ExceptHandler): + continue + broad = node.type is None or ( + isinstance(node.type, ast.Name) + and node.type.id in ("Exception", "BaseException") + ) + if not broad: + continue + header = lines[node.lineno - 1 : node.body[0].lineno - 1] + if any("noqa: BLE001" in h for h in header): + continue + body = "\n".join(lines[node.body[0].lineno - 1 : node.end_lineno]) + if _LOG_CALL_RE.search(body): + continue + if any(isinstance(n, ast.Raise) for b in node.body for n in ast.walk(b)): + continue + hits.append(node.lineno) + return hits + def _grep(pattern: str) -> list[str]: hits = [] @@ -114,6 +176,47 @@ def test_in_app_figure_payload_is_small(): plotly_embed._outputs.discard(out) +def _py3dmol_view_calls(source: str) -> list[int]: + """Line numbers constructing a py3Dmol view directly, under any import + alias: ``import py3Dmol as p; p.view(...)``, ``from py3Dmol import view`` + (audit INFRA-15: the old regex knew only ``py3Dmol``/``_p3d``).""" + tree = ast.parse(source) + modules, funcs = set(), set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + for a in node.names: + if a.name == "py3Dmol": + modules.add(a.asname or a.name) + elif isinstance(node, ast.ImportFrom) and node.module == "py3Dmol": + for a in node.names: + if a.name == "view": + funcs.add(a.asname or a.name) + hits = [] + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + f = node.func + if ( + isinstance(f, ast.Attribute) + and f.attr == "view" + and isinstance(f.value, ast.Name) + and f.value.id in modules + ) or (isinstance(f, ast.Name) and f.id in funcs): + hits.append(node.lineno) + return hits + + +def test_py3dmol_guard_sees_aliases(): + src = ( + "import py3Dmol as p\n" + "from py3Dmol import view as v\n" + "p.view(width=1)\n" + "v()\n" + "other.view()\n" + ) + assert _py3dmol_view_calls(src) == [3, 4] + + def test_no_bare_py3dmol_view(): """py3Dmol.view(...) defaults to a CDN js= URL that blanks views offline. @@ -122,12 +225,12 @@ def test_no_bare_py3dmol_view(): ``viz_assets.py`` is allowed to call ``py3Dmol.view`` directly (the factory itself). See reflections/01 Rule 1 + reflections/06. """ - # Match ``py3Dmol.view(`` or ``.view(width=`` style construction. - hits = [ - h - for h in _grep(r"\bpy3Dmol\.view\(|\b_p3d\.view\(") - if "viz_assets.py" not in h - ] + hits = [] + for path in sorted(SRC.rglob("*.py")): + if path.name == "viz_assets.py": + continue + for line in _py3dmol_view_calls(path.read_text(encoding="utf-8")): + hits.append(f"{path.relative_to(SRC.parent)}:{line}") assert not hits, ( "Direct py3Dmol.view() call found (fetches 3Dmol.js from a CDN, blank " "offline). Use quantui.viz_assets.make_view instead:\n" + "\n".join(hits) @@ -178,104 +281,245 @@ def test_no_bare_except_pass(): ) -def test_no_silent_broad_except_in_high_risk_files(): - """Fail CI when a new broad-except + pass lands in a high-risk file - without either a log call within 5 lines or a ``# noqa: BLE001 — `` - annotation on the ``except`` line. +def test_no_new_silent_broad_except(): + """Fail CI when a broad-except lands without a log call, a re-raise or a + ``# noqa: BLE001 — `` annotation on the ``except`` header. - "Broad" means ``except Exception:`` (with or without ``as ``) or - truly-bare ``except:``. Narrower catches (``except ImportError:``, - ``except (KeyError, ValueError):``, etc.) are not flagged — the whole - point of narrowing is to be explicit about the failure mode. - - "Silent" means the body is ``pass`` (or assignment-only without a log - call) within the next 10 source lines. - - A line carrying ``# noqa: BLE001`` is treated as explicitly-justified - and skipped. The convention requires a ``— `` suffix; this + "Broad" means ``except Exception`` / ``except BaseException`` (with or + without ``as ``) or a bare ``except:``. Narrower catches + (``except ImportError:``, ``except (KeyError, ValueError):``) are not + flagged — the whole point of narrowing is to be explicit about the + failure mode. The noqa convention requires a ``— `` suffix; this test does not enforce the format (too easy to game) — reviewers do. """ - except_re = re.compile(r"^\s*except\s*(Exception(\s+as\s+\w+)?)?\s*:\s*(#.*)?$") - log_call_re = re.compile( - r"\b(logger\.|_clog\.|calc_log\.log_event|log_event\(|" - r"_log_event|warnings\.warn)" - ) - violations: list[str] = [] - for path in SRC.rglob("*.py"): - if path.name not in _HIGH_RISK_FILES: - continue - lines = path.read_text(encoding="utf-8").splitlines() - for i, line in enumerate(lines): - m = except_re.match(line) - if not m: - continue - # Explicit noqa annotation = justified. Reviewers enforce - # that the trailing reason is present + sensible. - if "noqa: BLE001" in line: - continue - # Look at the body (next 10 non-blank lines) for a log call. - # If none, the block is silent — flag it. 10 is generous enough - # to allow multi-line log message arguments. - body = lines[i + 1 : i + 11] - if any(log_call_re.search(b) for b in body): - continue - # Also accept if the body re-raises (still surfaces the error). - if any("raise" in b for b in body[:2]): - continue + for path in sorted(SRC.rglob("*.py")): + hits = _silent_broad_excepts(path.read_text(encoding="utf-8")) + allowed = _SILENT_BROAD_EXCEPT_BASELINE.get(path.name, 0) + if len(hits) > allowed: + where = ", ".join(str(n) for n in hits) violations.append( - f"{path.relative_to(SRC.parent)}:{i + 1}: {line.strip()}\n" - f" (body: {body[0].strip() if body else ''})" + f"{path.relative_to(SRC.parent)}: {len(hits)} silent " + f"broad-excepts (allowed {allowed}) at lines {where}" ) assert not violations, ( - "Silent broad-except detected in a high-risk file. Either add a " - "log call (logger.X / calc_log.log_event) within 10 lines of the " - "``except``, narrow the exception type, or annotate with\n" + "Silent broad-except detected. Either add a log call " + "(logger.X / calc_log.log_event) inside the ``except`` block, narrow " + "the exception type, or annotate the ``except`` line with\n" " ``# noqa: BLE001 — ``\n" "where is one of: cleanup, telemetry self-guard, optional probe.\n" "See reflections/03-error-surfacing.md Rule 1.\n\n" + "\n".join(violations) ) -def test_silent_broad_except_guard_actually_catches_violations(tmp_path): - """Meta-guard: confirm the lint check above isn't trivially passing. +def test_silent_broad_except_baseline_names_real_files(): + names = {p.name for p in SRC.rglob("*.py")} + stale = sorted(set(_SILENT_BROAD_EXCEPT_BASELINE) - names) + assert not stale, f"baseline lists files that no longer exist: {stale}" - Builds a temporary high-risk-looking source file containing a known-bad - silent broad-except + pass and verifies the regex / logic flags it. - Without this test, an accidental regex break would silently accept - everything and we wouldn't notice. - """ - bad_source = ( + +def test_silent_broad_except_guard_actually_catches_violations(): + """Meta-guard: confirm the lint check above isn't trivially passing.""" + bad = "def foo():\n try:\n risky()\n except Exception:\n pass\n" + assert _silent_broad_excepts(bad) == [4] + + # A log call AFTER the handler (same 10 lines, outer indentation) does + # not excuse it — the old text window accepted this (audit INFRA-15). + after = ( "def foo():\n" " try:\n" " risky()\n" " except Exception:\n" " pass\n" + " logger.info('done')\n" ) - # Re-implement the matcher inline (mirrors the production logic) so - # changes to the production helper force a deliberate update here. - except_re = re.compile(r"^\s*except\s*(Exception(\s+as\s+\w+)?)?\s*:\s*(#.*)?$") - log_call_re = re.compile( - r"\b(logger\.|_clog\.|calc_log\.log_event|log_event\(|" - r"_log_event|warnings\.warn)" + assert _silent_broad_excepts(after) == [4] + + ok = ( + "def foo():\n" + " try:\n" + " risky()\n" + " except Exception as e:\n" + " logger.warning('failed: %s', e)\n" + " try:\n" + " risky()\n" + " except Exception:\n" + " raise\n" + " try:\n" + " risky()\n" + " except (\n" + " Exception\n" + " ): # noqa: BLE001 — cleanup\n" + " pass\n" + " try:\n" + " risky()\n" + " except ValueError:\n" + " pass\n" ) + assert _silent_broad_excepts(ok) == [] + assert _silent_broad_excepts("try:\n x()\nexcept:\n y = 1\n") == [3] - lines = bad_source.splitlines() - flagged = False - for i, line in enumerate(lines): - if not except_re.match(line): - continue - if "noqa: BLE001" in line: - continue - body = lines[i + 1 : i + 11] - if any(log_call_re.search(b) for b in body): - continue - if any("raise" in b for b in body[:2]): + +# ── Callback wrapping (audit INFRA-15) ─────────────────────────────────────── + + +def _unwrapped_observe_calls(source: str) -> list[int]: + """Line numbers of ``.observe(handler, ...)`` calls whose handler is not + passed through ``_safe_cb`` (``app._safe_cb(fn)`` or a local alias bound + from ``getattr(app, "_safe_cb", ...)`` / ``app._safe_cb``).""" + tree = ast.parse(source) + aliases = {"_safe_cb"} + for node in ast.walk(tree): + if isinstance(node, ast.Assign) and len(node.targets) == 1: + target, value = node.targets[0], node.value + if not isinstance(target, ast.Name): + continue + if isinstance(value, ast.Attribute) and value.attr == "_safe_cb": + aliases.add(target.id) + elif ( + isinstance(value, ast.Call) + and isinstance(value.func, ast.Name) + and value.func.id == "getattr" + and len(value.args) >= 2 + and isinstance(value.args[1], ast.Constant) + and value.args[1].value == "_safe_cb" + ): + aliases.add(target.id) + hits = [] + for node in ast.walk(tree): + if not ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr == "observe" + ): continue - flagged = True - assert flagged, ( - "The lint guard didn't flag a known-bad ``except Exception: pass`` " - "block. The regex or window logic has regressed — fix it before " - "trusting test_no_silent_broad_except_in_high_risk_files." + handler = node.args[0] if node.args else None + if handler is None: + handler = next((k.value for k in node.keywords if k.arg == "handler"), None) + wrapped = isinstance(handler, ast.Call) and ( + ( + isinstance(handler.func, ast.Attribute) + and handler.func.attr == "_safe_cb" + ) + or (isinstance(handler.func, ast.Name) and handler.func.id in aliases) + ) + if not wrapped: + hits.append(node.lineno) + return hits + + +def test_observe_handlers_go_through_safe_cb(): + """ipywidgets drops exceptions raised in ``.observe()`` handlers with no + trace in the UI; ``QuantUIApp._safe_cb`` logs them to the calc log. Every + ``.observe()`` in the package must wrap its handler with it.""" + hits = [] + for path in sorted(SRC.rglob("*.py")): + for line in _unwrapped_observe_calls(path.read_text(encoding="utf-8")): + hits.append(f"{path.relative_to(SRC.parent)}:{line}") + assert not hits, ( + "Raw .observe() handler (exceptions vanish silently). Wrap it: " + "``w.observe(app._safe_cb(fn), names=...)``:\n" + "\n".join(hits) ) + + +def test_observe_guard_catches_raw_handlers(): + src = ( + "w.observe(fn, names='value')\n" + "w.observe(app._safe_cb(fn), names='value')\n" + "safe = getattr(app, '_safe_cb', lambda f: f)\n" + "w.observe(safe(lambda c: g(c)), names='value')\n" + "w.observe(handler=lambda c: g(c), names='value')\n" + ) + assert _unwrapped_observe_calls(src) == [1, 5] + + +# ── Version + vendored-asset consistency (audit INFRA-15) ──────────────────── + +_ROOT = SRC.parent + + +def _pyproject_version() -> str: + text = (_ROOT / "pyproject.toml").read_text(encoding="utf-8") + project = text.split("[project]", 1)[1].split("\n[", 1)[0] + m = re.search(r'^version\s*=\s*"([^"]+)"', project, re.M) + assert m, "no version in [project] of pyproject.toml" + return m.group(1) + + +def test_version_consistent_with_pyproject_and_changelog(): + """pyproject version == quantui.__version__ == newest released CHANGELOG + entry (the first ``## [x.y.z]`` heading after ``## [Unreleased]``).""" + import quantui + + changelog = (_ROOT / "CHANGELOG.md").read_text(encoding="utf-8") + released = re.findall(r"^## \[(\d+\.\d+\.\d+[^\]]*)\]", changelog, re.M) + assert released, "no released ``## [x.y.z]`` entry in CHANGELOG.md" + pyproject = _pyproject_version() + assert ( + quantui.__version__ == pyproject + ), f"quantui.__version__ {quantui.__version__} != pyproject {pyproject}" + assert ( + released[0] == pyproject + ), f"top released CHANGELOG entry {released[0]} != pyproject {pyproject}" + + +def test_vendored_3dmol_matches_py3dmol_default(): + """The vendored 3Dmol.js must match the release line py3Dmol's own + ``view(js=...)`` default targets: py3Dmol generates JS against that API. + Major.minor must agree; a patch-level skew is tolerated (audit INFRA-16 + tracks the current 2.5.4 vs 2.5.5 one).""" + import inspect + + import pytest + + py3Dmol = pytest.importorskip("py3Dmol") + from quantui import viz_assets + + assert viz_assets.THREEDMOL_VERSION in viz_assets.CDN_URL + default_js = inspect.signature(py3Dmol.view).parameters["js"].default + m = re.search(r"3dmol@(\d+)\.(\d+)\.(\d+)", str(default_js), re.I) + assert m, f"cannot read the 3Dmol.js version from py3Dmol's default {default_js!r}" + vendored = viz_assets.THREEDMOL_VERSION.split(".")[:2] + assert vendored == [m.group(1), m.group(2)], ( + f"vendored 3Dmol.js {viz_assets.THREEDMOL_VERSION} vs py3Dmol default " + f"{'.'.join(m.groups())}: re-vendor data/js/3Dmol-min.js" + ) + + +def test_precommit_revs_satisfy_dev_extra_pins(): + """``.pre-commit-config.yaml`` (what CI's lint job runs) and the ``dev`` + extra (what a developer's bare ``black``/``ruff``/``mypy`` is) must agree, + or a local run passes code CI rejects (M-CLEAN CLEAN.2).""" + from packaging.specifiers import SpecifierSet + + config = (_ROOT / ".pre-commit-config.yaml").read_text(encoding="utf-8") + revs = {} + repo = "" + for line in config.splitlines(): + m = re.match(r"\s*-\s*repo:\s*(\S+)", line) + if m: + repo = m.group(1).rstrip("/").rsplit("/", 1)[-1] + repo = repo.replace("mirrors-", "").replace("-pre-commit", "") + continue + m = re.match(r"\s*rev:\s*v?(\S+)", line) + if m and repo: + revs[repo] = m.group(1) + pyproject = (_ROOT / "pyproject.toml").read_text(encoding="utf-8") + dev = pyproject.split("\ndev = [", 1)[1].split("\n]", 1)[0] + checked = [] + for tool in ("black", "ruff", "mypy"): + rev = revs.get(tool) + assert rev, f"no pre-commit rev found for {tool}" + # Only the specifier that applies to a supported CI Python (3.10+). + specs = [ + m.group(1) + for m in re.finditer(rf'"{tool}([^";]+)(;[^"]*)?"', dev) + if not m.group(2) or "3.10" in m.group(2) + ] + assert specs, f"no {tool} pin in the dev extra" + assert rev in SpecifierSet( + specs[0] + ), f"pre-commit {tool} rev {rev} is outside the dev extra's {specs[0]}" + checked.append(tool) + assert checked == ["black", "ruff", "mypy"] 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() 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_environment_yml.py b/tests/test_environment_yml.py new file mode 100644 index 00000000..161597e2 --- /dev/null +++ b/tests/test_environment_yml.py @@ -0,0 +1,141 @@ +"""Audit INFRA-10 — ``local-setup/environment.yml`` must not drift from +``pyproject.toml``. + +The conda env had drifted: no ``pytest-xdist`` while pyproject's ``addopts`` +carries ``-n=auto`` (so a bare ``pytest`` failed), ``mypy>=1.0.0`` instead of +CI's ``~=1.10.0``, ``voila`` uncapped against the ``[app]`` extra's ``<0.6``, +and no ``build`` / ``types-requests``. These tests compare the two files: + +* every ``[dev]`` tool is present in the env file; +* for each package declared in both, the env file's range is no wider than + pyproject's (every probed version the YAML accepts, pyproject accepts too). + +Line-based YAML parsing (no PyYAML dependency); pyproject via ``tomllib`` / +``tomli``. +""" + +from __future__ import annotations + +import re +from pathlib import Path +from typing import Dict, List, Tuple + +import pytest +from packaging.requirements import Requirement +from packaging.specifiers import SpecifierSet +from packaging.version import Version + +try: # Python 3.11+ + import tomllib +except ModuleNotFoundError: # pragma: no cover - 3.9/3.10 + tomllib = pytest.importorskip("tomli") + +_ROOT = Path(__file__).resolve().parent.parent +_ENV_YML = _ROOT / "local-setup" / "environment.yml" +_PYPROJECT = _ROOT / "pyproject.toml" + +# The env pins python=3.11; evaluate pyproject environment markers for that. +_MARKER_ENV = {"python_version": "3.11", "python_full_version": "3.11.0"} + +# conda-forge name -> PyPI name, where they differ. +_CONDA_TO_PYPI = {"python-build": "build"} + +# Extras whose packages the conda env is meant to provide. +_EXTRAS = ("pyscf", "ase", "ts", "app", "notebook", "dev") + + +def _norm(name: str) -> str: + name = re.sub(r"[-_.]+", "-", name).lower() + return _CONDA_TO_PYPI.get(name, name) + + +def _yaml_specs() -> Dict[str, SpecifierSet]: + specs: Dict[str, SpecifierSet] = {} + text = _ENV_YML.read_text(encoding="utf-8") + for raw in text.split("\ndependencies:", 1)[1].splitlines(): + line = raw.split("#", 1)[0].strip() + if not line.startswith("- "): + continue + item = line[2:].strip() + if not item or item.endswith(":") or item.startswith("-") or "@" in item: + continue # "pip:" header, "-e ..", git URLs, channel names + m = re.match(r"^([A-Za-z0-9_.\-]+)\s*(.*)$", item) + assert m, item + name, spec = m.group(1), m.group(2).replace(" ", "") + if spec.startswith("=") and not spec.startswith("=="): + continue # conda exact-ish pin such as python=3.11 + specs[_norm(name)] = SpecifierSet(spec) + return specs + + +def _pyproject_reqs() -> List[Tuple[str, Requirement]]: + data = tomllib.loads(_PYPROJECT.read_text(encoding="utf-8"))["project"] + out = [("dependencies", Requirement(r)) for r in data["dependencies"]] + for extra in _EXTRAS: + out += [(extra, Requirement(r)) for r in data["optional-dependencies"][extra]] + return [ + (group, r) + for group, r in out + if r.marker is None or r.marker.evaluate(_MARKER_ENV) + ] + + +def _probes(*specsets: SpecifierSet) -> List[Version]: + """Versions around every boundary mentioned in the given specifiers.""" + out = set() + for ss in specsets: + for spec in ss: + v = Version(spec.version.replace(".*", "")) + rel = list(v.release) + [0, 0] + major, minor, micro = rel[0], rel[1], rel[2] + out.update( + { + v, + Version(f"{major}.{minor}.{micro + 1}"), + Version(f"{major}.{minor + 1}.0"), + Version(f"{major + 1}.0.0"), + } + ) + if micro: + out.add(Version(f"{major}.{minor}.{micro - 1}")) + if minor: + out.add(Version(f"{major}.{minor - 1}.0")) + if major: + out.add(Version(f"{major - 1}.0.0")) + return sorted(out) + + +def test_dev_tools_present_in_env_file() -> None: + yml = _yaml_specs() + missing = sorted( + _norm(r.name) + for group, r in _pyproject_reqs() + if group == "dev" and _norm(r.name) not in yml + ) + assert not missing, f"environment.yml lacks [dev] tools: {missing}" + + +def test_voila_and_mypy_pinned_like_pyproject() -> None: + yml = _yaml_specs() + assert not yml["voila"].contains("0.6.0") + assert not yml["mypy"].contains("1.11.0") + assert not yml["mypy"].contains("1.9.0") + + +def test_env_ranges_within_pyproject_ranges() -> None: + yml = _yaml_specs() + problems = [] + for group, req in _pyproject_reqs(): + name = _norm(req.name) + if name not in yml or not req.specifier: + continue + y = yml[name] + for v in _probes(y, req.specifier): + if y.contains(v, prereleases=True) and not req.specifier.contains( + v, prereleases=True + ): + problems.append( + f"{name}: env '{y}' allows {v}, [{group}] '{req.specifier}' does not" + ) + break + assert not problems, "\n".join(problems) diff --git a/tests/test_est_calibration_resilience.py b/tests/test_est_calibration_resilience.py index cef1b809..39486a5a 100644 --- a/tests/test_est_calibration_resilience.py +++ b/tests/test_est_calibration_resilience.py @@ -238,7 +238,10 @@ def test_poll_loop_checks_stop_event(self): # button reaches the worker within poll_interval (500 ms). assert "stop_event" in src assert "is_set()" in src - assert ".terminate()" in src + # Termination goes through _terminate_worker_tree so the worker's + # own child processes (parallel IR pool) die with it (audit DATA-10). + assert "_terminate_worker_tree(worker)" in src + assert ".terminate()" in inspect.getsource(benchmarks._terminate_worker_tree) def test_saves_calibration_after_every_step(self): src = inspect.getsource(benchmarks.run_calibration) diff --git a/tests/test_exit_confirm.py b/tests/test_exit_confirm.py index e7c89b01..161f5039 100644 --- a/tests/test_exit_confirm.py +++ b/tests/test_exit_confirm.py @@ -51,6 +51,16 @@ def test_first_click_arms_without_shutting_down(self, app, monkeypatch): assert app._exit_warn_html.layout.display == "" assert "ends your session" in app._exit_warn_html.value + def test_arming_while_a_calculation_runs_warns_it_will_be_lost(self, app): + # Audit APP-15: shutdown kills the kernel mid-run with no warning. + app._calc_running = True + app._on_exit_clicked() + assert "calculation is still running" in app._exit_warn_html.value + app._on_exit_cancel() + app._calc_running = False + app._on_exit_clicked() + assert "still running" not in app._exit_warn_html.value + def test_cancel_disarms(self, app): app._on_exit_clicked() # arm assert app._exit_armed is True 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 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_hpc_audit_low.py b/tests/test_hpc_audit_low.py new file mode 100644 index 00000000..6215bf11 --- /dev/null +++ b/tests/test_hpc_audit_low.py @@ -0,0 +1,644 @@ +""" +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" + + +# --------------------------------------------------------------------------- +# 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 + + +# --------------------------------------------------------------------------- +# 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 "", 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 + + +# ── 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 + + +# ── 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 + + +# ── 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)] + ) + + +# ── 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 + + +# ── VIZ-14: smaller items ─────────────────────────────────────────────────── + + +class TestNmrPlotConventions: + def test_delta_axis_descends_left_to_right(self): + from quantui.nmr_plot import plot_nmr_spectrum + + fig = plot_nmr_spectrum([(1, 1.0), (2, 7.0)], ["C", "H", "H"]) + lo, hi = 0.0, 12.0 + assert list(fig.layout.xaxis.range) == [hi, lo] + asc = plot_nmr_spectrum([(1, 1.0)], ["C", "H"], descending=False) + assert list(asc.layout.xaxis.range) == [lo, hi] + + def test_carbon_merge_window_is_wider_than_proton(self): + from quantui.nmr_plot import plot_nmr_spectrum + + # Two "equivalent" carbons 0.2 ppm apart in an unsymmetrised geometry. + c = plot_nmr_spectrum([(0, 128.0), (1, 128.2)], ["C", "C"], nucleus_label="¹³C") + assert list(c.data[-1].y) == [2.0] + # The same 0.2 ppm gap stays two ¹H sticks. + h = plot_nmr_spectrum([(0, 2.0), (1, 2.2)], ["H", "H"], nucleus_label="¹H") + assert list(h.data[-1].y) == [1.0, 1.0] + + +class TestVizNits: + def test_auto_backend_prefers_py3dmol(self, monkeypatch): + from quantui import visualization_py3dmol as vp + + calls = [] + monkeypatch.setattr(vp, "PY3DMOL_AVAILABLE", True) + monkeypatch.setattr(vp, "PLOTLYMOL_AVAILABLE", True) + monkeypatch.setattr( + vp, "visualize_molecule_py3dmol", lambda *a, **k: calls.append("py3dmol") + ) + monkeypatch.setattr( + vp, "visualize_molecule_plotlymol", lambda *a, **k: calls.append("plotly") + ) + vp.visualize_molecule(_h2_molecule(), style="stick") + assert calls == ["py3dmol"] + + def test_malformed_frontier_index_entry_is_skipped(self, tmp_path): + import gzip + import json + + from quantui.orbital_visualization import FRONTIER_CUBES_DIR, load_frontier_cube + + d = tmp_path / FRONTIER_CUBES_DIR + d.mkdir() + (d / "homo.cube.gz").write_bytes(gzip.compress(b"cube")) + (d / "index.json").write_text( + json.dumps( + { + "orbitals": [ + {"index": "not-a-number", "file": "x.cube.gz"}, + {"index": None, "file": "x.cube.gz"}, + {"index": 4, "spin": "", "file": "homo.cube.gz"}, + ] + } + ) + ) + dest = tmp_path / "out.cube" + assert load_frontier_cube(tmp_path, 4, beta=False, dest=dest) is True + assert dest.read_text() == "cube" + + def test_history_orbitals_carry_the_method(self, monkeypatch, tmp_path): + from types import SimpleNamespace + from unittest.mock import Mock + + from quantui import app_analysis, results_storage + + monkeypatch.setattr( + results_storage, "load_orbitals", lambda d: SimpleNamespace(formula="") + ) + app = Mock() + app._show_orbital_diagram.return_value = True + ctx = SimpleNamespace( + live_result=None, result_dir=tmp_path, formula="H2O", method="B3LYP" + ) + assert app_analysis.pop_energies(app, ctx) + shown = app._show_orbital_diagram.call_args.args[0] + assert shown.method == "B3LYP" + + +class TestTddftTableStateLabels: + """UV-Vis and ECD tables call states S1… only for a singlet manifold + (audit UI-13 follow-up; same rule as the TD-DFT result card).""" + + def test_uv_table_prefix(self): + from quantui.app_visualization import uv_excitation_table_html + + closed = uv_excitation_table_html([200.0], [0.1], [6.2]) + open_ = uv_excitation_table_html([200.0], [0.1], [6.2], state_prefix="") + assert ">S1<" in closed + assert ">S1<" not in open_ and ">1<" in open_ + + def test_ecd_table_prefix(self): + from quantui.app_visualization import ecd_state_table_html + + assert ">S1<" in ecd_state_table_html([6.2], [1.0], [None]) + assert ">S1<" not in ecd_state_table_html([6.2], [1.0], [None], state_prefix="") + + def test_history_prefix_from_saved_result(self, tmp_path): + import json + from types import SimpleNamespace + + from quantui.app_analysis import _tddft_state_prefix + + (tmp_path / "result.json").write_text(json.dumps({"scf_variant": "UKS"})) + ctx = SimpleNamespace(live_result=None, result_dir=tmp_path) + assert _tddft_state_prefix(ctx) == "" + (tmp_path / "result.json").write_text(json.dumps({"scf_variant": "RKS"})) + assert _tddft_state_prefix(ctx) == "S" diff --git a/tests/test_xc_resolution.py b/tests/test_xc_resolution.py index 501b2a6a..4afeb35b 100644 --- a/tests/test_xc_resolution.py +++ b/tests/test_xc_resolution.py @@ -29,8 +29,6 @@ from __future__ import annotations -import inspect - import pytest from quantui.session_calc import ( @@ -249,54 +247,102 @@ def test_pbe_d3_energy_includes_dispersion(self): # ===================================================================== +class _ReachedD3(BaseException): + """Raised by the spy once an entry point reaches ``maybe_apply_d3``. + + A BaseException so the entry points' own ``except Exception`` rescue / + fallback paths cannot swallow it; nothing after the SCF setup runs. + """ + + +try: + import pyscf # noqa: F401 + + _PYSCF_AVAILABLE = True +except ImportError: + _PYSCF_AVAILABLE = False + + class TestEntryPointsUseHelpers: """The bug bit because freq_calc / tddft_calc / optimizer / nmr_calc - bypassed the alias lookup. These source-level tests guard against - a regression that re-introduces ``mf.xc = method`` directly. + bypassed the alias lookup (``mf.xc = method``). Behavioural (audit + INFRA-19): each entry point is run with ``PBE-D3`` (a display name that + is not a valid PySCF xc) and must hand ``maybe_apply_d3`` an SCF object + whose ``xc`` is already ``resolve_xc("PBE-D3")``. The spy stops the run + there, so no SCF is solved. These used to be ``inspect.getsource`` + string checks, which a dead copy of the call would also satisfy. """ - def test_session_calc_uses_resolve_xc(self): - # The real DFT branch lives in ``_run_session_calc_body`` (inner - # function ``run_in_session`` calls), so grep the module source - # rather than just the public wrapper. - from quantui import session_calc + @pytest.fixture + def spy(self, monkeypatch): + import quantui.session_calc as sc + + calls = {"resolve": [], "d3": []} + real_resolve = sc.resolve_xc + + def _resolve(method): + calls["resolve"].append(method) + return real_resolve(method) + + def _d3(mf, method, progress_stream=None): + calls["d3"].append((getattr(mf, "xc", None), method)) + raise _ReachedD3() + + monkeypatch.setattr(sc, "resolve_xc", _resolve) + monkeypatch.setattr(sc, "maybe_apply_d3", _d3) + return calls + + @staticmethod + def _h2(): + from quantui.molecule import Molecule + + return Molecule(["H", "H"], [[0.0, 0.0, 0.0], [0.0, 0.0, 0.74]]) + + def _assert_resolved(self, calls): + assert "PBE-D3" in calls["resolve"] + assert calls["d3"], "maybe_apply_d3 was never reached" + assert calls["d3"][0] == (resolve_xc("PBE-D3"), "PBE-D3") + + @pytest.mark.skipif(not _PYSCF_AVAILABLE, reason="needs PySCF") + def test_session_calc_uses_resolve_xc(self, spy): + from quantui.session_calc import run_in_session - src = inspect.getsource(session_calc) - assert "resolve_xc(method)" in src - assert "maybe_apply_d3(" in src - assert "mf, method, progress_stream=progress_stream" in src + with pytest.raises(_ReachedD3): + run_in_session(self._h2(), "PBE-D3", "STO-3G", verbose=0) + self._assert_resolved(spy) - def test_freq_calc_uses_resolve_xc(self): - from quantui import freq_calc + @pytest.mark.skipif(not _PYSCF_AVAILABLE, reason="needs PySCF") + def test_freq_calc_uses_resolve_xc(self, spy): + from quantui.freq_calc import run_freq_calc - # The full module source — covers both the outer SCF setup and - # any inner SCF helpers. - src = inspect.getsource(freq_calc) - assert "resolve_xc" in src - # The inner displaced-SCF helper reads mf.xc directly (which by - # then is already resolved), so maybe_apply_d3 only appears in - # the outer setup. One usage is enough. + with pytest.raises(_ReachedD3): + run_freq_calc(self._h2(), "PBE-D3", "STO-3G") + self._assert_resolved(spy) - def test_tddft_calc_uses_resolve_xc(self): - from quantui import tddft_calc + @pytest.mark.skipif(not _PYSCF_AVAILABLE, reason="needs PySCF") + def test_tddft_calc_uses_resolve_xc(self, spy): + from quantui.tddft_calc import run_tddft_calc - src = inspect.getsource(tddft_calc) - assert "resolve_xc" in src - assert "maybe_apply_d3" in src + with pytest.raises(_ReachedD3): + run_tddft_calc(self._h2(), "PBE-D3", "STO-3G", nstates=1) + self._assert_resolved(spy) - def test_optimizer_uses_resolve_xc(self): - from quantui import optimizer + @pytest.mark.skipif(not _PYSCF_AVAILABLE, reason="needs PySCF") + def test_optimizer_uses_resolve_xc(self, spy): + pytest.importorskip("ase") + from quantui.optimizer import optimize_geometry - src = inspect.getsource(optimizer) - assert "resolve_xc" in src - assert "maybe_apply_d3" in src + with pytest.raises(_ReachedD3): + optimize_geometry(self._h2(), "PBE-D3", "STO-3G", steps=1) + self._assert_resolved(spy) - def test_nmr_calc_uses_resolve_xc(self): - from quantui import nmr_calc + @pytest.mark.skipif(not _PYSCF_AVAILABLE, reason="needs PySCF") + def test_nmr_calc_uses_resolve_xc(self, spy): + from quantui.nmr_calc import run_nmr_calc - src = inspect.getsource(nmr_calc) - assert "resolve_xc" in src - assert "maybe_apply_d3" in src + with pytest.raises(_ReachedD3): + run_nmr_calc(self._h2(), "PBE-D3", "STO-3G") + self._assert_resolved(spy) def test_script_template_embeds_alias_resolution(self): # The script-export template generates a standalone .py file