vibe-sketcherDocumentation

Source code for vibesketcher.inputs.aiccm_replay

"""Replay an AICCM torus series from the vibe-qc result QVFs of its members (#194).

:func:`vibesketcher.inputs.aiccm.compare_series` reads the small
``.aiccm-result.json`` each generated script writes. That record is written by
our own script, so it repeats what the script was told rather than what the
engine did. A replay reads each member's vibe-qc result QVF instead and checks
the engine's own record against the plan before any energy is compared:

* the archive is intact (every member's SHA-256 matches its manifest entry);
* it was written by vibe-qc, and ``source.version`` is the planned release;
* ``provenance.jk_method_executed`` is the planned variant's route;
* the run converged (``run_status`` and ``scf_converged``);
* the job spec's SCF reference, functional, basis, charge and multiplicity
  are the plan's;
* the embedded input (``run_record/input.txt``) is byte-identical to a planned
  member script (by SHA-256 when the plan records it), and its ``TORUS`` and
  ``HAMILTONIAN_DIGEST`` constants are the plan's.

vibe-qc's QVF records neither the torus nor a Hamiltonian digest, so the torus
is taken from the embedded script and nowhere else; a QVF without the
embedded input is refused rather than matched by file name. The energy is
``provenance.scf_energy``, which vibe-qc writes from the SCF (orbital)
reference; a correlated series is therefore refused here and stays with the
script-written results. For SCF series on vibe-qc 0.19.2 that value equals the
script's ``result.energy`` per input cell on tori (1,1,1), (2,1,1) and (2,2,1)
(LiH four-center, checked 2026-11-20).

The route labels are those of ``PeriodicJKMethod`` in vibe-qc
``python/vibeqc/periodic_jk_method.py``, identical at tags v0.18.11 through
v0.19.2; the provenance fields are written by
``python/vibeqc/output/formats/qvf.py`` at the same tags.
"""

from __future__ import annotations

import ast
import hashlib
import io
import zipfile
from collections.abc import Sequence
from pathlib import PurePosixPath
from typing import Any

from vibesketcher.inputs.aiccm import NORMALISATION, RESULT_SCHEMA, SERIES_SCHEMA, compare_series
from vibesketcher.limits import check_archive, parse_json

__all__ = ["EXECUTED_ROUTES", "replay_series", "result_from_qvf"]

#: ``jk_method_executed`` for each front-door variant (vibe-qc v0.18.11-v0.19.2).
EXECUTED_ROUTES: dict[str, str] = {
    "four-center": "aiccm2026dev-a",
    "real-gamma": "real-gamma",
    "neutral-bloch": "neutral-bloch",
    "chi": "aiccm2026dev-b",
}


class _Refused(ValueError):
    pass


def _members(data: bytes, label: str) -> tuple[dict[str, Any], dict[str, bytes]]:
    """The manifest and every checksummed member, or ``_Refused`` naming the defect."""
    check_archive(data, f"{label} QVF")
    try:
        archive = zipfile.ZipFile(io.BytesIO(data))
    except zipfile.BadZipFile:
        raise _Refused(f"{label} is not a QVF archive") from None
    with archive:
        names = archive.namelist()
        if len(names) != len(set(names)):
            raise _Refused(f"{label} repeats an archive member")
        for name in names:
            path = PurePosixPath(name)
            if path.is_absolute() or ".." in path.parts or "\\" in name:
                raise _Refused(f"{label} has an unsafe member name {name!r}")
        if "manifest.json" not in names:
            raise _Refused(f"{label} has no manifest.json")
        manifest = parse_json(archive.read("manifest.json"), f"{label} manifest")
        if not isinstance(manifest, dict):
            raise _Refused(f"{label} manifest is not an object")
        files: dict[str, bytes] = {}
        for section in manifest.get("sections") or []:
            for item in (section.get("members") or {}).values():
                path_name = item.get("path") if isinstance(item, dict) else None
                if not isinstance(path_name, str) or path_name not in names:
                    raise _Refused(f"{label} lists a member it does not contain")
                body = archive.read(path_name)
                if hashlib.sha256(body).hexdigest() != item.get("sha256"):
                    raise _Refused(f"{label}: checksum of {path_name} differs from its manifest")
                files[path_name] = body
    return manifest, files


def _section(manifest: dict[str, Any], kind: str) -> dict[str, Any] | None:
    found = [s for s in manifest.get("sections") or [] if s.get("kind") == kind]
    return found[0] if len(found) == 1 else None


def _script_constants(script: str) -> dict[str, Any]:
    """The literal ``TORUS`` and ``HAMILTONIAN_DIGEST`` the periodic writer emits."""
    try:
        tree = ast.parse(script)
    except SyntaxError:
        return {}
    found: dict[str, Any] = {}
    for node in tree.body:
        if (
            isinstance(node, ast.Assign)
            and len(node.targets) == 1
            and isinstance(node.targets[0], ast.Name)
            and node.targets[0].id in ("TORUS", "HAMILTONIAN_DIGEST")
        ):
            try:
                found[node.targets[0].id] = ast.literal_eval(node.value)
            except ValueError:
                continue
    return found


[docs] def result_from_qvf(plan: dict[str, Any], data: bytes, *, label: str = "QVF") -> dict[str, Any]: """One series member's result, read from its vibe-qc result QVF. Returns a record in the ``.aiccm-result.json`` shape (plus ``source`` and ``script_sha256``) that :func:`compare_series` accepts, or raises ``ValueError`` naming every way the QVF differs from the plan. """ if plan.get("schema") != SERIES_SCHEMA: raise ValueError(f"not an AICCM series plan (schema {SERIES_SCHEMA})") identity = plan.get("hamiltonian_identity") or {} if identity.get("correlation"): raise ValueError( f"{label}: a QVF carries the SCF reference energy, not the correlated total; " "compare a correlated series from its .aiccm-result.json files" ) try: manifest, files = _members(data, label) except _Refused as error: raise ValueError(str(error)) from None reasons: list[str] = [] source = manifest.get("source") or {} provenance = manifest.get("provenance") or {} if source.get("program") != "vibe-qc": reasons.append(f"{label} was not written by vibe-qc") version = str(source.get("version")) planned_version = identity.get("engine_version") if version != planned_version: reasons.append(f"{label} ran on vibe-qc {version}, planned {planned_version}") variant = identity.get("variant") route = provenance.get("jk_method_executed") if route != EXECUTED_ROUTES.get(str(variant)): reasons.append(f"{label} executed {route!r}, not the {variant} route") converged = provenance.get("run_status") == "converged" and provenance.get("scf_converged") if not converged: reasons.append(f"{label} did not converge") energy = (provenance.get("scf_energy") or {}).get("value") if (provenance.get("scf_energy") or {}).get("units") != "hartree": reasons.append(f"{label} has no SCF energy in hartree") spec_section = _section(manifest, "job.spec") job: dict[str, Any] = {} if spec_section is not None: member = (spec_section.get("members") or {}).get("spec") or {} job = parse_json(files[member["path"]], f"{label} job spec") if member else {} expected = { "method": identity.get("scf_reference"), "functional": identity.get("functional"), "basis": identity.get("basis"), "multiplicity": identity.get("multiplicity"), } seen = { "method": str(job.get("method") or "").upper() or None, "functional": (str(job["functional"]).lower() if job.get("functional") else None), "basis": str(job.get("basis") or "").lower() or None, "multiplicity": job.get("multiplicity"), } for key, want in expected.items(): if seen[key] != want: reasons.append(f"{label} job spec has {key} {seen[key]!r}, planned {want!r}") record = _section(manifest, "run.record") member = ((record or {}).get("members") or {}).get("input") or {} script_bytes = files.get(member.get("path", "")) if member else None if script_bytes is None: raise ValueError("; ".join([*reasons, f"{label} does not embed its input script"])) script_sha = hashlib.sha256(script_bytes).hexdigest() constants = _script_constants(script_bytes.decode("utf-8", "replace")) torus = constants.get("TORUS") planned = {tuple(m["torus"]): m for m in plan.get("members", [])} if not isinstance(torus, tuple) or len(torus) != 3: reasons.append(f"{label}'s embedded script names no torus") torus = () elif torus not in planned: reasons.append(f"{label}'s embedded script is for torus {torus}, which is not planned") else: pinned = planned[torus].get("script_sha256") if pinned is not None and pinned != script_sha: reasons.append(f"{label}'s embedded script differs from the planned {torus} member") if constants.get("HAMILTONIAN_DIGEST") != plan.get("hamiltonian_digest"): reasons.append(f"{label}'s embedded script was written for another Hamiltonian") if reasons: raise ValueError("; ".join(reasons)) n_cells = 1 for n in torus: n_cells *= int(n) return { "schema": RESULT_SCHEMA, "structure": plan.get("structure"), "variant": variant, "torus": list(torus), "n_cells": n_cells, "hamiltonian_digest": constants["HAMILTONIAN_DIGEST"], "energy_normalisation": NORMALISATION, "engine_version_executed": version, "energy_per_cell_ha": energy, "converged": bool(converged), "source": "qvf", "script_sha256": script_sha, }
[docs] def replay_series(plan: dict[str, Any], qvfs: Sequence[bytes]) -> dict[str, Any]: """:func:`compare_series` over members read from their result QVFs. Every QVF is checked first and all refusals are reported together. """ results: list[dict[str, Any]] = [] reasons: list[str] = [] for index, data in enumerate(qvfs): try: results.append(result_from_qvf(plan, data, label=f"QVF {index + 1}")) except ValueError as error: reasons.append(str(error).removeprefix("cannot compare this series: ")) if reasons: raise ValueError("cannot replay this series: " + "; ".join(reasons)) table = compare_series(plan, results) table["replayed_from"] = "qvf" table["rows"] = [ {**row, "script_sha256": next(r["script_sha256"] for r in results if r["torus"] == row["torus"])} for row in table["rows"] ] # fmt: skip return table