Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(e2e): add per-family end-to-end regression runner (#9894)
Alexander Eichhornf32db70ee6f8
diff --git a/AGENTS.md b/AGENTS.mdindex 578f726f3f..f177d3d450 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -84,6 +84,7 @@ Main agent also owns machine-wide resources: dependency installs, generated API- `-n logical` fits CI runners that own the machine. Dev box: cap workers (`-n 4`, or plain `pytest`). Set `OMP_NUM_THREADS` when a run must stay light. Never start a suite during a generation.- `uv run --no-sync mypy scripts/invokeai-web.py` uses current exclusions. Optional diagnostic only: not a CI gate, not full type coverage.- Pick checks by behavior. Run required milestone gates before review. Rerun unchanged checks only with a reason.+- Family E2E runs (`scripts/family_e2e`, guide: `docs/src/content/docs/development/Guides/family-e2e.mdx`) after changes to what a model computes or how it loads: model-manager loading, probing, configs; quantization; attention; model cache, working memory; invocations that run models; webv2 graph builders. Offer a run of the affected families, never start one unasked; none for docs-, test- or UI-only changes. Offer only where a manifest is set up; otherwise name the missing run under open limits in the final report. After a yes: run the base commit and `accept` it as reference (its bundle then reports BASELINE), then the branch, with `expect: changed` on the cases the PR is meant to change. PR description gets the `summary.md` table; attach the `bundle` zip. Until A/B runs exist, time differences under about 10 % between sessions are noise.- Once test dependencies exist, install hooks per checkout: `uv run --no-sync pre-commit install`. Committed config does not install hooks.## Scratch files and repository hygienediff --git a/docs/src/content/docs/development/Guides/family-e2e.mdx b/docs/src/content/docs/development/Guides/family-e2e.mdxnew file mode 100644index 0000000000..0b677ff468--- /dev/null+++ b/docs/src/content/docs/development/Guides/family-e2e.mdx@@ -0,0 +1,181 @@+---+title: Family E2E Runs+lastUpdated: 2026-10-25+---++`scripts/family_e2e` runs model families end to end through the HTTP API of a server it launches itself. Per case and size it records the image, the run time, the time per denoise step and the VRAM the server process used, measured at driver level. The report compares them with an explicitly accepted reference and with the previous run of the same profile.++It is a developer tool. It runs on Windows with NVIDIA and AMD (ROCm) GPUs, where it samples memory through WDDM, and on Linux with NVIDIA GPUs, where it reads NVML. AMD GPUs on Linux are not supported yet. The two samplers count differently, so keep one profile per machine, operating system and GPU, and never compare peaks across them (see [Limits](#limits)).++## How a run works++1. **Scratch root.** The template root's `invokeai.yaml` and a snapshot of its SQLite database go to `<data_dir>/scratch-roots/<run_id>-default/`. The template's database files (with a WAL left by an unclean stop) are copied, and the copy is backed up through InvokeAI's database layer, so the WAL's contents are included and the template's files are only read.+ - The tool refuses while the database file is open in any process (Windows only), or while anything listens on the template's configured port. Either means its server is still running.+ - It also refuses while a model install is unfinished (see [Shared paths](#shared-paths)).+ - Stores whose files the database owns start empty in the scratch root: outputs, uploaded fonts, style preset images, workflow thumbnails and profiles. The scratch server reconciles them with its own database; at the template it would, for example, delete uploaded fonts its database does not list.+ - Every other path setting points back at the template root as an absolute path, so models, custom nodes and memory settings are the template's own.+ - The tool overrides a few settings: a free port on `127.0.0.1`, a plain-format log file in the run directory, the image index off, and the queue cleared at startup. SSL and `base_url` are dropped. On Linux the server sees only the selected GPU, as `cuda:0`, so a `device` of `cuda:N` becomes `cuda:0` and a `generation_devices` list with a CUDA device becomes `auto`.+ - `INVOKEAI_*` variables of the calling environment are not passed on. Put settings the server needs into the manifest's `server.env`.+2. **Server.** The tool checks that `server.python` imports `invokeai` from `server.code_dir`. It then starts `<python> <code_dir>/scripts/invokeai-web.py --root <scratch root>` and reads the actual port from the server log. Multiuser mode is refused.+ - On Windows the server runs in a job object of the runner, so it dies with the runner however the runner ends. On Linux it runs in a session of its own. `stop`, an interrupt or a plain kill (SIGTERM) of the runner ends it; a runner killed with SIGKILL leaves it running. While it holds more than 1 GiB on that GPU, `start` and `resume` name it as foreign load and refuse; `stop RUN` ends it. Otherwise the resumed runner stops it first, before it replaces `heartbeat.json`, which names the server for `stop`, or touches the scratch root. If it cannot stop the server, the runner refuses and leaves the scratch root and the server's entries in `heartbeat.json` as they are; `runner.log` names the pid and the run shows as failed.+3. **Graphs.** The real webv2 graph builders produce each case's batch through `pnpm graphs:export`, run in the tool checkout. Run `pnpm install` in `invokeai/frontend/webv2` there first.+ - The runner disables the invocation cache on every node and saves the batch as `graphs/<case_key>.json`.+ - It hashes the graph and its batch data. Uploaded image names are replaced by the input file's hash, so the graph hash changes only when the graph or an input changes.+ - Init and control images enter the canvas compiler as finished layers. One whose size differs from the case size is resized (LANCZOS) into `runs/<run_id>/inputs/` before upload. Reference images are uploaded as they are.+4. **Steps.** Per family the model cache is emptied first. Each case size then gets its warm-ups, then its measured runs.+ - Per run, the tool waits up to 10 minutes for the queue to drain, samples the server's GPU memory, enqueues the batch and follows its socket events.+ - When the run finishes, it saves the output image and the memory trace, reads the run's slice of the server log and appends a record to `records.jsonl`.+ - If the server dies during a step, that step gets an error record and a new server starts on a new scratch root. A case whose steps crashed the server twice is given up; its remaining steps are not run again, not even by `resume`.+5. **Report.** The server is stopped, the scratch root removed, and `report.html` and `summary.md` are written. The exit code is not 0 when a case fails or errors (see [Verdicts](#verdicts)).++## Data directory++```+<data_dir>/inputs/ input images the manifest refers to+<data_dir>/references/<profile>/<case_key>/ image.png, reference.json (written by `accept` only)+<data_dir>/runs/<run_id>/ run.json, records.jsonl, heartbeat.json, runner.log, server-default.log,+ run.lock, graphs/, images/, traces/<record_id>.csv.gz, report.html, summary.md,+ <run_id>.zip (written by `bundle` only)+<data_dir>/scratch-roots/<run_id>-default/+```++A model's key belongs to the local database and means nothing on another machine. So `run.json` also records, per case key, the models its graph uses as `case_models`: name, base, type, format, variant and hash. The source is kept only when it names the model anywhere: an HF repo id, or an http(s) URL of a public host (no private, loopback or link-local address, no single-label or `.local` name) without credentials, `;params`, query or fragment. The model's path is never recorded. The report and `summary.md` list each case's models with the hash cut to 12 digits. Runs written before this field show no models.++`run_id` is `YYYYMMDD-HHMMSS-<profile>`, and `case_key` is `<case id>@<width>x<height>`. The report looks for the previous run among the run directories whose name carries exactly its profile; it does not read the others, and notes an unreadable run of its own profile. A trace holds the raw samples as `series,t,bytes`: series `dedicated` or `shared` (Windows only), and `t` in seconds from the enqueue.++One runner per GPU: a lock file per adapter lives in `%LOCALAPPDATA%\invokeai-family-e2e\locks\` (`~/.cache/invokeai-family-e2e/locks/` on Linux), shared by every data directory on the machine. Runs on different GPUs of one machine can run side by side; give each its own profile, since the profile's latest run and references are shared. On Windows that needs cards whose names differ: there is no LUID selector. Running side by side changes run times, not peaks or images, so compare times only between runs made with the same number of runs alongside. The runs share the machine's RAM, so lower `max_cache_ram_gb` in each template root.++## Manifest++A YAML file per machine, operating system and GPU, kept with the data rather than in the repository. Start from `scripts/family_e2e/manifest.example.yaml`. Relative paths are relative to the manifest file.++| Field | Meaning |+| --- | --- |+| `profile` | Names runs and references. |+| `data_dir` | The data directory above. |+| `gpu` | Substring of the adapter name that matches exactly one adapter, e.g. `RTX 4090` or `9060`. `Radeon` alone also matches an AMD integrated GPU. On Linux it can also be an NVML UUID (`GPU-…`, listed by `nvidia-smi -L` and by the error for a name that matches several cards), which tells identical cards apart. A GPU NVML cannot query is left out with a warning. |+| `server.template_root` | The root whose settings and database are copied. The scratch server shares its other paths; see [Shared paths](#shared-paths). |+| `server.python` | The interpreter that runs the server. |+| `server.code_dir` | The checkout the server runs. Defaults to the tool's checkout. |+| `server.env` | Extra server environment, e.g. `HIP_VISIBLE_DEVICES`. On Linux the runner sets `CUDA_VISIBLE_DEVICES` to the selected GPU's UUID itself, so the server sees exactly that card, as `cuda:0`, and neither spreads its workers over the others nor borrows an idle one. A `CUDA_VISIBLE_DEVICES` here with any other value than that UUID is refused. The scratch root's `device: cuda:N` becomes `cuda:0` and a `generation_devices` list with a CUDA device becomes `auto` (see [How a run works](#how-a-run-works)). On Windows pin the server to the manifest's `gpu` here when the machine has several. Either way the first completed step fails the run when the server holds no memory on the selected card. |+| `defaults` | `warmup` (at least 1), `repeats`, `seed`, `prompt`, `negative_prompt`, `psnr_min_db`, `time_tolerance` (relative), `peak_tolerance_mb`, `run_timeout_s`. |+| `families[].cases[]` | `id`, `model` (key), `mode` (`txt2img`, `img2img` or `controlnet`), `sizes` (a list of `[width, height]`), `steps`, optional `seed` and `prompt`, `components` (component slot to model key), `loras`, `reference_images`, `init_image` (`path`, `strength`), `control` (`model`, `image`, `weight`, `begin`, `end`), `settings` (generate settings), per-case thresholds, and `expect`: `unchanged` (default) or `changed` for a case the code under test is meant to change (see [Verdicts](#verdicts)). |++Input paths are relative to `<data_dir>/inputs` and must exist. `init_image` belongs to `img2img` cases only and `control` to `controlnet` cases only. The exporter rejects an unknown `settings` key, component slot or model key; that case then gets error records and the run goes on. Several `sizes` per case give a size sweep for working-memory calibration.++## Commands++Run the tool from the repository root with the checkout's environment, for example `uv run --no-sync python -m scripts.family_e2e …`.++| Command | What it does |+| --- | --- |+| `start --manifest M [--family F]… [--case ID]…` | Checks the GPU lock, the template's server, unfinished model installs and foreign GPU load. It then creates the run, starts its runner in the background, waits until the runner has registered, and prints the run id, the runner's pid and paths. |+| `status [RUN]` | Shows progress, the current step, the heartbeat age and whether the runner is alive. |+| `stop [RUN]` | Marks the run stopped, then kills the runner and its server and removes the run's scratch roots. |+| `resume [RUN]` | Starts the runner of a stopped or crashed run again, and waits until it has registered. Refuses while the run's runner is alive. On Linux the runner first stops a server its killed predecessor left running (see [How a run works](#how-a-run-works)). |+| `report [RUN]` | Writes `report.html` and `summary.md` again. |+| `accept [RUN] [--case KEY]…` | Makes the run's measured results the references of its profile. Nothing else writes references. |+| `bundle [RUN] [--output PATH]` | Packs the run into a zip without this machine's paths, to attach to a PR or an issue (see [Bundle](#bundle)). |+| `run --run-dir D` | The runner in the foreground: what `start` and `resume` launch. It leaves a run that is not `running` as it is and exits with 130, also when `stop` marks the run while it runs. |++`RUN` is a run directory, or a run id together with `--manifest M`. Without it, the profile's latest run is used.++A runner registers before it does anything else: it writes its process into `heartbeat.json`, which `stop`, `status` and `resume` read. `stop` marks the run stopped before it reads that file. The mark and a registration each hold `run.lock`, so they cannot interleave: a runner registered before `stop` is killed, and one that registers after it finds the run stopped and exits without touching it. A runner that `stop` could not kill exits before its next server or step. It never overwrites a status other than `running`.++On Windows the background runner breaks away from the caller's job object, so a terminal or an agent harness that kills its job's processes does not end a long run. Where breakaway is refused, the runner is created through WMI. It then starts with the user's default environment instead of the caller's.++A resumed run skips every step that already has a final record and keeps the measures of the earlier sessions. Its new server starts with a cold model cache, so each case size with measures left first repeats its last warm-up, once. The manifest, the graphs, and the server's commit and dirty flag must not have changed since the run started; further edits to an already dirty checkout cannot be detected.++## Bundle++`bundle` writes one zip that opens without this machine's data, by default `<run_dir>/<run_id>.zip`, and prints its path and size. Apart from that default zip, the run directory stays as it is. It refuses while the run's runner is alive. A stopped or failed run can be bundled, and its report states the status; a run whose runner died without recording it shows as interrupted.++The zip holds one folder, `<run_id>/`, with:++- `bundle.json`, which describes the zip itself:+ - `format_version`: the layout of the zip and its files, now `2`. It changes when a reader such as an upload hub could misread a zip written the old way; a reader refuses a version it does not know. Version 2 adds the case statuses `CHANGED` and `BASELINE` to the report and summary. It covers both memory methods: a record's `memory.method` is `d3dkmt` (Windows) or `nvml` (Linux), and peaks of the two are not comparable.+ - `tool_commit`: the commit of the tool checkout that started the run, as in `run.json`, or `null`.+ - `created_at`: when the bundle was written, ISO 8601 in UTC with seconds and offset, e.g. `2026-10-21T01:30:00+00:00`, like the timestamps in `run.json`.+- `report.html` and `summary.md`, rendered for the zip. Every image the report shows lies in the zip: this run's under `images/`, the reference as `reference/<case_key>/image.png`, the previous run's under `previous/<run_id>/images/`, and the differences under `diff/`.+ - Pixels unchanged, metadata removed. The chunks that make up pixels and colours stay byte for byte (`IHDR`, `PLTE`, `IDAT`, `IEND`, `tRNS`, `gAMA`, `cHRM`, `sRGB`, `iCCP`, `sBIT`, `cICP`, `mDCv`, `cLLi`), so a recipient can recompute PSNR. Every other chunk goes: InvokeAI writes the generation's metadata and graph into text chunks, model paths included.+ - `image_sha256` in the records and in each `reference.json` is of the original file.+- `reference/<case_key>/reference.json` for each case whose accepted reference the report could read: the reference's run, graph hash, medians and environment, so a reader can tell `BASELINE` from `PASS` and redo the comparisons. A case without a readable reference has none; the file is optional in format version 2.+- `run.json`, `records.jsonl`, `graphs/` and `traces/`.++Logs, `heartbeat.json`, `inputs/`, `export/`, scratch roots and images the report does not show stay out. On the way in:++- **`run.json`.** A value that is an absolute path keeps only its last component: `manifest_path`, `code_dir`, `python`, `invokeai_file`, the paths in `server_cmd` and the path settings in `runtime_config`. `extra_env` keeps its variable names; its values become `<redacted>`. So do the `runtime_config` settings that hold a string, list or mapping under a name that looks like a credential (`token`, `secret`, `key`, `auth`, `credential`, `pass`, `api`, `proxy`, `db_url`); flags such as `log_tokenization` stay.+- **`reference.json`.** Its environment is sanitized like those in `run.json`, and its `extra_env` credentials are removed from all text like the run's own.+- **Records.** A foreign GPU process keeps its pid and memory; its name becomes `<process>`.+- **Graphs.** Model configs lose `path`, `config_path` and `source_api_response`. `source` and `source_url` stay only under the rule for `case_models` above. `graph_hashes` and each record's `graph_hash` still describe the graphs as they ran.+- **All text**, the rendered report included:+ - The value of an `extra_env` variable whose name looks like a credential becomes `<NAME>` of the variable, if it has 8 or more characters. That holds for every value such a name has in the environments of the run, its references and the previous runs it is compared with, e.g. a token rotated in between; their code directories become `<code_dir>` too. Other values, such as an allocator setting, stay, so the verdicts match the report on disk.+ - An http(s) URL loses its credentials, `;params`, query and fragment. A host of the local network (a private, loopback or link-local address, a single-label or `.local` name) becomes `<local host>`.+ - The run directory, data directory, template root and code directory become `<run_dir>`, `<data_dir>`, `<template_root>` and `<code_dir>`, with either separator and in any case. The rest of a path below them stays. The template root comes from the run's manifest, or from `--manifest`.+ - A path below the home directory becomes `<home>` and the path's last component.+ - The local path, local source and `config_path` of each model in the graphs and in the exporter's request (`export/export-request.json`, which lists every model of the server) become `<model NAME>`, followed by the rest of a path below them. A path in the directory that holds a model becomes `<model dir>` and its last component. They are matched exactly, so model paths with spaces are covered.+ - Any other absolute path with a drive letter, and any other absolute POSIX path of two or more components, keeps only its last component. The server's API and socket paths (`/api/…`, `/ws/…`), which the tool's errors quote, stay.+- The report compares the run's environment with the reference's and the previous run's after the same sanitizing, so nothing removed reappears as a change.++## Verdicts++Each case size gets one status, judged by the final attempt of each step. The first that applies:++| Status | When | Failure |+| --- | --- | --- |+| `ERROR` | A final step failed or errored. | yes |+| `FAIL` | An image does not have the requested size. | yes |+| `INVALID` | No measured image is valid for PSNR (see [Validity](#validity)). | no |+| `NO-REFERENCE` | No accepted reference, or it is unreadable. | no |+| `FAIL` | An image cannot be compared with the reference. | yes |+| `BASELINE` | The reference was accepted from this very run, so comparing with it says nothing; the report shows no deltas against it. Bundling a run after `accept` reports this. | no |+| `INVALID` | run.json has no thresholds for the case. | no |+| `CHANGED` | The case expects a change (`expect: changed`), and its minimum PSNR against the reference is below `psnr_min_db`. | no |+| `FAIL` | The case expects a change, but its minimum PSNR is at or above `psnr_min_db`; or it expects none, and the minimum PSNR is below it. | yes |+| `PASS` | Otherwise. | no |++The comparison with the previous run is informational: its outliers and flags never change a status. `report` and the runner exit with 1 when a case is `ERROR` or `FAIL`.++## Validity++A run's record can be complete and still unfit for some comparisons. Each invalid flag comes with its reason in `invalid_reasons`.++- **Residency.** The model cache logs `Loaded model '…' … VRAM: … (P%)` whenever a lock moves weights or leaves a model short of fully resident. A warm run usually logs nothing, because its models stay resident. The tool therefore keeps the latest line per model since the last cache flush. Time and memory are invalid when:+ - a line in the run's log slice is below 100 %, except a load under 1 MB such as a tokenizer, which has no weights to place and is logged at 0.0 %,+ - a `VRAM budget … is short` warning appears, or+ - no load of the graph's models with weights was seen since the flush ("residency unknown").+- **fp8.** With fp8 weights in play, an incompletely resident run does not reproduce its image, so PSNR is invalid too. fp8 is in play when a graph model sets `fp8_storage` in its default settings, or when the server's `fp8_compute` is on. Model configs do not record which checkpoints are scaled fp8, so then every graph counts.+- **Shared memory.** If the server's shared GPU memory grows by more than 256 MiB during a run, it paged to system memory: time and memory are invalid. Windows only; the Linux driver does not page video memory out, and NVML reports no shared usage.+- **Foreign load.** Another process above 1 GiB of dedicated GPU memory at either end of the run, or grown by more than 256 MiB, invalidates time and memory. So does a queue that is still busy after the 10-minute wait. The run is repeated, up to three attempts. `start` refuses outright when another process holds more than 1 GiB.++## Shared paths++The scratch server uses the template root's models directory, model caches, legacy model configs, custom fonts and custom nodes. Its startup touches them as starting the template's own server would:++- `models/README.txt` is written.+- Install claims (`*.invokeai_install_active`) of processes that no longer run are removed.+- Missing model files are reported in the log.+- `configs/` receives the legacy model configs of the server's code when they differ.+- `fonts/README.txt` is written when missing.+- Models a node fetches on first use are cached in `models/.download_cache`.++The server would also finish an incomplete install, but the model would then be registered in the scratch database only. So `start` and `resume` refuse while the models directory holds a `tmpinstall_*` entry: finish or cancel that install in the dev server first.++Database migrations of a newer `code_dir` run against the scratch database only. A migration that also moves or rewrites files acts on the shared models directory and caches; keep that in mind before pointing a run at a checkout ahead of the template's own server.++## Limits++- Memory is sampled every 3 ms with `D3DKMTQueryVideoMemoryInfo`: shorter peaks are missed. It counts resident memory (`CurrentUsage`), not commit, including the CUDA or HIP context and every resident model. That is why records keep a baseline and a peak per node.+- On Linux, memory is sampled every 5 ms from NVML: the `usedGpuMemory` that `nvmlDeviceGetComputeRunningProcesses_v3` lists for the serving interpreter, i.e. what the driver has allocated for it, its CUDA context included. The foreign-load checks also read the graphics processes. Records carry method `nvml` instead of `d3dkmt`. The two drivers size the context differently and count different things, so a peak on one is no baseline for the other.+ - Only the serving interpreter is sampled: a child process of the server that holds CUDA memory of its own counts as foreign load, as on Windows.+ - Where NVML does not attribute memory to processes (vGPU guests, MIG, some containers), the tool refuses with that reason: at `start` when a process already holds memory on the GPU, otherwise in the first step.+ - In a container with its own PID namespace NVML can list the host's pids. The server then reads as holding no memory, and the run fails its device check.+ - Under WSL, NVML runs on the Windows driver and reports no per-process memory, so the tool refuses; run it on Windows on that machine.+- With PyTorch's native allocator, reserved memory stays allocated between nodes, so a node's peak can stem from an earlier node. Compare peaks only between runs with the same allocator configuration; the run records the runtime config.+- On Windows with ROCm, HIP keeps freed blocks at driver level. Per-node peaks after the first large node are upper bounds there (observed on an RX 9060 XT).+- Time per step comes from the preview frames, which the server throttles to one per 0.1 s; a step's number is read from its progress percentage.+ - For txt2img and controlnet the case's `steps` fixes the step count.+ - img2img starts inside the schedule at a family-specific step, so the count is inferred. When steps are faster than 0.2 s that inference can be off by a factor, so the time per step is left empty.+- Ideogram 4 ignores `steps`; its step count follows `settings.ideogram4Steps` or `settings.ideogram4SamplerPreset`. `img2img` and `controlnet` are not available for ERNIE-Image and Ideogram 4. Dynamic prompts, canvas rasterization, video and upscale graphs are not covered.+- A bundle finds other paths in free text by their drive letter, or as POSIX paths of two or more components that start after a space, a quote or a bracket. Such a path, and a path below the home directory, keeps what follows a space in one of its directory names; a POSIX path at the root (`/x`) or right after `:` stays. A UNC path in free text stays as it is. An `extra_env` credential shorter than 8 characters is redacted in `run.json` only.+- AMD GPUs on Linux and A/B runs of two checkouts are not available yet.diff --git a/invokeai/frontend/webv2/ARCHITECTURE.md b/invokeai/frontend/webv2/ARCHITECTURE.mdindex f09172736e..b72c45fa8e 100644--- a/invokeai/frontend/webv2/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/ARCHITECTURE.md@@ -105,7 +105,7 @@ Feature interfaces stay ordinary module interfaces unless two adapters add lever| Nodes | Custom-node catalog/templates and execution lifecycle; Workflow editor and node manager | Platform; descriptors, catalog commands, execution snapshots and manager contribution || Queue | Backend queue state, realtime interpretation, submission/reconciliation and Queue UI; App runtime, Workbench aggregate/shell, Generation/Gallery/Workflow | Platform and public envelopes/capabilities from Identity, Models, Generation, Workflow, Upscale; backend port, queue reads/commands and widget contribution || Gallery | Image collection, selection, board policy and Gallery UI; App adapter, Generation, Workflow, Upscale, Models, Workbench image actions | Platform and Queue's public progress reads; gallery reads/commands and widget contribution |-| Generation | Generation settings, validation, graph compilation and Generate UI; Workbench invocation, Queue, Gallery, Workflow, Upscale | Platform and public Models/Gallery/Queue interfaces; settings/validation, compiled submission envelope and widget contribution |+| Generation | Generation settings, validation, graph compilation and Generate UI; Workbench invocation, Queue, Gallery, Workflow, Upscale | Platform and public Models/Gallery/Queue interfaces; settings/validation, compiled submission envelope, offline graph export and widget contribution || Workflow | Workflow document, validation, compilation, preview/editor/library and explicit publication; App adapter, Workbench invocation, Nodes | Platform and public Nodes/Models/Gallery/Queue/Generation interfaces; document reads/commands, compiled submission envelope and widget contribution || Upscale | Upscale settings, validation, compilation and UI; Workbench invocation and Queue | Platform and public Models/Gallery/Queue interfaces; value/validation reads, submission command and widget contribution || Intermediates | Per-project intermediates read models, cleanup previews/operations and the Settings section that manages them; Workbench settings, project menus, account administration | Platform plus Identity's public session/capability reads; query keys, read models, the focus intent, the browser hold lease and the `settingsContribution` metadata whose loader owns the section body |diff --git a/invokeai/frontend/webv2/package.json b/invokeai/frontend/webv2/package.jsonindex 502f901c55..d40e5faa16 100644--- a/invokeai/frontend/webv2/package.json+++ b/invokeai/frontend/webv2/package.json@@ -19,6 +19,7 @@"fix": "pnpm run lint:oxc:fix && pnpm run format:write","format:check": "oxfmt --check .","format:write": "oxfmt --write .",+ "graphs:export": "node scripts/export-graphs.mjs","i18n:report": "node scripts/i18n-report.mjs","i18n:report:verbose": "node scripts/i18n-report.mjs --verbose","lint": "pnpm run lint:code && pnpm run architecture:check",@@ -35,7 +36,7 @@"test:all": "pnpm run test && pnpm run test:browser && pnpm run test:fixtures","test:browser": "vitest run --config vitest.browser.config.mts","test:browser:update-goldens": "CANVAS_GOLDEN_UPDATE=1 vitest run --config vitest.browser.config.mts src/workbench/canvas-engine/render/golden",- "test:fixtures": "node --test scripts/mock-backend-fixtures.test.mjs scripts/preview-server.test.mjs scripts/run-project-file-journey.test.mjs scripts/locale-assets-plugin.test.mjs",+ "test:fixtures": "node --test scripts/mock-backend-fixtures.test.mjs scripts/preview-server.test.mjs scripts/run-project-file-journey.test.mjs scripts/locale-assets-plugin.test.mjs scripts/export-graphs.test.mjs","test:performance:architecture": "pnpm run test:performance:build && pnpm run test:performance:browser","test:performance:browser": "node scripts/measure-architecture-performance.mjs","test:performance:browser:profile": "node scripts/measure-architecture-performance.mjs --profile",diff --git a/invokeai/frontend/webv2/scripts/export-graphs.mjs b/invokeai/frontend/webv2/scripts/export-graphs.mjsnew file mode 100644index 0000000000..cc44c13719--- /dev/null+++ b/invokeai/frontend/webv2/scripts/export-graphs.mjs@@ -0,0 +1,80 @@+/**+ * `pnpm graphs:export <request.json> <response.json>` compiles offline export cases into the enqueue batches the UI+ * would send (src/app/graphExport.ts). Vite's module runner loads the TypeScript sources with the app's aliases and+ * opens no port. Exit 0 once the response is written, with per-case errors inside it; exit 2 for an unreadable or+ * malformed request, with no response written.+ */++import { readFile, writeFile } from 'node:fs/promises';+import { dirname, resolve } from 'node:path';+import process from 'node:process';+import { fileURLToPath } from 'node:url';+import { loadConfigFromFile, runnerImport } from 'vite';++const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');+const EXIT_MALFORMED_REQUEST = 2;++const rejectRequest = (message) => {+ process.stderr.write(`graphs:export: ${message}\n`);+ process.exitCode = EXIT_MALFORMED_REQUEST;+};++const readRequest = async (path) => {+ try {+ return JSON.parse(await readFile(path, 'utf8'));+ } catch (error) {+ rejectRequest(`cannot read ${path}: ${error instanceof Error ? error.message : String(error)}`);+ return undefined;+ }+};++/** Only the aliases and defines: plugins transform the browser bundle, not these pure modules. */+const loadExporter = async () => {+ const { config } = await loadConfigFromFile(+ { command: 'serve', mode: 'development' },+ resolve(PACKAGE_ROOT, 'vite.config.mts'),+ PACKAGE_ROOT,+ 'error'+ );+ const { module } = await runnerImport(resolve(PACKAGE_ROOT, 'src/app/graphExport.ts'), {+ define: config.define,+ logLevel: 'error',+ resolve: { alias: config.resolve.alias },+ root: PACKAGE_ROOT,+ });++ return module;+};++const main = async () => {+ const [requestPath, responsePath, ...extra] = process.argv.slice(2);++ if (!requestPath || !responsePath || extra.length > 0) {+ rejectRequest('usage: pnpm graphs:export <request.json> <response.json>');+ return;+ }++ const request = await readRequest(requestPath);++ if (request === undefined) {+ return;+ }++ const { exportGraphs, GraphExportRequestError } = await loadExporter();+ let response;++ try {+ response = exportGraphs(request);+ } catch (error) {+ if (error instanceof GraphExportRequestError) {+ rejectRequest(`malformed request: ${error.message}`);+ return;+ }++ throw error;+ }++ await writeFile(responsePath, `${JSON.stringify(response, null, 2)}\n`);+};++await main();diff --git a/invokeai/frontend/webv2/scripts/export-graphs.test.mjs b/invokeai/frontend/webv2/scripts/export-graphs.test.mjsnew file mode 100644index 0000000000..607daf3856--- /dev/null+++ b/invokeai/frontend/webv2/scripts/export-graphs.test.mjs@@ -0,0 +1,74 @@+import assert from 'node:assert/strict';+import { execFile } from 'node:child_process';+import { access, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { dirname, resolve } from 'node:path';+import test from 'node:test';+import { fileURLToPath } from 'node:url';+import { promisify } from 'node:util';++const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');+const CLI = resolve(PACKAGE_ROOT, 'scripts/export-graphs.mjs');+const CAPABILITIES = resolve(PACKAGE_ROOT, 'src/features/generation/core/__fixtures__/architectureCapabilities.json');++const runCli = async (context, requestText) => {+ const directory = await mkdtemp(resolve(tmpdir(), 'invokeai-graphs-export-'));+ context.after(() => rm(directory, { force: true, recursive: true }));+ const requestPath = resolve(directory, 'request.json');+ const responsePath = resolve(directory, 'response.json');+ await writeFile(requestPath, requestText);++ const { code, stderr } = await promisify(execFile)(process.execPath, [CLI, requestPath, responsePath], {+ cwd: PACKAGE_ROOT,+ }).then(+ ({ stderr }) => ({ code: 0, stderr }),+ (error) => ({ code: error.code, stderr: error.stderr })+ );+ const response = await access(responsePath).then(+ async () => JSON.parse(await readFile(responsePath, 'utf8')),+ () => null+ );++ return { code, response, stderr };+};++test('writes per-case results through the real module graph and exits 0', async (context) => {+ const capabilities = JSON.parse(await readFile(CAPABILITIES, 'utf8'));+ const sdxl = { base: 'sdxl', format: 'diffusers', hash: 'blake3:sdxl', key: 'sdxl', name: 'SDXL', type: 'main' };+ const testCase = { height: 1024, mode: 'txt2img', positive_prompt: 'a fox', seed: 7, steps: 4, width: 1024 };+ const request = {+ capabilities,+ cases: [+ { ...testCase, id: 'ok', model_key: 'sdxl' },+ { ...testCase, id: 'missing', model_key: 'missing' },+ ],+ models: [sdxl],+ version: 1,+ };++ const { code, response } = await runCli(context, JSON.stringify(request));++ assert.equal(code, 0);+ assert.equal(response.version, 1);+ assert.deepEqual(+ response.cases.map((result) => [result.id, 'batch' in result]),+ [+ ['ok', true],+ ['missing', false],+ ]+ );+ assert.match(response.cases[1].error, /model_key "missing"/);+});++for (const [label, requestText] of [+ ['unparsable JSON', '{ "version": 1,'],+ ['a malformed request', JSON.stringify({ cases: [], models: [], version: 1 })],+]) {+ test(`rejects ${label} with exit 2 and writes no response`, async (context) => {+ const { code, response, stderr } = await runCli(context, requestText);++ assert.equal(code, 2);+ assert.equal(response, null);+ assert.match(stderr, /^graphs:export: /);+ });+}diff --git a/invokeai/frontend/webv2/src/app/graphExport.test.ts b/invokeai/frontend/webv2/src/app/graphExport.test.tsnew file mode 100644index 0000000000..94905172b5--- /dev/null+++ b/invokeai/frontend/webv2/src/app/graphExport.test.ts@@ -0,0 +1,320 @@+import type { BackendGraphContract, BackendInvocationContract } from '@features/generation/contracts';+import type { SupportedGenerateBase } from '@features/generation/core/baseGenerationPolicies';++import { architectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';+import {+ generateGraphCases,+ satisfiedSettingsFor,+ type ModelShape,+} from '@features/generation/core/graphCoverage.testing';+import { withArchitectureCapabilities } from '@features/generation/graphExport';+import { describe, expect, it } from 'vitest';++import { exportGraphs, GraphExportRequestError, type GraphExportCaseResult } from './graphExport';++const model = (key: string, base: string, type: string, extra: Record<string, unknown> = {}) => ({+ base,+ hash: `blake3:${key}`,+ key,+ name: `${key} name`,+ type,+ ...extra,+});++const MODELS = [+ model('sdxl', 'sdxl', 'main', { format: 'diffusers', variant: 'normal' }),+ model('sdxl-lora', 'sdxl', 'lora', { format: 'lycoris' }),+ model('sdxl-canny', 'sdxl', 'controlnet', { format: 'diffusers' }),+ model('sdxl-ip-adapter', 'sdxl', 'ip_adapter', { format: 'invokeai' }),+ model('z-image-gguf', 'z-image', 'main', { format: 'gguf_quantized' }),+ model('qwen3-06b', 'any', 'qwen3_encoder', { format: 'checkpoint', variant: 'qwen3_06b' }),+ model('qwen3-4b', 'any', 'qwen3_encoder', { format: 'checkpoint', variant: 'qwen3_4b' }),+ model('qwen3-8b', 'any', 'qwen3_encoder', { format: 'checkpoint', variant: 'qwen3_8b' }),+ model('qwen3-4b-gguf', 'any', 'qwen3_encoder', { format: 'gguf_quantized', variant: 'qwen3_4b' }),+ model('sdxl-vae', 'sdxl', 'vae', { format: 'diffusers' }),+ model('flux-vae', 'flux', 'vae', { format: 'checkpoint' }),+];++const sdxlCase = (id: string, overrides: Record<string, unknown> = {}) => ({+ height: 832,+ id,+ mode: 'txt2img',+ model_key: 'sdxl',+ negative_prompt: 'blurry',+ positive_prompt: 'a lighthouse at dusk',+ seed: 4242,+ steps: 12,+ width: 1216,+ ...overrides,+});++const request = (cases: unknown[], models: unknown[] = MODELS) => ({+ capabilities: architectureCapabilitiesFixture,+ cases,+ models,+ version: 1,+});++const exportOne = (testCase: Record<string, unknown>, models?: unknown[]) => {+ const [result] = exportGraphs(request([testCase], models)).cases;++ if (!result || !('batch' in result)) {+ throw new Error(`expected a batch, got ${JSON.stringify(result)}`);+ }++ return result;+};++const nodesOfType = (graph: BackendGraphContract, type: string): BackendInvocationContract[] =>+ Object.values(graph.nodes).filter((node) => node.type === type);++/** A main model of `base` and the components it needs, as graph coverage builds them. */+const satisfiedFor = (base: SupportedGenerateBase, overrides: ModelShape['overrides']) =>+ withArchitectureCapabilities(architectureCapabilitiesFixture, () =>+ satisfiedSettingsFor(base, { label: base, overrides })+ );++const errorOf = (result: GraphExportCaseResult | undefined): string =>+ result && 'error' in result ? result.error : '';++describe('graph export', () => {+ it('sends the case through Generate: seed and prompts as batch data, size and steps in the graph', () => {+ const { batch, id } = exportOne(sdxlCase('sdxl-t2i', { loras: [{ key: 'sdxl-lora', weight: 0.65 }] }));+ const { graph } = batch;+ const noise = nodesOfType(graph, 'noise')[0];+ const denoise = graph.nodes.denoise_latents;++ expect(id).toBe('sdxl-t2i');+ expect(batch.data).toEqual([+ [+ { field_name: 'value', items: [4242], node_path: 'seed' },+ { field_name: 'value', items: ['a lighthouse at dusk'], node_path: 'positive_prompt' },+ { field_name: 'value', items: ['blurry'], node_path: 'negative_prompt' },+ ],+ ]);+ expect(batch.data[0]?.map((datum) => graph.nodes[datum.node_path]?.type)).toEqual(['integer', 'string', 'string']);+ expect(batch).toMatchObject({ destination: 'gallery', origin: 'graphs-export:sdxl-t2i' });+ expect(graph.id).toBe('sdxl-t2i');+ expect([noise?.width, noise?.height, denoise?.steps]).toEqual([1216, 832, 12]);+ expect(+ nodesOfType(graph, 'lora_selector').map((node) => [(node.lora as { key: string }).key, node.weight])+ ).toEqual([['sdxl-lora', 0.65]]);+ });++ it('adds SDXL reference images as full-strength IP-Adapter references with the installed adapter', () => {+ const { graph } = exportOne(sdxlCase('sdxl-refs', { reference_images: ['first.png', 'second.png'] })).batch;++ expect(nodesOfType(graph, 'ip_adapter')).toMatchObject(+ ['first.png', 'second.png'].map((imageName) => ({+ begin_step_percent: 0,+ clip_vision_model: 'ViT-H',+ end_step_percent: 1,+ image: { image_name: imageName },+ ip_adapter_model: { base: 'sdxl', key: 'sdxl-ip-adapter' },+ method: 'full',+ weight: 1,+ }))+ );+ });++ it('adds FLUX.2 reference images as Kontext conditioning, in order', () => {+ const { filled, model: main, settings } = satisfiedFor('flux2', { format: 'diffusers', variant: 'dev' });+ const { graph } = exportOne(+ sdxlCase('flux2-refs', {+ height: settings.height,+ model_key: main.key,+ negative_prompt: null,+ reference_images: ['first.png', 'second.png'],+ width: settings.width,+ }),+ [main, ...filled.map((key) => settings[key])]+ ).batch;+ const kontext = nodesOfType(graph, 'flux_kontext');+ const [firstCollect, lastCollect] = kontext.map(+ (node) => graph.edges.find((edge) => edge.source.node_id === node.id)?.destination.node_id+ );++ expect(kontext.map((node) => node.image)).toEqual([{ image_name: 'first.png' }, { image_name: 'second.png' }]);+ expect(graph.edges).toContainEqual({+ destination: { field: 'collection', node_id: lastCollect },+ source: { field: 'collection', node_id: firstCollect },+ });+ expect(graph.edges).toContainEqual(+ expect.objectContaining({+ destination: expect.objectContaining({ field: 'kontext_conditioning' }),+ source: { field: 'collection', node_id: lastCollect },+ })+ );+ });++ it('makes a lone Krea-2 reference the style reference and several references edit references', () => {+ const { filled, model: main, settings } = satisfiedFor('krea-2', { format: 'diffusers' });+ const krea2Case = (id: string, referenceImages: string[]) =>+ sdxlCase(id, {+ height: settings.height,+ model_key: main.key,+ reference_images: referenceImages,+ width: settings.width,+ });+ const models = [main, ...filled.map((key) => settings[key])];+ const style = exportOne(krea2Case('krea2-style', ['style.png']), models).batch.graph;+ const edit = exportOne(krea2Case('krea2-edit', ['first.png', 'second.png']), models).batch.graph;++ expect(nodesOfType(style, 'krea2_style_reference')).toMatchObject([+ { height: settings.height, image: { image_name: 'style.png' }, style_strength: 1, width: settings.width },+ ]);+ expect(nodesOfType(style, 'qwen_image_i2l')).toEqual([]);+ expect(nodesOfType(edit, 'krea2_style_reference')).toEqual([]);+ expect(nodesOfType(edit, 'qwen_image_i2l').map((node) => [node.image, node.reference])).toEqual([+ [{ image_name: 'first.png' }, true],+ [{ image_name: 'second.png' }, true],+ ]);+ });++ it('rejects reference images for a model without them and more than the model takes', () => {+ const [unsupported, tooMany] = exportGraphs(+ request([+ sdxlCase('z-image-refs', { model_key: 'z-image-gguf', reference_images: ['reference.png'] }),+ sdxlCase('sdxl-six-refs', { reference_images: ['1.png', '2.png', '3.png', '4.png', '5.png', '6.png'] }),+ ])+ ).cases;++ expect(errorOf(unsupported)).toBe('reference_images: z-image-gguf name takes no reference images.');+ expect(errorOf(tooMany)).toBe('Generate supports at most 5 reference images for sdxl name.');+ });++ it('sends img2img through Canvas with the uploaded image and strength', () => {+ const { graph } = exportOne(+ sdxlCase('sdxl-i2i', { init_image: { image_name: 'init.png', strength: 0.3 }, mode: 'img2img' })+ ).batch;++ expect(nodesOfType(graph, 'i2l').map((node) => node.image)).toEqual([{ image_name: 'init.png' }]);+ expect(graph.nodes.denoise_latents?.denoising_start).toBeCloseTo(0.7);+ expect(nodesOfType(graph, 'core_metadata')[0]).toMatchObject({ generation_mode: 'sdxl_img2img', strength: 0.3 });+ });++ it('adds each control entry as a Canvas control layer feeding the denoiser', () => {+ const { graph } = exportOne(+ sdxlCase('sdxl-control', {+ control: [{ begin: 0.1, end: 0.6, image_name: 'canny.png', model_key: 'sdxl-canny', weight: 0.9 }],+ mode: 'controlnet',+ })+ ).batch;+ const [controlNet] = nodesOfType(graph, 'controlnet');++ expect(controlNet).toMatchObject({+ begin_step_percent: 0.1,+ control_model: { key: 'sdxl-canny' },+ control_weight: 0.9,+ end_step_percent: 0.6,+ image: { image_name: 'canny.png' },+ });+ expect(graph.edges).toContainEqual({+ destination: { field: 'control', node_id: 'denoise_latents' },+ source: { field: 'collection', node_id: 'control_net_collector' },+ });+ });++ it('fills required components from the installed models and keeps explicit picks', () => {+ const zImage = { ...sdxlCase('z-image'), model_key: 'z-image-gguf' };++ // The 0.6B encoder is listed first but Z-Image cannot use it.+ expect(exportOne(zImage).components).toEqual({ qwen3EncoderModel: 'qwen3-4b', vae: 'flux-vae' });+ expect(exportOne({ ...zImage, components: { qwen3EncoderModel: 'qwen3-4b-gguf' } }).components).toEqual({+ qwen3EncoderModel: 'qwen3-4b-gguf',+ vae: 'flux-vae',+ });+ });++ it('rejects an installed component the slot does not offer', () => {+ const [result] = exportGraphs(+ request([sdxlCase('z-image', { components: { qwen3EncoderModel: 'qwen3-8b' }, model_key: 'z-image-gguf' })])+ ).cases;++ expect(errorOf(result)).toBe(+ 'components.qwen3EncoderModel: "qwen3-8b" cannot be the Qwen3 Encoder of z-image-gguf name. ' ++ 'Choices: qwen3-4b, qwen3-4b-gguf.'+ );+ });++ it.each(generateGraphCases)('compiles $label from exactly the components it needs', ({ base, shape }) => {+ const {+ filled,+ model: main,+ settings,+ } = withArchitectureCapabilities(architectureCapabilitiesFixture, () => satisfiedSettingsFor(base, shape));+ const components = Object.fromEntries(filled.map((key) => [key, (settings[key] as { key: string }).key]));+ const testCase = sdxlCase(base, { height: settings.height, model_key: main.key, width: settings.width });++ expect(exportOne(testCase, [main, ...filled.map((key) => settings[key])]).components).toEqual(components);+ });++ it('applies settings overrides and rejects values Generate would not keep', () => {+ const { graph } = exportOne(sdxlCase('cfg', { settings: { cfgScale: 3.5, scheduler: 'dpmpp_2m' } })).batch;+ const [badPid, badScheduler] = exportGraphs(+ request([+ sdxlCase('pid', { settings: { pidMode: 'sideways' } }),+ sdxlCase('scheduler', { settings: { scheduler: 'not-a-scheduler' } }),+ ])+ ).cases;++ expect(graph.nodes.denoise_latents).toMatchObject({ cfg_scale: 3.5, scheduler: 'dpmpp_2m' });+ expect(errorOf(badPid)).toMatch(/^settings\.pidMode: Generate does not keep "sideways"/);+ expect(errorOf(badScheduler)).toMatch(/^settings\.scheduler: .* Options: .*euler_a/);+ });++ it('reports unknown names per case, with the valid choices, and still exports the other cases', () => {+ const response = exportGraphs(+ request([+ sdxlCase('unknown-setting', { settings: { cfgscale: 3 } }),+ sdxlCase('unknown-slot', { components: { t5EncoderModel: 'qwen3-4b' }, model_key: 'z-image-gguf' }),+ sdxlCase('unknown-component', { components: { vae: 'missing-vae' }, model_key: 'z-image-gguf' }),+ sdxlCase('unknown-model', { model_key: 'missing' }),+ sdxlCase('unknown-lora', { loras: [{ key: 'missing-lora', weight: 1 }] }),+ sdxlCase('unknown-control', {+ control: [{ begin: 0, end: 1, image_name: 'canny.png', model_key: 'sdxl-lora', weight: 1 }],+ mode: 'controlnet',+ }),+ sdxlCase('ok'),+ ])+ );+ const errors = Object.fromEntries(response.cases.map((result) => [result.id, errorOf(result)]));++ expect(errors['unknown-setting']).toMatch(/^Unknown settings key "cfgscale"\. Valid keys: .*\bcfgScale\b/);+ expect(errors['unknown-slot']).toMatch(+ /^Unknown component slot "t5EncoderModel" .* Valid slots: .*qwen3EncoderModel, vae/+ );+ expect(errors['unknown-component']).toBe(+ 'components.vae: model key "missing-vae" is not installed. Choices: flux-vae.'+ );+ expect(errors['unknown-model']).toBe(+ 'model_key "missing" is not a selectable main model. Choices: sdxl, z-image-gguf.'+ );+ expect(errors['unknown-lora']).toMatch(/^loras\[0\]: "missing-lora" .* Choices: sdxl-lora\.$/);+ expect(errors['unknown-control']).toMatch(/^control\[0\]: "sdxl-lora" cannot drive .* Choices: sdxl-canny\.$/);+ expect(response.cases.find((result) => result.id === 'ok')).toHaveProperty('batch');+ });++ it('exports identical requests identically, with stable node ids', () => {+ const cases = [+ sdxlCase('t2i', { loras: [{ key: 'sdxl-lora', weight: 1 }], reference_images: ['reference.png'] }),+ sdxlCase('i2i', { init_image: { image_name: 'init.png', strength: 0.5 }, mode: 'img2img' }),+ { ...sdxlCase('z-image'), model_key: 'z-image-gguf' },+ ];+ const first = exportGraphs(request(cases));+ const nodeIds = first.cases.flatMap((result) => ('batch' in result ? Object.keys(result.batch.graph.nodes) : []));++ expect(exportGraphs(request(cases))).toEqual(first);+ expect(nodeIds.filter((id) => /_[a-z0-9]{7,9}_[a-z0-9]{4,6}$/.test(id))).toEqual([]);+ });++ it.each([+ ['a non-object request', []],+ ['another version', { ...request([]), version: 2 }],+ ['models that are not model configs', request([], [{ key: 'only-a-key' }])],+ ['cases without ids', request([{ mode: 'txt2img' }])],+ ['duplicate case ids', request([sdxlCase('same'), sdxlCase('same')])],+ ])('rejects %s as a malformed request', (_label, malformed) => {+ expect(() => exportGraphs(malformed)).toThrow(GraphExportRequestError);+ });+});diff --git a/invokeai/frontend/webv2/src/app/graphExport.ts b/invokeai/frontend/webv2/src/app/graphExport.tsnew file mode 100644index 0000000000..951736f752--- /dev/null+++ b/invokeai/frontend/webv2/src/app/graphExport.ts@@ -0,0 +1,247 @@+/**+ * Composition root of `pnpm graphs:export` (scripts/export-graphs.mjs): installed model configs, the capability table+ * and test cases become the enqueue batches the UI would send, offline, so end-to-end runs exercise the graphs users+ * submit. Each batch is what Generate or Canvas puts into `enqueue_batch` minus `runs`, `project_id` and+ * `idempotency_key`, with the case seed held fixed. Generation and Queue own every rule; this module maps the wire+ * format and supplies the Workbench defaults the widgets would.+ */++import type { GeneratePromptBatchPlan } from '@features/queue/contracts';++import {+ compileGraphExportCase,+ withArchitectureCapabilities,+ type ArchitectureCapabilitiesRow,+ type CompiledGraphExportCase,+ type GraphExportCase,+ type GraphExportEnvironment,+ type GraphExportMode,+} from '@features/generation/graphExport';+import { planGenerateSubmissionBatch } from '@features/queue/contracts';+import { resolveRandDeviceMetadata } from '@features/queue/devices';+import { SEED_MAX } from '@platform/core/seed';+import { DEFAULT_CANVAS_COMPOSITING } from '@workbench/widgets/canvas/invoke/canvasCompositing';+import { DEFAULT_CANVAS_SCALING } from '@workbench/widgets/canvas/invoke/canvasScaling';+import { DEFAULT_CANVAS_DENOISING_STRENGTH } from '@workbench/widgets/canvas/invoke/canvasStrength';++const GRAPH_EXPORT_VERSION = 1;++/** Durable outputs: Canvas staging would mark them intermediate. */+const DESTINATION = 'gallery';+/** Not a webv2 origin, so no open editor adopts the items as its own submissions. */+const ORIGIN_PREFIX = 'graphs-export:';+/** `DEFAULT_PROJECT_SETTINGS` (workbench/settings/store.ts); importing it would load the whole settings runtime. */+const PROJECT_SETTINGS = { useCpuNoise: true, useNsfwChecker: false, useWatermark: false };+/** ROCm builds of torch report their GPUs as CUDA devices as well. */+const GPU_DEVICE_OPTIONS = [{ device: 'cuda:0', name: 'GPU' }];+const MODES: readonly GraphExportMode[] = ['txt2img', 'img2img', 'controlnet'];+const CASE_FIELDS = [+ 'components',+ 'control',+ 'height',+ 'id',+ 'init_image',+ 'loras',+ 'mode',+ 'model_key',+ 'negative_prompt',+ 'positive_prompt',+ 'reference_images',+ 'seed',+ 'settings',+ 'steps',+ 'width',+];++/** The request itself is unusable; no response is written. */+export class GraphExportRequestError extends Error {+ override name = 'GraphExportRequestError';+}++export interface GraphExportBatch {+ data: GeneratePromptBatchPlan['data'];+ destination: typeof DESTINATION;+ graph: CompiledGraphExportCase['graph'];+ origin: string;+}++export type GraphExportCaseResult =+ | { id: string; batch: GraphExportBatch; components: Record<string, string> }+ | { id: string; error: string };++export interface GraphExportResponse {+ version: typeof GRAPH_EXPORT_VERSION;+ cases: GraphExportCaseResult[];+}++type JsonRecord = Record<string, unknown>;++const isRecord = (value: unknown): value is JsonRecord =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++const fail = (message: string): never => {+ throw new Error(message);+};++const readString = (record: JsonRecord, field: string, label = field): string =>+ typeof record[field] === 'string' ? record[field] : fail(`${label} must be a string.`);++const readNumber = (record: JsonRecord, field: string, label = field): number =>+ typeof record[field] === 'number' && Number.isFinite(record[field])+ ? record[field]+ : fail(`${label} must be a number.`);++const readInteger = (record: JsonRecord, field: string, min: number, max = Number.MAX_SAFE_INTEGER): number => {+ const value = record[field];++ return typeof value === 'number' && Number.isInteger(value) && value >= min && value <= max+ ? value+ : fail(`${field} must be an integer from ${min} to ${max}.`);+};++/** Absent and null both read as empty. */+const readList = <T>(record: JsonRecord, field: string, read: (item: unknown, label: string) => T): T[] => {+ const value = record[field] ?? [];++ return Array.isArray(value)+ ? value.map((item, index) => read(item, `${field}[${index}]`))+ : fail(`${field} must be a list.`);+};++const readObject = (value: unknown, label: string): JsonRecord =>+ isRecord(value) ? value : fail(`${label} must be an object.`);++const readCase = (record: JsonRecord): GraphExportCase => {+ const unknownField = Object.keys(record).find((field) => !CASE_FIELDS.includes(field));++ if (unknownField !== undefined) {+ fail(`Unknown case field "${unknownField}". Valid fields: ${CASE_FIELDS.join(', ')}.`);+ }++ const mode = record.mode;+ const components = readObject(record.components ?? {}, 'components');+ const initImage =+ record.init_image === undefined || record.init_image === null ? null : readObject(record.init_image, 'init_image');++ return {+ components: Object.fromEntries(+ Object.keys(components).map((slot) => [slot, readString(components, slot, `components.${slot}`)])+ ),+ control: readList(record, 'control', (item, label) => {+ const layer = readObject(item, label);++ return {+ begin: readNumber(layer, 'begin', `${label}.begin`),+ end: readNumber(layer, 'end', `${label}.end`),+ imageName: readString(layer, 'image_name', `${label}.image_name`),+ modelKey: readString(layer, 'model_key', `${label}.model_key`),+ weight: readNumber(layer, 'weight', `${label}.weight`),+ };+ }),+ height: readInteger(record, 'height', 1),+ id: readString(record, 'id'),+ initImage: initImage && {+ imageName: readString(initImage, 'image_name', 'init_image.image_name'),+ strength: readNumber(initImage, 'strength', 'init_image.strength'),+ },+ loras: readList(record, 'loras', (item, label) => {+ const lora = readObject(item, label);++ return { key: readString(lora, 'key', `${label}.key`), weight: readNumber(lora, 'weight', `${label}.weight`) };+ }),+ mode: MODES.includes(mode as GraphExportMode)+ ? (mode as GraphExportMode)+ : fail(`mode must be one of ${MODES.join(', ')}.`),+ modelKey: readString(record, 'model_key'),+ negativePrompt:+ record.negative_prompt === null || record.negative_prompt === undefined+ ? ''+ : readString(record, 'negative_prompt'),+ positivePrompt: readString(record, 'positive_prompt'),+ referenceImages: readList(record, 'reference_images', (item, label) =>+ typeof item === 'string' ? item : fail(`${label} must be an image name.`)+ ),+ seed: readInteger(record, 'seed', 0, SEED_MAX),+ settings: readObject(record.settings ?? {}, 'settings'),+ steps: readInteger(record, 'steps', 1),+ width: readInteger(record, 'width', 1),+ };+};++const exportCase = (record: JsonRecord, env: GraphExportEnvironment): GraphExportCaseResult => {+ const id = record.id as string;++ try {+ const { components, graph, submission } = compileGraphExportCase(readCase(record), env);+ const batch: GraphExportBatch = {+ data: planGenerateSubmissionBatch(submission).data,+ destination: DESTINATION,+ graph,+ origin: `${ORIGIN_PREFIX}${id}`,+ };++ return { batch, components, id };+ } catch (error) {+ return { error: error instanceof Error ? error.message : String(error), id };+ }+};++const isModelConfig = (value: unknown): value is GraphExportEnvironment['models'][number] =>+ isRecord(value) && ['key', 'name', 'base', 'type'].every((field) => typeof value[field] === 'string');++const isCapabilitiesRow = (value: unknown): value is ArchitectureCapabilitiesRow =>+ isRecord(value) && typeof value.base === 'string' && isRecord(value.features);++const readRequest = (request: unknown) => {+ if (!isRecord(request)) {+ throw new GraphExportRequestError('The request must be a JSON object.');+ }++ if (request.version !== GRAPH_EXPORT_VERSION) {+ throw new GraphExportRequestError(`Unsupported request version ${JSON.stringify(request.version)}; expected 1.`);+ }++ const { capabilities, cases, models } = request;++ if (!Array.isArray(models) || !models.every(isModelConfig)) {+ throw new GraphExportRequestError('models must be the `models` list of GET /api/v2/models/.');+ }++ if (!Array.isArray(capabilities) || !capabilities.every(isCapabilitiesRow)) {+ throw new GraphExportRequestError('capabilities must be the body of GET /api/v2/models/capabilities.');+ }++ if (!Array.isArray(cases) || !cases.every((item) => isRecord(item) && typeof item.id === 'string' && item.id)) {+ throw new GraphExportRequestError('cases must be a list of objects with a non-empty string id.');+ }++ const ids = cases.map((item) => item.id as string);+ const duplicate = ids.find((id, index) => ids.indexOf(id) !== index);++ if (duplicate !== undefined) {+ throw new GraphExportRequestError(`Case id "${duplicate}" is not unique.`);+ }++ return { capabilities, cases: cases as JsonRecord[], models };+};++/** Throws GraphExportRequestError for a malformed request; a case that cannot compile carries its error instead. */+export const exportGraphs = (request: unknown): GraphExportResponse => {+ const { capabilities, cases, models } = readRequest(request);+ const env: GraphExportEnvironment = {+ canvas: {+ compositing: DEFAULT_CANVAS_COMPOSITING,+ scaling: DEFAULT_CANVAS_SCALING,+ strength: DEFAULT_CANVAS_DENOISING_STRENGTH,+ },+ destination: DESTINATION,+ models,+ projectSettings: PROJECT_SETTINGS,+ randDevice: resolveRandDeviceMetadata(PROJECT_SETTINGS.useCpuNoise, GPU_DEVICE_OPTIONS),+ };++ return withArchitectureCapabilities(capabilities, () => ({+ cases: cases.map((record) => exportCase(record, env)),+ version: GRAPH_EXPORT_VERSION,+ }));+};diff --git a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.tsindex d19c4dc545..970b412849 100644--- a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts+++ b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts@@ -236,6 +236,7 @@ describe('feature public-interface registry', () => {]);expect(checkDependency('workbench/invocationSubmit.ts', '@features/generation/prompts')).toEqual([]);expect(checkDependency('app/GenerateWidgetSyncRuntime.tsx', '@features/generation/runtime')).toEqual([]);+ expect(checkDependency('app/graphExport.ts', '@features/generation/graphExport')).toEqual([]);expect(checkDependency('workbench/widgets/canvas/invoke.ts', '@features/generation/canvasGraph')).toEqual([]);expect(checkDependency('workbench/WorkbenchContext.tsx', '@features/intermediates/holdLease')).toEqual([]);expect(diff --git a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts b/invokeai/frontend/webv2/src/architecture/featureInterfaces.tsindex 4fae8e2053..c7fea1255f 100644--- a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts+++ b/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts@@ -23,6 +23,7 @@ export const FEATURE_PUBLIC_INTERFACES: Readonly<Record<string, readonly string['components','contracts','graph',+ 'graphExport','preview','prompts','queries',diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.tsindex 147154f516..f6c7828568 100644--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts@@ -1245,7 +1245,10 @@ export const getComponentSectionPolicy = (};};-const getComponentPolicyContext = (model: GenerateModelConfig, settings: GenerateSettings): ComponentPolicyContext => ({+export const getComponentPolicyContext = (+ model: GenerateModelConfig,+ settings: GenerateSettings+): ComponentPolicyContext => ({model,settings,selectedComponents: {@@ -1289,6 +1292,9 @@ const COMPONENT_SETTING_LABELS: Record<GenerateComponentValueKey, string> = {componentSourceModel: 'Component source',};+/** Every settings key that holds a component model. */+export const GENERATE_COMPONENT_VALUE_KEYS = Object.keys(COMPONENT_SETTING_LABELS) as GenerateComponentValueKey[];+const addClearedLabel = (labels: string[], label: string) => {if (!labels.includes(label)) {labels.push(label);@@ -1831,7 +1837,7 @@ const getSettingsWithCompatibleModelSelections = (const slotsByKey = new Map(policy.slots.map((slotPolicy) => [slotPolicy.key, slotPolicy]));const uiPolicy = getGenerationUiPolicy(model);- for (const key of Object.keys(COMPONENT_SETTING_LABELS) as GenerateComponentValueKey[]) {+ for (const key of GENERATE_COMPONENT_VALUE_KEYS) {if (!nextSettings[key]) {continue;}@@ -1948,7 +1954,7 @@ export const getGenerationModelAvailabilityReasons = (reasons.push(`Selected model "${model.name}" is no longer installed.`);}- for (const key of Object.keys(COMPONENT_SETTING_LABELS) as GenerateComponentValueKey[]) {+ for (const key of GENERATE_COMPONENT_VALUE_KEYS) {const value = settings[key];if (value && !hasModelKey(models, value.key, value.type)) {diff --git a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.tsindex 38d2ee3804..f1a513880e 100644--- a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts@@ -6,9 +6,11 @@ import {hasDynamicPromptSyntax,matchesKnownWildcard,normalizeWildcardValues,+ planGenerateSubmission,scanWildcardReferences,sanitizeDynamicPromptsConfig,sanitizeMaxPrompts,+ type GenerateSubmissionSource,} from './dynamicPrompts';describe('hasDynamicPromptSyntax', () => {@@ -239,3 +241,70 @@ describe('getWildcardValuesError', () => {expect(getWildcardValuesError(['x'.repeat(2_000)])).toBeNull();});});++const source = (overrides: Partial<GenerateSubmissionSource> = {}): GenerateSubmissionSource => ({+ batchCount: 2,+ negativePrompt: 'blurry',+ negativePromptEnabled: true,+ positivePrompt: 'a cat',+ promptTemplate: null,+ seed: 10,+ seedMode: 'increment',+ ...overrides,+});++describe('planGenerateSubmission', () => {+ it('merges the template and suppresses its negative side with the negative prompt', () => {+ const promptTemplate = {+ id: 't',+ name: 'Photo',+ negativePrompt: '{prompt}, lowres',+ positivePrompt: 'photo of {prompt}',+ };++ expect(planGenerateSubmission(source({ promptTemplate })).submission).toMatchObject({+ negativePrompt: 'blurry, lowres',+ positivePrompt: 'photo of a cat',+ });++ const suppressed = planGenerateSubmission(source({ negativePromptEnabled: false, promptTemplate }));++ expect(suppressed.submission.negativePrompt).toBe('');+ expect(suppressed.effectivePrompts.negativePrompt).toBe('blurry, lowres');+ });++ it('sends an expansion and its seed behaviour only for a prompt with dynamic syntax', () => {+ const expansion = ['a red cat', 'a green cat'];+ const expanded = planGenerateSubmission(+ source({ dynamicPromptsSeedBehaviour: 'per-image', positivePrompt: 'a {red|green} cat' }),+ expansion+ );+ const plain = planGenerateSubmission(source({ dynamicPromptsSeedBehaviour: 'per-image' }), expansion);++ expect(expanded.submission).toEqual({+ batchCount: 2,+ negativePrompt: 'blurry',+ positivePrompt: 'a {red|green} cat',+ positivePrompts: expansion,+ seed: 10,+ seedBehaviour: 'per-image',+ seedStep: 1,+ });+ // Two prompts per image across two runs consume four seeds.+ expect(expanded.seedPlan.nextSeed).toBe(14);+ expect(plain.submission).toEqual({+ batchCount: 2,+ negativePrompt: 'blurry',+ positivePrompt: 'a cat',+ seed: 10,+ seedStep: 1,+ });+ expect(plain.seedPlan.nextSeed).toBe(12);+ });++ it('holds a fixed seed', () => {+ const { seedPlan, submission } = planGenerateSubmission(source({ seedMode: 'fixed' }));++ expect([submission.seed, submission.seedStep, seedPlan.nextSeed]).toEqual([10, 0, null]);+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.tsindex 3512f3c45e..5296729523 100644--- a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts@@ -1,3 +1,9 @@+import { planSeedSubmission, type SeedMode, type SeedStep, type SeedSubmissionPlan } from '@platform/core/seed';++import type { EffectivePrompts, PromptTemplateSnapshot } from './promptTemplates';++import { getEffectivePrompts } from './promptTemplates';+const SEED_MAX = 4_294_967_295;export const DYNAMIC_PROMPTS_MIN_PROMPTS = 1;@@ -302,3 +308,75 @@ export const sanitizeSampleSeed = (value: unknown): number =>typeof value === 'number' && Number.isFinite(value) ? Math.abs(Math.round(value)) % SEED_MAX : 0;export const createDynamicPromptsSampleSeed = (): number => Math.floor(Math.random() * SEED_MAX);++/** The prompted, seeded values Generate, Canvas, Upscale and Video submit from. */+export interface GenerateSubmissionSource {+ batchCount: number;+ negativePrompt: string;+ negativePromptEnabled: boolean;+ positivePrompt: string;+ promptTemplate?: PromptTemplateSnapshot | null;+ seed: number;+ seedMode: SeedMode;+ dynamicPromptsSeedBehaviour?: DynamicPromptsSeedBehaviour;+}++/** The prompt and seed fields of a queued generate submission; the host adds the graph and its node ids. */+export interface GenerateSubmissionPrompts {+ batchCount: number;+ negativePrompt: string;+ positivePrompt: string;+ /** Present when the positive prompt expanded; the expansion is sent instead of the prompt. */+ positivePrompts?: string[];+ seed: number;+ seedBehaviour?: DynamicPromptsSeedBehaviour;+ seedStep: SeedStep;+}++export interface GenerateSubmissionPlan {+ /** Template-merged prompts, before negative-prompt suppression. */+ effectivePrompts: EffectivePrompts;+ seedPlan: SeedSubmissionPlan;+ submission: GenerateSubmissionPrompts;+}++/**+ * The prompts and seeds a submission sends. `expandedPositivePrompts` are what the host expanded the merged positive+ * prompt into; they count only when that prompt has dynamic syntax, so templates that introduce syntax count too.+ */+export const planGenerateSubmission = (+ source: GenerateSubmissionSource,+ expandedPositivePrompts?: string[]+): GenerateSubmissionPlan => {+ const effectivePrompts = getEffectivePrompts(source);+ // Record expansions even when only one prompt results.+ const positivePrompts =+ expandedPositivePrompts &&+ expandedPositivePrompts.length > 0 &&+ hasDynamicPromptSyntax(effectivePrompts.positivePrompt)+ ? expandedPositivePrompts+ : undefined;+ const seedBehaviour = positivePrompts ? source.dynamicPromptsSeedBehaviour : undefined;+ const seedPlan = planSeedSubmission({+ batchCount: source.batchCount,+ promptCount: positivePrompts?.length ?? 1,+ seedBehaviour: seedBehaviour ?? 'per-iteration',+ seedMode: source.seedMode,+ startSeed: source.seed,+ });++ return {+ effectivePrompts,+ seedPlan,+ submission: {+ batchCount: source.batchCount,+ // Disabling the negative prompt also suppresses the template's negative side.+ negativePrompt: source.negativePromptEnabled ? effectivePrompts.negativePrompt : '',+ positivePrompt: effectivePrompts.positivePrompt,+ ...(positivePrompts ? { positivePrompts } : {}),+ seed: source.seed,+ ...(seedBehaviour ? { seedBehaviour } : {}),+ seedStep: seedPlan.step,+ },+ };+};diff --git a/invokeai/frontend/webv2/src/features/generation/core/graphExport.ts b/invokeai/frontend/webv2/src/features/generation/core/graphExport.tsnew file mode 100644index 0000000000..0ddff84305--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/core/graphExport.ts@@ -0,0 +1,513 @@+/**+ * Offline export cases compile to the graph Generate or Canvas would submit: the model's defaults, the case's values+ * and component picks, required components filled from the installed models the way a user fills them, and the same+ * reconciliation and compilers the widget runs. Callers own the wire format and the Workbench canvas defaults.+ */++import type { GenerationModelCatalogItem as ModelConfig } from '@features/generation/core/contracts';++import { areJsonValuesStructurallyEqual } from '@platform/core/json';++import type { ArchitectureCapabilitiesRow } from './architectureCapabilities';+import type { ComponentPolicyContext, ComponentSlotPolicy } from './baseGenerationPolicies';+import type { ControlLayerGraphInput } from './canvas/addControlLayers';+import type { CanvasCompositingSettings, CanvasScalingSettings } from './canvas/types';+import type { BackendGraphContract, GenerationProjectSettings, ResultDestination } from './contracts';+import type { ComponentModelConfig, GenerateModelConfig, GenerateWidgetValues } from './types';++import { resetArchitectureCapabilities, setArchitectureCapabilities } from './architectureCapabilities';+import {+ coerceSchedulerForGraph,+ GENERATE_COMPONENT_VALUE_KEYS,+ getComponentPolicyContext,+ getComponentSectionPolicy,+ getDefaultGenerateSettings,+ getGenerateModelSelectionResult,+ getMissingReferenceImageFormat,+ getSchedulerOptions,+ isArchitectureDescribed,+ isGenerateModelSelectable,+ isLoraSupported,+ isReferenceImageSupported,+ withAddedReferenceImages,+} from './baseGenerationPolicies';+import { compileCanvasGraph } from './canvas/compileCanvasGraph';+import {+ CONTROL_ADAPTER_KINDS,+ isControlKindSupportedForBase,+ isControlModelUsableForKind,+} from './canvas/controlValidation';+import { hasDynamicPromptSyntax, planGenerateSubmission, type GenerateSubmissionPrompts } from './dynamicPrompts';+import { compileGenerateGraph } from './graph';+import { stabilizeBackendGraphNodeIds } from './previewGraph';+import { resolveGenerateWidgetValues } from './resolveGenerateWidgetValues';+import {+ deriveAspectRatioId,+ GENERATE_UI_STATE_KEYS,+ getModelDefaultVae,+ hasModelDefaultVae,+ isLoraCompatibleWithModel,+ isLoraModelConfig,+ isMainModelConfig,+ isModelIdentifierConfig,+ isVaeModelConfig,+} from './settings';++/** `txt2img` compiles like Generate; `img2img` and `controlnet` compile like a full-frame Canvas invoke. */+export type GraphExportMode = 'txt2img' | 'img2img' | 'controlnet';++export interface GraphExportCase {+ /** Becomes the graph id. */+ id: string;+ mode: GraphExportMode;+ modelKey: string;+ /** Picks keyed by component slot; required slots left out are filled from the installed models. */+ components: Readonly<Record<string, string>>;+ width: number;+ height: number;+ steps: number;+ seed: number;+ positivePrompt: string;+ negativePrompt: string;+ loras: readonly { key: string; weight: number }[];+ /** Uploaded image names. */+ referenceImages: readonly string[];+ /** An uploaded image already sized width × height, as the Canvas composite always is. */+ initImage: { imageName: string; strength: number } | null;+ /** Each image is an uploaded width × height control composite. */+ control: readonly { modelKey: string; imageName: string; weight: number; begin: number; end: number }[];+ /** Generate settings overrides. Keys the case sets through its own fields are rejected. */+ settings: Readonly<Record<string, unknown>>;+}++export interface GraphExportEnvironment {+ models: readonly ModelConfig[];+ destination: ResultDestination;+ projectSettings: GenerationProjectSettings;+ randDevice: string;+ /** What the Canvas widget supplies from its persisted values. */+ canvas: { compositing: CanvasCompositingSettings; scaling: CanvasScalingSettings; strength: number };+}++export interface CompiledGraphExportCase {+ /** Node ids are stabilized: identical cases compile to identical graphs. */+ graph: BackendGraphContract;+ /** The key of every component model the case compiled with, by settings key. */+ components: Record<string, string>;+ /** What Generate queues for the graph, with the prompt and seed node ids in `graph`. */+ submission: GenerateSubmissionPrompts & {+ negativePromptNodeId: string;+ positivePromptNodeId: string;+ seedNodeId: string;+ };+}++/** Keys a case sets through its own fields, picks as components, or that need backend catalogs or expansion. */+const NON_OVERRIDABLE_SETTINGS: ReadonlySet<string> = new Set([+ 'aspectRatioId',+ 'aspectRatioValue',+ 'dynamicPromptsCombinatorial',+ 'dynamicPromptsMaxPrompts',+ 'dynamicPromptsResample',+ 'dynamicPromptsSampleSeed',+ 'dynamicPromptsSeedBehaviour',+ 'height',+ 'loras',+ 'model',+ 'modelKey',+ 'negativePrompt',+ 'positivePrompt',+ 'promptTemplate',+ 'referenceImages',+ 'seed',+ 'seedMode',+ 'steps',+ 'width',+ ...GENERATE_COMPONENT_VALUE_KEYS,+ ...Object.keys(GENERATE_UI_STATE_KEYS),+]);++const listKeys = (keys: readonly string[]): string => (keys.length > 0 ? keys.join(', ') : 'none');++const listModelKeys = (models: readonly ModelConfig[]): string => listKeys(models.map((model) => model.key));++/** Hold `rows` as the capability table, which every Generation policy reads, while `run` compiles. */+export const withArchitectureCapabilities = <T>(rows: readonly ArchitectureCapabilitiesRow[], run: () => T): T => {+ setArchitectureCapabilities(rows);++ try {+ return run();+ } finally {+ resetArchitectureCapabilities();+ }+};++const getSelectableModel = (key: string, models: readonly ModelConfig[]): GenerateModelConfig => {+ const selectable = models.filter(isGenerateModelSelectable).filter(isArchitectureDescribed);+ const model = selectable.find((candidate) => candidate.key === key);++ if (!model) {+ throw new Error(`model_key "${key}" is not a selectable main model. Choices: ${listModelKeys(selectable)}.`);+ }++ return model;+};++/** Selecting the model, then "Reset to model defaults", which also applies the model's default VAE. */+const getModelDefaultValues = (model: GenerateModelConfig, models: readonly ModelConfig[]): GenerateWidgetValues => {+ const { settings } = getGenerateModelSelectionResult({+ currentValues: getDefaultGenerateSettings(model),+ model,+ models,+ });+ const vae = hasModelDefaultVae(model) ? getModelDefaultVae(model, models.filter(isVaeModelConfig)) : settings.vae;++ return { ...settings, model, vae };+};++const withCaseValues = (values: GenerateWidgetValues, input: GraphExportCase): GenerateWidgetValues => ({+ ...values,+ aspectRatioId: deriveAspectRatioId(input.width, input.height),+ aspectRatioValue: input.width / input.height,+ height: input.height,+ negativePrompt: input.negativePrompt,+ positivePrompt: input.positivePrompt,+ seed: input.seed,+ seedMode: 'fixed',+ steps: input.steps,+ width: input.width,+});++const withSettingsOverrides = (+ values: GenerateWidgetValues,+ overrides: GraphExportCase['settings']+): GenerateWidgetValues => {+ const validKeys = Object.keys(values)+ .filter((key) => !NON_OVERRIDABLE_SETTINGS.has(key))+ .sort();+ const unknownKey = Object.keys(overrides).find((key) => !validKeys.includes(key));++ if (unknownKey !== undefined) {+ throw new Error(`Unknown settings key "${unknownKey}". Valid keys: ${listKeys(validKeys)}.`);+ }++ return { ...values, ...overrides };+};++const fitsSlot = (slot: ComponentSlotPolicy, candidate: ModelConfig, ctx: ComponentPolicyContext): boolean =>+ (slot.modelTypes as readonly string[]).includes(candidate.type) && (!slot.filter || slot.filter(candidate, ctx));++/** The value the component picker commits for `model`, by the slot's value kind. */+const toSlotValue = (slot: ComponentSlotPolicy, model: ModelConfig): ComponentModelConfig | null => {+ switch (slot.valueKind) {+ case 'main':+ return isMainModelConfig(model) ? model : null;+ case 'vae':+ return isVaeModelConfig(model) ? model : null;+ case 'component':+ return isModelIdentifierConfig(model) ? model : null;+ }+};++const withComponentPicks = (+ values: GenerateWidgetValues,+ picks: GraphExportCase['components'],+ models: readonly ModelConfig[]+): GenerateWidgetValues => {+ const { slots } = getComponentSectionPolicy(values.model, values);+ let next = values;++ for (const [slotKey, modelKey] of Object.entries(picks)) {+ const slot = slots.find((candidate) => candidate.key === slotKey);++ if (!slot) {+ const validSlots = listKeys(slots.map((candidate) => candidate.key));++ throw new Error(`Unknown component slot "${slotKey}" for ${values.model.name}. Valid slots: ${validSlots}.`);+ }++ const ctx = getComponentPolicyContext(next.model, next);+ const fitting = models.filter((candidate) => fitsSlot(slot, candidate, ctx));+ const pick = fitting.find((candidate) => candidate.key === modelKey);+ const value = pick ? toSlotValue(slot, pick) : null;++ if (!value) {+ const problem = models.some((candidate) => candidate.key === modelKey)+ ? `"${modelKey}" cannot be the ${slot.label} of ${values.model.name}`+ : `model key "${modelKey}" is not installed`;++ throw new Error(`components.${slotKey}: ${problem}. Choices: ${listModelKeys(fitting)}.`);+ }++ next = { ...next, [slot.key]: value };+ }++ return next;+};++/** Pick the first installed model for the first required slot that is unfilled; null when none can be filled. */+const withFirstRequiredComponent = (+ values: GenerateWidgetValues,+ models: readonly ModelConfig[]+): GenerateWidgetValues | null => {+ const ctx = getComponentPolicyContext(values.model, values);++ for (const slot of getComponentSectionPolicy(values.model, values).slots) {+ const current = ctx.selectedComponents[slot.key];++ if (!slot.required?.(ctx) || (current && (!slot.filter || slot.filter(current as ModelConfig, ctx)))) {+ continue;+ }++ for (const candidate of models) {+ const value = fitsSlot(slot, candidate, ctx) ? toSlotValue(slot, candidate) : null;++ if (value) {+ return { ...values, [slot.key]: value };+ }+ }+ }++ return null;+};++const withLoras = (+ values: GenerateWidgetValues,+ loras: GraphExportCase['loras'],+ models: readonly ModelConfig[]+): GenerateWidgetValues => {+ if (loras.length === 0) {+ return values;+ }++ const { model } = values;++ if (!isLoraSupported(model)) {+ throw new Error(`${model.name} does not load LoRAs.`);+ }++ const compatible = models.filter(isLoraModelConfig).filter((lora) => isLoraCompatibleWithModel(lora, model));++ return {+ ...values,+ loras: loras.map(({ key, weight }, index) => {+ const lora = compatible.find((candidate) => candidate.key === key);++ if (!lora) {+ const choices = listModelKeys(compatible);++ throw new Error(`loras[${index}]: "${key}" is not an installed LoRA for ${model.name}. Choices: ${choices}.`);+ }++ return { isEnabled: true, model: lora, weight };+ }),+ };+};++/** Adding the images to the Reference Images section, which types each one for the model as it joins the list. */+const withReferenceImages = (+ values: GenerateWidgetValues,+ input: GraphExportCase,+ models: readonly ModelConfig[]+): GenerateWidgetValues => {+ if (input.referenceImages.length === 0) {+ return values;+ }++ const { model } = values;++ if (!isReferenceImageSupported(model)) {+ const format = getMissingReferenceImageFormat(model);++ throw new Error(+ `reference_images: ${model.name} takes no reference images${format ? ` in this format; they need ${format}` : ''}.`+ );+ }++ return {+ ...values,+ referenceImages: withAddedReferenceImages(+ model,+ models,+ values.referenceImages,+ input.referenceImages.map((imageName, index) => ({+ id: `reference_image_${index + 1}`,+ // Cases name images only; the output size stands in for dimensions that reach metadata, not inference.+ image: { original: { image: { height: input.height, image_name: imageName, width: input.width } } },+ }))+ ),+ };+};++/** The widget reconciles after every commit; reconciliation can pick a FLUX.2 component source. */+const reconcile = (values: GenerateWidgetValues, models: readonly ModelConfig[]): GenerateWidgetValues => {+ const resolved = resolveGenerateWidgetValues({ models, storedValues: values });++ if (!resolved) {+ throw new Error('Generate cannot resolve settings without the capability table.');+ }++ return resolved.values;+};++/** Report a requested value the widget would not keep instead of compiling a graph nobody asked for. */+const assertRequestedValuesKept = (values: GenerateWidgetValues, input: GraphExportCase): void => {+ for (const [key, requested] of Object.entries(input.settings)) {+ const kept = values[key as keyof GenerateWidgetValues];++ if (!areJsonValuesStructurallyEqual(kept, requested)) {+ throw new Error(+ `settings.${key}: Generate does not keep ${JSON.stringify(requested)}; it holds ${JSON.stringify(kept)}.`+ );+ }+ }++ if ('scheduler' in input.settings && coerceSchedulerForGraph(values.model, values.scheduler) !== values.scheduler) {+ const options = getSchedulerOptions(values.model).map((option) => option.value);++ throw new Error(+ `settings.scheduler: ${values.model.name} does not use "${values.scheduler}". Options: ${listKeys(options)}.`+ );+ }++ for (const [key, requested] of Object.entries(input.components)) {+ const kept = values[key as keyof GenerateWidgetValues] as ComponentModelConfig | null;++ if (kept?.key !== requested) {+ throw new Error(+ `components.${key}: Generate replaces "${requested}" with ${kept ? `"${kept.key}"` : 'nothing'}.`+ );+ }+ }+};++const getControlLayers = (+ input: GraphExportCase,+ model: GenerateModelConfig,+ models: readonly ModelConfig[]+): ControlLayerGraphInput[] => {+ // A layer's kind is the one its model can drive on this base, the kind a user switches the layer to.+ const getKind = (candidate: ModelConfig) =>+ candidate.base === model.base+ ? CONTROL_ADAPTER_KINDS.find(+ (kind) => isControlKindSupportedForBase(model.base, kind) && isControlModelUsableForKind(candidate, kind)+ )+ : undefined;++ return input.control.map((layer, index) => {+ const adapter = models.find((candidate) => candidate.key === layer.modelKey);+ const kind = adapter ? getKind(adapter) : undefined;++ if (!adapter || !kind) {+ const choices = listModelKeys(models.filter((candidate) => getKind(candidate) !== undefined));+ const problem = `"${layer.modelKey}" cannot drive a control layer of ${model.name}`;++ throw new Error(`control[${index}]: ${problem}. Choices: ${choices}.`);+ }++ return {+ beginEndStepPct: [layer.begin, layer.end],+ // A new ControlNet layer starts "balanced", which the compiler sends for null; other kinds carry no mode.+ controlMode: null,+ id: `control_${index + 1}`,+ imageName: layer.imageName,+ kind,+ model: {+ base: adapter.base,+ key: adapter.key,+ name: adapter.name,+ type: adapter.type,+ ...(typeof adapter.hash === 'string' ? { hash: adapter.hash } : {}),+ },+ modelCondInChannels: typeof adapter.cond_in_channels === 'number' ? adapter.cond_in_channels : null,+ weight: layer.weight,+ };+ });+};++const assertModeInputs = (input: GraphExportCase): void => {+ if (input.mode === 'txt2img' && (input.initImage || input.control.length > 0)) {+ throw new Error('txt2img cases take no init_image or control; use img2img or controlnet.');+ }++ if (input.mode === 'img2img' && !input.initImage) {+ throw new Error('img2img cases need init_image.');+ }++ if (input.mode === 'controlnet' && input.control.length === 0) {+ throw new Error('controlnet cases need at least one control entry.');+ }+};++/** Throws a message naming the offending field and its valid choices when the case cannot compile. */+export const compileGraphExportCase = (+ input: GraphExportCase,+ env: GraphExportEnvironment+): CompiledGraphExportCase => {+ assertModeInputs(input);++ const { models } = env;+ let values = withCaseValues(getModelDefaultValues(getSelectableModel(input.modelKey, models), models), input);+ values = withSettingsOverrides(values, input.settings);+ values = withComponentPicks(values, input.components, models);+ values = withLoras(values, input.loras, models);+ values = reconcile(withReferenceImages(values, input, models), models);++ // Filling one slot can satisfy or require another; the bound stops a reconciliation that keeps undoing a pick.+ for (let pass = 0; pass < GENERATE_COMPONENT_VALUE_KEYS.length; pass += 1) {+ const filled = withFirstRequiredComponent(values, models);++ if (!filled) {+ break;+ }++ values = reconcile(filled, models);+ }++ assertRequestedValuesKept(values, input);++ // No expansion: the UI expands dynamic prompts through the backend before it queues.+ const { effectivePrompts, submission } = planGenerateSubmission(values);++ if (hasDynamicPromptSyntax(effectivePrompts.positivePrompt)) {+ throw new Error(+ 'positive_prompt has dynamic prompt syntax, which only the backend expands; export each expansion.'+ );+ }++ const compiled =+ input.mode === 'txt2img'+ ? compileGenerateGraph(values, values.model, env.destination, env.projectSettings, env.randDevice)+ : compileCanvasGraph({+ bbox: { height: input.height, width: input.width, x: 0, y: 0 },+ compositeImageName: input.initImage?.imageName ?? null,+ compositing: env.canvas.compositing,+ controlLayers: getControlLayers(input, values.model, models),+ destination: env.destination,+ mode: input.initImage ? 'img2img' : 'txt2img',+ model: values.model,+ projectSettings: env.projectSettings,+ randDevice: env.randDevice,+ scaling: env.canvas.scaling,+ settings: values,+ strength: input.initImage?.strength ?? env.canvas.strength,+ });++ const stable = stabilizeBackendGraphNodeIds(compiled.backendGraph, {+ negativePromptNodeId: compiled.negativePromptNodeId,+ positivePromptNodeId: compiled.positivePromptNodeId,+ seedNodeId: compiled.seedNodeId,+ });++ return {+ components: Object.fromEntries(+ GENERATE_COMPONENT_VALUE_KEYS.flatMap((key) => {+ const component = values[key];++ return component ? [[key, component.key]] : [];+ })+ ),+ graph: { ...stable.graph, id: input.id },+ submission: { ...submission, ...stable.nodeIds },+ };+};diff --git a/invokeai/frontend/webv2/src/features/generation/core/previewGraph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/previewGraph.test.tsindex 8858477edb..026722eab6 100644--- a/invokeai/frontend/webv2/src/features/generation/core/previewGraph.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/previewGraph.test.ts@@ -10,7 +10,7 @@ import {setArchitectureCapabilities,} from './architectureCapabilities';import { getDefaultGenerateSettings } from './baseGenerationPolicies';-import { compileGeneratePreviewGraph, stabilizeBackendGraphIds } from './previewGraph';+import { compileGeneratePreviewGraph, stabilizeBackendGraphIds, stabilizeBackendGraphNodeIds } from './previewGraph';const sdxlModel: MainModelConfig = { base: 'sdxl', key: 'sdxl-model', name: 'SDXL', type: 'main' };@@ -191,4 +191,21 @@ describe('stabilizeBackendGraphIds', () => {source: { field: 'value', node_id: 'seed' },});});++ it('follows fixed node ids that lose their name to an earlier created id', () => {+ const graph = {+ edges: [],+ id: 'graph',+ nodes: {+ seed_lqx1abc_a1b2c3: { id: 'seed_lqx1abc_a1b2c3', type: 'noise' },+ seed: { id: 'seed', type: 'integer' },+ positive_prompt: { id: 'positive_prompt', type: 'string' },+ },+ };++ const result = stabilizeBackendGraphNodeIds(graph, { positive: 'positive_prompt', seed: 'seed' });++ expect(result.nodeIds).toEqual({ positive: 'positive_prompt', seed: 'seed_2' });+ expect(result.graph.nodes[result.nodeIds.seed]?.type).toBe('integer');+ });});diff --git a/invokeai/frontend/webv2/src/features/generation/core/previewGraph.ts b/invokeai/frontend/webv2/src/features/generation/core/previewGraph.tsindex 12c3659af8..9d829efdbf 100644--- a/invokeai/frontend/webv2/src/features/generation/core/previewGraph.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/previewGraph.ts@@ -31,7 +31,11 @@ export type GeneratePreviewResult =const CREATED_ID_PATTERN = /^(.+)_[a-z0-9]{7,9}_[a-z0-9]{4,6}$/;-export const stabilizeBackendGraphIds = (graph: BackendGraphContract): BackendGraphContract => {+/** Stabilize ids and follow `nodeIds` through the renames: a fixed id loses its name to an earlier created one. */+export const stabilizeBackendGraphNodeIds = <T extends Record<string, string>>(+ graph: BackendGraphContract,+ nodeIds: T+): { graph: BackendGraphContract; nodeIds: T } => {const rename = new Map<string, string>();const used = new Set<string>();@@ -50,26 +54,27 @@ export const stabilizeBackendGraphIds = (graph: BackendGraphContract): BackendGrrename.set(id, candidate);}+ const renamed = (id: string): string => rename.get(id) ?? id;+return {- edges: graph.edges.map((edge) => ({- destination: {- field: edge.destination.field,- node_id: rename.get(edge.destination.node_id) ?? edge.destination.node_id,- },- source: { field: edge.source.field, node_id: rename.get(edge.source.node_id) ?? edge.source.node_id },- ...(edge.type ? { type: edge.type } : {}),- })),- id: 'generate-preview',- nodes: Object.fromEntries(- Object.entries(graph.nodes).map(([id, node]) => {- const nextId = rename.get(id) ?? id;-- return [nextId, { ...node, id: nextId }];- })- ),+ graph: {+ edges: graph.edges.map((edge) => ({+ destination: { field: edge.destination.field, node_id: renamed(edge.destination.node_id) },+ source: { field: edge.source.field, node_id: renamed(edge.source.node_id) },+ ...(edge.type ? { type: edge.type } : {}),+ })),+ id: 'generate-preview',+ nodes: Object.fromEntries(+ Object.entries(graph.nodes).map(([id, node]) => [renamed(id), { ...node, id: renamed(id) }])+ ),+ },+ nodeIds: Object.fromEntries(Object.entries(nodeIds).map(([key, id]) => [key, renamed(id)])) as T,};};+export const stabilizeBackendGraphIds = (graph: BackendGraphContract): BackendGraphContract =>+ stabilizeBackendGraphNodeIds(graph, {}).graph;+const toPreviewContract = (backendGraph: BackendGraphContract, label: string): GraphContract => ({backendGraph,edges: backendGraph.edges.map((edge, index) => ({diff --git a/invokeai/frontend/webv2/src/features/generation/graphExport.ts b/invokeai/frontend/webv2/src/features/generation/graphExport.tsnew file mode 100644index 0000000000..2d1915f7a7--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/graphExport.ts@@ -0,0 +1,10 @@+/** Offline graph export for tooling such as `pnpm graphs:export`; the browser bundle never loads it. */+export {+ compileGraphExportCase,+ withArchitectureCapabilities,+ type CompiledGraphExportCase,+ type GraphExportCase,+ type GraphExportEnvironment,+ type GraphExportMode,+} from './core/graphExport';+export type { ArchitectureCapabilitiesRow } from './core/architectureCapabilities';diff --git a/invokeai/frontend/webv2/src/features/generation/settings.ts b/invokeai/frontend/webv2/src/features/generation/settings.tsindex 2fbe184132..228f78ec5b 100644--- a/invokeai/frontend/webv2/src/features/generation/settings.ts+++ b/invokeai/frontend/webv2/src/features/generation/settings.ts@@ -124,6 +124,7 @@ export {DYNAMIC_PROMPTS_MIN_PROMPTS,hasDynamicPromptSyntax,isDynamicPromptsSeedBehaviour,+ planGenerateSubmission,sanitizeDynamicPromptsConfig,sanitizeMaxPrompts,sanitizeSampleSeed,diff --git a/invokeai/frontend/webv2/src/features/queue/contracts.ts b/invokeai/frontend/webv2/src/features/queue/contracts.tsindex d9374a3a87..4a9b43cca7 100644--- a/invokeai/frontend/webv2/src/features/queue/contracts.ts+++ b/invokeai/frontend/webv2/src/features/queue/contracts.ts@@ -57,6 +57,11 @@ export {shouldSubmitPendingQueueItem,} from './core/submissionRules';export { extractGenerationMeta, getResultImageName, type QueueGenerationMeta } from './core/generationMeta';+export {+ planGenerateSubmissionBatch,+ type GeneratePromptBatchPlan,+ type GeneratePromptSubmission,+} from './core/promptBatch';export {buildProjectQueueItemOriginPrefix,buildQueueItemOrigin,diff --git a/invokeai/frontend/webv2/src/features/queue/core/promptBatch.ts b/invokeai/frontend/webv2/src/features/queue/core/promptBatch.tsindex 1a42d04dfb..36339aac9b 100644--- a/invokeai/frontend/webv2/src/features/queue/core/promptBatch.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/promptBatch.ts@@ -339,3 +339,37 @@ export const buildGeneratePromptBatchPlan = ({runs: isHeld ? iterations : 1,};};++/** The prompt and seed fields of a generate submission, from compilation to `enqueue_batch`. */+export interface GeneratePromptSubmission {+ batchCount: number;+ negativePrompt: string;+ negativePromptNodeId: string;+ positivePrompt: string;+ positivePromptNodeId: string;+ /**+ * Prompts to submit as a batch dimension, already expanded by the caller.+ * Absent or empty submits `positivePrompt` verbatim.+ */+ positivePrompts?: string[];+ seed: number;+ seedBehaviour?: QueuePromptSeedBehaviour;+ seedNodeId: string;+ seedStep: QueueSeedStep;+ /** Legacy recovery maps the old random toggle to seedStep and preserves its expansion rules. */+ legacySeedPlan?: true;+}++/** The batch data and run count `enqueue_batch` receives for a generate submission. */+export const planGenerateSubmissionBatch = (submission: GeneratePromptSubmission): GeneratePromptBatchPlan =>+ (submission.legacySeedPlan ? buildLegacyGeneratePromptBatchPlan : buildGeneratePromptBatchPlan)({+ batchCount: sanitizeBatchCount(submission.batchCount),+ negativePrompt: submission.negativePrompt,+ negativePromptNodeId: submission.negativePromptNodeId,+ positivePromptNodeId: submission.positivePromptNodeId,+ prompts: submission.positivePrompts?.length ? submission.positivePrompts : [submission.positivePrompt],+ seed: submission.seed,+ seedBehaviour: submission.seedBehaviour ?? 'per-iteration',+ seedNodeId: submission.seedNodeId,+ seedStep: submission.seedStep,+ });diff --git a/invokeai/frontend/webv2/src/features/queue/core/types.ts b/invokeai/frontend/webv2/src/features/queue/core/types.tsindex e2dd92e53b..f1f07df5ea 100644--- a/invokeai/frontend/webv2/src/features/queue/core/types.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/types.ts@@ -1,4 +1,5 @@import type {+ GeneratePromptSubmission,QueuePromptSeedBehaviour,QueueSeedStep,QueueWorkflowBatchDatum,@@ -58,23 +59,7 @@ export interface QueueEnqueueWorkflowRequest extends QueueEnqueueRequestBase {batchData?: QueueWorkflowBatchDatum[][];}-export interface QueueEnqueueGenerateRequest extends QueueEnqueueRequestBase {- negativePrompt: string;- negativePromptNodeId: string;- positivePrompt: string;- positivePromptNodeId: string;- /**- * Prompts to submit as a batch dimension, already expanded by the caller.- * Absent or empty submits `positivePrompt` verbatim.- */- positivePrompts?: string[];- seed: number;- seedBehaviour?: QueuePromptSeedBehaviour;- seedNodeId: string;- seedStep: QueueSeedStep;- /** Legacy recovery maps the old random toggle to seedStep and preserves its expansion rules. */- legacySeedPlan?: true;-}+export interface QueueEnqueueGenerateRequest extends QueueEnqueueRequestBase, GeneratePromptSubmission {}export interface QueueEnqueueResult {batchId?: string;diff --git a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.tsindex bba8d8a270..cbfa9fbe79 100644--- a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts@@ -8,12 +8,7 @@ import type {QueueResultVideoOptions,} from '@features/queue/core/types';-import {- buildGeneratePromptBatchPlan,- buildLegacyGeneratePromptBatchPlan,- buildQueueWorkflowBatchPlan,- sanitizeBatchCount,-} from '@features/queue/core/promptBatch';+import { buildQueueWorkflowBatchPlan, planGenerateSubmissionBatch } from '@features/queue/core/promptBatch';import { mapWithConcurrency } from '@platform/core/concurrency';import { addOutputImageNames, getOutputImageNames } from '@platform/core/outputImages';import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';@@ -78,20 +73,7 @@ const mapEnqueueResult = (value: unknown, isReceipt = false): QueueEnqueueResult};export const enqueueGenerate = async (request: QueueEnqueueGenerateRequest): Promise<QueueEnqueueResult> => {- const planInput = {- batchCount: sanitizeBatchCount(request.batchCount),- negativePrompt: request.negativePrompt,- negativePromptNodeId: request.negativePromptNodeId,- positivePromptNodeId: request.positivePromptNodeId,- prompts: request.positivePrompts?.length ? request.positivePrompts : [request.positivePrompt],- seed: request.seed,- seedBehaviour: request.seedBehaviour ?? 'per-iteration',- seedNodeId: request.seedNodeId,- };- const plan = (request.legacySeedPlan ? buildLegacyGeneratePromptBatchPlan : buildGeneratePromptBatchPlan)({- ...planInput,- seedStep: request.seedStep,- });+ const plan = planGenerateSubmissionBatch(request);const result = await apiFetchJson<unknown>('/api/v1/queue/default/enqueue_batch', {body: JSON.stringify({batch: {diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex 28024163ea..bbf565f0b5 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -87,7 +87,6 @@ import {generatedVideoToGalleryItem,settleGallerySearchScope,} from '@features/gallery/contracts';-import { planSeedSubmission } from '@platform/core/seed';import { describeError } from '@platform/logging/normalize';import { WIDGET_REGIONS } from '@workbench/layoutContracts';import { prependProjectEvent, PROJECT_EVENT_LIMIT } from '@workbench/projectEvents';@@ -143,14 +142,13 @@ import {applyProjectPromptDraft,cloneGenerateWidgetValues,createDynamicPromptsSampleSeed,- getEffectivePrompts,getGenerationModelAvailabilityReasons,getPromptDraftFromValues,getPromptHistoryItemFromGenerateSettings,- hasDynamicPromptSyntax,migrateProjectPromptDraft,normalizeGenerateSettings,normalizeGenerateWidgetValues,+ planGenerateSubmission,removePromptHistoryItem,sanitizeBatchCount,syncGenerateWidgetValuesWithModels,@@ -3599,36 +3597,21 @@ const enqueueCompiledSnapshot = (: route.sourceId === 'video'? videoSettings: null;- // Resolve template-merged prompts here, where Generate and Canvas submissions converge; Upscale merges to- // identity.- const effectivePrompts = sourceGenerateSettings ? getEffectivePrompts(sourceGenerateSettings) : null;- // Record expansions for Generate routes even when only one prompt results. Inspect merged prompts because- // templates may introduce dynamic syntax.- const expandedPositivePrompts =- route.sourceId !== 'upscale' &&- route.sourceId !== 'video' &&- compiled.positivePrompts &&- compiled.positivePrompts.length > 0 &&- effectivePrompts &&- hasDynamicPromptSyntax(effectivePrompts.positivePrompt)- ? compiled.positivePrompts- : undefined;- const expandedSeedBehaviour = expandedPositivePrompts- ? (canvasGenerateSettings ?? generateSettings)?.dynamicPromptsSeedBehaviour- : undefined;+ // Resolve template-merged prompts and seeds here, where Generate and Canvas submissions converge; Upscale and Video+ // merge to identity and never expand.+ const submissionPlan = sourceGenerateSettings+ ? planGenerateSubmission(+ sourceGenerateSettings,+ route.sourceId === 'upscale' || route.sourceId === 'video' ? undefined : compiled.positivePrompts+ )+ : null;+ const effectivePrompts = submissionPlan?.effectivePrompts ?? null;+ const expandedPositivePrompts = submissionPlan?.submission.positivePrompts;// The draw the expansion used. Generate expands before dispatch, so the project's sample seed may have rotated// since; recall and rotation follow the expansion, not the project.const expansionSampleSeed = expandedPositivePrompts ? (compiled.positivePromptsSampleSeed ?? null) : null;// Compilation already reserved the starting seed; failures and cancellations do not roll the sequence back.- const seedPlan = sourceGenerateSettings- ? planSeedSubmission({- batchCount: sourceGenerateSettings.batchCount,- promptCount: expandedPositivePrompts?.length ?? 1,- seedBehaviour: expandedSeedBehaviour ?? 'per-iteration',- seedMode: sourceGenerateSettings.seedMode,- startSeed: sourceGenerateSettings.seed,- })- : null;+ const seedPlan = submissionPlan?.seedPlan ?? null;const backendSubmission: QueueCompiledSubmission = !backendGraph? { error: `${route.sourceId} queue item is missing a compiled backend graph.`, kind: 'invalid' }: route.sourceId === 'workflow'@@ -3645,21 +3628,14 @@ const enqueueCompiledSnapshot = (// active workflow changes....(compiled.projectWorkflowId ? { projectWorkflowId: compiled.projectWorkflowId } : {}),}- : sourceGenerateSettings && effectivePrompts+ : submissionPlan? {- batchCount: sourceGenerateSettings.batchCount,+ ...submissionPlan.submission,graph: backendGraph,kind: 'generate',- // Disabling the negative prompt also suppresses the template's negative side.- negativePrompt: sourceGenerateSettings.negativePromptEnabled ? effectivePrompts.negativePrompt : '',negativePromptNodeId: generate?.negativePromptNodeId ?? 'negative_prompt',- positivePrompt: effectivePrompts.positivePrompt,positivePromptNodeId: generate?.positivePromptNodeId ?? 'positive_prompt',- ...(expandedPositivePrompts ? { positivePrompts: expandedPositivePrompts } : {}),- seed: sourceGenerateSettings.seed,- ...(expandedSeedBehaviour ? { seedBehaviour: expandedSeedBehaviour } : {}),seedNodeId: generate?.seedNodeId ?? 'seed',- seedStep: seedPlan?.step ?? 0,}: { error: `${route.sourceId} queue item is missing source submission metadata.`, kind: 'invalid' };// A workflow compiles every node's board in (Auto included), so its board-less results stay Uncategorized.diff --git a/scripts/family_e2e/__init__.py b/scripts/family_e2e/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/scripts/family_e2e/__main__.py b/scripts/family_e2e/__main__.pynew file mode 100644index 0000000000..e9fd859831--- /dev/null+++ b/scripts/family_e2e/__main__.py@@ -0,0 +1,291 @@+"""Command line of the family E2E tool: `python -m scripts.family_e2e <command>`.++See docs/src/content/docs/development/Guides/family-e2e.mdx.+"""++from __future__ import annotations++import argparse+import logging+import os+import signal+import sys+import time+from datetime import datetime, timezone+from pathlib import Path++from scripts.family_e2e.bundle import write_bundle+from scripts.family_e2e.detach import RUNNER_LOG, DetachError, spawn_runner+from scripts.family_e2e.gpu_memory import UnsupportedPlatformError+from scripts.family_e2e.graphs import ExportError+from scripts.family_e2e.manifest import Manifest, ManifestError, load_manifest+from scripts.family_e2e.metrics import MB+from scripts.family_e2e.records import RUN_INFO_FILE, load_records, load_run_info, run_id_profile, write_run_info+from scripts.family_e2e.references import AcceptError, accept+from scripts.family_e2e.report import write_report+from scripts.family_e2e.runner import (+ SERVER_ROLES,+ RunnerError,+ RunStopped,+ finish_run,+ gpu_lock,+ is_alive,+ kill_identified,+ load_run_manifest,+ new_run,+ open_gpu,+ preflight,+ read_heartbeat,+ remaining_steps,+ remove_scratch_roots,+ run,+ run_lock,+ wait_for_runner,+)+from scripts.family_e2e.server import ServerError++logger = logging.getLogger("family_e2e")+# Windows refuses to open heartbeat.json for a moment while the runner replaces it.+STOP_HEARTBEAT_WAIT_S = 1.0+STOP_HEARTBEAT_POLL_S = 0.02+EXPECTED_ERRORS = (+ ManifestError,+ RunnerError,+ ServerError,+ ExportError,+ AcceptError,+ DetachError,+ UnsupportedPlatformError,+ # load_records names the malformed line of a damaged records.jsonl.+ ValueError,+)+++class UsageError(ValueError):+ pass+++def _data_dir(run_dir: Path) -> Path:+ # <data_dir>/runs/<run_id>+ return run_dir.parent.parent+++def _resolve_run(arg: str | None, manifest_path: Path | None) -> Path:+ """A run directory, a run id of the manifest's data dir, or (no argument) the manifest profile's latest run."""+ if arg is not None and Path(arg).is_dir():+ return Path(arg).resolve()+ if manifest_path is None:+ raise UsageError("pass a run directory, or --manifest to look up run ids and the latest run")+ manifest = load_manifest(manifest_path)+ runs_dir = manifest.data_dir / "runs"+ if arg is not None:+ if not (runs_dir / arg / RUN_INFO_FILE).is_file():+ raise UsageError(f"no run {arg} in {runs_dir}")+ return runs_dir / arg+ runs = sorted(+ d.name+ for d in runs_dir.glob("*")+ if run_id_profile(d.name) == manifest.profile and (d / RUN_INFO_FILE).is_file()+ )+ if not runs:+ raise UsageError(f"no runs of profile {manifest.profile} in {runs_dir}")+ return runs_dir / runs[-1]+++def _check_startable(manifest: Manifest) -> None:+ gpu = open_gpu(manifest.gpu)+ with gpu_lock(gpu.adapter):+ preflight(manifest, gpu)+++def _print_started(run_dir: Path, pid: int) -> None:+ print(f"run {run_dir.name}")+ print(f"dir {run_dir}")+ print(f"runner pid {pid}, log {run_dir / RUNNER_LOG}")+ print(f"report {run_dir / 'report.html'} (when finished)")+ print(f"status python -m scripts.family_e2e status {run_dir}")+++def _start_runner(run_dir: Path) -> int:+ """Starts the runner in the background and returns its pid once it registered: from then on `stop` finds it."""+ previous = read_heartbeat(run_dir).get("runner")+ return int(wait_for_runner(run_dir, spawn_runner(run_dir), previous)[0])+++def cmd_start(args: argparse.Namespace) -> int:+ _check_startable(load_manifest(args.manifest))+ run_dir = new_run(args.manifest, args.family, args.case)+ _print_started(run_dir, _start_runner(run_dir))+ return 0+++def _interrupt(signum: int, frame: object) -> None:+ raise KeyboardInterrupt+++def cmd_run(args: argparse.Namespace) -> int:+ # A plain kill (SIGTERM) would end the runner without its cleanup, and on Linux the server, in a session of its+ # own, would keep running. As an interrupt it stops the server, removes the scratch root and marks the run stopped.+ signal.signal(signal.SIGTERM, _interrupt)+ try:+ return run(args.run_dir.resolve())+ except RunStopped as e:+ logger.info("%s", e)+ return 130+ except KeyboardInterrupt:+ return 130+ except Exception:+ logger.exception("the runner failed")+ return 2+++def cmd_resume(args: argparse.Namespace) -> int:+ run_dir = _resolve_run(args.run, args.manifest)+ if is_alive(read_heartbeat(run_dir).get("runner")):+ raise UsageError(f"the runner of {run_dir.name} is still running")+ _check_startable(load_run_manifest(load_run_info(run_dir)))+ with run_lock(run_dir):+ info = load_run_info(run_dir)+ write_run_info(run_dir, info.model_copy(update={"status": "running", "finished_at": None}))+ _print_started(run_dir, _start_runner(run_dir))+ return 0+++def cmd_status(args: argparse.Namespace) -> int:+ run_dir = _resolve_run(args.run, args.manifest)+ info = load_run_info(run_dir)+ records = load_records(run_dir)+ left = remaining_steps(info.plan, records)+ heartbeat = read_heartbeat(run_dir)+ alive = is_alive(heartbeat.get("runner"))+ print(f"run {info.run_id} ({info.status})")+ print(f"dir {run_dir}")+ print(f"progress {len(info.plan) - len(left)}/{len(info.plan)} steps final, {len(records)} records")+ print(f"invalid {sum(1 for r in records if r.invalid_reasons)} records with invalid reasons")+ print(f"errors {sum(1 for r in records if r.status != 'completed')} records not completed")+ if heartbeat:+ updated = datetime.fromisoformat(heartbeat["updated_at"])+ age = (datetime.now(timezone.utc) - updated).total_seconds()+ state = "alive" if alive else "gone"+ print(f"runner {state}, step: {heartbeat.get('step')}, heartbeat {age:.0f}s ago")+ print(f"log {run_dir / RUNNER_LOG}")+ if (run_dir / "report.html").is_file():+ print(f"report {run_dir / 'report.html'}")+ if info.status == "running" and not alive:+ print(f"the runner is gone; continue with: python -m scripts.family_e2e resume {run_dir}")+ return 0+++def cmd_stop(args: argparse.Namespace) -> int:+ run_dir = _resolve_run(args.run, args.manifest)+ # Marked before the heartbeat is read, under the run lock a runner registers under: a runner registered before is+ # in the heartbeat and is killed, one that registers after finds the run stopped and leaves it untouched.+ was_running = finish_run(run_dir, "stopped")+ heartbeat = read_heartbeat(run_dir)+ # A running run has a registered runner, so an empty read is most likely one that met the runner's replace.+ deadline = time.monotonic() + STOP_HEARTBEAT_WAIT_S+ while was_running and not heartbeat and time.monotonic() < deadline:+ time.sleep(STOP_HEARTBEAT_POLL_S)+ heartbeat = read_heartbeat(run_dir)+ # The runner first: it would otherwise notice its server dying and record a crash.+ for role in ("runner", *SERVER_ROLES):+ if kill_identified(heartbeat.get(role)):+ print(f"killed {role} (pid {int(heartbeat[role][0])}) and its descendants")+ info = load_run_info(run_dir)+ # Nothing of the run is alive any more, so its scratch roots are unused.+ for leftover in remove_scratch_roots(_data_dir(run_dir), info):+ print(f"could not remove {leftover}")+ print(f"{info.run_id} stopped; continue with: python -m scripts.family_e2e resume {run_dir}")+ return 0+++def cmd_accept(args: argparse.Namespace) -> int:+ run_dir = _resolve_run(args.run, args.manifest)+ for reference in accept(_data_dir(run_dir), run_dir, args.case or None):+ print(f"accepted {reference.case_key} from {reference.source_run_id}")+ return 0+++def cmd_report(args: argparse.Namespace) -> int:+ run_dir = _resolve_run(args.run, args.manifest)+ result = write_report(_data_dir(run_dir), run_dir)+ print(f"report {result.report_html}")+ print(f"summary {result.summary_md}")+ print(+ f"{result.failures} failures, {result.outliers} outliers, {result.invalid} invalid, "+ f"{result.changed} changed as expected, {result.baseline} baseline"+ )+ return 1 if result.failures else 0+++def cmd_bundle(args: argparse.Namespace) -> int:+ run_dir = _resolve_run(args.run, args.manifest)+ if is_alive(read_heartbeat(run_dir).get("runner")):+ raise UsageError(f"the runner of {run_dir.name} is still running; bundle the run once it finished or stopped")+ output = (args.output or run_dir / f"{run_dir.name}.zip").resolve()+ size = write_bundle(_data_dir(run_dir), run_dir, output, args.manifest)+ print(f"bundle {output}")+ print(f"size {size / MB:.1f} MB")+ return 0+++def _parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ prog="python -m scripts.family_e2e", description="End-to-end runs per model family."+ )+ commands = parser.add_subparsers(dest="command", required=True)++ start = commands.add_parser("start", help="create a run and start its runner in the background")+ start.add_argument("--manifest", type=Path, required=True)+ start.add_argument("--family", action="append", default=[], help="only this family (repeatable)")+ start.add_argument("--case", action="append", default=[], help="only this case id (repeatable)")+ start.set_defaults(handler=cmd_start)++ runner = commands.add_parser("run", help="run the remaining steps of a run in the foreground (what start launches)")+ runner.add_argument("--run-dir", type=Path, required=True)+ runner.add_argument("--log-file", type=Path, help="append stdout and stderr to this file")+ runner.set_defaults(handler=cmd_run)++ for name, handler, help_text in (+ ("resume", cmd_resume, "start the runner of a stopped or crashed run again"),+ ("status", cmd_status, "show progress and whether the runner is alive"),+ ("stop", cmd_stop, "kill the runner and its server"),+ ("accept", cmd_accept, "make a run's measured results the references of its profile"),+ ("report", cmd_report, "write report.html and summary.md of a run again"),+ ("bundle", cmd_bundle, "pack a run into a zip without this machine's paths, to attach elsewhere"),+ ):+ command = commands.add_parser(name, help=help_text)+ command.add_argument("run", nargs="?", help="run directory or run id; default: the profile's latest run")+ command.add_argument("--manifest", type=Path, help="resolves run ids and the latest run")+ if name == "accept":+ command.add_argument("--case", action="append", default=[], help="only this case key (repeatable)")+ if name == "bundle":+ command.add_argument("--output", type=Path, help="the zip to write; default: <run dir>/<run id>.zip")+ command.set_defaults(handler=handler)+ return parser+++def _redirect_stdio(path: Path) -> None:+ # A background runner has no usable stdio; tracebacks of a crash must land in its log too.+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND)+ os.dup2(fd, 1)+ os.dup2(fd, 2)+ os.close(fd)+ sys.stdout = open(1, "w", encoding="utf-8", buffering=1, closefd=False)+ sys.stderr = open(2, "w", encoding="utf-8", buffering=1, closefd=False)+++def main(argv: list[str] | None = None) -> int:+ args = _parser().parse_args(argv)+ if getattr(args, "log_file", None):+ _redirect_stdio(args.log_file)+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s", stream=sys.stderr)+ try:+ return args.handler(args)+ except (UsageError, *EXPECTED_ERRORS) as e:+ print(f"error: {e}", file=sys.stderr)+ return 2+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/family_e2e/bundle.py b/scripts/family_e2e/bundle.pynew file mode 100644index 0000000000..7846117ac3--- /dev/null+++ b/scripts/family_e2e/bundle.py@@ -0,0 +1,410 @@+"""A run as one zip to attach elsewhere: report, summary, run data, graphs and traces, without this machine's paths.++The run directory stays as it is, apart from the default zip. The report and summary are rendered for the zip. Every+image they show is copied in with its pixels unchanged and its metadata removed, so a recipient can recompute PSNR.+Logs, the heartbeat, inputs and images the report does not show stay out. `Sanitizer` says what is removed from the+rest. `bundle.json` tells a reader, e.g. an upload hub, the zip's format version.+"""++from __future__ import annotations++import json+import os+import re+import tempfile+import urllib.parse+import zipfile+from collections.abc import Iterable+from pathlib import Path, PureWindowsPath+from typing import Any, NamedTuple++from scripts.family_e2e.graphs import (+ EXPORT_REQUEST_FILE,+ is_public_host,+ is_public_url,+ model_identifiers,+ shareable_source,+)+from scripts.family_e2e.manifest import ManifestError, load_manifest+from scripts.family_e2e.records import (+ RECORDS_FILE,+ RUN_INFO_FILE,+ Environment,+ Record,+ Reference,+ RunInfo,+ load_records,+ load_run_info,+)+from scripts.family_e2e.references import REFERENCE_FILE, load_reference+from scripts.family_e2e.report import DIFF_DIR, REPORT_FILE, SUMMARY_FILE, previous_runs, render_report+from scripts.family_e2e.runner import EXPORT_DIR, now_iso++BUNDLE_FILE = "bundle.json"+FORMAT_VERSION = 2+"""The layout of the zip and its files; a reader refuses a version it does not know. 2: the CHANGED and BASELINE+case statuses."""+GRAPHS_DIR = "graphs"+TRACES_DIR = "traces"+REFERENCE_DIR = "reference"+"""Per case key, the accepted reference's image.png and reference.json."""+REDACTED = "<redacted>"+PROCESS = "<process>"+INTERRUPTED = "interrupted"+"""How the bundle names a run that run.json calls running: its runner is gone without recording it."""+# Where a model lives on this machine, and the verbatim answer of the API it was installed from.+LOCAL_MODEL_FIELDS = ("path", "config_path", "source_api_response")+# Names of settings and environment variables that hold credentials. The server masks the settings it knows, by+# convention only, and code_dir may be an older checkout.+CREDENTIAL_NAME = re.compile(r"token|secret|key|auth|credential|pass|api|proxy|db_url", re.IGNORECASE)+# A shorter credential would match all over the text, e.g. HF_HUB_DISABLE_IMPLICIT_TOKEN=1.+MIN_SECRET_LENGTH = 8+# The rest of a path in free text, up to the next whitespace or quote.+_PATH_TAIL = r"[^\s\"'<>|*?]*"+DRIVE_PATH = re.compile(r"(?<![A-Za-z0-9])[A-Za-z]:[\\/]" + _PATH_TAIL)+# An absolute POSIX path of two or more components. Not after a word character, `.`, `:`, `/`, `~`, `-` or `>`: that+# leaves URL paths, relative paths, ratios such as MiB/s and the rest of a path after a placeholder alone. Nor the+# server's API and socket paths, which the tool's own errors quote (`GET /api/v1/... -> 404`).+POSIX_PATH = re.compile(r"(?<![\w.:/~>-])/(?!(?:api|ws)/)(?:[^\s/\"'<>|*?]+/)+" + _PATH_TAIL)+URL = re.compile(r"https?://[^\s\"'<>]+", re.IGNORECASE)+PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"+# The chunks that make up an image's pixels and colours; every other chunk is metadata. InvokeAI writes the+# generation's metadata and graph into tEXt chunks, with model configs and their paths.+PNG_IMAGE_CHUNKS = frozenset(+ {+ b"IHDR",+ b"PLTE",+ b"IDAT",+ b"IEND",+ b"tRNS",+ b"gAMA",+ b"cHRM",+ b"sRGB",+ b"iCCP",+ b"sBIT",+ b"cICP",+ b"mDCv",+ b"cLLi",+ }+)+++class Root(NamedTuple):+ """A directory of this machine whose paths become `placeholder` in a bundle."""++ placeholder: str+ path: str+ keep_subpath: bool+ """Below the tool's own directories the rest of a path names nothing private; below home it can."""+++class Sanitizer:+ """Removes this machine's paths, credentials and process names from what goes into a bundle.++ `env` holds (name, value) pairs: one name can come with several values, e.g. a token rotated between the run+ and its reference. `text` applies, in this order: each value of a credential-named variable in `env` becomes+ `<VARIABLE>`; an http(s)+ URL loses its credentials, `;params`, query and fragment, and a host of the local network becomes `<local host>`;+ a path below a root becomes the root's placeholder,+ followed by the rest of the path, or by its last component only where the root does not keep subpaths (either+ separator, doubled backslashes and any case match); any other absolute drive path, and any other absolute POSIX+ path of two or more components except the server's `/api/` and `/ws/` paths, keeps only its last component.+ """++ def __init__(self, roots: list[Root], env: Iterable[tuple[str, str]]) -> None:+ placeholders: dict[str, str] = {}+ # Sorted, so a value under two names always gets the same one.+ for name, value in sorted(set(env)):+ if CREDENTIAL_NAME.search(name) and len(value) >= MIN_SECRET_LENGTH:+ placeholders.setdefault(value, f"<{name}>")+ # The longest first: a value that contains another goes whole.+ self._secrets = sorted(placeholders.items(), key=lambda item: -len(item[0]))+ self._roots: dict[str, Root] = {}+ for root in roots:+ key = _normalized(root.path)+ # A bare drive or "/" would swallow every path.+ if key.strip("/") and not re.fullmatch(r"[a-z]:", key):+ self._roots.setdefault(key, root)+ # The longest first, so the run directory wins over the data directory that holds it.+ alternatives = "|".join(_pattern(key) for key in sorted(self._roots, key=len, reverse=True))+ self._root_paths = (+ re.compile("(" + alternatives + r")(?![\w.-])([\\/]" + _PATH_TAIL + ")?", re.IGNORECASE)+ if self._roots+ else None+ )++ def text(self, value: str) -> str:+ for secret, placeholder in self._secrets:+ value = value.replace(secret, placeholder)+ value = URL.sub(lambda match: _strip_url(match.group()), value)+ if self._root_paths is not None:+ value = self._root_paths.sub(self._replace_root, value)+ value = DRIVE_PATH.sub(lambda match: _last_component(match.group()), value)+ return POSIX_PATH.sub(lambda match: _last_component(match.group()), value)++ def _replace_root(self, match: re.Match[str]) -> str:+ root = self._roots[_normalized(match[1])]+ tail = match[2] or ""+ if root.keep_subpath or not tail.strip("\\/"):+ return root.placeholder + tail+ return root.placeholder + tail[0] + _last_component(tail)++ def json(self, value: Any, whole_paths: bool = False) -> Any:+ """Every string through `text`; with `whole_paths`, a string that is an absolute path keeps its last component."""+ if isinstance(value, str):+ return _last_component(value) if whole_paths and _is_absolute(value) else self.text(value)+ if isinstance(value, list):+ return [self.json(item, whole_paths) for item in value]+ if isinstance(value, dict):+ return {key: self.json(item, whole_paths) for key, item in value.items()}+ return value++ def environment(self, environment: Environment) -> Environment:+ """Paths keep their last component; extra_env keeps only its names, runtime_config no credentials."""+ data = environment.model_dump(mode="json")+ data["extra_env"] = dict.fromkeys(data["extra_env"], REDACTED)+ runtime_config = data["runtime_config"]+ config = runtime_config.get("config", runtime_config)+ if isinstance(config, dict):+ for key, value in config.items():+ # Only a value can be a credential; flags such as log_tokenization stay.+ if value and isinstance(value, (str, list, dict)) and CREDENTIAL_NAME.search(key):+ config[key] = REDACTED+ # The tool and the server write every string here, so one that is an absolute path is a path.+ return Environment.model_validate(self.json(data, whole_paths=True))++ def run_info(self, info: RunInfo) -> RunInfo:+ data = self.json(info.model_dump(mode="json", exclude={"environments"}), whole_paths=True)+ data["environments"] = {arm: self.environment(env) for arm, env in info.environments.items()}+ return RunInfo.model_validate(data)++ def reference(self, reference: Reference) -> Reference:+ data = self.json(reference.model_dump(mode="json", exclude={"environment"}))+ data["environment"] = self.environment(reference.environment)+ return Reference.model_validate(data)++ def record(self, record: Record) -> Record:+ """The text rule; foreign GPU processes keep their pid and memory but not their names."""+ data = record.model_dump(mode="json")+ for process in data["memory"]["foreign"] if data["memory"] else []:+ if process["name"]:+ # The invalid reason quotes the process as `pid N (name)`.+ data["invalid_reasons"] = [+ reason.replace(f"({process['name']})", f"({PROCESS})") for reason in data["invalid_reasons"]+ ]+ process["name"] = PROCESS+ return Record.model_validate(self.json(data))++ def graph(self, batch: Any) -> Any:+ """Model configs lose LOCAL_MODEL_FIELDS, and their source and source URL unless anyone may see them.++ The run's graph hashes are of the graphs before this.+ """+ for config in list(model_identifiers(batch)):+ for name in LOCAL_MODEL_FIELDS:+ config.pop(name, None)+ if shareable_source(config) is None:+ config.pop("source", None)+ if not is_public_url(config.get("source_url")):+ config.pop("source_url", None)+ return self.json(batch)+++def _normalized(path: str) -> str:+ return re.sub(r"[\\/]+", "/", path).rstrip("/").lower()+++def _pattern(normalized: str) -> str:+ return r"[\\/]+".join(re.escape(part) for part in normalized.split("/"))+++def _is_absolute(value: str) -> bool:+ return PureWindowsPath(value).is_absolute() or value.startswith("/")+++def _last_component(path: str) -> str:+ return re.split(r"[\\/]+", path.rstrip("\\/"))[-1]+++def _parent(path: str) -> str:+ return "/".join(re.split(r"[\\/]+", path.rstrip("\\/"))[:-1])+++def _strip_url(url: str) -> str:+ try:+ parts = urllib.parse.urlsplit(url)+ host = parts.netloc.rpartition("@")[2] if is_public_host(parts.hostname) else "<local host>"+ except ValueError:+ return "<url>"+ return urllib.parse.urlunsplit((parts.scheme, host, parts.path.split(";")[0], "", ""))+++def _png_without_metadata(data: bytes) -> bytes:+ """Only the PNG_IMAGE_CHUNKS, byte for byte, so the decoded pixels and colours stay exactly the same."""+ if not data.startswith(PNG_SIGNATURE):+ raise ValueError("not a PNG file")+ kept, offset = [PNG_SIGNATURE], len(PNG_SIGNATURE)+ while offset + 8 <= len(data):+ kind = data[offset + 4 : offset + 8]+ end = offset + 12 + int.from_bytes(data[offset : offset + 4], "big")+ if end > len(data):+ break+ if kind in PNG_IMAGE_CHUNKS:+ kept.append(data[offset:end])+ if kind == b"IEND":+ return b"".join(kept)+ offset = end+ raise ValueError("the PNG ends before its IEND chunk")+++class _Links:+ """Names each image the report shows inside the zip: its path below the directory it comes from, plus a prefix."""++ def __init__(self, sources: list[tuple[Path, str]]) -> None:+ self._sources = sources+ self.files: dict[str, Path] = {}++ def href(self, path: Path) -> str:+ for directory, prefix in self._sources:+ if path.is_relative_to(directory):+ name = prefix + path.relative_to(directory).as_posix()+ self.files[name] = path+ return urllib.parse.quote(name)+ raise ValueError(f"the report shows {path}, which lies outside the directories a bundle takes images from")+++def _model_roots(run_dir: Path) -> list[Root]:+ """The local paths of the models in the run's graphs and in its exporter request, which lists every model.++ Exact paths cover a model path with spaces in an error message. Below a model's own path the rest stays; below+ the directory holding it, only the last component.+ """+ sources = sorted((run_dir / GRAPHS_DIR).glob("*.json"))+ request = run_dir / EXPORT_DIR / EXPORT_REQUEST_FILE+ if request.is_file():+ sources.append(request)+ roots = []+ for source in sources:+ for config in model_identifiers(json.loads(source.read_text(encoding="utf-8"))):+ fields = (+ ("path", "config_path", "source") if config.get("source_type") == "path" else ("path", "config_path")+ )+ for field in fields:+ value = config.get(field)+ if isinstance(value, str) and _is_absolute(value):+ roots.append(Root(f"<model {config.get('name') or config['key']}>", value, keep_subpath=True))+ roots.append(Root("<model dir>", _parent(value), keep_subpath=False))+ return roots+++def _references(data_dir: Path, info: RunInfo, case_keys: list[str]) -> dict[str, Reference]:+ """The accepted references of the run's cases, loaded as the report loads them; unreadable ones are left out."""+ references = {}+ for case_key in case_keys:+ try:+ loaded = load_reference(data_dir, info.profile, case_key)+ except (OSError, ValueError):+ continue+ if loaded is not None:+ references[case_key] = loaded[0]+ return references+++def _sanitizer(+ data_dir: Path, run_dir: Path, info: RunInfo, earlier: list[Environment], manifest_path: Path | None+) -> Sanitizer:+ """`earlier`: the environments of the references and previous runs the report compares with. They come from+ other runs, may hold other paths and credentials, and the report prints facts of them."""+ environments = [*info.environments.values(), *earlier]+ roots = [Root("<run_dir>", str(run_dir), True), Root("<data_dir>", str(data_dir), True)]+ roots += [Root("<code_dir>", environment.code_dir, True) for environment in environments]+ try:+ manifest = load_manifest(manifest_path or Path(info.manifest_path))+ except ManifestError:+ pass # the manifest is gone: its template root is caught as a drive path only+ else:+ roots.append(Root("<template_root>", str(manifest.server.template_root), True))+ roots.append(Root("<home>", str(Path.home()), False))+ env = [(name, value) for environment in environments for name, value in environment.extra_env.items()]+ return Sanitizer(roots + _model_roots(run_dir), env)+++def write_bundle(data_dir: Path, run_dir: Path, output: Path, manifest_path: Path | None = None) -> int:+ """Writes the bundle of the run to `output` and returns its size in bytes.++ The run's runner must be gone. `manifest_path` overrides the manifest recorded in run.json, whose template root+ is redacted too.+ """+ info = load_run_info(run_dir)+ run_records = load_records(run_dir)+ case_keys = list(dict.fromkeys([step.case_key for step in info.plan] + [record.case_key for record in run_records]))+ references = _references(data_dir, info, case_keys)+ earlier = [reference.environment for reference in references.values()]+ earlier += [env for run in previous_runs(data_dir, info, case_keys) for env in run.environments.values()]+ sanitizer = _sanitizer(data_dir, run_dir, info, earlier, manifest_path)+ bundled_info = sanitizer.run_info(info)+ records = [sanitizer.record(record) for record in run_records]+ with tempfile.TemporaryDirectory(prefix="family-e2e-bundle-") as staging:+ links = _Links(+ [+ (run_dir, ""),+ (Path(staging), ""),+ (data_dir / "references" / info.profile, f"{REFERENCE_DIR}/"),+ (data_dir / "runs", "previous/"),+ ]+ )+ report = render_report(+ data_dir,+ run_dir,+ bundled_info,+ records,+ diff_dir=Path(staging) / DIFF_DIR,+ href=links.href,+ scrubber=sanitizer,+ status=INTERRUPTED if info.status == "running" else None,+ )+ texts = {+ BUNDLE_FILE: json.dumps(+ {"format_version": FORMAT_VERSION, "tool_commit": info.tool_commit, "created_at": now_iso()}, indent=2+ ),+ REPORT_FILE: report.html,+ SUMMARY_FILE: report.summary,+ RUN_INFO_FILE: bundled_info.model_dump_json(indent=2),+ RECORDS_FILE: "".join(record.model_dump_json() + "\n" for record in records),+ }+ for path in sorted((run_dir / GRAPHS_DIR).glob("*.json")):+ graph = sanitizer.graph(json.loads(path.read_text(encoding="utf-8")))+ texts[f"{GRAPHS_DIR}/{path.name}"] = json.dumps(graph, indent=2)+ for case_key, reference in references.items():+ texts[f"{REFERENCE_DIR}/{case_key}/{REFERENCE_FILE}"] = sanitizer.reference(reference).model_dump_json(+ indent=2+ )+ files = {f"{TRACES_DIR}/{path.name}": path for path in sorted((run_dir / TRACES_DIR).glob("*.csv.gz"))}+ _write_zip(output, info.run_id, texts, links.files | files)+ return output.stat().st_size+++def _write_zip(output: Path, folder: str, texts: dict[str, str], files: dict[str, Path]) -> None:+ """Writes the zip, its members under `folder/`, beside `output` first: a failure leaves no partial bundle.++ `files` are compressed already (PNG, gzip) and are stored as they are, PNGs without their metadata.+ """+ output.parent.mkdir(parents=True, exist_ok=True)+ fd, tmp_name = tempfile.mkstemp(dir=output.parent, prefix=f".{output.name}.", suffix=".tmp")+ os.close(fd)+ tmp = Path(tmp_name)+ try:+ with zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED) as archive:+ for name, text in texts.items():+ archive.writestr(f"{folder}/{name}", text)+ for name, path in files.items():+ data = path.read_bytes()+ if name.endswith(".png"):+ try:+ data = _png_without_metadata(data)+ except ValueError as e:+ raise ValueError(f"cannot bundle {name}: {e}") from None+ archive.writestr(f"{folder}/{name}", data, zipfile.ZIP_STORED)+ os.replace(tmp, output)+ finally:+ tmp.unlink(missing_ok=True)diff --git a/scripts/family_e2e/client.py b/scripts/family_e2e/client.pynew file mode 100644index 0000000000..ed5949c1f1--- /dev/null+++ b/scripts/family_e2e/client.py@@ -0,0 +1,303 @@+"""HTTP and socket.io client for the server under test, and the run timing built from its events.++This process must never import torch: a CUDA context here would land on the GPU being measured. Socket events are+stamped on arrival with `time.perf_counter()`, the clock of the memory sampler; the server's own event timestamps+have whole-second resolution, and `time.monotonic()` ticks only every 15.6 ms on Windows.+"""++from __future__ import annotations++import mimetypes+import threading+import time+from collections import defaultdict, deque+from collections.abc import Callable+from dataclasses import dataclass+from pathlib import Path+from typing import Any++import requests+import socketio++from scripts.family_e2e.records import ModelLoad, NodeTiming, Timing++QUEUE_ID = "default"+SOCKETIO_PATH = "/ws/socket.io"+REQUEST_TIMEOUT_S = 120.0+# While waiting for a queue item, its status is also polled, in case a socket event was lost.+POLL_S = 2.0+EVENT_GRACE_S = 1.0+TERMINAL_STATUSES = ("completed", "failed", "canceled")+EVENT_NAMES = (+ "invocation_started",+ "invocation_progress",+ "invocation_complete",+ "invocation_error",+ "queue_item_status_changed",+ "model_load_started",+ "model_load_complete",+)+# Upper bound for the step count inferred from progress percentages.+MAX_INFERRED_STEPS = 1000+# The server drops an image-bearing progress frame sent sooner than this after the previous one+# (invokeai/app/services/progress_previews/progress_previews_default.py).+PREVIEW_INTERVAL_S = 0.1+++class ApiError(RuntimeError):+ pass+++class InvokeClient:+ def __init__(self, base_url: str) -> None:+ self.base_url = base_url.rstrip("/")+ self._http = requests.Session()++ def _request(self, method: str, path: str, **kwargs: Any) -> requests.Response:+ response = self._http.request(method, self.base_url + path, timeout=REQUEST_TIMEOUT_S, **kwargs)+ if response.status_code >= 400:+ raise ApiError(f"{method} {path} -> {response.status_code}: {response.text[:2000]}")+ return response++ def get(self, path: str, **params: Any) -> Any:+ return self._request("GET", path, params=params or None).json()++ def post(self, path: str, body: Any = None) -> Any:+ return self._request("POST", path, json=body).json()++ def image_bytes(self, image_name: str) -> bytes:+ return self._request("GET", f"/api/v1/images/i/{image_name}/full").content++ def upload_image(self, path: Path) -> str:+ content_type = mimetypes.guess_type(path.name)[0] or "image/png"+ with path.open("rb") as f:+ dto = self._request(+ "POST",+ "/api/v1/images/upload",+ params={"image_category": "user", "is_intermediate": "true"},+ files={"file": (path.name, f, content_type)},+ ).json()+ return dto["image_name"]++ def enqueue(self, batch: dict[str, Any]) -> int:+ result = self.post(f"/api/v1/queue/{QUEUE_ID}/enqueue_batch", {"batch": batch, "prepend": False})+ if len(result["item_ids"]) != 1:+ raise ApiError(f"expected one queue item from the batch, got {len(result['item_ids'])}")+ return result["item_ids"][0]++ def queue_item(self, item_id: int) -> dict[str, Any]:+ return self.get(f"/api/v1/queue/{QUEUE_ID}/i/{item_id}")++ def queue_busy(self) -> bool:+ queue = self.get(f"/api/v1/queue/{QUEUE_ID}/status")["queue"]+ return queue["pending"] + queue["in_progress"] > 0++ def cancel(self, item_id: int) -> None:+ self._request("PUT", f"/api/v1/queue/{QUEUE_ID}/i/{item_id}/cancel")+++@dataclass(frozen=True)+class Event:+ name: str+ t: float+ """`time.perf_counter()` at arrival."""+ data: dict[str, Any]+++class EventRecorder:+ """Records the queue and model-load events of a server from connect to close."""++ def __init__(self, base_url: str) -> None:+ self._base_url = base_url+ # Polling only: websocket-client is not installed, and polling delivers within a few ms on localhost.+ self._sio = socketio.Client(reconnection=True)+ self._events: list[Event] = []+ self._changed = threading.Condition()+ self._sio.on("connect", self._subscribe)+ for name in EVENT_NAMES:+ self._sio.on(name, self._handler(name))++ def _subscribe(self) -> None:+ # Also runs after a reconnect, which starts a new socket without room memberships.+ self._sio.emit("subscribe_queue", {"queue_id": QUEUE_ID})++ def _handler(self, name: str) -> Callable[[dict[str, Any]], None]:+ def handle(data: dict[str, Any]) -> None:+ t = time.perf_counter()+ if name == "invocation_progress":+ # Preview images are large and only their presence matters (it marks denoise steps).+ data = {k: v for k, v in data.items() if k != "image"} | {"has_image": data.get("image") is not None}+ with self._changed:+ self._events.append(Event(name, t, data))+ self._changed.notify_all()++ return handle++ def connect(self) -> None:+ self._sio.connect(self._base_url, socketio_path=SOCKETIO_PATH, transports=["polling"], wait_timeout=30)+ # The connect handler's emit is not acknowledged; this call returns once the server joined the rooms.+ self._sio.call("subscribe_queue", {"queue_id": QUEUE_ID}, timeout=30)++ def close(self) -> None:+ self._sio.disconnect()++ def mark(self) -> int:+ with self._changed:+ return len(self._events)++ def since(self, mark: int) -> list[Event]:+ with self._changed:+ return self._events[mark:]++ def wait(self, timeout: float) -> None:+ with self._changed:+ self._changed.wait(timeout)+++def wait_for_item(+ client: InvokeClient,+ recorder: EventRecorder,+ mark: int,+ item_id: int,+ timeout: float,+ tick: Callable[[], None],+) -> tuple[dict[str, Any], float]:+ """Waits for the item to finish. Returns the item and the `perf_counter` time it finished.++ The finish time is the last arrival among the item's events once its terminal status event is in. A poll that+ sees the item finished first waits EVENT_GRACE_S for that event, because the poll can overtake the events still+ in transit; without it, the poll time stands in. `tick` runs before every check, at least every POLL_S seconds,+ and may raise to abort the wait. Raises TimeoutError.+ """+ deadline = time.perf_counter() + timeout+ next_poll = time.perf_counter() + POLL_S+ polled: tuple[dict[str, Any], float] | None = None+ while True:+ tick()+ own = _item_events(recorder.since(mark), item_id)+ latest = max((e.t for e in own), default=0.0)+ if any(e.name == "queue_item_status_changed" and e.data.get("status") in TERMINAL_STATUSES for e in own):+ return client.queue_item(item_id), latest+ now = time.perf_counter()+ if polled is not None and now - polled[1] >= EVENT_GRACE_S:+ return polled[0], max(polled[1], latest)+ if polled is None and now >= next_poll:+ item = client.queue_item(item_id)+ if item["status"] in TERMINAL_STATUSES:+ polled = (item, now)+ next_poll = now + POLL_S+ if now >= deadline:+ raise TimeoutError(f"queue item {item_id} did not finish within {timeout:.0f}s")+ recorder.wait(min(POLL_S, EVENT_GRACE_S, max(0.0, deadline - now)))+++def wait_for_idle_queue(client: InvokeClient, timeout: float, tick: Callable[[], None]) -> bool:+ """Waits until the queue has nothing pending or in progress; False if it is still busy after `timeout`."""+ deadline = time.perf_counter() + timeout+ while True:+ tick()+ if not client.queue_busy():+ return True+ if time.perf_counter() >= deadline:+ return False+ time.sleep(POLL_S)+++def _item_events(events: list[Event], item_id: int) -> list[Event]:+ return [e for e in events if e.data.get("item_id") == item_id]+++def per_step_seconds(progress: list[tuple[float, float]], expected_steps: int | None = None) -> float | None:+ """Seconds per denoise step from (arrival time, percentage) pairs of one denoise node.++ Image-bearing progress frames are throttled server-side and the throttled steps emit nothing, so each frame's+ step comes from its percentage (k / N); the slope over the first and last frame then needs no frame in between.+ N is `expected_steps` (a run over the full schedule) when every percentage fits it. Otherwise it is the smallest+ count every percentage fits, which may be a divisor of the real one when only every other step left a frame; a+ step slower than two throttle intervals rules that out, and a faster one gives None.+ """+ if len(progress) < 2:+ return None++ def fits(n: int) -> bool:+ return all(abs(p * n - round(p * n)) < 1e-6 for _, p in progress)++ trusted = expected_steps is not None and fits(expected_steps)+ steps = expected_steps if trusted else next((n for n in range(1, MAX_INFERRED_STEPS + 1) if fits(n)), None)+ if steps is None:+ return None+ (t_first, p_first), (t_last, p_last) = progress[0], progress[-1]+ k_first, k_last = round(p_first * steps), round(p_last * steps)+ if k_last <= k_first:+ return None+ seconds = (t_last - t_first) / (k_last - k_first)+ if not trusted and seconds < 2 * PREVIEW_INTERVAL_S:+ return None+ return seconds+++def build_timing(+ events: list[Event],+ item_id: int,+ t_enqueue: float,+ t_done: float,+ item: dict[str, Any],+ expected_steps: int | None = None,+) -> Timing:+ """Run timing from the recorded events; every `t_*` is relative to the enqueue instant.++ `expected_steps` is the denoise step count when the run covers the whole schedule (not img2img).+ """+ # The socket client runs every handler on its own thread, so the list order can differ from the arrival order.+ events = sorted(events, key=lambda e: e.t)+ own = _item_events(events, item_id)+ starts: dict[str, tuple[str, str, float]] = {}+ ends: dict[str, float] = {}+ progress: dict[str, list[tuple[float, float]]] = defaultdict(list)+ for event in own:+ invocation = event.data.get("invocation") or {}+ prepared_id = invocation.get("id")+ if prepared_id is None:+ continue+ if event.name == "invocation_started":+ starts[prepared_id] = (event.data["invocation_source_id"], invocation.get("type", ""), event.t)+ elif event.name in ("invocation_complete", "invocation_error"):+ ends[prepared_id] = event.t+ elif event.name == "invocation_progress" and event.data.get("has_image"):+ percentage = event.data.get("percentage")+ if percentage is not None:+ progress[prepared_id].append((event.t, percentage))++ nodes = [+ NodeTiming(+ node_id=source_id,+ type=node_type,+ t_start=t - t_enqueue,+ t_end=ends[prepared_id] - t_enqueue if prepared_id in ends else None,+ )+ for prepared_id, (source_id, node_type, t) in sorted(starts.items(), key=lambda kv: kv[1][2])+ ]++ # Model load events carry no queue item; within the run's window they belong to it.+ pending: dict[tuple[str, str | None], deque[int]] = defaultdict(deque)+ loads: list[dict[str, Any]] = []+ for event in events:+ if event.name not in ("model_load_started", "model_load_complete") or not t_enqueue <= event.t <= t_done:+ continue+ key = ((event.data.get("config") or {}).get("key", ""), event.data.get("submodel_type"))+ if event.name == "model_load_started":+ pending[key].append(len(loads))+ loads.append({"model": key[0], "submodel": key[1], "t_start": event.t - t_enqueue, "t_end": None})+ elif pending[key]:+ loads[pending[key].popleft()]["t_end"] = event.t - t_enqueue++ # The denoise node is the one with the most preview frames.+ denoise = max(progress.values(), key=len, default=[])+ return Timing(+ total_s=t_done - t_enqueue,+ nodes=nodes,+ model_loads=[ModelLoad(**load) for load in loads],+ per_step_s=per_step_seconds(denoise, expected_steps),+ queue_started_at=item.get("started_at"),+ queue_completed_at=item.get("completed_at"),+ )diff --git a/scripts/family_e2e/detach.py b/scripts/family_e2e/detach.pynew file mode 100644index 0000000000..8b827a3fcd--- /dev/null+++ b/scripts/family_e2e/detach.py@@ -0,0 +1,78 @@+"""Starting the runner as a background process that outlives the caller.++On Windows the runner breaks away from the caller's job object, so a caller that kills its job's processes (an agent+harness does after two hours) cannot take a long run with it. Where the job forbids breakaway, the runner is created+through WMI instead, which puts it in no job of the caller; such a process starts with the user's default+environment, not the caller's.+"""++from __future__ import annotations++import os+import subprocess+import sys+from pathlib import Path++from scripts.family_e2e.manifest import TOOL_CHECKOUT++RUNNER_LOG = "runner.log"+WMI_TIMEOUT_S = 120++# Hidden window: WMI shows a console program's window otherwise.+_WMI_CREATE = (+ "$startup = New-CimInstance -ClassName Win32_ProcessStartup -ClientOnly -Property @{ShowWindow=[uint16]0}; "+ "$r = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{"+ "CommandLine=$env:FAMILY_E2E_COMMAND; CurrentDirectory=$env:FAMILY_E2E_CWD; ProcessStartupInformation=$startup}; "+ "if ($r.ReturnValue -ne 0) { [Console]::Error.WriteLine('Win32_Process.Create returned ' + $r.ReturnValue); exit 1 }; "+ "$r.ProcessId"+)+++class DetachError(RuntimeError):+ pass+++def runner_command(run_dir: Path) -> list[str]:+ return [+ sys.executable,+ "-X",+ "utf8",+ "-m",+ "scripts.family_e2e",+ "run",+ "--run-dir",+ str(run_dir),+ "--log-file",+ str(run_dir / RUNNER_LOG),+ ]+++def spawn_runner(run_dir: Path) -> int:+ """Starts the runner for `run_dir` in the background and returns the started process's pid."""+ args = runner_command(run_dir)+ stdio = {"stdin": subprocess.DEVNULL, "stdout": subprocess.DEVNULL, "stderr": subprocess.DEVNULL}+ if sys.platform != "win32":+ return subprocess.Popen(args, cwd=TOOL_CHECKOUT, start_new_session=True, **stdio).pid+ # CREATE_NO_WINDOW, not DETACHED_PROCESS: a venv's python.exe is a launcher, and under DETACHED_PROCESS the+ # interpreter it starts gets a new visible console, which the server and every tool call would then share.+ flags = subprocess.CREATE_NO_WINDOW | subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.CREATE_BREAKAWAY_FROM_JOB+ try:+ return subprocess.Popen(args, cwd=TOOL_CHECKOUT, creationflags=flags, close_fds=True, **stdio).pid+ except OSError:+ return _spawn_via_wmi(args)+++def _spawn_via_wmi(args: list[str]) -> int:+ # Passed through the environment, so neither PowerShell nor WMI has to parse quoting of their own.+ env = os.environ | {"FAMILY_E2E_COMMAND": subprocess.list2cmdline(args), "FAMILY_E2E_CWD": str(TOOL_CHECKOUT)}+ result = subprocess.run(+ ["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", _WMI_CREATE],+ env=env,+ capture_output=True,+ text=True,+ timeout=WMI_TIMEOUT_S,+ check=False,+ )+ if result.returncode != 0:+ raise DetachError(f"starting the runner through WMI failed:\n{result.stderr.strip()}")+ return int(result.stdout.strip().splitlines()[-1])diff --git a/scripts/family_e2e/gpu_memory.py b/scripts/family_e2e/gpu_memory.pynew file mode 100644index 0000000000..590647cd32--- /dev/null+++ b/scripts/family_e2e/gpu_memory.py@@ -0,0 +1,604 @@+"""Driver-level video memory of another process, sampled without a GPU context of our own.++The allocator's own figure (``torch.cuda.max_memory_allocated``) misses its pools and the cuDNN/MIOpen workspaces, so+the real peak runs 25-75 % above it. What the driver charges the process is what decides whether a card of a given size+copes, and Windows reports it per process and adapter through the WDDM kernel thunks: ``D3DKMTQueryVideoMemoryInfo``+on another process's handle answers in about a microsecond, so the dedicated (local segment) usage can be sampled every+few milliseconds. The bytes Windows has paged out to system memory are only visible in the ``GPU Process Memory``+performance counters (``Shared Usage``), read through PDH at a slower rate.++The client never imports torch: a CUDA/HIP context of its own would sit on the same adapter and distort what the+server can allocate. This module is the Windows (WDDM) implementation and covers NVIDIA and AMD/ROCm alike;+`nvml_memory` offers the same interface for NVIDIA GPUs on Linux and shares the types defined here.+"""++import bisect+import ctypes+import functools+import logging+import operator+import re+import sys+import threading+import time+from dataclasses import dataclass+from types import SimpleNamespace++_STATUS_SUCCESS = 0x00000000+# The target has no allocation context on the adapter: it never opened it, or has closed it again.+_STATUS_INVALID_PARAMETER = 0xC000000D+_STATUS_ACCESS_DENIED = 0xC0000022+# D3DKMTQueryVideoMemoryInfo answers STATUS_ACCESS_DENIED for PROCESS_QUERY_LIMITED_INFORMATION; it needs the full+# query right (measured on Windows 10 22H2 with an NVIDIA and an AMD driver).+_PROCESS_QUERY_INFORMATION = 0x0400+_STILL_ACTIVE = 259+_ERROR_ACCESS_DENIED = 5+_ERROR_INVALID_PARAMETER = 87++_KMTQAITYPE_ADAPTERREGISTRYINFO = 8+_KMTQAITYPE_ADAPTERTYPE = 15+# D3DKMT_KMD_DRIVER_VERSION: the kernel-mode driver's version, the one Device Manager shows.+_KMTQAITYPE_KMD_DRIVER_VERSION = 49+# D3DKMT_ADAPTERTYPE bits.+_ADAPTER_RENDER_SUPPORTED = 1 << 0+_ADAPTER_SOFTWARE_DEVICE = 1 << 2+_ADAPTER_COMPUTE_ONLY = 1 << 11+_MEMORY_SEGMENT_GROUP_LOCAL = 0+_MAX_PATH = 260++_PDH_FMT_LARGE = 0x00000400+_PDH_MORE_DATA = 0x800007D2+_PDH_NO_DATA = 0x800007D5+# PDH_CSTATUS_VALID_DATA and PDH_CSTATUS_NEW_DATA; any other status leaves `largeValue` undefined.+_PDH_VALID_DATA = (0x00000000, 0x00000001)+# English paths; PdhAddEnglishCounterW resolves them on a localized Windows too.+_PDH_DEDICATED_USAGE = r"\GPU Process Memory(*)\Dedicated Usage"+_PDH_SHARED_USAGE = r"\GPU Process Memory(*)\Shared Usage"+_PDH_INSTANCE = re.compile(r"pid_(\d+)_luid_0x([0-9a-f]{8})_0x([0-9a-f]{8})_phys_(\d+)", re.IGNORECASE)++_logger = logging.getLogger(__name__)++# Win32 types spelled as fixed-width ctypes, so this module imports on every platform.+_UINT = ctypes.c_uint32+_LONG = ctypes.c_int32+_NTSTATUS = ctypes.c_uint32+++class UnsupportedPlatformError(RuntimeError):+ """GPU memory sampling is not available here: not implemented for this operating system or GPU vendor, or the+ driver cannot attribute memory to processes."""+++@dataclass(frozen=True)+class Adapter:+ luid: int | None+ """``(HighPart << 32) | LowPart``, as D3DKMT and the PDH instance names spell it; ``None`` for an NVML device."""+ description: str+ driver_version: str | None = None+ """As Device Manager shows it, e.g. ``32.0.16.1047``, or NVML's ``580.95.05``; ``None`` when not reported."""+ uuid: str | None = None+ """NVML's device UUID, ``GPU-…``; ``None`` for a WDDM adapter. A hardware serial: never written to records."""++ def __post_init__(self) -> None:+ if (self.luid is None) == (self.uuid is None):+ raise ValueError(f"adapter {self.description!r} needs either a LUID (WDDM) or a UUID (NVML)")++ @property+ def key(self) -> str:+ """The adapter's identity as text: the LUID in hex, or the NVML UUID."""+ return f"{self.luid:x}" if self.luid is not None else str(self.uuid)+++@dataclass(frozen=True)+class ProcessUsage:+ dedicated_bytes: int+ shared_bytes: int+++@dataclass(frozen=True)+class MemoryTrace:+ """Samples of one process's usage on one adapter, stamped with the client's ``time.perf_counter()``.++ The trace is a sample-and-hold step function: a value stands from its timestamp until the next sample.+ """++ method: str+ interval_ms: float+ """Mean spacing of the dedicated samples; the configured interval while they span no measurable time."""+ dedicated: tuple[tuple[float, int], ...]+ """Bytes in video memory: local-segment ``CurrentUsage`` (method ``d3dkmt``) or ``usedGpuMemory`` (``nvml``)."""+ shared: tuple[tuple[float, int], ...]+ """PDH ``Shared Usage`` in bytes: what Windows keeps of this process's allocations in system memory. Empty for+ ``nvml``: the Linux driver does not page video memory out to system memory."""++ def peak(self, t0: float | None = None, t1: float | None = None) -> int | None:+ """The highest dedicated usage in ``[t0, t1]``: the value in effect at ``t0`` and every sample up to ``t1``.++ Counting the value in effect at ``t0`` keeps a window shorter than the sampling interval from coming back+ empty. ``None`` bounds are open; ``None`` is returned when no sample falls on or before ``t1``.+ """+ if t0 is not None and t1 is not None and t1 < t0:+ raise ValueError(f"window ends before it starts: [{t0}, {t1}]")+ samples = self.dedicated+ lo = 0+ if t0 is not None:+ lo = bisect.bisect_left(samples, t0, key=_sample_time)+ if lo > 0 and (lo == len(samples) or samples[lo][0] > t0):+ lo -= 1+ hi = len(samples) if t1 is None else bisect.bisect_right(samples, t1, key=_sample_time)+ return max((value for _, value in samples[lo:hi]), default=None)++ def at(self, t: float) -> int | None:+ """The dedicated usage in effect at ``t``: the last sample at or before it."""+ index = bisect.bisect_right(self.dedicated, t, key=_sample_time)+ return self.dedicated[index - 1][1] if index else None+++_sample_time = operator.itemgetter(0)+++class _Luid(ctypes.Structure):+ _fields_ = [("LowPart", _UINT), ("HighPart", _LONG)]+++class _AdapterInfo(ctypes.Structure):+ """``D3DKMT_ADAPTERINFO``."""++ _fields_ = [("hAdapter", _UINT), ("AdapterLuid", _Luid), ("NumOfSources", _UINT), ("bPrecise", _LONG)]+++class _EnumAdapters2(ctypes.Structure):+ """``D3DKMT_ENUMADAPTERS2``."""++ _fields_ = [("NumAdapters", _UINT), ("pAdapters", ctypes.POINTER(_AdapterInfo))]+++class _QueryAdapterInfo(ctypes.Structure):+ """``D3DKMT_QUERYADAPTERINFO``."""++ _fields_ = [("hAdapter", _UINT), ("Type", ctypes.c_int), ("pData", ctypes.c_void_p), ("DataSize", _UINT)]+++class _AdapterRegistryInfo(ctypes.Structure):+ """``D3DKMT_ADAPTERREGISTRYINFO``."""++ _fields_ = [+ ("AdapterString", ctypes.c_wchar * _MAX_PATH),+ ("BiosString", ctypes.c_wchar * _MAX_PATH),+ ("DacType", ctypes.c_wchar * _MAX_PATH),+ ("ChipType", ctypes.c_wchar * _MAX_PATH),+ ]+++class _OpenAdapterFromLuid(ctypes.Structure):+ """``D3DKMT_OPENADAPTERFROMLUID``."""++ _fields_ = [("AdapterLuid", _Luid), ("hAdapter", _UINT)]+++class _CloseAdapter(ctypes.Structure):+ """``D3DKMT_CLOSEADAPTER``."""++ _fields_ = [("hAdapter", _UINT)]+++class _QueryVideoMemoryInfo(ctypes.Structure):+ """``D3DKMT_QUERYVIDEOMEMORYINFO``. A null ``hProcess`` means the calling process."""++ _fields_ = [+ ("hProcess", ctypes.c_void_p),+ ("hAdapter", _UINT),+ ("MemorySegmentGroup", ctypes.c_int),+ ("Budget", ctypes.c_uint64),+ ("CurrentUsage", ctypes.c_uint64),+ ("CurrentReservation", ctypes.c_uint64),+ ("AvailableForReservation", ctypes.c_uint64),+ ("PhysicalAdapterIndex", _UINT),+ ]+++class _PdhCounterValue(ctypes.Structure):+ """``PDH_FMT_COUNTERVALUE`` read as ``PDH_FMT_LARGE``."""++ _fields_ = [("CStatus", ctypes.c_uint32), ("largeValue", ctypes.c_int64)]+++class _PdhCounterValueItem(ctypes.Structure):+ """``PDH_FMT_COUNTERVALUE_ITEM_W``."""++ _fields_ = [("szName", ctypes.c_wchar_p), ("FmtValue", _PdhCounterValue)]+++def _require_windows() -> None:+ if sys.platform != "win32":+ raise UnsupportedPlatformError(f"this sampler reads WDDM, which only Windows has, not {sys.platform}")+++def _win32() -> SimpleNamespace:+ """gdi32, kernel32 and pdh with the prototypes used here; loaded on first use, since only Windows has them."""+ gdi32 = ctypes.WinDLL("gdi32")+ for name in (+ "D3DKMTEnumAdapters2",+ "D3DKMTQueryAdapterInfo",+ "D3DKMTOpenAdapterFromLuid",+ "D3DKMTQueryVideoMemoryInfo",+ "D3DKMTCloseAdapter",+ ):+ fn = getattr(gdi32, name)+ fn.argtypes = [ctypes.c_void_p]+ fn.restype = _NTSTATUS++ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)+ kernel32.OpenProcess.argtypes = [ctypes.c_uint32, ctypes.c_int32, ctypes.c_uint32]+ kernel32.OpenProcess.restype = ctypes.c_void_p+ kernel32.GetExitCodeProcess.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_uint32)]+ kernel32.GetExitCodeProcess.restype = ctypes.c_int32+ kernel32.CloseHandle.argtypes = [ctypes.c_void_p]+ kernel32.CloseHandle.restype = ctypes.c_int32++ pdh = ctypes.WinDLL("pdh")+ prototypes = {+ "PdhOpenQueryW": [ctypes.c_wchar_p, ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p)],+ "PdhAddEnglishCounterW": [ctypes.c_void_p, ctypes.c_wchar_p, ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p)],+ "PdhCollectQueryData": [ctypes.c_void_p],+ "PdhGetFormattedCounterArrayW": [+ ctypes.c_void_p,+ ctypes.c_uint32,+ ctypes.POINTER(ctypes.c_uint32),+ ctypes.POINTER(ctypes.c_uint32),+ ctypes.c_void_p,+ ],+ "PdhCloseQuery": [ctypes.c_void_p],+ }+ for name, argtypes in prototypes.items():+ fn = getattr(pdh, name)+ fn.argtypes = argtypes+ fn.restype = ctypes.c_uint32+ return SimpleNamespace(gdi32=gdi32, kernel32=kernel32, pdh=pdh)+++def _check(status: int, call: str) -> None:+ if status != _STATUS_SUCCESS:+ raise OSError(f"{call} failed with status {status:#010x}")+++def _luid_value(luid: _Luid) -> int:+ return ((luid.HighPart & 0xFFFFFFFF) << 32) | luid.LowPart+++def _luid_struct(value: int) -> _Luid:+ return _Luid(value & 0xFFFFFFFF, value >> 32)+++def _query_adapter_info(handle: int, info_type: int, data: ctypes.Structure | ctypes.c_uint32 | ctypes.c_uint64) -> int:+ query = _QueryAdapterInfo(handle, info_type, ctypes.cast(ctypes.byref(data), ctypes.c_void_p), ctypes.sizeof(data))+ return _win32().gdi32.D3DKMTQueryAdapterInfo(ctypes.byref(query))+++def _describe(info: _AdapterInfo) -> Adapter | None:+ """The adapter, or ``None`` for one that cannot hold a compute process's memory or cannot be named."""+ adapter_type = _UINT()+ if _query_adapter_info(info.hAdapter, _KMTQAITYPE_ADAPTERTYPE, adapter_type) != _STATUS_SUCCESS:+ return None+ # The Microsoft Basic Render Driver is a software device; display-only adapters (indirect displays) run nothing.+ if adapter_type.value & _ADAPTER_SOFTWARE_DEVICE:+ return None+ if not adapter_type.value & (_ADAPTER_RENDER_SUPPORTED | _ADAPTER_COMPUTE_ONLY):+ return None+ registry = _AdapterRegistryInfo()+ if _query_adapter_info(info.hAdapter, _KMTQAITYPE_ADAPTERREGISTRYINFO, registry) != _STATUS_SUCCESS:+ return None+ version = ctypes.c_uint64()+ status = _query_adapter_info(info.hAdapter, _KMTQAITYPE_KMD_DRIVER_VERSION, version)+ return Adapter(+ luid=_luid_value(info.AdapterLuid),+ description=registry.AdapterString,+ driver_version=_format_driver_version(version.value) if status == _STATUS_SUCCESS else None,+ )+++def _format_driver_version(packed: int) -> str | None:+ """A driver version packed as four 16-bit fields, most significant first, in dotted form; 0 is unknown."""+ if not packed:+ return None+ return ".".join(str(packed >> shift & 0xFFFF) for shift in (48, 32, 16, 0))+++def list_adapters() -> list[Adapter]:+ """The hardware GPU adapters, in the order the kernel enumerates them."""+ _require_windows()+ gdi32 = _win32().gdi32+ # A null array asks for the size: the call answers the most adapters it could return.+ enum = _EnumAdapters2(0, None)+ _check(gdi32.D3DKMTEnumAdapters2(ctypes.byref(enum)), "D3DKMTEnumAdapters2")+ infos = (_AdapterInfo * enum.NumAdapters)()+ enum.pAdapters = infos+ _check(gdi32.D3DKMTEnumAdapters2(ctypes.byref(enum)), "D3DKMTEnumAdapters2")+ opened = infos[: enum.NumAdapters]+ try:+ return [adapter for adapter in map(_describe, opened) if adapter is not None]+ finally:+ for info in opened:+ gdi32.D3DKMTCloseAdapter(ctypes.byref(_CloseAdapter(info.hAdapter)))+++def _select_adapter(+ adapters: list[Adapter],+ description_substring: str,+ no_match_hint: str | None = None,+ several_hint: str | None = None,+) -> Adapter:+ """The one adapter whose description contains the substring. The error lists every adapter with its LUID or UUID,+ followed by ``no_match_hint`` when none matches and ``several_hint`` when several do."""+ needle = description_substring.casefold()+ matches = [adapter for adapter in adapters if needle in adapter.description.casefold()]+ if len(matches) == 1:+ return matches[0]+ available = "; ".join(f"{adapter.description} ({_identity(adapter)})" for adapter in adapters) or "none"+ found = "No adapter matches" if not matches else f"{len(matches)} adapters match"+ hint = several_hint if matches else no_match_hint+ raise LookupError(f"{found} {description_substring!r}. Adapters: {available}" + (f". {hint}" if hint else ""))+++def _identity(adapter: Adapter) -> str:+ return f"LUID {adapter.luid:#x}" if adapter.luid is not None else str(adapter.uuid)+++def find_adapter(description_substring: str) -> Adapter:+ """The one adapter whose description contains the substring, ignoring case. ``LookupError`` for none or several."""+ return _select_adapter(list_adapters(), description_substring)+++def _parse_instance(name: str) -> tuple[int, int] | None:+ """``(pid, luid)`` of a ``GPU Process Memory`` instance on physical adapter 0, else ``None``."""+ match = _PDH_INSTANCE.fullmatch(name)+ if match is None or match[4] != "0":+ return None+ return int(match[1]), (int(match[2], 16) << 32) | int(match[3], 16)+++class _GpuProcessMemoryCounters:+ """One PDH query over every process's ``GPU Process Memory`` instances.++ Only the first query in a process is slow to open (about 0.35 s while PDH loads the provider); a collection costs+ well under a millisecond.+ """++ def __init__(self) -> None:+ pdh = _win32().pdh+ self._query = ctypes.c_void_p()+ _check(pdh.PdhOpenQueryW(None, None, ctypes.byref(self._query)), "PdhOpenQueryW")+ try:+ self._dedicated = self._add(_PDH_DEDICATED_USAGE)+ self._shared = self._add(_PDH_SHARED_USAGE)+ except BaseException:+ self.close()+ raise++ def _add(self, path: str) -> ctypes.c_void_p:+ counter = ctypes.c_void_p()+ status = _win32().pdh.PdhAddEnglishCounterW(self._query, path, None, ctypes.byref(counter))+ _check(status, f"PdhAddEnglishCounterW({path})")+ return counter++ def collect(self) -> dict[tuple[int, int], ProcessUsage]:+ """Usage keyed by ``(pid, luid)``, for every process that has opened an adapter."""+ status = _win32().pdh.PdhCollectQueryData(self._query)+ if status == _PDH_NO_DATA:+ return {}+ _check(status, "PdhCollectQueryData")+ dedicated = self._values(self._dedicated)+ shared = self._values(self._shared)+ return {+ key: ProcessUsage(dedicated.get(key, 0), shared.get(key, 0)) for key in dedicated.keys() | shared.keys()+ }++ def _values(self, counter: ctypes.c_void_p) -> dict[tuple[int, int], int]:+ pdh = _win32().pdh+ size, count = ctypes.c_uint32(0), ctypes.c_uint32(0)+ status = pdh.PdhGetFormattedCounterArrayW(+ counter, _PDH_FMT_LARGE, ctypes.byref(size), ctypes.byref(count), None+ )+ if status == _STATUS_SUCCESS:+ return {}+ if status != _PDH_MORE_DATA:+ _check(status, "PdhGetFormattedCounterArrayW")+ buffer = (ctypes.c_byte * size.value)()+ status = pdh.PdhGetFormattedCounterArrayW(+ counter, _PDH_FMT_LARGE, ctypes.byref(size), ctypes.byref(count), buffer+ )+ _check(status, "PdhGetFormattedCounterArrayW")+ items = ctypes.cast(buffer, ctypes.POINTER(_PdhCounterValueItem))+ values: dict[tuple[int, int], int] = {}+ for item in items[: count.value]:+ key = _parse_instance(item.szName or "")+ if key is not None and item.FmtValue.CStatus in _PDH_VALID_DATA:+ values[key] = int(item.FmtValue.largeValue)+ return values++ def close(self) -> None:+ if self._query:+ _win32().pdh.PdhCloseQuery(self._query)+ self._query = ctypes.c_void_p()+++def process_usage_on_adapter(adapter: Adapter) -> dict[int, ProcessUsage]:+ """Every process that has opened the adapter, by pid, with its dedicated and shared usage."""+ _require_windows()+ counters = _GpuProcessMemoryCounters()+ try:+ usage = counters.collect()+ finally:+ counters.close()+ return {pid: value for (pid, luid), value in usage.items() if luid == adapter.luid}+++class ProcessMemorySampler:+ """Samples one process's usage on one adapter on a background thread, from ``start()`` until ``stop()``.++ Dedicated usage is read every ``interval_s``, shared usage every ``shared_interval_s``. A process that has not+ opened the adapter yet reads as zero. Sampling ends early when the process exits.++ ``pid`` must be the process that allocates. On Windows the ``python.exe`` in a venv's ``Scripts`` folder and the+ console-script ``.exe`` files there are launchers: they run the interpreter as a child process and read as zero.+ """++ def __init__(self, pid: int, adapter: Adapter, interval_s: float = 0.003, shared_interval_s: float = 0.1) -> None:+ _require_windows()+ if pid <= 0:+ raise ValueError(f"invalid pid {pid}")+ if interval_s <= 0 or shared_interval_s <= 0:+ raise ValueError(f"sampling intervals must be positive, got {interval_s} and {shared_interval_s}")+ self._pid = pid+ self._adapter = adapter+ self._interval_s = interval_s+ self._shared_interval_s = shared_interval_s+ self._dedicated: list[tuple[float, int]] = []+ self._shared: list[tuple[float, int]] = []+ self._process: int | None = None+ self._adapter_handle: int | None = None+ self._counters: _GpuProcessMemoryCounters | None = None+ self._stopping = threading.Event()+ self._thread: threading.Thread | None = None+ self._trace: MemoryTrace | None = None+ self._warned: set[str] = set()++ def start(self) -> None:+ """Open the process and the adapter, take one sample and start the sampling thread."""+ if self._thread is not None or self._trace is not None:+ raise RuntimeError("a sampler starts once")+ try:+ self._open()+ self._sample_dedicated(raise_on_failure=True)+ self._sample_shared(raise_on_failure=True)+ except BaseException:+ self._close()+ raise+ self._thread = threading.Thread(target=self._run, name=f"gpu-memory-sampler-{self._pid}", daemon=True)+ self._thread.start()++ def stop(self) -> MemoryTrace:+ """Stop sampling, release the handles and return the trace; later calls return the same trace."""+ if self._trace is None:+ self._stopping.set()+ if self._thread is not None:+ self._thread.join()+ self._close()+ self._trace = MemoryTrace(+ method="d3dkmt",+ interval_ms=self._mean_interval_ms(),+ dedicated=tuple(self._dedicated),+ shared=tuple(self._shared),+ )+ return self._trace++ def _open(self) -> None:+ win32 = _win32()+ process = win32.kernel32.OpenProcess(_PROCESS_QUERY_INFORMATION, 0, self._pid)+ if not process:+ error = ctypes.get_last_error()+ if error == _ERROR_INVALID_PARAMETER:+ raise ProcessLookupError(f"no process with pid {self._pid}")+ if error == _ERROR_ACCESS_DENIED:+ raise PermissionError(f"access denied opening process {self._pid} for memory queries")+ raise ctypes.WinError(error)+ self._process = process+ if self._exited():+ raise ProcessLookupError(f"process {self._pid} has exited")++ opened = _OpenAdapterFromLuid(_luid_struct(self._adapter.luid), 0)+ status = win32.gdi32.D3DKMTOpenAdapterFromLuid(ctypes.byref(opened))+ _check(status, f"D3DKMTOpenAdapterFromLuid for {self._adapter.description} (LUID {self._adapter.luid:#x})")+ self._adapter_handle = opened.hAdapter+ # The target's STATUS_INVALID_PARAMETER only means "no allocation on this adapter" once the same call has+ # succeeded for this process, which proves the adapter handle and the struct layout.+ status, _ = self._query_usage(None)+ _check(status, "D3DKMTQueryVideoMemoryInfo for the sampling process")+ self._counters = _GpuProcessMemoryCounters()++ def _close(self) -> None:+ win32 = _win32()+ if self._counters is not None:+ self._counters.close()+ self._counters = None+ if self._adapter_handle is not None:+ win32.gdi32.D3DKMTCloseAdapter(ctypes.byref(_CloseAdapter(self._adapter_handle)))+ self._adapter_handle = None+ if self._process is not None:+ win32.kernel32.CloseHandle(self._process)+ self._process = None++ def _query_usage(self, process: int | None) -> tuple[int, int]:+ assert self._adapter_handle is not None+ info = _QueryVideoMemoryInfo(process, self._adapter_handle, _MEMORY_SEGMENT_GROUP_LOCAL)+ status = _win32().gdi32.D3DKMTQueryVideoMemoryInfo(ctypes.byref(info))+ return status, int(info.CurrentUsage)++ def _exited(self) -> bool:+ code = ctypes.c_uint32()+ if not _win32().kernel32.GetExitCodeProcess(self._process, ctypes.byref(code)):+ raise ctypes.WinError(ctypes.get_last_error())+ return code.value != _STILL_ACTIVE++ def _sample_dedicated(self, raise_on_failure: bool = False) -> bool:+ """Append one dedicated sample; ``False`` once the process has exited."""+ t = time.perf_counter()+ status, usage = self._query_usage(self._process)+ if status == _STATUS_SUCCESS:+ self._dedicated.append((t, usage))+ return True+ if self._exited():+ if raise_on_failure:+ raise ProcessLookupError(f"process {self._pid} has exited")+ return False+ if status == _STATUS_INVALID_PARAMETER:+ self._dedicated.append((t, 0))+ return True+ if raise_on_failure:+ if status == _STATUS_ACCESS_DENIED:+ raise PermissionError(f"access denied querying video memory of process {self._pid}")+ _check(status, f"D3DKMTQueryVideoMemoryInfo for process {self._pid}")+ self._warn_once("dedicated", f"D3DKMTQueryVideoMemoryInfo failed with status {status:#010x}; sample skipped")+ return True++ def _sample_shared(self, raise_on_failure: bool = False) -> None:+ assert self._counters is not None+ t = time.perf_counter()+ try:+ usage = self._counters.collect().get((self._pid, self._adapter.luid))+ except OSError as error:+ if raise_on_failure:+ raise+ self._warn_once("shared", f"{error}; shared sample skipped")+ return+ self._shared.append((t, 0 if usage is None else usage.shared_bytes))++ def _warn_once(self, series: str, message: str) -> None:+ if series not in self._warned:+ self._warned.add(series)+ _logger.warning(f"GPU memory sampler for process {self._pid}: {message} (further failures not logged)")++ def _run(self) -> None:+ clock = time.perf_counter+ next_dedicated = clock() + self._interval_s+ next_shared = clock() + self._shared_interval_s+ while not self._stopping.is_set():+ delay = next_dedicated - clock()+ if delay > 0:+ time.sleep(delay)+ if not self._sample_dedicated():+ return+ now = clock()+ if now >= next_shared:+ self._sample_shared()+ next_shared = now + self._shared_interval_s+ # A fixed rate: a late wake-up shortens the next sleep instead of delaying every later sample, and after a+ # stall (GIL, suspend) sampling resumes from now rather than bursting to catch up.+ next_dedicated = max(next_dedicated + self._interval_s, now)++ def _mean_interval_ms(self) -> float:+ span = self._dedicated[-1][0] - self._dedicated[0][0] if len(self._dedicated) > 1 else 0.0+ if span <= 0:+ return self._interval_s * 1000+ return span / (len(self._dedicated) - 1) * 1000diff --git a/scripts/family_e2e/graphs.py b/scripts/family_e2e/graphs.pynew file mode 100644index 0000000000..4313ed85ac--- /dev/null+++ b/scripts/family_e2e/graphs.py@@ -0,0 +1,224 @@+"""Graphs for the cases: the exporter request, the webv2 exporter call, and the runner's batch policy.++The webv2 exporter builds each case's batch with the real frontend graph builders (contract 1 in+`.scratch/agents/family-e2e/contract.md`). The runner then disables the invocation cache on every node, so repeated+runs really execute, and hashes the result so a frontend graph change shows up against the reference.+"""++from __future__ import annotations++import copy+import hashlib+import ipaddress+import json+import shutil+import subprocess+import urllib.parse+from collections.abc import Iterator+from dataclasses import dataclass+from pathlib import Path+from typing import Any++from scripts.family_e2e.manifest import TOOL_CHECKOUT, ResolvedCase+from scripts.family_e2e.server import spawn_in_job, terminate++EXPORT_VERSION = 1+WEBV2_DIR = TOOL_CHECKOUT / "invokeai" / "frontend" / "webv2"+EXPORT_TIMEOUT_S = 600+EXPORT_REQUEST_FILE = "export-request.json"+"""In the exporter's work directory; holds every model config of the server, paths included."""+# Hosts that name a machine only on its own network.+LOCAL_HOST_SUFFIXES = (".local", ".localhost")+++class ExportError(RuntimeError):+ pass+++@dataclass(frozen=True)+class PreparedGraph:+ batch: dict[str, Any]+ """The `batch` body for enqueue_batch."""+ graph_hash: str+ model_keys: frozenset[str]+ """Keys of every model identifier in the graph (main model, components, LoRAs, control models)."""+ components: dict[str, str]+ """The exporter's resolved component choice, for provenance."""+++def build_export_request(+ cases: list[ResolvedCase],+ models: list[dict[str, Any]],+ capabilities: Any,+ image_names: dict[str, dict[tuple[str, bool], str]],+) -> dict[str, Any]:+ """`image_names` maps each case key's (manifest input path, used at the case size) to the uploaded image name."""+ request_cases = []+ for case in cases:+ spec = case.spec+ names = image_names[case.case_key]+ request_cases.append(+ {+ "id": case.case_key,+ "mode": spec.mode,+ "model_key": spec.model,+ "components": spec.components,+ "width": case.width,+ "height": case.height,+ "steps": spec.steps,+ "seed": case.seed,+ "positive_prompt": case.prompt,+ "negative_prompt": case.negative_prompt,+ "loras": [{"key": lora.key, "weight": lora.weight} for lora in spec.loras],+ "reference_images": [names[(path, False)] for path in spec.reference_images],+ "init_image": (+ None+ if spec.init_image is None+ else {"image_name": names[(spec.init_image.path, True)], "strength": spec.init_image.strength}+ ),+ "control": [+ {+ "model_key": c.model,+ "image_name": names[(c.image, True)],+ "weight": c.weight,+ "begin": c.begin,+ "end": c.end,+ }+ for c in spec.control+ ],+ "settings": spec.settings,+ }+ )+ return {"version": EXPORT_VERSION, "models": models, "capabilities": capabilities, "cases": request_cases}+++def run_pnpm_exporter(request: dict[str, Any], work_dir: Path) -> dict[str, Any]:+ """Runs `pnpm graphs:export` in the tool checkout's webv2 package. Per-case errors stay in the response."""+ pnpm = shutil.which("pnpm")+ if pnpm is None:+ raise ExportError("pnpm is not on PATH; the graph exporter runs with pnpm from invokeai/frontend/webv2")+ work_dir.mkdir(parents=True, exist_ok=True)+ # Absolute: pnpm runs the exporter from the webv2 package directory.+ request_path = (work_dir / EXPORT_REQUEST_FILE).resolve()+ response_path = (work_dir / "export-response.json").resolve()+ request_path.write_text(json.dumps(request), encoding="utf-8")+ response_path.unlink(missing_ok=True)+ # pnpm is a shim (pnpm.cmd on Windows) around node: a timeout must kill the whole tree, not just the shim.+ process, job = spawn_in_job(+ [pnpm, "graphs:export", str(request_path), str(response_path)],+ cwd=WEBV2_DIR,+ stdin=subprocess.DEVNULL,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ )+ try:+ stdout, stderr = process.communicate(timeout=EXPORT_TIMEOUT_S)+ except subprocess.TimeoutExpired:+ raise ExportError(f"pnpm graphs:export did not finish within {EXPORT_TIMEOUT_S}s") from None+ finally:+ # A finished communicate() has reaped pnpm already; children it left behind still hold its group's id.+ terminate(process, job)+ if process.returncode != 0 or not response_path.is_file():+ output = (stderr or stdout).decode("utf-8", errors="replace")+ raise ExportError(f"pnpm graphs:export exited with {process.returncode}:\n{output[-4000:]}")+ response = json.loads(response_path.read_text(encoding="utf-8"))+ if response.get("version") != EXPORT_VERSION:+ raise ExportError(f"exporter answered version {response.get('version')!r}, expected {EXPORT_VERSION}")+ return response+++def model_identifiers(value: Any) -> Iterator[dict[str, Any]]:+ """Every model identifier in a graph: a ModelIdentifierField {"key", "hash", "name", "base", "type", ...}.++ The webv2 builders put the model's whole config there, path and source included.+ """+ if isinstance(value, dict):+ if isinstance(value.get("key"), str) and "base" in value and "type" in value:+ yield value+ for item in value.values():+ yield from model_identifiers(item)+ elif isinstance(value, list):+ for item in value:+ yield from model_identifiers(item)+++def is_public_url(value: object) -> bool:+ """An http(s) URL of a public host, without the places a download token would hide: credentials, `;params`,+ query or fragment."""+ if not isinstance(value, str) or ";" in value:+ return False+ try:+ parts = urllib.parse.urlsplit(value)+ host = parts.hostname+ except ValueError:+ return False+ if parts.scheme not in ("http", "https") or parts.query or parts.fragment or "@" in parts.netloc:+ return False+ return is_public_host(host)+++def is_public_host(host: str | None) -> bool:+ """A host anyone can reach: no private, loopback or link-local address, and no name of the local network."""+ if not host:+ return False+ try:+ return ipaddress.ip_address(host).is_global+ except ValueError:+ # A single label (localhost, a LAN machine's name) resolves only on its own network.+ return "." in host and not host.endswith(LOCAL_HOST_SUFFIXES)+++def shareable_source(config: dict[str, Any]) -> str | None:+ """A model config's source when it names the model on any machine: an HF repo id or a public URL."""+ source, source_type = config.get("source"), config.get("source_type")+ if source_type == "hf_repo_id" or (source_type == "url" and is_public_url(source)):+ return source if isinstance(source, str) else None+ return None+++def _replace_strings(value: Any, replacements: dict[str, str]) -> Any:+ if isinstance(value, str):+ return replacements.get(value, value)+ if isinstance(value, dict):+ return {k: _replace_strings(v, replacements) for k, v in value.items()}+ if isinstance(value, list):+ return [_replace_strings(v, replacements) for v in value]+ return value+++def prepare_batch(batch: dict[str, Any], components: dict[str, str], input_ids: dict[str, str]) -> PreparedGraph:+ """Applies the runner policy to an exported batch and hashes it.++ `input_ids` maps uploaded image names to a stable identity of the input file. Upload names differ on every+ server start, so the hash covers the input's identity instead.+ """+ batch = copy.deepcopy(batch)+ for node in batch["graph"]["nodes"].values():+ node["use_cache"] = False+ batch["runs"] = 1+ hashed = _replace_strings({"graph": batch["graph"], "data": batch.get("data")}, input_ids)+ canonical = json.dumps(hashed, sort_keys=True, separators=(",", ":"), ensure_ascii=False)+ return PreparedGraph(+ batch=batch,+ graph_hash=hashlib.sha256(canonical.encode("utf-8")).hexdigest(),+ model_keys=frozenset(identifier["key"] for identifier in model_identifiers(batch["graph"])),+ components=components,+ )+++def output_image_name(graph: dict[str, Any], session: dict[str, Any]) -> str:+ """The image of the graph's one non-intermediate node that produced an image."""+ mapping = session.get("source_prepared_mapping") or {}+ results = session.get("results") or {}+ names = []+ for node_id, node in graph["nodes"].items():+ # The server's default: a node without the field is not intermediate.+ if node.get("is_intermediate", False):+ continue+ for prepared_id in mapping.get(node_id, []):+ image = (results.get(prepared_id) or {}).get("image")+ if isinstance(image, dict) and isinstance(image.get("image_name"), str):+ names.append(image["image_name"])+ if len(names) != 1:+ raise ValueError(f"expected one output image from the graph's non-intermediate nodes, found {len(names)}")+ return names[0]diff --git a/scripts/family_e2e/manifest.example.yaml b/scripts/family_e2e/manifest.example.yamlnew file mode 100644index 0000000000..dbb5134d95--- /dev/null+++ b/scripts/family_e2e/manifest.example.yaml@@ -0,0 +1,82 @@+# Family E2E manifest, example for the first wave. Copy it next to your data directory, replace every <...> (paths+# and the model keys of your install; GET /api/v2/models/ lists the keys), then:+# python -m scripts.family_e2e start --manifest <this file>+# Relative paths are relative to this file.++profile: rtx4090 # names runs and references; one profile per machine, operating system and GPU+data_dir: <data dir> # inputs/, references/, runs/, scratch-roots/+gpu: RTX 4090 # substring of the adapter name; must match one adapter ("Radeon" also matches an AMD iGPU, use "9060")+# On Linux also an NVML UUID (GPU-...), which tells identical cards apart; the runner pins the server to that card.++server:+ # Its invokeai.yaml and a database snapshot are copied; its server must be off. The scratch server shares its+ # models directory: it writes models/README.txt and removes install claims of processes that no longer run there.+ template_root: <template root>+ # The server's interpreter: <checkout>/.venv/Scripts/python.exe on Windows, <checkout>/.venv/bin/python on Linux.+ python: <python>+ # code_dir: <checkout> # the checkout the server runs; default: the checkout this tool runs from+ env: {} # extra server environment, e.g. {HIP_VISIBLE_DEVICES: "0"} for ROCm++defaults:+ warmup: 1+ repeats: 3+ seed: 1234+ prompt: A red fox sitting in the snow, soft winter light, blurred pine forest in the background.+ negative_prompt: null+ psnr_min_db: 30+ time_tolerance: 0.10 # relative+ peak_tolerance_mb: 256+ run_timeout_s: 1800++families:+ - family: z-image+ cases:+ - id: zimage-turbo-t2i+ model: <z-image-turbo-key>+ steps: 8+ sizes: [[1024, 1024], [1536, 1536]] # several sizes: a sweep for working-memory calibration+ - id: zimage-turbo-i2i+ model: <z-image-turbo-key>+ mode: img2img+ steps: 8+ sizes: [[1024, 1024]]+ init_image: {path: fox-1024.png, strength: 0.6} # under <data_dir>/inputs+ settings: {scheduler: heun} # Heun has ignored the img2img start point before++ - family: flux2+ cases:+ - id: flux2-klein4b-t2i+ model: <flux2-klein-4b-key>+ steps: 4+ sizes: [[1024, 1024]]+ - id: flux2-klein4b-ref+ model: <flux2-klein-4b-key>+ steps: 4+ sizes: [[1024, 1024]]+ reference_images: [fox-1024.png]++ - family: krea2+ cases:+ - id: krea2-turbo-t2i+ model: <krea2-turbo-key>+ steps: 8+ sizes: [[1024, 1024]]+ - id: krea2-turbo-lora+ model: <krea2-turbo-key>+ steps: 8+ sizes: [[1024, 1024]]+ loras: [{key: <krea2-lora-key>, weight: 0.8}]++ - family: sdxl+ cases:+ - id: sdxl-t2i+ model: <sdxl-key>+ steps: 25+ sizes: [[1024, 1024]]+ - id: sdxl-controlnet+ model: <sdxl-key>+ mode: controlnet+ steps: 25+ sizes: [[1024, 1024]]+ control: [{model: <sdxl-canny-controlnet-key>, image: fox-canny-1024.png, weight: 0.75, begin: 0.0, end: 0.8}]+ psnr_min_db: 28 # per-case thresholds override the defaultsdiff --git a/scripts/family_e2e/manifest.py b/scripts/family_e2e/manifest.pynew file mode 100644index 0000000000..57b9fbbe37--- /dev/null+++ b/scripts/family_e2e/manifest.py@@ -0,0 +1,265 @@+"""The manifest of one profile: the server to launch, the cases to run, and how they expand into planned steps."""++from __future__ import annotations++from collections.abc import Sequence+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Literal++import yaml+from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator++from scripts.family_e2e.records import Expect, PlannedStep, Thresholds++TOOL_CHECKOUT = Path(__file__).resolve().parents[2]+DEFAULT_ARM = "default"+# Profile, family and case names end up in directory names and record ids (`<case_key>.<arm>.<kind>...`).+_NAME = r"^[A-Za-z0-9][A-Za-z0-9_-]*$"++Mode = Literal["txt2img", "img2img", "controlnet"]+++class ManifestError(ValueError):+ pass+++class _Strict(BaseModel):+ model_config = ConfigDict(extra="forbid")+++class ServerSpec(_Strict):+ template_root: Path+ python: Path+ code_dir: Path = TOOL_CHECKOUT+ env: dict[str, str] = {}+++class Defaults(_Strict):+ warmup: int = Field(default=1, ge=1)+ repeats: int = Field(default=3, ge=1)+ seed: int = 1234+ prompt: str+ negative_prompt: str | None = None+ psnr_min_db: float = 30.0+ time_tolerance: float = Field(default=0.10, gt=0)+ peak_tolerance_mb: float = Field(default=256.0, gt=0)+ run_timeout_s: float = Field(default=1800.0, gt=0)+++class LoraSpec(_Strict):+ key: str+ weight: float = 1.0+++class InitImageSpec(_Strict):+ path: str+ strength: float = Field(gt=0, le=1)+++class ControlSpec(_Strict):+ model: str+ image: str+ weight: float = 1.0+ begin: float = Field(default=0.0, ge=0, le=1)+ end: float = Field(default=1.0, ge=0, le=1)+++class CaseSpec(_Strict):+ id: str = Field(pattern=_NAME)+ model: str+ components: dict[str, str] = {}+ mode: Mode = "txt2img"+ sizes: list[tuple[int, int]] = Field(min_length=1)+ steps: int = Field(gt=0)+ seed: int | None = None+ prompt: str | None = None+ loras: list[LoraSpec] = []+ reference_images: list[str] = []+ init_image: InitImageSpec | None = None+ control: list[ControlSpec] = []+ settings: dict[str, Any] = {}+ psnr_min_db: float | None = None+ time_tolerance: float | None = Field(default=None, gt=0)+ peak_tolerance_mb: float | None = Field(default=None, gt=0)+ expect: Expect = "unchanged"+ """`changed` for a case the code under test is meant to change: then a match with the reference fails."""++ @model_validator(mode="after")+ def _check(self) -> CaseSpec:+ for width, height in self.sizes:+ if width <= 0 or height <= 0 or width % 8 or height % 8:+ raise ValueError(f"size {width}x{height} must be positive multiples of 8")+ if len(set(self.sizes)) != len(self.sizes):+ raise ValueError("sizes must be unique")+ # A field the mode does not use would be silently ignored by the exporter.+ if (self.mode == "img2img") != (self.init_image is not None):+ raise ValueError("init_image is required for mode img2img and allowed only there")+ if (self.mode == "controlnet") != bool(self.control):+ raise ValueError("control is required for mode controlnet and allowed only there")+ return self++ def input_paths(self) -> list[str]:+ paths = list(self.reference_images) + [c.image for c in self.control]+ if self.init_image is not None:+ paths.append(self.init_image.path)+ return paths+++class FamilySpec(_Strict):+ family: str = Field(pattern=_NAME)+ cases: list[CaseSpec] = Field(min_length=1)+++class Manifest(_Strict):+ profile: str = Field(pattern=_NAME)+ data_dir: Path+ gpu: str = Field(+ min_length=1, description="Substring of the adapter description, e.g. 'RTX 4090', or on Linux an NVML UUID"+ )+ server: ServerSpec+ defaults: Defaults+ families: list[FamilySpec] = Field(min_length=1)++ @model_validator(mode="after")+ def _unique_names(self) -> Manifest:+ families = [f.family for f in self.families]+ if len(set(families)) != len(families):+ raise ValueError("family names must be unique")+ ids = [c.id for f in self.families for c in f.cases]+ duplicates = sorted({i for i in ids if ids.count(i) > 1})+ if duplicates:+ raise ValueError(f"case ids must be unique across the manifest: {', '.join(duplicates)}")+ return self++ @property+ def inputs_dir(self) -> Path:+ return self.data_dir / "inputs"++ def input_file(self, relative: str) -> Path:+ """The file a manifest input path names: under `<data_dir>/inputs`, never outside it."""+ inputs = self.inputs_dir.resolve()+ path = (inputs / relative).resolve()+ if not path.is_relative_to(inputs):+ raise ManifestError(f"input {relative!r} resolves outside {inputs}")+ return path+++@dataclass(frozen=True)+class ResolvedCase:+ """One case at one size: the unit graphs, references and thresholds are keyed by."""++ case_key: str+ family: str+ spec: CaseSpec+ width: int+ height: int+ seed: int+ prompt: str+ negative_prompt: str | None+ thresholds: Thresholds+++def case_key(case_id: str, width: int, height: int) -> str:+ return f"{case_id}@{width}x{height}"+++def load_manifest(path: Path) -> Manifest:+ """Reads and validates a manifest. Relative paths in it are relative to the manifest file; inputs must exist."""+ try:+ raw = yaml.safe_load(path.read_text(encoding="utf-8"))+ except (OSError, yaml.YAMLError) as e:+ raise ManifestError(f"cannot read manifest {path}: {e}") from e+ if not isinstance(raw, dict):+ raise ManifestError(f"manifest {path} must be a mapping")+ try:+ manifest = Manifest.model_validate(raw)+ except ValidationError as e:+ raise ManifestError(f"invalid manifest {path}:\n{e}") from e++ base = path.resolve().parent+ server = manifest.server+ manifest = manifest.model_copy(+ update={+ "data_dir": base / manifest.data_dir,+ "server": server.model_copy(+ update={+ "template_root": base / server.template_root,+ "python": base / server.python,+ "code_dir": base / server.code_dir,+ }+ ),+ }+ )+ missing = [+ f"{case.id}: {relative}"+ for family in manifest.families+ for case in family.cases+ for relative in case.input_paths()+ if not manifest.input_file(relative).is_file()+ ]+ if missing:+ raise ManifestError(f"missing input files under {manifest.inputs_dir}:\n" + "\n".join(missing))+ return manifest+++def resolve_cases(manifest: Manifest, families: Sequence[str] = (), case_ids: Sequence[str] = ()) -> list[ResolvedCase]:+ """The selected cases in manifest order: family order, then case order, then size order.++ A case is selected when it passes both filters; an empty filter passes everything.+ """+ known_families = {f.family for f in manifest.families}+ known_cases = {c.id for f in manifest.families for c in f.cases}+ unknown = [f for f in families if f not in known_families] + [c for c in case_ids if c not in known_cases]+ if unknown:+ raise ManifestError(+ f"unknown family or case: {', '.join(unknown)} "+ f"(families: {', '.join(sorted(known_families))}; cases: {', '.join(sorted(known_cases))})"+ )+ defaults = manifest.defaults+ resolved: list[ResolvedCase] = []+ for family in manifest.families:+ if families and family.family not in families:+ continue+ for case in family.cases:+ if case_ids and case.id not in case_ids:+ continue+ thresholds = Thresholds(+ psnr_min_db=defaults.psnr_min_db if case.psnr_min_db is None else case.psnr_min_db,+ time_tolerance=defaults.time_tolerance if case.time_tolerance is None else case.time_tolerance,+ peak_tolerance_mb=(+ defaults.peak_tolerance_mb if case.peak_tolerance_mb is None else case.peak_tolerance_mb+ ),+ expect=case.expect,+ )+ for width, height in case.sizes:+ resolved.append(+ ResolvedCase(+ case_key=case_key(case.id, width, height),+ family=family.family,+ spec=case,+ width=width,+ height=height,+ seed=defaults.seed if case.seed is None else case.seed,+ prompt=defaults.prompt if case.prompt is None else case.prompt,+ negative_prompt=defaults.negative_prompt,+ thresholds=thresholds,+ )+ )+ if not resolved:+ raise ManifestError("the family/case filters select no case")+ return resolved+++def plan_steps(cases: list[ResolvedCase], warmup: int, repeats: int, arm: str = DEFAULT_ARM) -> list[PlannedStep]:+ """Warm-ups, then measures, per case key, in case order."""+ steps: list[PlannedStep] = []+ for case in cases:+ for kind, count in (("warmup", warmup), ("measure", repeats)):+ steps.extend(+ PlannedStep(+ case_key=case.case_key, case_id=case.spec.id, family=case.family, arm=arm, kind=kind, rep=rep+ )+ for rep in range(count)+ )+ return stepsdiff --git a/scripts/family_e2e/metrics.py b/scripts/family_e2e/metrics.pynew file mode 100644index 0000000000..d9be470ebb--- /dev/null+++ b/scripts/family_e2e/metrics.py@@ -0,0 +1,136 @@+"""Image quality and statistics helpers for the family E2E report."""++from __future__ import annotations++import math+import statistics+from collections import defaultdict+from collections.abc import Iterable, Sequence+from dataclasses import dataclass, field+from pathlib import Path++import numpy as np+from PIL import Image++from scripts.family_e2e.records import Record++MB = 2**20+DIFF_GAIN = 10+"""Amplification of the absolute difference image; a 1-level difference shows as 10 levels."""+MAD_FACTOR = 3.0+++class ImageSizeMismatchError(ValueError):+ def __init__(self, a: np.ndarray, b: np.ndarray) -> None:+ super().__init__(f"size mismatch: {a.shape[1]}x{a.shape[0]} vs {b.shape[1]}x{b.shape[0]}")+++def load_rgb(path: Path) -> np.ndarray:+ """Returns the image as an HxWx3 uint8 array; alpha is dropped."""+ with Image.open(path) as image:+ return np.asarray(image.convert("RGB"), dtype=np.uint8)+++def _difference(a: np.ndarray, b: np.ndarray) -> np.ndarray:+ if a.shape != b.shape:+ raise ImageSizeMismatchError(a, b)+ return np.subtract(a, b, dtype=np.int16)+++def psnr(a: np.ndarray, b: np.ndarray) -> float:+ """PSNR in dB over all channels of two 8-bit RGB images; identical images give `math.inf`."""+ mse = float(np.mean(np.square(_difference(a, b), dtype=np.int32)))+ if mse == 0:+ return math.inf+ return 10 * math.log10(255**2 / mse)+++def write_diff_image(a: np.ndarray, b: np.ndarray, path: Path) -> None:+ """Writes |a - b| amplified by DIFF_GAIN as a PNG."""+ diff = np.abs(_difference(a, b)).astype(np.int32) * DIFF_GAIN+ path.parent.mkdir(parents=True, exist_ok=True)+ Image.fromarray(np.clip(diff, 0, 255).astype(np.uint8)).save(path)+++def median(values: Sequence[float]) -> float | None:+ return statistics.median(values) if values else None+++def mad(values: Sequence[float]) -> float | None:+ """Median absolute deviation from the median."""+ center = median(values)+ if center is None:+ return None+ return statistics.median([abs(v - center) for v in values])+++@dataclass(frozen=True)+class MeasuredValues:+ """Per-run values of completed measured records; each metric only from records valid for it."""++ total_s: list[float] = field(default_factory=list)+ per_step_s: list[float] = field(default_factory=list)+ process_peak_bytes: list[int] = field(default_factory=list)+ node_peak_bytes: dict[str, list[int]] = field(default_factory=lambda: defaultdict(list))+ node_baseline_bytes: dict[str, list[int]] = field(default_factory=lambda: defaultdict(list))+ node_duration_s: dict[str, list[float]] = field(default_factory=lambda: defaultdict(list))+++def measured_values(records: Iterable[Record]) -> MeasuredValues:+ values = MeasuredValues()+ for record in records:+ if record.kind != "measure" or record.status != "completed":+ continue+ if record.valid_timing and record.timing is not None:+ values.total_s.append(record.timing.total_s)+ if record.timing.per_step_s is not None:+ values.per_step_s.append(record.timing.per_step_s)+ for node in record.timing.nodes:+ if node.t_end is not None:+ values.node_duration_s[node.node_id].append(node.t_end - node.t_start)+ if record.valid_memory and record.memory is not None:+ if record.memory.process_peak_bytes is not None:+ values.process_peak_bytes.append(record.memory.process_peak_bytes)+ for node in record.memory.nodes:+ if node.peak_bytes is not None:+ values.node_peak_bytes[node.node_id].append(node.peak_bytes)+ if node.baseline_bytes is not None:+ values.node_baseline_bytes[node.node_id].append(node.baseline_bytes)+ return values+++@dataclass(frozen=True)+class Delta:+ """The current median against a comparison value (reference or previous run)."""++ current: float+ baseline: float+ outlier: bool++ @property+ def delta(self) -> float:+ return self.current - self.baseline++ @property+ def relative(self) -> float | None:+ return self.delta / self.baseline if self.baseline else None+++def _compare(values: Sequence[float], baseline: float, tolerance: float) -> Delta | None:+ current = median(values)+ if current is None:+ return None+ deviation = abs(current - baseline)+ # A deviation within the run-to-run noise of this run's own measurements is not an outlier.+ noise = MAD_FACTOR * (mad(values) or 0.0)+ return Delta(current=current, baseline=baseline, outlier=deviation > tolerance and deviation > noise)+++def compare_time(values: Sequence[float], baseline: float, tolerance: float) -> Delta | None:+ """`tolerance` is relative to the baseline (0.10 = 10 %). Returns None without current values."""+ return _compare(values, baseline, tolerance * abs(baseline))+++def compare_peak(values: Sequence[float], baseline: float, tolerance_mb: float) -> Delta | None:+ """Values and baseline in bytes, tolerance absolute in MB (2**20 bytes). Returns None without current values."""+ return _compare(values, baseline, tolerance_mb * MB)diff --git a/scripts/family_e2e/nvml_memory.py b/scripts/family_e2e/nvml_memory.pynew file mode 100644index 0000000000..6c796aea89--- /dev/null+++ b/scripts/family_e2e/nvml_memory.py@@ -0,0 +1,340 @@+"""Driver-level video memory of another process on Linux with an NVIDIA GPU, read through NVML.++The Linux counterpart of `gpu_memory`, with the same interface and types. NVML ships with the NVIDIA driver+(``libnvidia-ml.so.1``) and lists every compute process on a device with ``usedGpuMemory``: what the driver has+allocated for that process, its CUDA context included. One ``nvmlDeviceGetComputeRunningProcesses_v3`` call returns+the whole list, so the sampler reads it at a fixed rate and picks out its process; the one-off listing behind the+foreign-load checks adds the graphics processes. The Linux driver does not page video memory out to system memory,+so there is no shared series.++Like `gpu_memory`, this never imports torch: a CUDA context of the client's own would sit on the same device and+distort what the server can allocate. AMD (ROCm) GPUs on Linux are not supported yet.+"""++import ctypes+import functools+import logging+import sys+import threading+import time++import psutil++from scripts.family_e2e.gpu_memory import Adapter, MemoryTrace, ProcessUsage, UnsupportedPlatformError, _select_adapter++_LIBRARY_NAMES = ("libnvidia-ml.so.1", "libnvidia-ml.so")+_NVML_SUCCESS = 0+_NVML_ERROR_NOT_SUPPORTED = 3+_NVML_ERROR_INSUFFICIENT_SIZE = 7+_NVML_ERROR_LIB_RM_VERSION_MISMATCH = 18+# `usedGpuMemory` where the driver does not account memory per process: vGPU guests, MIG, some containers.+_NVML_VALUE_NOT_AVAILABLE = 0xFFFFFFFFFFFFFFFF+# NVML_DEVICE_NAME_V2_BUFFER_SIZE, NVML_DEVICE_UUID_V2_BUFFER_SIZE and NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE.+_NAME_BUFFER_SIZE = 96+_UUID_BUFFER_SIZE = 96+_DRIVER_VERSION_BUFFER_SIZE = 80+# Room for processes that start between NVML's count and the fill.+_SPARE_PROCESS_ENTRIES = 8+_LIST_ATTEMPTS = 4+_AMD_NOTE = "AMD (ROCm) GPUs on Linux are not supported yet"++_logger = logging.getLogger(__name__)+++class _ProcessInfo(ctypes.Structure):+ """``nvmlProcessInfo_t``, the entry ``nvmlDeviceGetComputeRunningProcesses_v3`` fills."""++ _fields_ = [+ ("pid", ctypes.c_uint),+ ("usedGpuMemory", ctypes.c_ulonglong),+ ("gpuInstanceId", ctypes.c_uint),+ ("computeInstanceId", ctypes.c_uint),+ ]+++_PROCESS_LIST = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(_ProcessInfo)]+_PROTOTYPES = {+ "nvmlInit_v2": [],+ "nvmlErrorString": [ctypes.c_int],+ "nvmlSystemGetDriverVersion": [ctypes.c_char_p, ctypes.c_uint],+ "nvmlDeviceGetCount_v2": [ctypes.POINTER(ctypes.c_uint)],+ "nvmlDeviceGetHandleByIndex_v2": [ctypes.c_uint, ctypes.POINTER(ctypes.c_void_p)],+ "nvmlDeviceGetHandleByUUID": [ctypes.c_char_p, ctypes.POINTER(ctypes.c_void_p)],+ "nvmlDeviceGetName": [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_uint],+ "nvmlDeviceGetUUID": [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_uint],+ "nvmlDeviceGetComputeRunningProcesses_v3": _PROCESS_LIST,+ "nvmlDeviceGetGraphicsRunningProcesses_v3": _PROCESS_LIST,+}+++def _open_library() -> ctypes.CDLL:+ for name in _LIBRARY_NAMES:+ try:+ return ctypes.CDLL(name)+ except OSError:+ continue+ raise UnsupportedPlatformError(+ f"GPU memory sampling on {sys.platform} reads NVML, which comes with the NVIDIA driver, but neither "+ f"{' nor '.join(_LIBRARY_NAMES)} loads. {_AMD_NOTE}."+ )+++def _declare(lib: ctypes.CDLL) -> None:+ """Declares the prototypes used here, so ctypes passes device handles at full pointer width."""+ for function, argtypes in _PROTOTYPES.items():+ try:+ fn = getattr(lib, function)+ except AttributeError:+ raise UnsupportedPlatformError(f"NVML has no {function}: the NVIDIA driver is too old") from None+ fn.argtypes = argtypes+ fn.restype = ctypes.c_char_p if function == "nvmlErrorString" else ctypes.c_int+++def _nvml() -> ctypes.CDLL:+ """NVML, initialised on first use and never shut down: every later call and sampler thread shares the one init."""+ lib = _open_library()+ _declare(lib)+ status = lib.nvmlInit_v2()+ if status == _NVML_ERROR_LIB_RM_VERSION_MISMATCH:+ raise UnsupportedPlatformError(+ "NVML does not match the loaded NVIDIA kernel module (driver/library version mismatch), as after a driver "+ "upgrade until the machine restarts; reboot, then try again"+ )+ if status != _NVML_SUCCESS:+ raise UnsupportedPlatformError(f"nvmlInit_v2 failed: {_error_string(lib, status)} (NVML error {status})")+ return lib+++def _error_string(lib: ctypes.CDLL, status: int) -> str:+ text = lib.nvmlErrorString(status)+ return text.decode("utf-8", errors="replace") if text else "unknown error"+++def _check(lib: ctypes.CDLL, status: int, call: str) -> None:+ if status != _NVML_SUCCESS:+ raise OSError(f"{call} failed: {_error_string(lib, status)} (NVML error {status})")+++def _text(buffer: ctypes.Array[ctypes.c_char]) -> str:+ return buffer.value.decode("utf-8", errors="replace")+++def list_adapters() -> list[Adapter]:+ """The NVIDIA GPUs NVML sees, in its enumeration order.++ A GPU NVML cannot query (no permission in a cgroup, lost after an Xid error) is left out with a warning, so the+ others stay usable.+ """+ lib = _nvml()+ driver = ctypes.create_string_buffer(_DRIVER_VERSION_BUFFER_SIZE)+ _check(lib, lib.nvmlSystemGetDriverVersion(driver, len(driver)), "nvmlSystemGetDriverVersion")+ count = ctypes.c_uint()+ _check(lib, lib.nvmlDeviceGetCount_v2(ctypes.byref(count)), "nvmlDeviceGetCount_v2")+ adapters = []+ for index in range(count.value):+ try:+ adapters.append(_describe(lib, index, _text(driver) or None))+ except OSError as error:+ _logger.warning(f"NVIDIA GPU {index} left out: {error}")+ return adapters+++def _describe(lib: ctypes.CDLL, index: int, driver_version: str | None) -> Adapter:+ handle = ctypes.c_void_p()+ _check(+ lib, lib.nvmlDeviceGetHandleByIndex_v2(index, ctypes.byref(handle)), f"nvmlDeviceGetHandleByIndex_v2({index})"+ )+ name = ctypes.create_string_buffer(_NAME_BUFFER_SIZE)+ _check(lib, lib.nvmlDeviceGetName(handle, name, len(name)), f"nvmlDeviceGetName({index})")+ uuid = ctypes.create_string_buffer(_UUID_BUFFER_SIZE)+ _check(lib, lib.nvmlDeviceGetUUID(handle, uuid, len(uuid)), f"nvmlDeviceGetUUID({index})")+ return Adapter(luid=None, uuid=_text(uuid), description=_text(name), driver_version=driver_version)+++def find_adapter(name_or_uuid: str) -> Adapter:+ """The NVIDIA GPU with this UUID, else the one whose name contains the text, ignoring case.++ ``LookupError`` for none or several; the message lists every GPU with its UUID. A UUID tells identical cards+ apart, e.g. two runs side by side, one per GPU; the runner pins each server to its UUID.+ """+ adapters = list_adapters()+ for adapter in adapters:+ if adapter.uuid is not None and adapter.uuid.casefold() == name_or_uuid.casefold():+ return adapter+ return _select_adapter(+ adapters,+ name_or_uuid,+ no_match_hint=f"NVML lists NVIDIA GPUs only; {_AMD_NOTE}",+ several_hint="set gpu to the UUID of one of them; the runner pins the server to that GPU",+ )+++def _not_attributed(adapter: Adapter) -> UnsupportedPlatformError:+ return UnsupportedPlatformError(+ f"NVML does not attribute memory to processes on {adapter.description} (usedGpuMemory is not available, as "+ "in vGPU guests, MIG instances and some containers); sampling needs a GPU the driver accounts per process"+ )+++class _ProcessTable:+ """The compute (or graphics) processes on one GPU, read into entries kept between reads: one NVML call while they+ fit."""++ def __init__(self, adapter: Adapter, graphics: bool = False) -> None:+ if adapter.uuid is None:+ raise ValueError(f"{adapter.description} is not an NVML device")+ self._lib = _nvml()+ self._handle = ctypes.c_void_p()+ status = self._lib.nvmlDeviceGetHandleByUUID(adapter.uuid.encode("ascii"), ctypes.byref(self._handle))+ _check(self._lib, status, f"nvmlDeviceGetHandleByUUID for {adapter.description}")+ self._graphics = graphics+ self._function = (+ "nvmlDeviceGetGraphicsRunningProcesses_v3" if graphics else "nvmlDeviceGetComputeRunningProcesses_v3"+ )+ self._list = getattr(self._lib, self._function)+ self._entries = (_ProcessInfo * _SPARE_PROCESS_ENTRIES)()++ def read(self) -> dict[int, int]:+ """``usedGpuMemory`` by pid, ``_NVML_VALUE_NOT_AVAILABLE`` where the driver does not attribute memory.++ A graphics listing the device does not support (compute-only cards and modes) has no processes.+ """+ for _ in range(_LIST_ATTEMPTS):+ count = ctypes.c_uint(len(self._entries))+ status = self._list(self._handle, ctypes.byref(count), self._entries)+ if status == _NVML_SUCCESS:+ return {entry.pid: entry.usedGpuMemory for entry in self._entries[: count.value]}+ if status == _NVML_ERROR_NOT_SUPPORTED and self._graphics:+ return {}+ if status != _NVML_ERROR_INSUFFICIENT_SIZE:+ _check(self._lib, status, self._function)+ # NVML has set the count it needs; the spare entries leave room for processes that start meanwhile.+ self._entries = (_ProcessInfo * (count.value + _SPARE_PROCESS_ENTRIES))()+ raise OSError(f"{self._function}: the process count kept growing over {_LIST_ATTEMPTS} attempts")+++def process_usage_on_adapter(adapter: Adapter) -> dict[int, ProcessUsage]:+ """Every compute and graphics process on the GPU, by pid, with its memory as dedicated usage; NVML has no shared+ usage.++ A process with both kinds of context is listed in both lists, with the same memory, so the larger value stands.+ A graphics process whose memory NVML does not attribute is left out: the compute list already tells whether the+ driver accounts memory per process.+ """+ compute = _ProcessTable(adapter).read()+ if _NVML_VALUE_NOT_AVAILABLE in compute.values():+ raise _not_attributed(adapter)+ used = dict(compute)+ for pid, value in _ProcessTable(adapter, graphics=True).read().items():+ if value != _NVML_VALUE_NOT_AVAILABLE:+ used[pid] = max(used.get(pid, 0), value)+ return {pid: ProcessUsage(dedicated_bytes=value, shared_bytes=0) for pid, value in used.items()}+++class ProcessMemorySampler:+ """Samples one process's memory on one NVIDIA GPU on a background thread, from ``start()`` until ``stop()``.++ ``usedGpuMemory`` is read every ``interval_s``. A process NVML does not list (it has not opened the GPU yet, or+ holds nothing there) reads as zero. Sampling ends early when the process exits.++ ``pid`` must be the process that allocates: NVML charges memory to the process that holds it, not to its parent.+ """++ def __init__(self, pid: int, adapter: Adapter, interval_s: float = 0.005) -> None:+ if pid <= 0:+ raise ValueError(f"invalid pid {pid}")+ if interval_s <= 0:+ raise ValueError(f"the sampling interval must be positive, got {interval_s}")+ self._pid = pid+ self._adapter = adapter+ self._interval_s = interval_s+ self._samples: list[tuple[float, int]] = []+ self._process: psutil.Process | None = None+ self._table: _ProcessTable | None = None+ self._stopping = threading.Event()+ self._thread: threading.Thread | None = None+ self._trace: MemoryTrace | None = None+ self._warned: set[str] = set()++ def start(self) -> None:+ """Resolve the process and the GPU, take one sample and start the sampling thread."""+ if self._thread is not None or self._trace is not None:+ raise RuntimeError("a sampler starts once")+ try:+ # Holds the create time, so a later process that reuses the pid does not pass for this one.+ self._process = psutil.Process(self._pid)+ except psutil.NoSuchProcess:+ raise ProcessLookupError(f"no process with pid {self._pid}") from None+ self._table = _ProcessTable(self._adapter)+ self._sample(raise_on_failure=True)+ self._thread = threading.Thread(target=self._run, name=f"gpu-memory-sampler-{self._pid}", daemon=True)+ self._thread.start()++ def stop(self) -> MemoryTrace:+ """Stop sampling and return the trace; later calls return the same trace."""+ if self._trace is None:+ self._stopping.set()+ if self._thread is not None:+ self._thread.join()+ self._trace = MemoryTrace(+ method="nvml", interval_ms=self._mean_interval_ms(), dedicated=tuple(self._samples), shared=()+ )+ return self._trace++ def _exited(self) -> bool:+ assert self._process is not None+ try:+ # psutil counts a zombie as running, but its memory went with its exit.+ return not self._process.is_running() or self._process.status() == psutil.STATUS_ZOMBIE+ except psutil.NoSuchProcess:+ return True++ def _sample(self, raise_on_failure: bool = False) -> bool:+ """Append one sample; ``False`` once the process has exited."""+ assert self._table is not None+ t = time.perf_counter()+ try:+ used = self._table.read().get(self._pid)+ except OSError as error:+ if raise_on_failure:+ raise+ self._warn_once("error", f"{error}; sample skipped")+ return True+ if used is None:+ if self._exited():+ if raise_on_failure:+ raise ProcessLookupError(f"process {self._pid} has exited")+ return False+ used = 0+ elif used == _NVML_VALUE_NOT_AVAILABLE:+ if raise_on_failure:+ raise _not_attributed(self._adapter)+ self._warn_once("unavailable", "NVML reports its memory as not available; sample skipped")+ return True+ self._samples.append((t, used))+ return True++ def _warn_once(self, kind: str, message: str) -> None:+ if kind not in self._warned:+ self._warned.add(kind)+ _logger.warning(f"GPU memory sampler for process {self._pid}: {message} (further failures not logged)")++ def _run(self) -> None:+ clock = time.perf_counter+ next_sample = clock() + self._interval_s+ while not self._stopping.is_set():+ delay = next_sample - clock()+ if delay > 0:+ time.sleep(delay)+ if not self._sample():+ return+ # A fixed rate, as in gpu_memory: a late wake-up shortens the next sleep, and after a stall sampling+ # resumes from now rather than bursting to catch up.+ next_sample = max(next_sample + self._interval_s, clock())++ def _mean_interval_ms(self) -> float:+ span = self._samples[-1][0] - self._samples[0][0] if len(self._samples) > 1 else 0.0+ if span <= 0:+ return self._interval_s * 1000+ return span / (len(self._samples) - 1) * 1000diff --git a/scripts/family_e2e/records.py b/scripts/family_e2e/records.pynew file mode 100644index 0000000000..63cc2622bf--- /dev/null+++ b/scripts/family_e2e/records.py@@ -0,0 +1,317 @@+"""Persistent records of a family E2E run: one JSON line per generation, plus the run info and references.++Times are seconds; `t_*` fields are relative to the enqueue instant (client `time.perf_counter()`). Paths stored in+records are relative to the run directory.+"""++from __future__ import annotations++import os+import re+import tempfile+import time+from pathlib import Path+from typing import Any, Literal++from pydantic import BaseModel, ConfigDict, ValidationError++RECORDS_FILE = "records.jsonl"+RUN_INFO_FILE = "run.json"+RUN_ID = re.compile(r"^\d{8}-\d{6}-(?P<profile>.+)$")+"""`YYYYMMDD-HHMMSS-<profile>`, also the name of the run's directory."""++# Windows refuses os.replace while another process (e.g. `status`) holds the target open; such reads are brief.+REPLACE_ATTEMPTS = 20+REPLACE_RETRY_DELAY_S = 0.05++Kind = Literal["warmup", "measure"]+Expect = Literal["unchanged", "changed"]+"""What a case's image should do against its reference: stay the same, or change (a PR meant to change it)."""+++class _Model(BaseModel):+ # Records are written by one module and read by others; a misspelled field must fail loudly.+ model_config = ConfigDict(extra="forbid")+++class NodeTiming(_Model):+ node_id: str+ type: str+ t_start: float+ t_end: float | None+++class ModelLoad(_Model):+ model: str+ submodel: str | None+ t_start: float+ t_end: float | None+++class Timing(_Model):+ total_s: float+ """Enqueue to completed."""+ nodes: list[NodeTiming]+ model_loads: list[ModelLoad]+ per_step_s: float | None+ """Slope over the denoise node's invocation_progress events."""+ queue_started_at: str | None+ queue_completed_at: str | None+++class NodeMemory(_Model):+ node_id: str+ baseline_bytes: int | None+ peak_bytes: int | None+++class ForeignProcess(_Model):+ pid: int+ name: str | None+ dedicated_bytes: int+++class Memory(_Model):+ method: str+ interval_ms: float+ process_baseline_bytes: int | None+ """Just before enqueue."""+ process_peak_bytes: int | None+ nodes: list[NodeMemory]+ shared_max_delta_bytes: int | None+ """max(shared) - shared at enqueue."""+ foreign: list[ForeignProcess]+ """Other processes on the adapter above the threshold during the window."""+ trace: str | None+ """traces/<record_id>.csv.gz with columns series,t,bytes (series = dedicated|shared, t relative to enqueue)."""+++class Residency(_Model):+ model: str+ submodel: str | None+ vram_mb: float+ total_mb: float | None = None+ """The model's size as the cache logs it; absent in records written before the field existed."""+ percent: float+++class Record(_Model):+ record_id: str+ """`<case_key>.<arm>.<kind>.<rep>.<attempt>`."""+ run_id: str+ arm: str+ """`default` for normal runs, `A`/`B` for A/B runs."""+ case_id: str+ case_key: str+ """`<case_id>@<W>x<H>`."""+ family: str+ width: int+ height: int+ steps: int+ seed: int+ kind: Kind+ rep: int+ attempt: int+ queue_item_id: int | None+ graph_hash: str+ status: Literal["completed", "failed", "canceled", "error"]+ error: str | None+ image_path: str | None+ image_sha256: str | None+ image_width: int | None+ image_height: int | None+ timing: Timing | None+ memory: Memory | None+ residency: list[Residency]+ uses_fp8: bool+ valid_timing: bool+ valid_memory: bool+ valid_psnr: bool+ invalid_reasons: list[str]+++class Environment(_Model):+ code_dir: str+ git_commit: str | None+ git_branch: str | None+ git_dirty: bool | None+ python: str+ invokeai_file: str+ """`invokeai.__file__` as resolved by the server interpreter."""+ app_version: dict[str, Any]+ app_deps: dict[str, Any]+ runtime_config: dict[str, Any]+ gpu_description: str+ gpu_luid: int | None+ """None on Linux. NVML's device UUID is not recorded: a hardware serial that bundles would carry along."""+ gpu_driver: str | None = None+ """Absent in run.json and reference.json files written before the field existed."""+ server_cmd: list[str]+ extra_env: dict[str, str]+++class PlannedStep(_Model):+ case_key: str+ case_id: str+ family: str+ arm: str+ kind: Kind+ rep: int+++class Thresholds(_Model):+ psnr_min_db: float+ time_tolerance: float+ """Relative, e.g. 0.10 for 10 %."""+ peak_tolerance_mb: float+ expect: Expect = "unchanged"+ """Absent in run.json files written before the field existed."""+++class ModelIdentity(_Model):+ """A model as another machine can recognise it; `key` is local to this machine's database."""++ key: str+ name: str+ base: str+ type: str+ format: str | None+ variant: str | None+ hash: str | None+ source: str | None+ """An HF repo id or a public http(s) URL (`graphs.shareable_source`); None for a local path, a host of the local+ network, or a URL that may carry a token."""+++class RunInfo(_Model):+ run_id: str+ profile: str+ created_at: str+ finished_at: str | None+ status: Literal["running", "completed", "failed", "stopped"]+ manifest_path: str+ manifest_sha256: str+ tool_commit: str | None+ environments: dict[str, Environment]+ """Keyed by arm."""+ plan: list[PlannedStep]+ case_thresholds: dict[str, Thresholds]+ """Keyed by case_key."""+ graph_hashes: dict[str, str]+ """Keyed by case_key."""+ case_models: dict[str, list[ModelIdentity]] = {}+ """Keyed by case_key: the models its graph uses, main model first. Absent in runs written before the field."""+++class Reference(_Model):+ profile: str+ case_key: str+ source_run_id: str+ accepted_at: str+ image_sha256: str+ graph_hash: str+ environment: Environment+ total_s_median: float | None+ per_step_s_median: float | None+ process_peak_bytes_median: int | None+ node_peak_bytes_median: dict[str, int]+ """node_id -> bytes."""+++def append_record(run_dir: Path, record: Record) -> None:+ """Appends one line to records.jsonl and makes it durable before returning.++ An incomplete trailing line left by a killed writer is dropped first, so a resumed run keeps the file parseable.+ """+ path = run_dir / RECORDS_FILE+ line = (record.model_dump_json() + "\n").encode("utf-8")+ with open(path, "a+b") as f:+ _drop_incomplete_tail(f)+ f.write(line)+ f.flush()+ os.fsync(f.fileno())+++def _drop_incomplete_tail(f: Any) -> None:+ size = f.seek(0, os.SEEK_END)+ if size == 0:+ return+ f.seek(size - 1)+ if f.read(1) == b"\n":+ return+ f.seek(0)+ content = f.read()+ keep = content.rfind(b"\n") + 1+ tail = content[keep:]+ try:+ Record.model_validate_json(tail)+ except ValidationError:+ f.truncate(keep)+ else:+ f.write(b"\n")+ f.seek(0, os.SEEK_END)+++def load_records(run_dir: Path) -> list[Record]:+ """Loads all records. A run without records yields an empty list.++ An unparseable last line without a line terminator is the trace of a killed writer and is skipped; any other+ malformed line raises ValueError.+ """+ path = run_dir / RECORDS_FILE+ try:+ content = path.read_bytes()+ except FileNotFoundError:+ return []+ lines = content.split(b"\n")+ # A complete file ends with "\n", so the final element is empty; otherwise it is an unterminated tail.+ tail = lines.pop()+ records: list[Record] = []+ for number, line in enumerate(lines, start=1):+ if not line.strip():+ continue+ try:+ records.append(Record.model_validate_json(line))+ except ValidationError as e:+ raise ValueError(f"{path}: line {number} is not a valid record: {e}") from e+ if tail.strip():+ try:+ records.append(Record.model_validate_json(tail))+ except ValidationError:+ pass+ return records+++def write_bytes_atomic(path: Path, data: bytes) -> None:+ """Writes `data` to `path` so that readers see either the old or the new file, never a partial one."""+ fd, tmp_name = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")+ tmp = Path(tmp_name)+ try:+ with os.fdopen(fd, "wb") as f:+ f.write(data)+ f.flush()+ os.fsync(f.fileno())+ for attempt in range(REPLACE_ATTEMPTS):+ try:+ os.replace(tmp, path)+ return+ except PermissionError:+ if attempt == REPLACE_ATTEMPTS - 1:+ raise+ time.sleep(REPLACE_RETRY_DELAY_S)+ finally:+ tmp.unlink(missing_ok=True)+++def write_run_info(run_dir: Path, info: RunInfo) -> None:+ write_bytes_atomic(run_dir / RUN_INFO_FILE, info.model_dump_json(indent=2).encode("utf-8"))+++def load_run_info(run_dir: Path) -> RunInfo:+ return RunInfo.model_validate_json((run_dir / RUN_INFO_FILE).read_bytes())+++def run_id_profile(run_id: str) -> str | None:+ """The profile part of a run id, or None for a name that is no run id."""+ match = RUN_ID.match(run_id)+ return match["profile"] if match else Nonediff --git a/scripts/family_e2e/references.py b/scripts/family_e2e/references.pynew file mode 100644index 0000000000..9b004efa2f--- /dev/null+++ b/scripts/family_e2e/references.py@@ -0,0 +1,124 @@+"""Accepted references: the image and medians a later run is compared against.++References change only through `accept`, an explicit user command; nothing else in the tool writes them.+"""++from __future__ import annotations++import hashlib+import logging+import statistics+from collections import defaultdict+from datetime import datetime, timezone+from pathlib import Path++from scripts.family_e2e.manifest import DEFAULT_ARM+from scripts.family_e2e.metrics import measured_values, median+from scripts.family_e2e.records import Record, Reference, load_records, load_run_info, write_bytes_atomic++REFERENCE_FILE = "reference.json"+REFERENCE_IMAGE = "image.png"++logger = logging.getLogger(__name__)+++class AcceptError(ValueError):+ pass+++def reference_dir(data_dir: Path, profile: str, case_key: str) -> Path:+ return data_dir / "references" / profile / case_key+++def load_reference(data_dir: Path, profile: str, case_key: str) -> tuple[Reference, Path] | None:+ """Returns the reference and the path of its image (which may be missing), or None if none was accepted."""+ directory = reference_dir(data_dir, profile, case_key)+ try:+ content = (directory / REFERENCE_FILE).read_bytes()+ except FileNotFoundError:+ return None+ return Reference.model_validate_json(content), directory / REFERENCE_IMAGE+++def accept(data_dir: Path, run_dir: Path, case_keys: list[str] | None) -> list[Reference]:+ """Makes the measured results of `run_dir` the references of its profile, for `case_keys` or all its cases.++ Every requested case is checked before anything is written; any problem raises AcceptError and changes nothing.+ """+ info = load_run_info(run_dir)+ records = load_records(run_dir)+ arms = sorted(set(info.environments) | {r.arm for r in records})+ if arms != [DEFAULT_ARM]:+ raise AcceptError(f"run {info.run_id} has arms {', '.join(arms)}; references come only from normal runs")+ environment = info.environments.get(DEFAULT_ARM)+ if environment is None:+ raise AcceptError(f"run {info.run_id} has no recorded environment")++ by_case: dict[str, list[Record]] = defaultdict(list)+ for record in records:+ by_case[record.case_key].append(record)+ if case_keys is None:+ planned = [step.case_key for step in info.plan]+ case_keys = list(dict.fromkeys(planned + list(by_case)))+ if not case_keys:+ raise AcceptError(f"run {info.run_id} has no cases")++ accepted_at = datetime.now(timezone.utc).isoformat(timespec="seconds")+ staged: list[tuple[Reference, bytes]] = []+ problems: list[str] = []+ for case_key in dict.fromkeys(case_keys):+ measured = [r for r in by_case.get(case_key, []) if r.kind == "measure" and r.status == "completed"]+ candidates = [r for r in measured if r.valid_psnr and r.image_path]+ if not candidates:+ problems.append(f"{case_key}: no completed measured record with an image valid for PSNR")+ continue+ source = candidates[0]+ if (source.image_width, source.image_height) != (source.width, source.height):+ problems.append(+ f"{case_key}: image {source.image_width}x{source.image_height} is not the requested "+ f"{source.width}x{source.height}"+ )+ continue+ assert source.image_path is not None+ try:+ image = (run_dir / source.image_path).read_bytes()+ except OSError as e:+ problems.append(f"{case_key}: cannot read {source.image_path}: {e}")+ continue+ distinct = {r.image_sha256 for r in candidates}+ if len(distinct) > 1:+ logger.warning(+ "%s: the %d measured images are not identical (%d distinct); the reference uses %s",+ case_key,+ len(candidates),+ len(distinct),+ source.record_id,+ )+ values = measured_values(measured)+ process_peak = median(values.process_peak_bytes)+ reference = Reference(+ profile=info.profile,+ case_key=case_key,+ source_run_id=info.run_id,+ accepted_at=accepted_at,+ image_sha256=hashlib.sha256(image).hexdigest(),+ graph_hash=source.graph_hash,+ environment=environment,+ total_s_median=median(values.total_s),+ per_step_s_median=median(values.per_step_s),+ process_peak_bytes_median=None if process_peak is None else round(process_peak),+ node_peak_bytes_median={+ node_id: round(statistics.median(peaks)) for node_id, peaks in values.node_peak_bytes.items()+ },+ )+ staged.append((reference, image))+ if problems:+ raise AcceptError(f"nothing accepted from run {info.run_id}:\n" + "\n".join(problems))++ for reference, image in staged:+ directory = reference_dir(data_dir, reference.profile, reference.case_key)+ directory.mkdir(parents=True, exist_ok=True)+ write_bytes_atomic(directory / REFERENCE_IMAGE, image)+ write_bytes_atomic(directory / REFERENCE_FILE, reference.model_dump_json(indent=2).encode("utf-8"))+ logger.info("accepted %s from run %s", reference.case_key, reference.source_run_id)+ return [reference for reference, _ in staged]diff --git a/scripts/family_e2e/report.py b/scripts/family_e2e/report.pynew file mode 100644index 0000000000..2df7689159--- /dev/null+++ b/scripts/family_e2e/report.py@@ -0,0 +1,1206 @@+"""Static HTML report and Markdown summary of one run against the accepted references and the previous run.++The report only reads records and references. `write_report` writes report.html, summary.md and diff/ inside the run+directory; `render_report` renders them for another place, such as a bundle.+"""++from __future__ import annotations++import hashlib+import html+import json+import math+import os+import urllib.parse+from collections import Counter+from collections.abc import Callable, Iterable+from dataclasses import dataclass, field+from pathlib import Path+from typing import Literal, Protocol++import numpy as np++from scripts.family_e2e.manifest import DEFAULT_ARM+from scripts.family_e2e.metrics import (+ DIFF_GAIN,+ MB,+ Delta,+ compare_peak,+ compare_time,+ load_rgb,+ measured_values,+ median,+ psnr,+ write_diff_image,+)+from scripts.family_e2e.records import (+ Environment,+ ModelIdentity,+ Record,+ Reference,+ RunInfo,+ Thresholds,+ load_records,+ load_run_info,+ run_id_profile,+ write_bytes_atomic,+)+from scripts.family_e2e.references import load_reference+from scripts.family_e2e.residency import resident, weightless++REPORT_FILE = "report.html"+SUMMARY_FILE = "summary.md"+DIFF_DIR = "diff"+# invokeai.yaml settings that change speed, memory peaks or (sage, int8_compute) the image itself; SageAttention is+# attention_backend=sage, rocm_aotriton_experimental picks the attention kernels on AMD GPUs, and int8_compute runs+# int8 checkpoints on int8 matmul kernels.+RUNTIME_CONFIG_KEYS = (+ "pytorch_cuda_alloc_conf",+ "enable_partial_loading",+ "device_working_mem_gb",+ "attention_type",+ "attention_slice_size",+ "attention_backend",+ "rocm_aotriton_experimental",+ "int8_compute",+)++# CHANGED: a case expected to change differs from its reference. BASELINE: its reference comes from this run, so+# there is nothing to compare against. Neither is a failure.+Status = Literal["PASS", "CHANGED", "BASELINE", "FAIL", "ERROR", "INVALID", "NO-REFERENCE"]+STATUSES: tuple[Status, ...] = ("PASS", "CHANGED", "BASELINE", "FAIL", "ERROR", "INVALID", "NO-REFERENCE")+Unit = Literal["s", "bytes"]+++@dataclass(frozen=True)+class RenderedReport:+ html: str+ summary: str+ failures: int+ """Cases with status FAIL or ERROR."""+ outliers: int+ """Cases with at least one outlier against the reference or the previous run."""+ invalid: int+ """Cases with status INVALID or with measured runs invalid for time, VRAM or PSNR (e.g. partial residency)."""+ changed: int+ """Cases with status CHANGED."""+ baseline: int+ """Cases with status BASELINE."""+++@dataclass(frozen=True)+class ReportResult:+ """Where `write_report` wrote the report, with the counts of its RenderedReport."""++ report_html: Path+ summary_md: Path+ failures: int+ outliers: int+ invalid: int+ changed: int+ baseline: int+++def write_report(data_dir: Path, run_dir: Path) -> ReportResult:+ report = render_report(+ data_dir,+ run_dir,+ load_run_info(run_dir),+ load_records(run_dir),+ diff_dir=run_dir / DIFF_DIR,+ href=lambda path: _href(path, run_dir),+ )+ report_path = run_dir / REPORT_FILE+ summary_path = run_dir / SUMMARY_FILE+ write_bytes_atomic(report_path, report.html.encode("utf-8"))+ write_bytes_atomic(summary_path, report.summary.encode("utf-8"))+ return ReportResult(+ report_path, summary_path, report.failures, report.outliers, report.invalid, report.changed, report.baseline+ )+++class Scrubber(Protocol):+ """What a rendered report must not show, for a report that leaves this machine."""++ def text(self, value: str) -> str:+ """Cleans the text of an error the report describes itself, e.g. an unreadable earlier run or image."""+ ...++ def environment(self, environment: Environment) -> Environment:+ """Cleans an environment the report compares; it treats the run's own and the earlier ones alike."""+ ...+++class _Unchanged:+ def text(self, value: str) -> str:+ return value++ def environment(self, environment: Environment) -> Environment:+ return environment+++_UNCHANGED = _Unchanged()+++def render_report(+ data_dir: Path,+ run_dir: Path,+ info: RunInfo,+ records: list[Record],+ *,+ diff_dir: Path,+ href: Callable[[Path], str],+ scrubber: Scrubber = _UNCHANGED,+ status: str | None = None,+) -> RenderedReport:+ """Evaluates the run's cases and renders the report; writes nothing but the difference images into `diff_dir`.++ `href` links each image file the report shows. `status` names the run's state when its recorded status is out+ of date, e.g. for a run whose runner died.+ """+ context = _Context(+ data_dir, run_dir, info, _History(data_dir, info), _ImageCache(scrubber.text), diff_dir, scrubber+ )+ cases = [+ _evaluate_safely(context, arm, case_key, case_records)+ for (arm, case_key), case_records in _group(info, records).items()+ ]+ notes = [scrubber.text(note) for note in context.history.notes]+ run_status = status or info.status+ return RenderedReport(+ html=_render_html(context, cases, notes, href, run_status),+ summary=_render_summary(info, cases, notes, run_status),+ failures=sum(case.status in ("FAIL", "ERROR") for case in cases),+ outliers=sum(case.has_outliers for case in cases),+ invalid=sum(case.status == "INVALID" or bool(case.invalid_metrics) for case in cases),+ changed=sum(case.status == "CHANGED" for case in cases),+ baseline=sum(case.status == "BASELINE" for case in cases),+ )+++def previous_runs(data_dir: Path, info: RunInfo, case_keys: Iterable[str]) -> list[RunInfo]:+ """The earlier runs the report compares the cases with, each once."""+ history = _History(data_dir, info)+ runs: dict[str, RunInfo] = {}+ for case_key in case_keys:+ previous = history.previous(case_key)+ if previous is not None:+ runs.setdefault(previous.run.info.run_id, previous.run.info)+ return list(runs.values())+++# ---------------------------------------------------------------------------------------------------------------------+# Inputs+++def _group(info: RunInfo, records: list[Record]) -> dict[tuple[str, str], list[Record]]:+ """Records by (arm, case_key) in plan order, default arm first; planned cases without records stay visible."""+ keys = [(step.arm, step.case_key) for step in info.plan] + [(r.arm, r.case_key) for r in records]+ ordered = sorted(dict.fromkeys(keys), key=lambda key: key[0] != DEFAULT_ARM)+ groups: dict[tuple[str, str], list[Record]] = {key: [] for key in ordered}+ for record in records:+ groups[(record.arm, record.case_key)].append(record)+ return groups+++@dataclass(frozen=True)+class _Run:+ run_dir: Path+ info: RunInfo+ records: list[Record]+++@dataclass(frozen=True)+class _Previous:+ run: _Run+ records: list[Record]+ """Completed measured records of the case."""+ image_path: Path | None+++class _History:+ """Earlier runs of the same profile, newest first, read only when a case needs them.++ The profile comes from the directory name, so runs of other profiles are never read: one that another version+ of the tool wrote would not load, and is no previous run anyway.+ """++ def __init__(self, data_dir: Path, current: RunInfo) -> None:+ self._profile = current.profile+ runs_dir = data_dir / "runs"+ names = sorted((d.name for d in runs_dir.iterdir() if d.is_dir()), reverse=True) if runs_dir.is_dir() else []+ self._candidates = [+ runs_dir / name for name in names if name < current.run_id and run_id_profile(name) == current.profile+ ]+ self._loaded: dict[Path, _Run | None] = {}+ self.notes: list[str] = []++ def previous(self, case_key: str) -> _Previous | None:+ """The latest earlier normal run with completed measured records of `case_key`."""+ for run_dir in self._candidates:+ run = self._load(run_dir)+ if run is None:+ continue+ case_records = [r for r in run.records if r.case_key == case_key and r.arm == DEFAULT_ARM]+ records = [r for r in _final_records(case_records) if r.kind == "measure" and r.status == "completed"]+ if records:+ source = next((r for r in records if r.valid_psnr and r.image_path), None)+ image_path = run_dir / source.image_path if source and source.image_path else None+ return _Previous(run, records, image_path)+ return None++ def _load(self, run_dir: Path) -> _Run | None:+ if run_dir not in self._loaded:+ run: _Run | None = None+ try:+ info = load_run_info(run_dir)+ if info.profile == self._profile:+ run = _Run(run_dir, info, load_records(run_dir))+ except FileNotFoundError:+ pass+ except (OSError, ValueError) as e:+ self.notes.append(f"Earlier run {run_dir.name} skipped, unreadable: {_first_line(e)}")+ self._loaded[run_dir] = run+ return self._loaded[run_dir]+++class _ImageCache:+ def __init__(self, scrub: Callable[[str], str]) -> None:+ self._arrays: dict[Path, np.ndarray | str] = {}+ self._scrub = scrub++ def get(self, path: Path) -> np.ndarray | str:+ """The decoded image, or why it is unavailable."""+ if path not in self._arrays:+ try:+ self._arrays[path] = load_rgb(path)+ except FileNotFoundError:+ self._arrays[path] = "image missing"+ except OSError as e: # PIL names the file in its message+ self._arrays[path] = f"image unreadable: {self._scrub(_first_line(e))}"+ return self._arrays[path]+++@dataclass(frozen=True)+class _Context:+ data_dir: Path+ run_dir: Path+ info: RunInfo+ history: _History+ images: _ImageCache+ diff_dir: Path+ scrubber: Scrubber+++def _node_types(run_dir: Path, case_key: str) -> dict[str, str]:+ """node_id -> node type from graphs/<case_key>.json (a graph, or a batch holding one under `graph`)."""+ try:+ data = json.loads((run_dir / "graphs" / f"{case_key}.json").read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return {}+ graph = data.get("graph", data) if isinstance(data, dict) else None+ nodes = graph.get("nodes") if isinstance(graph, dict) else None+ if not isinstance(nodes, dict):+ return {}+ return {node_id: str(node["type"]) for node_id, node in nodes.items() if isinstance(node, dict) and "type" in node}+++def _environment_facts(env: Environment) -> dict[str, str | None]:+ """The parts of an environment that change images, times or memory peaks."""+ deps = {name.lower(): version for name, version in env.app_deps.items()}+ config = env.runtime_config.get("config", env.runtime_config)+ if not isinstance(config, dict):+ config = {}++ def text(value: object) -> str | None:+ return None if value is None else str(value)++ return {+ "app version": text(env.app_version.get("version")),+ "torch": text(deps.get("torch")),+ "CUDA": text(deps.get("cuda")),+ "GPU": env.gpu_description,+ "GPU driver": env.gpu_driver,+ **{key: text(config.get(key)) for key in RUNTIME_CONFIG_KEYS},+ }+++def _environment_changes(before: Environment, after: Environment | None) -> list[str]:+ if after is None:+ return ["this run has no recorded environment"]+ old, new = _environment_facts(before), _environment_facts(after)+ return [f"{key} {_dash(old[key])} → {_dash(new[key])}" for key in old if old[key] != new[key]]+++# ---------------------------------------------------------------------------------------------------------------------+# Evaluation+++@dataclass(frozen=True)+class _Image:+ title: str+ path: Path | None+ caption: str+++@dataclass+class _Row:+ record: Record+ psnr_reference: float | str | None = None+ psnr_previous: float | str | None = None+ final: bool = True+ """The last attempt of its step; earlier attempts were retried and do not count."""++ @property+ def rated(self) -> bool:+ """Counts for the quality verdict."""+ r = self.record+ return self.final and r.kind == "measure" and r.status == "completed" and r.valid_psnr and bool(r.image_path)+++@dataclass(frozen=True)+class _Metric:+ label: str+ unit: Unit+ values: list[float]+ reference: float | None+ previous: float | None+ vs_reference: Delta | None+ vs_previous: Delta | None+ invalid: str | None = None+ """Why there are no values although measured runs completed."""++ @property+ def median_text(self) -> str:+ return "invalid" if self.invalid else _value_text(median(self.values), self.unit)+++@dataclass(frozen=True)+class _Node:+ label: str+ duration_s: float | None+ baseline_bytes: float | None+ peak: _Metric+++@dataclass+class _Case:+ arm: str+ case_key: str+ family: str+ status: Status = "PASS"+ size: tuple[int, int] | None = None+ reasons: list[str] = field(default_factory=list)+ flags: list[str] = field(default_factory=list)+ outliers: list[str] = field(default_factory=list)+ node_outliers: list[str] = field(default_factory=list)+ invalid_metrics: list[str] = field(default_factory=list)+ min_psnr: float | None = None+ psnr_min_db: float | None = None+ rows: list[_Row] = field(default_factory=list)+ metrics: list[_Metric] = field(default_factory=list)+ nodes: list[_Node] = field(default_factory=list)+ images: list[_Image] = field(default_factory=list)+ reference: Reference | None = None+ models: list[ModelIdentity] = field(default_factory=list)++ @property+ def has_outliers(self) -> bool:+ return bool(self.outliers or self.node_outliers)++ @property+ def label(self) -> str:+ return self.case_key if self.arm == DEFAULT_ARM else f"{self.case_key} [{self.arm}]"++ @property+ def anchor(self) -> str:+ return "case-" + "".join(c if c.isalnum() else "-" for c in self.label)+++def _evaluate_safely(context: _Context, arm: str, case_key: str, records: list[Record]) -> _Case:+ family = records[0].family if records else next((s.family for s in context.info.plan if s.case_key == case_key), "")+ case = _Case(arm, case_key, family, models=context.info.case_models.get(case_key, []))+ try:+ _evaluate(context, case, records)+ except Exception as e: # one broken case must not hide the others+ case.status = "ERROR"+ case.reasons.append(f"the report could not evaluate this case: {context.scrubber.text(repr(e))}")+ return case+++def _evaluate(context: _Context, case: _Case, records: list[Record]) -> None:+ info, images = context.info, context.images+ if records:+ case.size = (records[0].width, records[0].height)+ thresholds = info.case_thresholds.get(case.case_key)+ case.psnr_min_db = thresholds.psnr_min_db if thresholds else None++ reference_image: np.ndarray | str | None = None+ reference_problem: str | None = None+ try:+ loaded = load_reference(context.data_dir, info.profile, case.case_key)+ except ValueError as e:+ loaded, reference_problem = None, f"reference.json unreadable: {_first_line(e)}"+ if loaded is not None:+ case.reference, reference_path = loaded+ reference_image = images.get(reference_path)+ if isinstance(reference_image, str):+ reference_problem = f"reference {reference_image}"+ elif hashlib.sha256(reference_path.read_bytes()).hexdigest() != case.reference.image_sha256:+ case.flags.append("reference image does not match reference.json")+ source = case.reference.source_run_id+ caption = "accepted from this run" if source == info.run_id else f"accepted from {source}"+ case.images.append(_Image("Reference", reference_path, caption))+ else:+ case.images.append(_Image("Reference", None, reference_problem or "no accepted reference"))++ previous = context.history.previous(case.case_key)+ previous_image = images.get(previous.image_path) if previous and previous.image_path else None++ final = _final_records(records)+ final_ids = {r.record_id for r in final}+ for record in records:+ row = _Row(record, final=record.record_id in final_ids)+ if record.status == "completed" and record.image_path:+ image = images.get(context.run_dir / record.image_path)+ row.psnr_reference = _psnr_or_problem(image, reference_image)+ row.psnr_previous = _psnr_or_problem(image, previous_image)+ case.rows.append(row)++ _set_status(case, final, thresholds, reference_problem, info.run_id)+ _compare_metrics(case, context.run_dir, final, previous, thresholds)+ _set_change_flags(context, case, previous)+ _add_images(case, context, reference_image, previous, previous_image)+++def _psnr_or_problem(image: np.ndarray | str, other: np.ndarray | str | None) -> float | str | None:+ if other is None or isinstance(other, str):+ return None+ if isinstance(image, str):+ return image+ try:+ return psnr(image, other)+ except ValueError as e:+ return str(e)+++def _set_status(+ case: _Case, final: list[Record], thresholds: Thresholds | None, reference_problem: str | None, run_id: str+) -> None:+ """Judges each step by its final attempt; a failure that a later attempt recovered from stays visible as a flag.++ Errors, invalid runs and a missing reference come first. A reference set from this run gives BASELINE. Then the+ minimum PSNR against the reference decides: below the threshold is FAIL, or CHANGED for a case expected to change,+ which fails when it matches instead.+ """+ rated = [row for row in case.rows if row.rated]+ values = [row.psnr_reference for row in rated if isinstance(row.psnr_reference, float)]+ case.min_psnr = min(values) if values else None+ case.flags += [+ f"earlier attempt {row.record.record_id} {row.record.status}: {row.record.error or 'no error message'}"+ for row in case.rows+ if not row.final and row.record.status in ("failed", "error")+ ]+ errored = [r for r in final if r.status in ("failed", "error")]+ wrong_size = [+ r+ for r in final+ if r.status == "completed"+ and r.image_width is not None+ and (r.image_width, r.image_height) != (r.width, r.height)+ ]+ unrated = [f"{row.record.record_id}: {row.psnr_reference}" for row in rated if isinstance(row.psnr_reference, str)]++ if errored:+ case.status = "ERROR"+ case.reasons += [f"{r.record_id}: {r.status}: {r.error or 'no error message'}" for r in errored]+ elif wrong_size:+ case.status = "FAIL"+ case.reasons += [+ f"{r.record_id}: image is {r.image_width}x{r.image_height}, requested {r.width}x{r.height}"+ for r in wrong_size+ ]+ elif not rated:+ case.status = "INVALID"+ case.reasons += _invalid_reasons([r for r in final if r.kind == "measure"])+ elif case.reference is None or reference_problem is not None:+ case.status = "NO-REFERENCE"+ case.reasons.append(reference_problem or "no accepted reference; set one with `accept`")+ elif unrated:+ case.status = "FAIL"+ case.reasons += unrated+ elif case.reference.source_run_id == run_id:+ case.status = "BASELINE"+ case.reasons.append("reference set from this run")+ elif thresholds is None:+ case.status = "INVALID"+ case.reasons.append("run.json has no thresholds for this case")+ else:+ differs = case.min_psnr is not None and case.min_psnr < thresholds.psnr_min_db+ min_psnr = f"min PSNR {_psnr_text(case.min_psnr)}"+ if thresholds.expect == "changed":+ case.status = "CHANGED" if differs else "FAIL"+ case.reasons.append(+ f"differs from reference as expected ({min_psnr})"+ if differs+ else f"expected a change, but the output matches the reference ({min_psnr})"+ )+ elif differs:+ case.status = "FAIL"+ case.reasons.append(f"{min_psnr} is below {thresholds.psnr_min_db:g} dB")+++def _invalid_reasons(measured: list[Record]) -> list[str]:+ """Why no measured image is rated; the per-metric reasons are in `invalid_metrics`."""+ if not measured:+ return ["no measured records"]+ reasons = Counter(r.status if r.status != "completed" else "no image" for r in measured if not r.image_path)+ lines = [f"{reason} ({count} of {len(measured)} measured)" for reason, count in reasons.items()]+ return lines or ["no measured image is valid for PSNR"]+++def _final_records(records: list[Record]) -> list[Record]:+ """The last attempt of each step of one case and arm, in record order.++ The runner retries a step whose attempt foreign load spoiled, and `resume` reruns a step that failed.+ """+ final: dict[tuple[str, int], Record] = {}+ for record in records:+ step = (record.kind, record.rep)+ if step not in final or record.attempt > final[step].attempt:+ final[step] = record+ return [record for record in records if final[(record.kind, record.rep)] is record]+++_VALIDITY: tuple[tuple[str, Callable[[Record], bool]], ...] = (+ ("time", lambda r: r.valid_timing),+ ("VRAM", lambda r: r.valid_memory),+ ("PSNR", lambda r: r.valid_psnr),+)+++def _set_invalid_metrics(case: _Case, final: list[Record]) -> dict[str, str]:+ """Lists which metrics the final measured runs could not deliver and why; returns metric -> reasons."""+ notes: Counter[tuple[tuple[str, ...], str]] = Counter()+ reasons_by_metric: dict[str, dict[str, None]] = {name: {} for name, _ in _VALIDITY}+ for record in final:+ if record.status != "completed":+ continue+ affected = tuple(name for name, valid in _VALIDITY if not valid(record))+ for reason in dict.fromkeys(record.invalid_reasons or ["no reason recorded"]) if affected else []:+ notes[(affected, reason)] += 1+ for name in affected:+ reasons_by_metric[name][reason] = None+ case.invalid_metrics = [+ f"{_join(affected)} invalid: {reason} ({count} of {len(final)} measured)"+ for (affected, reason), count in notes.items()+ ]+ return {name: "; ".join(reasons) for name, reasons in reasons_by_metric.items() if reasons}+++def _join(names: tuple[str, ...]) -> str:+ return names[0] if len(names) == 1 else f"{', '.join(names[:-1])} and {names[-1]}"+++def _compare_metrics(+ case: _Case, run_dir: Path, final: list[Record], previous: _Previous | None, thresholds: Thresholds | None+) -> None:+ current = measured_values(final)+ before = measured_values(previous.records if previous else [])+ # A reference from this run holds this run's own medians; comparing against them says nothing.+ reference = None if case.status == "BASELINE" else case.reference+ invalid = _set_invalid_metrics(case, [r for r in final if r.kind == "measure"])++ def metric(+ label: str,+ unit: Unit,+ values: list[float],+ ref: float | None,+ prev: float | None,+ outliers: list[str],+ invalid_reason: str | None = None,+ ) -> _Metric:+ def compare(baseline: float | None) -> Delta | None:+ if baseline is None or thresholds is None:+ return None+ if unit == "s":+ return compare_time(values, baseline, thresholds.time_tolerance)+ return compare_peak(values, baseline, thresholds.peak_tolerance_mb)++ reason = invalid_reason if not values else None+ result = _Metric(label, unit, values, ref, prev, compare(ref), compare(prev), reason)+ for target, delta in (("reference", result.vs_reference), ("previous run", result.vs_previous)):+ if delta is not None and delta.outlier:+ outliers.append(f"{label} vs {target}: {_delta_text(delta, unit)}")+ return result++ case.metrics = [+ metric(+ "Total time",+ "s",+ current.total_s,+ reference.total_s_median if reference else None,+ median(before.total_s),+ case.outliers,+ invalid.get("time"),+ ),+ metric(+ "Time per step",+ "s",+ current.per_step_s,+ reference.per_step_s_median if reference else None,+ median(before.per_step_s),+ case.outliers,+ invalid.get("time"),+ ),+ metric(+ "VRAM peak",+ "bytes",+ [float(v) for v in current.process_peak_bytes],+ reference.process_peak_bytes_median if reference else None,+ median(before.process_peak_bytes),+ case.outliers,+ invalid.get("VRAM"),+ ),+ ]++ types = _node_types(run_dir, case.case_key)+ for record in final:+ for node in record.timing.nodes if record.timing else []:+ types.setdefault(node.node_id, node.type)+ for node_id in dict.fromkeys([*current.node_duration_s, *current.node_peak_bytes]):+ label = f"{types[node_id]} · {node_id}" if node_id in types else node_id+ peak = metric(+ f"{label} peak",+ "bytes",+ [float(v) for v in current.node_peak_bytes.get(node_id, [])],+ reference.node_peak_bytes_median.get(node_id) if reference else None,+ median(before.node_peak_bytes.get(node_id, [])),+ case.node_outliers,+ )+ duration = median(current.node_duration_s.get(node_id, []))+ case.nodes.append(_Node(label, duration, median(current.node_baseline_bytes.get(node_id, [])), peak))+++def _set_change_flags(context: _Context, case: _Case, previous: _Previous | None) -> None:+ info, clean = context.info, context.scrubber.environment+ graph_hash = info.graph_hashes.get(case.case_key) or next((row.record.graph_hash for row in case.rows), None)+ environment = info.environments.get(case.arm)+ environment = None if environment is None else clean(environment)+ if case.reference is not None:+ if graph_hash != case.reference.graph_hash:+ case.flags.append("graph changed vs reference")+ changes = _environment_changes(clean(case.reference.environment), environment)+ if changes:+ case.flags.append("environment changed vs reference: " + "; ".join(changes))+ if previous is not None:+ previous_hash = previous.run.info.graph_hashes.get(case.case_key) or previous.records[0].graph_hash+ if graph_hash != previous_hash:+ case.flags.append("graph changed vs previous run")+ previous_environment = previous.run.info.environments.get(DEFAULT_ARM)+ if previous_environment is not None:+ changes = _environment_changes(clean(previous_environment), environment)+ if changes:+ case.flags.append("environment changed vs previous run: " + "; ".join(changes))+ shas = {row.record.image_sha256 for row in case.rows if row.rated}+ if len(shas) > 1:+ case.flags.append(f"measured images differ from each other ({len(shas)} distinct)")+++def _add_images(+ case: _Case,+ context: _Context,+ reference_image: np.ndarray | str | None,+ previous: _Previous | None,+ previous_image: np.ndarray | str | None,+) -> None:+ candidates = [row for row in case.rows if row.rated] or [+ row for row in case.rows if row.record.status == "completed" and row.record.image_path+ ]+ # The worst image tells most about a quality regression.+ shown = min(candidates, key=_psnr_sort_key, default=None)+ shown_path = context.run_dir / shown.record.image_path if shown and shown.record.image_path else None+ if shown is None:+ case.images.append(_Image("This run", None, "no image"))+ else:+ case.images.append(_Image("This run", shown_path, shown.record.record_id))++ if previous is None:+ case.images.append(_Image("Previous run", None, "no earlier run of this case"))+ elif previous.image_path is None:+ case.images.append(_Image("Previous run", None, f"{previous.run.info.run_id} has no image valid for PSNR"))+ else:+ case.images.append(_Image("Previous run", previous.image_path, previous.run.info.run_id))++ base, base_name = (+ (reference_image, "reference") if isinstance(reference_image, np.ndarray) else (previous_image, "previous run")+ )+ title = f"Difference ×{DIFF_GAIN}"+ image = context.images.get(shown_path) if shown_path else None+ if not isinstance(image, np.ndarray) or not isinstance(base, np.ndarray):+ case.images.append(_Image(title, None, "needs this run's image and a reference or previous image"))+ return+ suffix = "" if case.arm == DEFAULT_ARM else f".{case.arm}"+ diff_path = context.diff_dir / f"{case.case_key}{suffix}.png"+ try:+ write_diff_image(image, base, diff_path)+ identical = np.array_equal(image, base)+ except ValueError as e:+ case.images.append(_Image(title, None, str(e)))+ else:+ case.images.append(_Image(title, diff_path, f"this run vs {base_name}" + (" · identical" if identical else "")))+++def _psnr_sort_key(row: _Row) -> float:+ if isinstance(row.psnr_reference, str): # a missing or mismatched image is the worst+ return -math.inf+ return row.psnr_reference if row.psnr_reference is not None else math.inf+++# ---------------------------------------------------------------------------------------------------------------------+# Formatting+++def _first_line(error: BaseException) -> str:+ return str(error).strip().splitlines()[0] if str(error).strip() else type(error).__name__+++def _dash(value: object) -> str:+ return "—" if value is None else str(value)+++def _psnr_text(value: float | str | None) -> str:+ if value is None:+ return "—"+ if isinstance(value, str):+ return value+ return "∞" if math.isinf(value) else f"{value:.2f} dB"+++def _value_text(value: float | None, unit: Unit) -> str:+ if value is None:+ return "—"+ if unit == "bytes":+ return f"{value / MB:,.0f} MB"+ return f"{value:.3f} s" if abs(value) < 10 else f"{value:.2f} s"+++def _delta_text(delta: Delta, unit: Unit) -> str:+ sign = "+" if delta.delta >= 0 else "-"+ amount = _value_text(abs(delta.delta), unit)+ return f"{sign}{amount}" if delta.relative is None else f"{sign}{amount} ({delta.relative:+.1%})"+++def _relative_text(delta: Delta | None) -> str:+ if delta is None or delta.relative is None:+ return "—"+ return f"{delta.relative:+.1%}"+++def _short_hash(value: str | None) -> str:+ """`blake3:<64 hex>` as `blake3:<12 hex>`: enough to tell models apart."""+ if not value:+ return "—"+ algorithm, _, digest = value.rpartition(":")+ return f"{algorithm}:{digest[:12]}" if algorithm else digest[:12]+++def _model_text(model: ModelIdentity) -> str:+ return f"{model.name} ({model.type}, {_short_hash(model.hash)})"+++def _href(path: Path, run_dir: Path) -> str:+ return urllib.parse.quote(Path(os.path.relpath(path, run_dir)).as_posix())+++def _e(value: object) -> str:+ return html.escape(str(value))+++# ---------------------------------------------------------------------------------------------------------------------+# HTML++_CSS = """+:root { color-scheme: light dark;+ --bg: #f6f7f9; --card: #ffffff; --fg: #1f2328; --muted: #59636e; --border: #d1d9e0; --stripe: #f3f5f7;+ --pass-bg: #dafbe1; --pass-fg: #116329; --fail-bg: #ffebe9; --fail-fg: #a40e26;+ --invalid-bg: #fff1c2; --invalid-fg: #6f4400; --noref-bg: #ddf4ff; --noref-fg: #0a3069;+ --changed-bg: #fbefff; --changed-fg: #6e40c9; --baseline-bg: #eaeef2; --baseline-fg: #424a53;+ --warn: #9a6700; --link: #0969da; }+@media (prefers-color-scheme: dark) { :root {+ --bg: #0d1117; --card: #161b22; --fg: #e6edf3; --muted: #9198a1; --border: #30363d; --stripe: #1b2129;+ --pass-bg: #12361f; --pass-fg: #7ee2a8; --fail-bg: #4a1a1f; --fail-fg: #ffa198;+ --invalid-bg: #3b2e0a; --invalid-fg: #e3b341; --noref-bg: #0f2a4a; --noref-fg: #79c0ff;+ --changed-bg: #2e1f4d; --changed-fg: #d2a8ff; --baseline-bg: #262c36; --baseline-fg: #b7bdc8;+ --warn: #e3b341; --link: #4493f8; } }+* { box-sizing: border-box; }+body { margin: 0; background: var(--bg); color: var(--fg);+ font: 14px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }+main { max-width: 1440px; margin: 0 auto; padding: 24px 32px 48px; }+a { color: var(--link); }+h1 { font-size: 22px; margin: 0 0 4px; }+h2 { font-size: 17px; margin: 32px 0 12px; }+h3 { font-size: 16px; margin: 0; display: flex; gap: 10px; align-items: baseline; flex-wrap: wrap; }+h4 { font-size: 13px; margin: 20px 0 6px; color: var(--muted); text-transform: uppercase; letter-spacing: .04em; }+.muted { color: var(--muted); font-weight: normal; }+.meta { color: var(--muted); margin: 0; }+.counts { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 12px; }+.badge { display: inline-block; padding: 1px 9px; border-radius: 999px; font-size: 12px; font-weight: 600;+ white-space: nowrap; }+.s-PASS { background: var(--pass-bg); color: var(--pass-fg); }+.s-FAIL, .s-ERROR { background: var(--fail-bg); color: var(--fail-fg); }+.s-INVALID { background: var(--invalid-bg); color: var(--invalid-fg); }+.s-NO-REFERENCE { background: var(--noref-bg); color: var(--noref-fg); }+.s-CHANGED { background: var(--changed-bg); color: var(--changed-fg); }+.s-BASELINE { background: var(--baseline-bg); color: var(--baseline-fg); }+.s-outlier { background: var(--invalid-bg); color: var(--invalid-fg); }+table { border-collapse: collapse; width: 100%; background: var(--card); }+th, td { text-align: left; padding: 5px 10px; border-bottom: 1px solid var(--border); vertical-align: top; }+th { font-weight: 600; color: var(--muted); font-size: 12px; }+tbody tr:nth-child(even) { background: var(--stripe); }+td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }+.table-wrap { overflow-x: auto; border: 1px solid var(--border); border-radius: 8px; }+.table-wrap table { border: 0; }+.case { background: var(--card); border: 1px solid var(--border); border-radius: 10px; padding: 18px 20px;+ margin: 18px 0; }+.case ul { margin: 8px 0 0; padding-left: 20px; }+.case ul.models { list-style: none; padding: 0; margin: 6px 0 0; display: flex; flex-wrap: wrap; gap: 2px 20px;+ font-size: 13px; }+.reasons li { color: var(--fail-fg); }+.case.s-INVALID-case .reasons li, .case.s-NO-REFERENCE-case .reasons li, .case.s-CHANGED-case .reasons li,+.case.s-BASELINE-case .reasons li { color: var(--fg); }+.flags li { color: var(--warn); }+.outlier { color: var(--warn); font-weight: 600; }+td.invalid { color: var(--invalid-fg); font-weight: 600; cursor: help; text-decoration: underline dotted; }+.images { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 14px; margin-top: 14px; }+figure { margin: 0; }+figcaption { font-size: 12px; margin-bottom: 4px; }+figcaption strong { display: block; font-size: 13px; }+figure img { display: block; width: 100%; height: auto; border: 1px solid var(--border); border-radius: 6px;+ background: var(--stripe); }+.placeholder { display: flex; align-items: center; justify-content: center; text-align: center; padding: 12px;+ border: 1px dashed var(--border); border-radius: 6px; color: var(--muted); }+tr.warmup td { color: var(--muted); font-style: italic; }+table.generations td:first-child { white-space: nowrap; }+table.compact { width: auto; min-width: 50%; }+.notes li { color: var(--warn); }+@media (max-width: 900px) { .images { grid-template-columns: repeat(2, minmax(0, 1fr)); } main { padding: 16px; } }+"""+++def _render_html(+ context: _Context, cases: list[_Case], notes: list[str], href: Callable[[Path], str], run_status: str+) -> str:+ info = context.info+ counts = Counter(case.status for case in cases)+ outliers = sum(case.has_outliers for case in cases)+ count_badges = "".join(+ f'<span class="badge s-{status}">{counts[status]} {status}</span>' for status in STATUSES if counts[status]+ )+ if outliers:+ count_badges += f'<span class="badge s-outlier">{outliers} with outliers</span>'+ invalid_metrics = sum(bool(case.invalid_metrics) for case in cases)+ if invalid_metrics:+ count_badges += f'<span class="badge s-INVALID">{invalid_metrics} with invalid metrics</span>'+ finished = f" · finished {_e(info.finished_at)}" if info.finished_at else ""+ parts = [+ '<!doctype html><html lang="en"><head><meta charset="utf-8">',+ '<meta name="viewport" content="width=device-width, initial-scale=1">',+ f"<title>Family E2E {_e(info.run_id)}</title><style>{_CSS}</style></head><body><main>",+ f'<header><h1>Family E2E report</h1><p class="meta">{_e(info.run_id)} · profile {_e(info.profile)} · '+ f"run {_e(run_status)} · started {_e(info.created_at)}{finished}</p>",+ f'<div class="counts">{count_badges or "<span class=muted>no cases</span>"}</div></header>',+ ]+ if run_status != "completed":+ notes = [f"The run is {run_status}; cases it did not reach show as INVALID.", *notes]+ if notes:+ parts.append('<ul class="notes">' + "".join(f"<li>{_e(note)}</li>" for note in notes) + "</ul>")+ parts.append(_environment_html(info))+ parts.append(_overview_html(cases))+ parts += [_case_html(case, href) for case in cases]+ parts.append("</main></body></html>")+ return "\n".join(parts)+++def _environment_html(info: RunInfo) -> str:+ arms = list(info.environments)+ if not arms:+ return "<h2>Environment</h2><p class=muted>No environment recorded.</p>"+ facts = {arm: _environment_facts(env) for arm, env in info.environments.items()}+ rows: list[tuple[str, list[str]]] = []+ rows.append(("code", [env.code_dir for env in info.environments.values()]))+ rows.append(+ (+ "commit",+ [+ f"{_dash(env.git_commit)[:12]} {_dash(env.git_branch)}" + (" (dirty)" if env.git_dirty else "")+ for env in info.environments.values()+ ],+ )+ )+ for key in next(iter(facts.values())):+ rows.append((key, [_dash(facts[arm][key]) for arm in arms]))+ header = "".join(f"<th>{_e(arm)}</th>" for arm in arms)+ body = "".join(+ f"<tr><th scope=row>{_e(key)}</th>" + "".join(f"<td>{_e(v)}</td>" for v in values) + "</tr>"+ for key, values in rows+ )+ manifest = f"manifest {_e(info.manifest_path)} · sha256 {_e(info.manifest_sha256[:12])}"+ tool = f" · tool commit {_e(info.tool_commit[:12])}" if info.tool_commit else ""+ return (+ f'<h2>Environment</h2><div class="table-wrap"><table class="compact"><thead><tr><th></th>{header}</tr></thead>'+ f'<tbody>{body}</tbody></table></div><p class="meta">{manifest}{tool}</p>'+ )+++def _overview_html(cases: list[_Case]) -> str:+ rows = []+ for case in cases:+ time, peak = (case.metrics[0], case.metrics[2]) if case.metrics else (None, None)+ threshold = f" / {case.psnr_min_db:g}" if case.psnr_min_db is not None else ""+ notes = len(_flag_lines(case))+ rows.append(+ f'<tr><td><a href="#{case.anchor}">{_e(case.label)}</a></td><td>{_e(case.family)}</td>'+ f'<td><span class="badge s-{case.status}">{case.status}</span></td>'+ f'<td class="num">{_e(_psnr_text(case.min_psnr))}{_e(threshold)}</td>'+ + _overview_metric_cells(time)+ + _overview_metric_cells(peak)+ + f'<td class="num">{notes or ""}</td></tr>'+ )+ return (+ '<h2>Cases</h2><div class="table-wrap"><table><thead><tr><th>Case</th><th>Family</th><th>Status</th>'+ '<th class="num">min PSNR / threshold (dB)</th><th class="num">Time</th><th class="num">vs ref</th>'+ '<th class="num">vs prev</th><th class="num">VRAM peak</th><th class="num">vs ref</th>'+ '<th class="num">vs prev</th><th class="num">Flags</th></tr></thead><tbody>'+ + "".join(rows)+ + "</tbody></table></div>"+ )+++def _overview_metric_cells(metric: _Metric | None) -> str:+ if metric is None:+ return '<td class="num">—</td>' * 3+ if metric.invalid:+ cells = [f'<td class="num invalid" title="{_e(metric.invalid)}">invalid</td>']+ else:+ cells = [f'<td class="num">{_e(metric.median_text)}</td>']+ for delta in (metric.vs_reference, metric.vs_previous):+ css = "num outlier" if delta is not None and delta.outlier else "num"+ cells.append(f'<td class="{css}">{_e(_relative_text(delta))}</td>')+ return "".join(cells)+++def _case_html(case: _Case, href: Callable[[Path], str]) -> str:+ size = f" · {case.size[0]}×{case.size[1]}" if case.size else ""+ parts = [+ f'<article class="case s-{case.status}-case" id="{case.anchor}">',+ f'<h3><span class="badge s-{case.status}">{case.status}</span>{_e(case.label)}'+ f'<span class="muted">{_e(case.family)}{size}</span></h3>',+ ]+ if case.models:+ parts.append(_models_html(case.models))+ if case.reasons:+ parts.append('<ul class="reasons">' + "".join(f"<li>{_e(r)}</li>" for r in case.reasons) + "</ul>")+ flags = _flag_lines(case)+ if flags:+ parts.append('<ul class="flags">' + "".join(f"<li>{_e(f)}</li>" for f in flags) + "</ul>")+ if case.images:+ parts.append('<div class="images">' + "".join(_figure_html(i, case, href) for i in case.images) + "</div>")+ if case.metrics:+ parts.append("<h4>Measurements (measured runs valid for the metric)</h4>" + _metrics_table(case.metrics))+ if case.nodes:+ parts.append("<h4>Per node</h4>" + _nodes_table(case.nodes))+ if case.rows:+ parts.append("<h4>Generations</h4>" + _rows_table(case.rows))+ parts.append("</article>")+ return "\n".join(parts)+++def _flag_lines(case: _Case) -> list[str]:+ lines = [f"invalid metrics: {note}" for note in case.invalid_metrics]+ lines += case.flags + [f"outlier: {o}" for o in case.outliers]+ if case.node_outliers:+ lines.append(f"outlier: {len(case.node_outliers)} per-node peak comparisons, marked under Per node")+ return lines+++def _models_html(models: list[ModelIdentity]) -> str:+ items = "".join(+ f'<li>{_e(m.name)} <span class="muted">{_e(m.type)} · <span title="{_e(_dash(m.hash))}">'+ f"{_e(_short_hash(m.hash))}</span></span></li>"+ for m in models+ )+ return f'<ul class="models" aria-label="Models">{items}</ul>'+++def _figure_html(image: _Image, case: _Case, href: Callable[[Path], str]) -> str:+ ratio = f"{case.size[0]} / {case.size[1]}" if case.size else "1 / 1"+ caption = f"<figcaption><strong>{_e(image.title)}</strong>{_e(image.caption)}</figcaption>"+ if image.path is None or not image.path.is_file():+ reason = image.caption if image.path is None else f"missing: {image.path.name}"+ return f'<figure>{caption}<div class="placeholder" style="aspect-ratio: {ratio}">{_e(reason)}</div></figure>'+ link = href(image.path)+ alt = f"{image.title} for {case.label}"+ return (+ f'<figure>{caption}<a href="{link}"><img src="{link}" alt="{_e(alt)}" loading="lazy" '+ f'style="aspect-ratio: {ratio}"></a></figure>'+ )+++def _delta_cell(delta: Delta | None, unit: Unit) -> str:+ if delta is None:+ return '<td class="num">—</td>'+ if delta.outlier:+ return f'<td class="num outlier">{_e(_delta_text(delta, unit))} · outlier</td>'+ return f'<td class="num">{_e(_delta_text(delta, unit))}</td>'+++def _metric_cells(metric: _Metric) -> str:+ return (+ f'<td class="num">{_e(metric.median_text)}</td>'+ f'<td class="num">{_e(_value_text(metric.reference, metric.unit))}</td>'+ + _delta_cell(metric.vs_reference, metric.unit)+ + f'<td class="num">{_e(_value_text(metric.previous, metric.unit))}</td>'+ + _delta_cell(metric.vs_previous, metric.unit)+ )+++def _runs_text(metric: _Metric) -> str:+ if metric.invalid:+ return f"invalid: {metric.invalid}"+ return ", ".join(_value_text(v, metric.unit) for v in metric.values) or "no values"+++def _metrics_table(metrics: list[_Metric]) -> str:+ rows = "".join(+ f"<tr><th scope=row>{_e(m.label)}</th>" + _metric_cells(m) + f'<td class="num">{_e(_runs_text(m))}</td></tr>'+ for m in metrics+ )+ return (+ '<div class="table-wrap"><table><thead><tr><th>Metric</th><th class="num">Median</th>'+ '<th class="num">Reference</th><th class="num">vs reference</th><th class="num">Previous run</th>'+ '<th class="num">vs previous</th><th class="num">Runs</th></tr></thead>'+ f"<tbody>{rows}</tbody></table></div>"+ )+++def _nodes_table(nodes: list[_Node]) -> str:+ rows = "".join(+ f"<tr><th scope=row>{_e(n.label)}</th>"+ f'<td class="num">{_e(_value_text(n.duration_s, "s"))}</td>'+ f'<td class="num">{_e(_value_text(n.baseline_bytes, "bytes"))}</td>' + _metric_cells(n.peak) + "</tr>"+ for n in nodes+ )+ return (+ '<div class="table-wrap"><table><thead><tr><th>Node</th><th class="num">Time</th>'+ '<th class="num">Baseline</th><th class="num">Peak</th><th class="num">Reference</th>'+ '<th class="num">vs reference</th><th class="num">Previous run</th><th class="num">vs previous</th>'+ f"</tr></thead><tbody>{rows}</tbody></table></div>"+ )+++def _residency_text(record: Record) -> str:+ # Weightless loads (tokenizers) say nothing about where the weights are: the record is "residency unknown".+ if all(weightless(r) for r in record.residency):+ return "unknown"+ short = [r for r in record.residency if not resident(r)]+ if not short:+ return "100 %"+ lowest = min(short, key=lambda r: r.percent)+ model = f"{lowest.model}/{lowest.submodel}" if lowest.submodel else lowest.model+ return f"{lowest.percent:.0f} % ({model})"+++def _generation_text(record: Record) -> str:+ kind = "warm-up" if record.kind == "warmup" else "measured"+ return f"{kind} · rep {record.rep} · attempt {record.attempt}"+++def _rows_table(rows: list[_Row]) -> str:+ body = []+ last_attempt: dict[tuple[str, int], int] = {}+ for row in rows:+ key = (row.record.kind, row.record.rep)+ last_attempt[key] = max(last_attempt.get(key, row.record.attempt), row.record.attempt)+ for row in sorted(rows, key=lambda row: row.record.kind != "warmup"):+ r = row.record+ invalid = [name for name, valid in _VALIDITY if not valid(r)]+ notes = [*([r.error] if r.error else []), *r.invalid_reasons]+ if r.attempt < last_attempt[(r.kind, r.rep)]:+ notes.append(f"retried as attempt {last_attempt[(r.kind, r.rep)]}")+ peak = r.memory.process_peak_bytes if r.memory else None+ body.append(+ f'<tr class="{r.kind}"><td>{_e(_generation_text(r))}</td><td>{_e(r.status)}</td>'+ f"<td>{_e('valid' if not invalid else 'invalid: ' + ', '.join(invalid))}</td>"+ f'<td class="num">{_e(_value_text(r.timing.total_s if r.timing else None, "s"))}</td>'+ f'<td class="num">{_e(_value_text(r.timing.per_step_s if r.timing else None, "s"))}</td>'+ f'<td class="num">{_e(_value_text(peak, "bytes"))}</td>'+ f'<td class="num">{_e(_psnr_text(row.psnr_reference))}</td>'+ f'<td class="num">{_e(_psnr_text(row.psnr_previous))}</td>'+ f"<td>{_e(_residency_text(r))}</td><td>{_e('; '.join(notes))}</td></tr>"+ )+ return (+ '<div class="table-wrap"><table class="generations"><thead><tr><th>Generation</th><th>Status</th><th>Validity</th>'+ '<th class="num">Total</th><th class="num">Per step</th><th class="num">VRAM peak</th>'+ '<th class="num">PSNR vs reference</th><th class="num">PSNR vs previous</th><th>Residency</th>'+ f"<th>Notes</th></tr></thead><tbody>{''.join(body)}</tbody></table></div>"+ )+++# ---------------------------------------------------------------------------------------------------------------------+# Markdown+++def _render_summary(info: RunInfo, cases: list[_Case], notes: list[str], run_status: str) -> str:+ counts = Counter(case.status for case in cases)+ outliers = sum(case.has_outliers for case in cases)+ invalid_metrics = sum(bool(case.invalid_metrics) for case in cases)+ tally = ", ".join(f"{counts[s]} {s}" for s in STATUSES if counts[s]) or "no cases"+ lines = [+ f"# Family E2E {info.run_id}",+ "",+ f"Profile {info.profile}, run {run_status}: {tally}, {outliers} with outliers, "+ f"{invalid_metrics} with invalid metrics.",+ "",+ "| Case | Status | min PSNR | Time | vs ref | vs prev | VRAM peak | vs ref | vs prev |",+ "| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |",+ ]+ for case in cases:+ cells = [case.label.replace("|", "\\|"), case.status, _psnr_text(case.min_psnr)]+ for metric in (case.metrics[0], case.metrics[2]) if case.metrics else (None, None):+ if metric is None:+ cells += ["—"] * 3+ continue+ cells.append(metric.median_text)+ for delta in (metric.vs_reference, metric.vs_previous):+ text = _relative_text(delta)+ cells.append(f"**{text}**" if delta is not None and delta.outlier else text)+ lines.append("| " + " | ".join(cells) + " |")++ # The sizes of a case share its models; each distinct list once.+ models: dict[tuple[str, ...], list[str]] = {}+ for case in cases:+ if case.models:+ models.setdefault(tuple(_model_text(m) for m in case.models), []).append(case.label)+ if models:+ lines += ["", "## Models", ""]+ lines += [f"- {', '.join(labels)}: {'; '.join(texts)}" for texts, labels in models.items()]++ attention = []+ for case in cases:+ if case.status != "PASS":+ attention += [f"- {case.status} {case.label}: {reason}" for reason in case.reasons or [""]]+ attention += [f"- INVALID METRICS {case.label}: {note}" for note in case.invalid_metrics]+ attention += [f"- OUTLIER {case.label}: {outlier}" for outlier in case.outliers]+ if case.node_outliers:+ attention.append(f"- OUTLIER {case.label}: {len(case.node_outliers)} per-node peak comparisons, see report")+ # One environment change usually affects every case; list each distinct flag once.+ flagged: dict[str, list[str]] = {}+ for case in cases:+ for flag in case.flags:+ flagged.setdefault(flag, []).append(case.label)+ attention += [f"- FLAG {', '.join(labels)}: {flag}" for flag, labels in flagged.items()]+ attention += [f"- NOTE {note}" for note in notes]+ if attention:+ lines += ["", "## Attention", "", *attention]+ return "\n".join(lines) + "\n"diff --git a/scripts/family_e2e/residency.py b/scripts/family_e2e/residency.pynew file mode 100644index 0000000000..59dd7eb968--- /dev/null+++ b/scripts/family_e2e/residency.py@@ -0,0 +1,99 @@+"""Model residency read from the server log: was every model a run used fully in VRAM?++The model cache logs one `Loaded model '<key>' (...) ... VRAM: <mb>MB (<p>%)` line (INFO) for every lock that moves+weights or leaves the model short of fully resident (`ModelCache._load_locked_model`). A lock that finds the model+already fully resident logs that line at DEBUG only, so warm runs usually show no line at all. The tracker therefore+keeps the latest line per model since the last cache flush: a run is residency-valid when every line in its log+window is resident (`resident`), no "VRAM budget ... short" warning appears in the window, and at least one of the+graph's models has been seen loaded with weights since the flush. A run without such a line is "residency unknown"+and invalid. A load under WEIGHTLESS_MB, such as a tokenizer submodel, has no weights to place: the cache logs it at+0.0 %, and it counts as resident but tells nothing about where the weights are.+"""++from __future__ import annotations++import re+from collections.abc import Iterable+from dataclasses import dataclass++from scripts.family_e2e.records import Residency++# `ModelCache._load_locked_model`. The device label is "cuda device #0", "cuda device", "mps device", ...+LOAD_LINE = re.compile(+ r"Loaded model '(?P<key>[^']+)' \([^)]*\) onto .+? in [\d.]+s\. "+ r"Total model size: (?P<total>[\d.]+)MB, VRAM: (?P<vram>[\d.]+)MB \((?P<percent>[\d.]+)%\)"+)+# Same method, first pass of a lock whose budget stays short after offloading everything offloadable.+SHORT_LINE = re.compile(r"VRAM budget for '(?P<key>[^']+)' is short by \d+MB")+# The log prints one decimal: "100.0%" covers everything from 99.95 %.+FULL_PERCENT = 99.95+# A tokenizer logs "Total model size: 0.03MB"; the smallest weighted submodels are hundreds of MB.+WEIGHTLESS_MB = 1.0+++@dataclass(frozen=True)+class LogWindow:+ loads: list[Residency]+ short: list[str]+ """Cache keys named by "VRAM budget ... short" warnings."""+++def parse_log(text: str) -> LogWindow:+ loads = []+ for match in LOAD_LINE.finditer(text):+ # Cache keys are `<model key>` or `<model key>:<submodel>`; model keys are UUIDs.+ model, _, submodel = match["key"].partition(":")+ loads.append(+ Residency(+ model=model,+ submodel=submodel or None,+ vram_mb=float(match["vram"]),+ total_mb=float(match["total"]),+ percent=float(match["percent"]),+ )+ )+ return LogWindow(loads=loads, short=[m["key"] for m in SHORT_LINE.finditer(text)])+++def weightless(residency: Residency) -> bool:+ return residency.total_mb is not None and residency.total_mb < WEIGHTLESS_MB+++def resident(residency: Residency) -> bool:+ """Whether the load left the model's weights fully in VRAM; a weightless load has none to place."""+ return residency.percent >= FULL_PERCENT or weightless(residency)+++def _label(residency: Residency) -> str:+ return f"{residency.model}:{residency.submodel}" if residency.submodel else residency.model+++class ResidencyTracker:+ """The latest residency of every model loaded since the last cache flush (empty_model_cache or a new server)."""++ def __init__(self) -> None:+ self._latest: dict[tuple[str, str | None], Residency] = {}++ def reset(self) -> None:+ self._latest.clear()++ def observe(self, window: LogWindow, graph_models: Iterable[str]) -> tuple[list[Residency], list[str]]:+ """Folds in one run's log window. Returns the residency of the graph's models and the invalid reasons."""+ for load in window.loads:+ self._latest[(load.model, load.submodel)] = load+ reasons = [+ f"residency: {_label(load)} loaded with {load.percent:.1f}% of its weights in VRAM"+ for load in window.loads+ if not resident(load)+ ]+ reasons.extend(f"residency: VRAM budget short for {key}" for key in window.short)+ models = set(graph_models)+ relevant = [r for (model, _), r in self._latest.items() if model in models]+ if all(weightless(r) for r in relevant):+ reasons.append("residency unknown: no load with weights for the graph's models since the last cache flush")+ reasons.extend(+ f"residency: {_label(r)} at {r.percent:.1f}% since an earlier run"+ for r in relevant+ if not resident(r) and r not in window.loads+ )+ return relevant, reasonsdiff --git a/scripts/family_e2e/runner.py b/scripts/family_e2e/runner.pynew file mode 100644index 0000000000..da0060cbd8--- /dev/null+++ b/scripts/family_e2e/runner.py@@ -0,0 +1,1192 @@+"""The runner: executes a run's plan against a server it launches, and writes records, traces and the report.++One server lifetime: preflight -> scratch root and server -> environment -> models and capabilities -> input uploads+-> graph export -> per family: empty the model cache, then per case key the warm-ups and measures -> stop the server.+The GPU lock is held throughout and the report is written at the end. A runner first stops a server that an earlier+runner of the run left running (`stop_surviving_server`). Every new server lifetime (a resumed run, or a restart+after the server crashed in a step) skips steps that already have a final record and repeats the last warm-up of+every case key with measures left, because the new server starts with a cold model cache.++`stop` and the runner agree through run.json under the run lock (`run_lock`): the runner names itself in the heartbeat+before anything else (`register_runner`), and `stop` marks the run stopped before it reads the heartbeat. So `stop`+either finds the runner and kills it, or the runner finds the run stopped and leaves it untouched. The runner checks+again before every server and every step (`ensure_running`), and never overwrites a status other than `running`.+"""++from __future__ import annotations++import csv+import gzip+import hashlib+import io+import json+import logging+import os+import sys+import time+from collections.abc import Callable, Iterator+from contextlib import contextmanager+from dataclasses import dataclass+from datetime import datetime, timezone+from pathlib import Path+from typing import Any, BinaryIO, Protocol++import psutil+from PIL import Image++from scripts.family_e2e import gpu_memory, nvml_memory+from scripts.family_e2e.client import (+ ApiError,+ EventRecorder,+ InvokeClient,+ build_timing,+ wait_for_idle_queue,+ wait_for_item,+)+from scripts.family_e2e.detach import RUNNER_LOG+from scripts.family_e2e.graphs import (+ PreparedGraph,+ build_export_request,+ output_image_name,+ prepare_batch,+ run_pnpm_exporter,+ shareable_source,+)+from scripts.family_e2e.manifest import (+ DEFAULT_ARM,+ TOOL_CHECKOUT,+ Manifest,+ ResolvedCase,+ load_manifest,+ plan_steps,+ resolve_cases,+)+from scripts.family_e2e.records import (+ Environment,+ ForeignProcess,+ Memory,+ ModelIdentity,+ NodeMemory,+ PlannedStep,+ Record,+ RunInfo,+ Timing,+ append_record,+ load_records,+ load_run_info,+ write_bytes_atomic,+ write_run_info,+)+from scripts.family_e2e.report import write_report+from scripts.family_e2e.residency import ResidencyTracker, parse_log+from scripts.family_e2e.server import (+ ServerError,+ ServerProcess,+ build_scratch_root,+ free_port,+ git_state,+ kill_group,+ launch_server,+ living_members,+ pending_installs,+ read_template_settings,+ remove_tree,+ template_server_running,+)++logger = logging.getLogger("family_e2e")++HEARTBEAT_FILE = "heartbeat.json"+RUN_LOCK_FILE = "run.lock"+# Holders keep the run lock for one read and one write of a small JSON file.+RUN_LOCK_TIMEOUT_S = 30.0+RUN_LOCK_POLL_S = 0.01+# A started runner registers once its interpreter has imported the tool, which takes seconds on a busy machine.+REGISTER_TIMEOUT_S = 120.0+REGISTER_POLL_S = 0.05+# The heartbeat entries that identify the server's processes. The launcher (the process the runner started, which+# leads the server's process group on POSIX) comes first: its tree and group take the serving process along.+SERVER_ROLES = ("server_launcher", "server")+EXPORT_DIR = "export"+"""The graph exporter's work directory in the run directory."""+HEARTBEAT_INTERVAL_S = 30.0+# Machine-wide, not per data directory: two data directories can share a GPU.+LOCK_DIR = Path(os.environ.get("LOCALAPPDATA") or Path.home() / ".cache") / "invokeai-family-e2e" / "locks"+MAX_ATTEMPTS = 3+# A case whose steps crashed the server this often is given up; its remaining steps count as final.+MAX_SERVER_CRASHES = 2+# Windows Subsystem for Linux names its kernel so; NVML there runs on the Windows driver (WDDM).+WSL_KERNEL_RELEASE = Path("/proc/sys/kernel/osrelease")+QUEUE_DRAIN_TIMEOUT_S = 600.0+KILL_WAIT_S = 30.0+KILL_POLL_S = 0.02+MIB = 2**20+GIB = 2**30+# Thresholds on the per-process dedicated usage of process_usage (PDH on Windows, NVML on Linux); never mixed with+# the sampler's trace.+FOREIGN_BYTES = GIB+FOREIGN_GROWTH_BYTES = 256 * MIB+SHARED_GROWTH_BYTES = 256 * MIB+CANCEL_WAIT_S = 120.0+# Reasons that make a run repeat (up to MAX_ATTEMPTS records per step); the generation itself was fine.+FOREIGN_GPU_LOAD = "foreign GPU load"+FOREIGN_QUEUE_ITEM = "foreign queue item"+SERVER_CRASHED = "server crashed"+++class RunnerError(RuntimeError):+ pass+++class RunStopped(Exception):+ """The run is no longer `running`, normally because `stop` marked it: the runner leaves it as it is."""+++class ServerCrashed(Exception):+ """The server died during a step; the step has its error record and the session restarts the server."""+++class Sampler(Protocol):+ def start(self) -> None: ...+ def stop(self) -> gpu_memory.MemoryTrace: ...+++@dataclass(frozen=True)+class Gpu:+ """The adapter under test and how to read memory on it: `gpu_memory` (WDDM) on Windows, `nvml_memory` on Linux.++ Tests substitute fakes for both."""++ adapter: gpu_memory.Adapter+ process_usage: Callable[[], dict[int, gpu_memory.ProcessUsage]]+ sampler: Callable[[int], Sampler]+++def open_gpu(description: str) -> Gpu:+ if sys.platform == "win32":+ backend = gpu_memory+ elif sys.platform == "linux":+ if _under_wsl():+ raise gpu_memory.UnsupportedPlatformError(+ "this Linux runs under WSL, where NVML reports no per-process memory (the Windows driver owns the GPU); "+ "run the tool on Windows on this machine"+ )+ backend = nvml_memory+ else:+ raise gpu_memory.UnsupportedPlatformError(+ f"GPU memory sampling is implemented for Windows (WDDM) and for NVIDIA GPUs on Linux (NVML), not for "+ f"{sys.platform}"+ )+ try:+ adapter = backend.find_adapter(description)+ except (LookupError, OSError) as e:+ raise RunnerError(str(e)) from e+ return Gpu(+ adapter=adapter,+ process_usage=lambda: backend.process_usage_on_adapter(adapter),+ sampler=lambda pid: backend.ProcessMemorySampler(pid, adapter),+ )+++def _under_wsl() -> bool:+ try:+ return "microsoft" in WSL_KERNEL_RELEASE.read_text(encoding="utf-8").lower()+ except OSError:+ return False+++def device_env(adapter: gpu_memory.Adapter, server_env: dict[str, str]) -> dict[str, str]:+ """What pins the server to the adapter. On Linux CUDA_VISIBLE_DEVICES names the NVML UUID, so a server on a machine+ with several GPUs neither spreads its workers over them nor borrows an idle one; a manifest that pins it to another+ device is refused. WDDM adapters have no such selector: the manifest's env pins the server there.+ """+ if adapter.uuid is None:+ return {}+ pinned = server_env.get("CUDA_VISIBLE_DEVICES")+ if pinned is not None and pinned.strip().casefold() != adapter.uuid.casefold():+ raise RunnerError(+ f"server.env sets CUDA_VISIBLE_DEVICES={pinned}, but gpu selects {adapter.description} ({adapter.uuid}); "+ "drop it from server.env, the runner pins the server to the selected GPU"+ )+ return {"CUDA_VISIBLE_DEVICES": adapter.uuid}+++Exporter = Callable[[dict[str, Any], Path], dict[str, Any]]+++def now_iso() -> str:+ return datetime.now(timezone.utc).isoformat(timespec="seconds")+++def file_sha256(path: Path) -> str:+ return hashlib.sha256(path.read_bytes()).hexdigest()+++def _step_id(step: PlannedStep | Record) -> tuple[str, str, str, int]:+ return (step.case_key, step.arm, step.kind, step.rep)+++def needs_retry(record: Record) -> bool:+ return record.status == "completed" and any(+ reason.startswith((FOREIGN_GPU_LOAD, FOREIGN_QUEUE_ITEM)) for reason in record.invalid_reasons+ )+++def crashed_server(record: Record) -> bool:+ return any(reason.startswith(SERVER_CRASHED) for reason in record.invalid_reasons)+++def remaining_steps(plan: list[PlannedStep], records: list[Record]) -> list[PlannedStep]:+ """Planned steps without a final record, in plan order.++ A step is final when its last record completed and needs no retry, or when its retries are used up. Every step of+ a case key whose steps crashed the server MAX_SERVER_CRASHES times is final too, so a crashing case cannot keep a+ run (or its resumes) restarting the server forever.+ """+ attempts: dict[tuple[str, str, str, int], list[Record]] = {}+ crashes: dict[str, int] = {}+ for record in records:+ attempts.setdefault(_step_id(record), []).append(record)+ crashes[record.case_key] = crashes.get(record.case_key, 0) + crashed_server(record)+ remaining = []+ for step in plan:+ own = sorted(attempts.get(_step_id(step), []), key=lambda r: r.attempt)+ last = own[-1] if own else None+ done = last is not None and last.status == "completed" and (not needs_retry(last) or len(own) >= MAX_ATTEMPTS)+ if not done and crashes.get(step.case_key, 0) < MAX_SERVER_CRASHES:+ remaining.append(step)+ return remaining+++@contextmanager+def gpu_lock(adapter: gpu_memory.Adapter) -> Iterator[None]:+ """Holds `LOCK_DIR/<adapter key>.lock` so a second runner on the same GPU fails fast."""+ path = LOCK_DIR / f"{adapter.key}.lock"+ path.parent.mkdir(parents=True, exist_ok=True)+ with open(path, "a+b") as f:+ try:+ _lock_file(f, lock=True)+ except OSError:+ raise RunnerError(f"another runner is using {adapter.description} (lock {path})") from None+ try:+ yield+ finally:+ _lock_file(f, lock=False)+++@contextmanager+def run_lock(run_dir: Path) -> Iterator[None]:+ """Holds `<run_dir>/run.lock`, which orders status changes of run.json and the runner's registration between the+ runner, `stop` and `resume`. Waits while another process holds it; the operating system releases the lock of a+ killed holder."""+ with open(run_dir / RUN_LOCK_FILE, "a+b") as f:+ deadline = time.monotonic() + RUN_LOCK_TIMEOUT_S+ while True:+ try:+ _lock_file(f, lock=True)+ break+ except OSError:+ if time.monotonic() >= deadline:+ raise RunnerError(f"{run_dir / RUN_LOCK_FILE} stayed locked for {RUN_LOCK_TIMEOUT_S:g}s") from None+ time.sleep(RUN_LOCK_POLL_S)+ try:+ yield+ finally:+ _lock_file(f, lock=False)+++def _lock_file(f: BinaryIO, lock: bool) -> None:+ if sys.platform == "win32":+ import msvcrt++ f.seek(0)+ msvcrt.locking(f.fileno(), msvcrt.LK_NBLCK if lock else msvcrt.LK_UNLCK, 1)+ else:+ import fcntl++ fcntl.flock(f, (fcntl.LOCK_EX | fcntl.LOCK_NB) if lock else fcntl.LOCK_UN)+++def process_identity(pid: int) -> list[float] | None:+ """[pid, create time]: tells a live process from a later one that reuses its pid."""+ try:+ return [pid, psutil.Process(pid).create_time()]+ except psutil.Error:+ return None+++def _identified(identity: list[float] | None) -> psutil.Process | None:+ """The process named by [pid, create time], also one that exited and is not reaped yet (a zombie)."""+ if not identity:+ return None+ try:+ process = psutil.Process(int(identity[0]))+ return process if abs(process.create_time() - identity[1]) < 1.0 else None+ except psutil.Error:+ return None+++def _running(process: psutil.Process) -> bool:+ """Whether a process still runs: a zombie has exited and holds no memory, files or port any more."""+ try:+ return process.is_running() and process.status() != psutil.STATUS_ZOMBIE+ except psutil.Error:+ return False+++def is_alive(identity: list[float] | None) -> bool:+ process = _identified(identity)+ return process is not None and _running(process)+++def _led_group(process: psutil.Process) -> list[int]:+ """The living members of the process group that a captured process leads (POSIX); none when it leads none.++ Until it is reaped a process holds its pid, so a group of that id can only be one it created. That holds for a+ zombie too, whose group can still have living members (macOS does not even tell a zombie's group id).+ is_running() checks the create time, so a pid reused since the process was captured is left alone.+ """+ if sys.platform == "win32" or not process.is_running():+ return []+ return living_members(process.pid)+++def _still_running(identity: list[float] | None) -> list[int]:+ """The pids that still run of the process named by `identity`: itself unless it is a zombie, and the living+ members of the group it leads."""+ process = _identified(identity)+ if process is None:+ return []+ return sorted({*([process.pid] if _running(process) else []), *_led_group(process)})+++def kill_identified(identity: list[float] | None) -> bool:+ """Kills what still runs of the process named by [pid, create time] and its descendants, and waits until it has+ exited. Returns whether anything ran.++ Descendants come from psutil, which drops processes older than their supposed parent; a raw parent-pid walk+ (taskkill /T) can follow a reused pid into an unrelated tree. On POSIX the groups that processes of the tree lead+ are killed too (the runner and the server launcher each lead one): a descendant whose parent died is in no tree+ any more, but still in its group. A zombie still matches its identity and still leads its group, so orphaned+ members of a zombie leader's group are killed; the zombie itself has nothing left to kill.+ """+ root = _identified(identity)+ if root is None:+ return False+ try:+ tree = [root, *root.children(recursive=True)]+ except psutil.Error:+ return False+ groups = [process.pid for process in tree if _led_group(process)]+ processes = [process for process in tree if _running(process)]+ if not groups and not processes:+ return False+ for pgid in groups:+ try:+ kill_group(pgid)+ except PermissionError:+ pass # a living member refused the signal; it shows as still running+ for process in processes:+ try:+ process.kill()+ except psutil.NoSuchProcess:+ pass+ # Polled rather than psutil.wait_procs, which takes a zombie for running until its parent reaps it.+ deadline = time.monotonic() + KILL_WAIT_S+ while time.monotonic() < deadline and (+ any(_running(process) for process in processes) or any(living_members(pgid) for pgid in groups)+ ):+ time.sleep(KILL_POLL_S)+ return True+++def scratch_root(data_dir: Path, run_id: str, arm: str) -> Path:+ return data_dir / "scratch-roots" / f"{run_id}-{arm}"+++def remove_scratch_roots(data_dir: Path, info: RunInfo) -> list[str]:+ """Deletes the scratch roots of the run's arms; returns the paths that could not be deleted."""+ leftovers: list[str] = []+ for arm in sorted({DEFAULT_ARM, *info.environments}):+ leftovers.extend(remove_tree(scratch_root(data_dir, info.run_id, arm)))+ return leftovers+++def read_heartbeat(run_dir: Path) -> dict[str, Any]:+ try:+ return json.loads((run_dir / HEARTBEAT_FILE).read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return {}+++def ensure_running(run_dir: Path) -> None:+ """Raises RunStopped unless run.json still says `running`.++ Under the run lock: Windows refuses to open run.json for a moment while `stop` replaces it, which would end the+ runner as failed instead of stopped.+ """+ with run_lock(run_dir):+ _raise_unless_running(run_dir)+++def _raise_unless_running(run_dir: Path) -> None:+ """ensure_running for a caller that holds the run lock: the lock belongs to a file handle, so taking it again would+ wait for itself."""+ status = load_run_info(run_dir).status+ if status != "running":+ raise RunStopped(f"run {run_dir.name} is {status}; the runner leaves it as it is")+++def finish_run(run_dir: Path, status: str) -> bool:+ """Ends a running run with `status` and returns True. Any other status stays: the runner does not overwrite a+ stop, and `stop` does not overwrite a finished run."""+ with run_lock(run_dir):+ info = load_run_info(run_dir)+ if info.status != "running":+ return False+ write_run_info(run_dir, info.model_copy(update={"status": status, "finished_at": now_iso()}))+ return True+++def register_runner(run_dir: Path) -> None:+ """Names this process as the run's runner in heartbeat.json, before the runner does anything else.++ Under the run lock, as `stop` marks the run stopped: a runner registered first is in the heartbeat that `stop`+ reads next, and one that comes later finds the run stopped (RunStopped). The server entries an earlier runner left+ stay for stop_surviving_server. While another runner of the run is alive this refuses.+ """+ with run_lock(run_dir):+ _raise_unless_running(run_dir)+ heartbeat = read_heartbeat(run_dir)+ other = heartbeat.get("runner")+ if other and int(other[0]) != os.getpid() and is_alive(other):+ raise RunnerError(f"runner pid {int(other[0])} of run {run_dir.name} is still running")+ heartbeat.update(runner=process_identity(os.getpid()), step="starting", updated_at=now_iso())+ write_bytes_atomic(run_dir / HEARTBEAT_FILE, json.dumps(heartbeat, indent=2).encode("utf-8"))+++def wait_for_runner(run_dir: Path, spawned_pid: int, previous: list[float] | None) -> list[float]:+ """Waits until a runner other than `previous` registered for the run, and returns its identity.++ `spawned_pid` is the process `start` or `resume` launched: the runner, or a venv launcher whose child it is. Once+ that has exited, a registration that has not appeared will not appear any more.+ """+ try:+ spawned: psutil.Process | None = psutil.Process(spawned_pid)+ except psutil.NoSuchProcess:+ spawned = None+ deadline = time.monotonic() + REGISTER_TIMEOUT_S+ while True:+ # Before the heartbeat is read: a runner that registered and exited at once still counts.+ exited = spawned is None or not _running(spawned)+ registered = read_heartbeat(run_dir).get("runner")+ if registered and registered != previous:+ return registered+ if exited:+ if load_run_info(run_dir).status == "stopped":+ raise RunnerError(f"run {run_dir.name} was stopped before its runner registered")+ raise RunnerError(f"the runner exited before it registered; see {run_dir / RUNNER_LOG}")+ if time.monotonic() >= deadline:+ raise RunnerError(+ f"the runner (pid {spawned_pid}) did not register within {REGISTER_TIMEOUT_S:g}s; see "+ f"{run_dir / RUNNER_LOG}. `python -m scripts.family_e2e stop {run_dir}` keeps it from starting"+ )+ time.sleep(REGISTER_POLL_S)+++def stop_surviving_server(run_dir: Path) -> None:+ """Stops a server that an earlier runner of the run left running, before anything replaces what identifies it.++ On POSIX the server runs in a session of its own and survives a runner killed with SIGKILL; on Windows the+ runner's job object ends it with the runner. The heartbeat's identities are all `stop` finds that server by, so+ while a recorded server process cannot be stopped this refuses, before the heartbeat or a scratch root changes.+ Call it under the GPU lock: a live runner of the run would hold it, so the recorded server is no live runner's.+ """+ heartbeat = read_heartbeat(run_dir)+ survivors = {+ int(heartbeat[role][0]): heartbeat[role] for role in SERVER_ROLES if _still_running(heartbeat.get(role))+ }+ refused: dict[int, str] = {}+ for pid, identity in survivors.items():+ running = ", ".join(str(p) for p in _still_running(identity))+ logger.warning("an earlier runner of this run left its server running (pid %d: %s); stopping it", pid, running)+ try:+ kill_identified(identity)+ except psutil.Error as e:+ refused[pid] = f"the kill was refused: {type(e).__name__} {e}"+ left = {pid: running for pid, identity in survivors.items() if (running := _still_running(identity))}+ if left:+ waited = f"{KILL_WAIT_S:g}s after the kill"+ details = ", ".join(+ f"pid {pid} ({refused.get(pid, waited)}; still running: {', '.join(str(p) for p in running)})"+ for pid, running in left.items()+ )+ raise RunnerError(+ f"the server an earlier runner left running cannot be stopped: {details}. heartbeat.json and the scratch "+ f"roots stay as they are; end it, e.g. with `python -m scripts.family_e2e stop {run_dir}`, then resume"+ )+++def _process_name(pid: int) -> str | None:+ try:+ return psutil.Process(pid).name()+ except psutil.Error:+ return None+++def foreign_processes(+ before: dict[int, gpu_memory.ProcessUsage], after: dict[int, gpu_memory.ProcessUsage], own: set[int]+) -> list[ForeignProcess]:+ """Other processes above FOREIGN_BYTES at either end of a window, or grown by more than FOREIGN_GROWTH_BYTES."""+ foreign = []+ for pid in sorted((set(before) | set(after)) - own):+ start = before[pid].dedicated_bytes if pid in before else 0+ end = after[pid].dedicated_bytes if pid in after else 0+ if max(start, end) > FOREIGN_BYTES or end - start > FOREIGN_GROWTH_BYTES:+ foreign.append(ForeignProcess(pid=pid, name=_process_name(pid), dedicated_bytes=max(start, end)))+ return foreign+++def _describe(processes: list[ForeignProcess]) -> str:+ return ", ".join(f"pid {p.pid} ({p.name or '?'}) {p.dedicated_bytes / MIB:.0f} MiB" for p in processes)+++def preflight(manifest: Manifest, gpu: Gpu) -> None:+ """Refuses to run next to the template's dev server or next to other GPU load."""+ spec = manifest.server+ device_env(gpu.adapter, spec.env)+ for path in (spec.python, spec.code_dir / "scripts" / "invokeai-web.py"):+ if not path.is_file():+ raise RunnerError(f"{path} does not exist")+ template_root = spec.template_root+ settings = read_template_settings(template_root)+ pending = pending_installs(template_root, settings)+ if pending:+ raise RunnerError(+ f"the models directory of {template_root} holds unfinished installs "+ f"({', '.join(p.name for p in pending)}); finish or cancel the pending model install in the dev server first"+ )+ if template_server_running(settings):+ raise RunnerError(+ f"something listens on port {settings.get('port', 9090)}, the port of the template root {template_root}; "+ "stop its server first (the tool copies its database)"+ )+ try:+ usage = gpu.process_usage()+ except OSError as e:+ raise RunnerError(f"cannot list the processes on {gpu.adapter.description}: {e}") from e+ # A server that just crashed can linger in the counters for a moment.+ busy = [p for p in foreign_processes(usage, usage, own=set()) if psutil.pid_exists(p.pid)]+ if busy:+ raise RunnerError(+ f"other processes use more than 1 GiB on {gpu.adapter.description}: {_describe(busy)}. One may be the "+ "server of an earlier run whose runner was killed; `python -m scripts.family_e2e stop RUN` ends it"+ )+++def uses_fp8(model_keys: frozenset[str], configs: dict[str, dict[str, Any]], fp8_compute: bool) -> bool:+ """Whether fp8 weights may be in play, which makes a partially resident run irreproducible.++ `fp8_storage` in a model's default settings keeps its weights in fp8. With the runtime setting `fp8_compute`,+ the server keeps any scaled-fp8 checkpoint packed and runs fp8 matmuls only for layers already in VRAM; model+ configs do not record whether a checkpoint is scaled fp8, so every graph counts then.+ """+ return fp8_compute or any(+ ((configs.get(key) or {}).get("default_settings") or {}).get("fp8_storage") for key in model_keys+ )+++def model_identities(+ model_keys: frozenset[str], main_key: str, configs: dict[str, dict[str, Any]]+) -> list[ModelIdentity]:+ """What identifies a graph's models on another machine, the case's main model first; never their path here.++ Not by type: a graph can hold several main models, e.g. Z-Image's text encoder source.+ """+ identities = []+ for key in model_keys:+ config = configs[key]+ identities.append(+ ModelIdentity(+ key=key,+ name=config["name"],+ base=config["base"],+ type=config["type"],+ format=config.get("format"),+ variant=config.get("variant"),+ hash=config.get("hash"),+ source=shareable_source(config),+ )+ )+ return sorted(identities, key=lambda m: (m.key != main_key, m.type, m.name))+++def write_trace(path: Path, trace: gpu_memory.MemoryTrace, t_enqueue: float) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ with gzip.open(path, "wt", encoding="utf-8", newline="") as f:+ writer = csv.writer(f)+ writer.writerow(["series", "t", "bytes"])+ for series, samples in (("dedicated", trace.dedicated), ("shared", trace.shared)):+ writer.writerows((series, f"{t - t_enqueue:.6f}", value) for t, value in samples)+++def _sample_at(samples: tuple[tuple[float, int], ...], t: float) -> int | None:+ before = [value for ts, value in samples if ts <= t]+ return before[-1] if before else None+++def build_memory(+ trace: gpu_memory.MemoryTrace,+ timing: Timing,+ t_enqueue: float,+ t_done: float,+ foreign: list[ForeignProcess],+ trace_path: str,+) -> Memory:+ nodes = []+ for node in timing.nodes:+ start = t_enqueue + node.t_start+ end = t_enqueue + (node.t_end if node.t_end is not None else timing.total_s)+ nodes.append(+ NodeMemory(+ node_id=node.node_id, baseline_bytes=trace.at(start), peak_bytes=trace.peak(start, max(start, end))+ )+ )+ shared_start = _sample_at(trace.shared, t_enqueue)+ shared_window = [value for ts, value in trace.shared if t_enqueue <= ts <= t_done]+ return Memory(+ method=trace.method,+ interval_ms=trace.interval_ms,+ process_baseline_bytes=trace.at(t_enqueue),+ process_peak_bytes=trace.peak(t_enqueue, t_done),+ nodes=nodes,+ shared_max_delta_bytes=None if shared_start is None else max([shared_start, *shared_window]) - shared_start,+ foreign=foreign,+ trace=trace_path,+ )+++def new_run(manifest_path: Path, families: list[str], case_ids: list[str]) -> Path:+ """Creates the run directory and its run.json with the expanded plan."""+ manifest = load_manifest(manifest_path)+ cases = resolve_cases(manifest, families, case_ids)+ run_id = f"{datetime.now():%Y%m%d-%H%M%S}-{manifest.profile}"+ run_dir = manifest.data_dir / "runs" / run_id+ try:+ run_dir.mkdir(parents=True)+ except FileExistsError:+ raise RunnerError(f"run {run_id} exists already; start again in a second") from None+ info = RunInfo(+ run_id=run_id,+ profile=manifest.profile,+ created_at=now_iso(),+ finished_at=None,+ status="running",+ manifest_path=str(manifest_path.resolve()),+ manifest_sha256=file_sha256(manifest_path),+ tool_commit=git_state(TOOL_CHECKOUT)[0],+ environments={},+ plan=plan_steps(cases, manifest.defaults.warmup, manifest.defaults.repeats),+ case_thresholds={case.case_key: case.thresholds for case in cases},+ graph_hashes={},+ )+ write_run_info(run_dir, info)+ return run_dir+++def load_run_manifest(info: RunInfo) -> Manifest:+ path = Path(info.manifest_path)+ if file_sha256(path) != info.manifest_sha256:+ raise RunnerError(f"{path} changed since run {info.run_id} started; start a new run")+ return load_manifest(path)+++def run(run_dir: Path, gpu_factory: Callable[[str], Gpu] = open_gpu, export: Exporter = run_pnpm_exporter) -> int:+ """Executes the remaining steps of a run, then writes the report. Returns 1 when the report has failures.++ Raises RunStopped, with run.json and the report left as they are, once the run is no longer `running`.+ """+ register_runner(run_dir)+ info = load_run_info(run_dir)+ manifest = load_run_manifest(info)+ try:+ gpu = gpu_factory(manifest.gpu)+ with gpu_lock(gpu.adapter):+ ensure_running(run_dir)+ stop_surviving_server(run_dir)+ _Session(run_dir, manifest, gpu, export).run()+ except RunStopped:+ raise+ except BaseException as e:+ finish_run(run_dir, "stopped" if isinstance(e, KeyboardInterrupt) else "failed")+ try:+ write_report(manifest.data_dir, run_dir)+ except Exception:+ logger.exception("writing the report of the aborted run failed")+ raise+ finish_run(run_dir, "completed")+ result = write_report(manifest.data_dir, run_dir)+ logger.info(+ "report %s: %d failures, %d outliers, %d invalid",+ result.report_html,+ result.failures,+ result.outliers,+ result.invalid,+ )+ return 1 if result.failures else 0+++class _Session:+ """One server lifetime of a run."""++ def __init__(self, run_dir: Path, manifest: Manifest, gpu: Gpu, export: Exporter) -> None:+ self.run_dir = run_dir+ self.manifest = manifest+ self.gpu = gpu+ self.export = export+ self.info = load_run_info(run_dir)+ self.arm = DEFAULT_ARM+ self.records = load_records(run_dir)+ self.tracker = ResidencyTracker()+ self.server: ServerProcess | None = None+ self.step_label = "starting"+ self.last_beat = 0.0+ all_cases = {case.case_key: case for case in resolve_cases(manifest)}+ self.cases = {step.case_key: all_cases[step.case_key] for step in self.info.plan}++ def heartbeat(self, step_label: str | None = None) -> None:+ if step_label is not None:+ self.step_label = step_label+ data = {+ "runner": process_identity(os.getpid()),+ "server": process_identity(self.server.pid) if self.server else None,+ "server_launcher": process_identity(self.server.process.pid) if self.server else None,+ "step": self.step_label,+ "updated_at": now_iso(),+ }+ write_bytes_atomic(self.run_dir / HEARTBEAT_FILE, json.dumps(data, indent=2).encode("utf-8"))+ self.last_beat = time.perf_counter()++ def tick(self) -> None:+ if time.perf_counter() - self.last_beat >= HEARTBEAT_INTERVAL_S:+ self.heartbeat()++ def run(self) -> None:+ self.heartbeat("preflight")+ todo = remaining_steps(self.info.plan, self.records)+ if not todo:+ logger.info("every planned step has a final record")+ # Each crash adds a crash record to a case, and MAX_SERVER_CRASHES of them make the case final: this ends.+ while todo:+ ensure_running(self.run_dir)+ preflight(self.manifest, self.gpu)+ if not self.serve_once(todo):+ return+ todo = remaining_steps(self.info.plan, self.records)++ def serve_once(self, todo: list[PlannedStep]) -> bool:+ """One server lifetime over `todo`. Returns True when the server crashed in a step."""+ root = scratch_root(self.manifest.data_dir, self.info.run_id, self.arm)+ log_path = self.run_dir / f"server-{self.arm}.log"+ try:+ pin = device_env(self.gpu.adapter, self.manifest.server.env)+ build_scratch_root(self.manifest.server.template_root, root, log_path, free_port(), bool(pin))+ self.heartbeat("starting the server")+ self.server = launch_server(+ self.manifest.server,+ root,+ log_path,+ self.run_dir / f"server-{self.arm}.console.log",+ pin,+ )+ try:+ self.heartbeat("server ready")+ self.serve(self.server, todo)+ except ServerCrashed as e:+ logger.error("%s; starting a new server", e)+ return True+ finally:+ self.server.stop()+ self.server = None+ finally:+ # stop() returns once the server tree has exited, so its database files are closed by now.+ leftovers = remove_tree(root)+ if leftovers:+ logger.warning("could not remove the scratch root %s: %s", root, ", ".join(leftovers))+ return False++ def serve(self, server: ServerProcess, todo: list[PlannedStep]) -> None:+ client = InvokeClient(server.base_url)+ recorder = EventRecorder(server.base_url)+ recorder.connect()+ try:+ runtime_config = self.record_environment(server, client)+ models = client.get("/api/v2/models/")["models"]+ capabilities = client.get("/api/v2/models/capabilities")+ configs = {model["key"]: model for model in models}+ todo_cases = [self.cases[key] for key in dict.fromkeys(step.case_key for step in todo)]+ image_names, input_ids = self.upload_inputs(client, todo_cases)+ graphs, errors = self.export_graphs(todo_cases, configs, capabilities, image_names, input_ids)+ fp8_compute = bool(runtime_config.get("config", {}).get("fp8_compute"))++ adapter_checked = False+ for family in dict.fromkeys(step.family for step in todo):+ client.post("/api/v2/models/empty_model_cache")+ self.tracker.reset()+ family_steps = [step for step in todo if step.family == family]+ for case_key in dict.fromkeys(step.case_key for step in family_steps):+ steps = [step for step in family_steps if step.case_key == case_key]+ if case_key in errors:+ for step in steps:+ self.store(self.error_record(step, f"graph export failed: {errors[case_key]}"))+ continue+ if steps[0].kind == "measure":+ steps = [self.last_warmup(case_key), *steps]+ graph = graphs[case_key]+ fp8 = uses_fp8(graph.model_keys, configs, fp8_compute)+ for step in steps:+ record = self.execute_step(step, graph, fp8, client, recorder, server)+ if not adapter_checked and record.status == "completed":+ self.check_server_on_adapter(server)+ adapter_checked = True+ finally:+ recorder.close()++ def record_environment(self, server: ServerProcess, client: InvokeClient) -> dict[str, Any]:+ try:+ runtime_config = client.get("/api/v1/app/runtime_config")+ except ApiError as e:+ raise RunnerError(f"cannot read the runtime config ({e}); the scratch server must run single-user") from e+ if runtime_config.get("config", {}).get("multiuser"):+ raise RunnerError("the template root enables multiuser; the tool needs a single-user server")+ spec = self.manifest.server+ commit, branch, dirty = git_state(spec.code_dir)+ environment = Environment(+ code_dir=str(spec.code_dir),+ git_commit=commit,+ git_branch=branch,+ git_dirty=dirty,+ python=str(spec.python),+ invokeai_file=server.invokeai_file,+ app_version=client.get("/api/v1/app/version"),+ app_deps=client.get("/api/v1/app/app_deps"),+ runtime_config=runtime_config,+ gpu_description=self.gpu.adapter.description,+ gpu_luid=self.gpu.adapter.luid,+ gpu_driver=self.gpu.adapter.driver_version,+ server_cmd=server.cmd,+ extra_env=dict(spec.env),+ )+ previous = self.info.environments.get(self.arm)+ # Edits to an already dirty checkout cannot be told apart; a commit or a dirty flag that changed can.+ if previous is not None and (previous.git_commit, previous.git_dirty, previous.app_version) != (+ environment.git_commit,+ environment.git_dirty,+ environment.app_version,+ ):+ raise RunnerError(+ f"the server code changed since run {self.info.run_id} started (commit {previous.git_commit}, dirty "+ f"{previous.git_dirty} -> commit {environment.git_commit}, dirty {environment.git_dirty}); "+ "start a new run"+ )+ self.info.environments[self.arm] = environment+ self.save_info()+ return runtime_config++ def save_info(self) -> None:+ """Writes the session's run.json while the run is still running; `stop` owns it otherwise."""+ with run_lock(self.run_dir):+ _raise_unless_running(self.run_dir)+ write_run_info(self.run_dir, self.info)++ def upload_inputs(+ self, client: InvokeClient, cases: list[ResolvedCase]+ ) -> tuple[dict[str, dict[tuple[str, bool], str]], dict[str, str]]:+ """Uploads every input once per size it is needed at.++ Returns case key -> (manifest path, used at the case size) -> image name, and image name -> a stable identity+ of the input. Init and control images enter the canvas compiler as finished layers, which the UI always+ composites at the generation size; reference images are used as they are.+ """+ uploaded: dict[tuple[str, tuple[int, int] | None], str] = {}+ input_ids: dict[str, str] = {}+ names_by_case: dict[str, dict[tuple[str, bool], str]] = {}+ for case in cases:+ spec = case.spec+ usages = [(path, False) for path in spec.reference_images] + [(c.image, True) for c in spec.control]+ if spec.init_image is not None:+ usages.append((spec.init_image.path, True))+ names: dict[tuple[str, bool], str] = {}+ for relative, at_case_size in usages:+ key = (relative, (case.width, case.height) if at_case_size else None)+ if key not in uploaded:+ path, identity = self.input_at_size(relative, key[1])+ uploaded[key] = client.upload_image(path)+ input_ids[uploaded[key]] = identity+ names[(relative, at_case_size)] = uploaded[key]+ names_by_case[case.case_key] = names+ return names_by_case, input_ids++ def input_at_size(self, relative: str, size: tuple[int, int] | None) -> tuple[Path, str]:+ """The input file to upload and its identity; a LANCZOS copy in the run directory when the size differs."""+ source = self.manifest.input_file(relative)+ identity = f"input:{file_sha256(source)}"+ with Image.open(source) as image:+ if size is None or image.size == size:+ return source, identity+ original = image.size+ resized = image.convert("RGB").resize(size, Image.Resampling.LANCZOS)+ target = (+ self.run_dir+ / "inputs"+ / f"{Path(relative).with_suffix('').as_posix().replace('/', '_')}@{size[0]}x{size[1]}.png"+ )+ target.parent.mkdir(exist_ok=True)+ resized.save(target)+ logger.info("input %s is %dx%d; uploading a resized copy %s", relative, *original, target)+ return target, f"{identity}@{size[0]}x{size[1]}"++ def export_graphs(+ self,+ cases: list[ResolvedCase],+ configs: dict[str, dict[str, Any]],+ capabilities: Any,+ image_names: dict[str, dict[tuple[str, bool], str]],+ input_ids: dict[str, str],+ ) -> tuple[dict[str, PreparedGraph], dict[str, str]]:+ self.heartbeat("exporting graphs")+ request = build_export_request(cases, list(configs.values()), capabilities, image_names)+ response = self.export(request, self.run_dir / EXPORT_DIR)+ entries = {entry["id"]: entry for entry in response["cases"]}+ graphs: dict[str, PreparedGraph] = {}+ errors: dict[str, str] = {}+ graph_dir = self.run_dir / "graphs"+ graph_dir.mkdir(exist_ok=True)+ for case in cases:+ entry = entries.get(case.case_key)+ if entry is None or "error" in entry:+ errors[case.case_key] = entry["error"] if entry else "the exporter returned no entry"+ logger.error("%s: %s", case.case_key, errors[case.case_key])+ continue+ graph = prepare_batch(entry["batch"], entry.get("components", {}), input_ids)+ graphs[case.case_key] = graph+ (graph_dir / f"{case.case_key}.json").write_text(json.dumps(graph.batch, indent=2), encoding="utf-8")+ changed = [+ key+ for key, graph in graphs.items()+ if self.info.graph_hashes.get(key, graph.graph_hash) != graph.graph_hash+ ]+ if changed:+ raise RunnerError(f"graphs changed since run {self.info.run_id} started: {', '.join(changed)}")+ self.info.graph_hashes.update({key: graph.graph_hash for key, graph in graphs.items()})+ self.info.case_models.update(+ {+ key: model_identities(graph.model_keys, self.cases[key].spec.model, configs)+ for key, graph in graphs.items()+ }+ )+ self.save_info()+ return graphs, errors++ def last_warmup(self, case_key: str) -> PlannedStep:+ return [s for s in self.info.plan if s.case_key == case_key and s.kind == "warmup"][-1]++ def check_server_on_adapter(self, server: ServerProcess) -> None:+ usage = self.gpu.process_usage().get(server.pid)+ if usage is None or usage.dedicated_bytes == 0:+ raise RunnerError(+ f"the server (pid {server.pid}) has no memory on {self.gpu.adapter.description}: it runs on another "+ "device; check CUDA_VISIBLE_DEVICES / HIP_VISIBLE_DEVICES in the manifest's server env"+ )++ def store(self, record: Record) -> None:+ append_record(self.run_dir, record)+ self.records.append(record)+ peak = record.memory.process_peak_bytes if record.memory else None+ logger.info(+ "%s: %s%s%s%s",+ record.record_id,+ record.status,+ f" {record.timing.total_s:.2f}s" if record.timing else "",+ f" peak {peak / MIB:.0f} MiB" if peak is not None else "",+ f" invalid: {'; '.join(record.invalid_reasons)}" if record.invalid_reasons else "",+ )++ def execute_step(+ self,+ step: PlannedStep,+ graph: PreparedGraph,+ fp8: bool,+ client: InvokeClient,+ recorder: EventRecorder,+ server: ServerProcess,+ ) -> Record:+ """Runs a step, repeating it while foreign load spoiled the measurement and attempts are left.++ Raises ServerCrashed, after storing the step's error record, when the server died during the step.+ """+ attempts = [r for r in self.records if _step_id(r) == _step_id(step)]+ while True:+ ensure_running(self.run_dir)+ attempt = max((r.attempt for r in attempts), default=0) + 1+ self.heartbeat(f"{step.case_key} {step.kind} {step.rep} attempt {attempt}")+ try:+ record = self.run_once(step, attempt, graph, fp8, client, recorder, server)+ except Exception as e:+ if server.alive():+ raise+ reason = f"{SERVER_CRASHED} ({server.end_status()}): {type(e).__name__}: {e}"+ fields = self.base_record(step, attempt, graph.graph_hash, fp8)+ fields.update(error=reason, invalid_reasons=[reason])+ self.store(Record(**fields))+ raise ServerCrashed(f"{step.case_key} {step.kind} {step.rep}: {reason}") from e+ self.store(record)+ attempts.append(record)+ if not needs_retry(record) or len(attempts) >= MAX_ATTEMPTS:+ return record++ def base_record(self, step: PlannedStep, attempt: int, graph_hash: str, fp8: bool) -> dict[str, Any]:+ case = self.cases[step.case_key]+ return {+ "record_id": f"{step.case_key}.{step.arm}.{step.kind}.{step.rep}.{attempt}",+ "run_id": self.info.run_id,+ "arm": step.arm,+ "case_id": step.case_id,+ "case_key": step.case_key,+ "family": step.family,+ "width": case.width,+ "height": case.height,+ "steps": case.spec.steps,+ "seed": case.seed,+ "kind": step.kind,+ "rep": step.rep,+ "attempt": attempt,+ "queue_item_id": None,+ "graph_hash": graph_hash,+ "status": "error",+ "error": None,+ "image_path": None,+ "image_sha256": None,+ "image_width": None,+ "image_height": None,+ "timing": None,+ "memory": None,+ "residency": [],+ "uses_fp8": fp8,+ "valid_timing": False,+ "valid_memory": False,+ "valid_psnr": False,+ "invalid_reasons": [],+ }++ def error_record(self, step: PlannedStep, error: str) -> Record:+ attempt = max((r.attempt for r in self.records if _step_id(r) == _step_id(step)), default=0) + 1+ fields = self.base_record(step, attempt, graph_hash="", fp8=False)+ fields.update(error=error, invalid_reasons=[error])+ return Record(**fields)++ def run_once(+ self,+ step: PlannedStep,+ attempt: int,+ graph: PreparedGraph,+ fp8: bool,+ client: InvokeClient,+ recorder: EventRecorder,+ server: ServerProcess,+ ) -> Record:+ fields = self.base_record(step, attempt, graph.graph_hash, fp8)+ reasons: list[str] = []++ def watch() -> None:+ # Checked before every HTTP poll: a dead server's port refuses connections only after seconds on Windows.+ if not server.alive():+ raise ServerError(f"the server process exited ({server.end_status()})")+ self.tick()++ if not wait_for_idle_queue(client, QUEUE_DRAIN_TIMEOUT_S, watch):+ reasons.append(f"{FOREIGN_QUEUE_ITEM}: the queue was still busy after {QUEUE_DRAIN_TIMEOUT_S:.0f}s")+ usage_before = self.gpu.process_usage()+ sampler = self.gpu.sampler(server.pid)+ sampler.start()+ try:+ log_offset = server.log_size()+ mark = recorder.mark()+ t_enqueue = time.perf_counter()+ item_id = client.enqueue(graph.batch)+ fields["queue_item_id"] = item_id+ try:+ item, t_done = wait_for_item(+ client, recorder, mark, item_id, self.manifest.defaults.run_timeout_s, watch+ )+ except TimeoutError as e:+ client.cancel(item_id)+ try:+ wait_for_item(client, recorder, mark, item_id, CANCEL_WAIT_S, watch)+ except TimeoutError:+ logger.warning("queue item %d is still running after its cancel", item_id)+ fields.update(error=str(e), invalid_reasons=[str(e)])+ return Record(**fields)+ finally:+ trace = sampler.stop()+ usage_after = self.gpu.process_usage()++ status = item["status"]+ fields["status"] = status+ # Only img2img starts inside the schedule, at a step count each family derives differently.+ case = self.cases[step.case_key]+ expected_steps = None if case.spec.mode == "img2img" else case.spec.steps+ timing = build_timing(recorder.since(mark), item_id, t_enqueue, t_done, item, expected_steps)+ residency, residency_reasons = self.tracker.observe(parse_log(server.read_log(log_offset)), graph.model_keys)+ foreign = foreign_processes(usage_before, usage_after, own={server.pid, server.process.pid})+ trace_path = f"traces/{fields['record_id']}.csv.gz"+ write_trace(self.run_dir / trace_path, trace, t_enqueue)+ memory = build_memory(trace, timing, t_enqueue, t_done, foreign, trace_path)+ fields.update(timing=timing, memory=memory, residency=residency)++ completed = status == "completed"+ valid_timing = valid_memory = valid_psnr = completed+ if completed:+ try:+ fields.update(self.save_image(fields["record_id"], graph, item, client))+ except (ValueError, ApiError) as e:+ fields["error"] = f"no output image: {e}"+ reasons.append(fields["error"])+ valid_psnr = False+ else:+ fields["error"] = f"{item.get('error_type')}: {item.get('error_message')}"+ reasons.append(f"generation {status}")+ if residency_reasons:+ reasons.extend(residency_reasons)+ valid_timing = valid_memory = False+ if fp8:+ reasons.append("fp8 weights with incomplete residency do not reproduce")+ valid_psnr = False+ if memory.shared_max_delta_bytes is not None and memory.shared_max_delta_bytes > SHARED_GROWTH_BYTES:+ reasons.append(f"paged to shared memory: +{memory.shared_max_delta_bytes / MIB:.0f} MiB")+ valid_timing = valid_memory = False+ if foreign:+ reasons.append(f"{FOREIGN_GPU_LOAD}: {_describe(foreign)}")+ if any(r.startswith((FOREIGN_GPU_LOAD, FOREIGN_QUEUE_ITEM)) for r in reasons):+ valid_timing = valid_memory = False+ fields.update(+ valid_timing=valid_timing, valid_memory=valid_memory, valid_psnr=valid_psnr, invalid_reasons=reasons+ )+ return Record(**fields)++ def save_image(+ self, record_id: str, graph: PreparedGraph, item: dict[str, Any], client: InvokeClient+ ) -> dict[str, Any]:+ data = client.image_bytes(output_image_name(graph.batch["graph"], item["session"]))+ relative = f"images/{record_id}.png"+ path = self.run_dir / relative+ path.parent.mkdir(exist_ok=True)+ path.write_bytes(data)+ with Image.open(io.BytesIO(data)) as image:+ width, height = image.size+ return {+ "image_path": relative,+ "image_sha256": hashlib.sha256(data).hexdigest(),+ "image_width": width,+ "image_height": height,+ }diff --git a/scripts/family_e2e/server.py b/scripts/family_e2e/server.pynew file mode 100644index 0000000000..c1327e32cc--- /dev/null+++ b/scripts/family_e2e/server.py@@ -0,0 +1,598 @@+"""The server under test: a scratch root built from the template root, and the InvokeAI process serving it.++The tool never attaches to a running server. It copies the template's `invokeai.yaml` and a snapshot of its SQLite+database into a scratch root, points the shared paths back at the template root, and launches the server's own+interpreter on it.+"""++from __future__ import annotations++import ctypes+import logging+import os+import re+import shutil+import signal+import socket+import subprocess+import sys+import time+from dataclasses import dataclass+from pathlib import Path+from typing import IO, Any++import psutil+import requests+import yaml++from scripts.family_e2e.manifest import ServerSpec++logger = logging.getLogger("family_e2e")++CONFIG_FILE = "invokeai.yaml"+DB_FILE = "invokeai.db"+# The path settings of InvokeAIAppConfig (invokeai/app/services/config/config_default.py) and their defaults, which+# are relative to the root. Stores whose files the database owns go into the scratch root: the server reconciles them+# with its own (scratch) database, e.g. FontService deletes uploaded fonts the database does not list. The rest+# resolves against the template root, as for the template's own server.+SCRATCH_PATHS = {+ "outputs_dir": "outputs",+ "db_dir": "databases",+ "profiles_dir": "profiles",+ "fonts_storage_dir": "fonts-uploaded",+ "style_presets_dir": "style_presets",+ "workflow_thumbnails_dir": "workflow_thumbnails",+}+TEMPLATE_PATHS: dict[str, str | None] = {+ "models_dir": "models",+ "convert_cache_dir": "models/.convert_cache",+ "download_cache_dir": "models/.download_cache",+ "legacy_conf_dir": "configs",+ "fonts_dir": "fonts",+ "custom_nodes_dir": "nodes",+ "legacy_models_yaml_path": None,+}+# The client speaks plain HTTP to the root path.+DROPPED_SETTINGS = ("ssl_certfile", "ssl_keyfile", "base_url")+# ModelInstallService's TMPDIR_PREFIX (invokeai/app/services/model_install/model_install_default.py).+INSTALL_TMPDIR_PREFIX = "tmpinstall_"++RUNNING_LINE = re.compile(r"Invoke running on https?://\S+?:(\d+)")+# Localhost answers at once when something listens; Windows retries a refused connect for about two seconds.+PORT_PROBE_TIMEOUT_S = 0.25+STARTUP_TIMEOUT_S = 900.0+STARTUP_POLL_S = 1.0+STOP_TIMEOUT_S = 60.0+# Windows can refuse a delete for a moment after the last handle of a killed process closed.+REMOVE_ATTEMPTS = 10+REMOVE_RETRY_S = 0.2+GIT_TIMEOUT_S = 30.0+INTERPRETER_CHECK_TIMEOUT_S = 120.0+++class ServerError(RuntimeError):+ pass+++def read_template_settings(template_root: Path) -> dict[str, Any]:+ """The template's `invokeai.yaml` settings (empty when the root has none), refusing what the tool cannot copy."""+ path = template_root / CONFIG_FILE+ settings: dict[str, Any] = {}+ if path.is_file():+ settings = yaml.safe_load(path.read_text(encoding="utf-8")) or {}+ if not str(settings.get("schema_version", "")).startswith("4."):+ raise ServerError(f"{path} has schema {settings.get('schema_version')!r}; start its server once to migrate")+ if settings.get("db_url"):+ raise ServerError(f"{path} uses db_url; only a SQLite database can be copied into a scratch root")+ return settings+++def pending_installs(template_root: Path, settings: dict[str, Any]) -> list[Path]:+ """Unfinished model installs in the template's models directory.++ The scratch server's install service resumes them at startup: the files would land in the template's models+ directory while the model is registered in the scratch database only.+ """+ models_dir = (template_root / settings.get("models_dir", TEMPLATE_PATHS["models_dir"])).resolve()+ return sorted(models_dir.glob(f"{INSTALL_TMPDIR_PREFIX}*"))+++def template_server_running(settings: dict[str, Any]) -> bool:+ """Whether something listens on the template's configured port, i.e. its dev server may still be running."""+ host = settings.get("host", "127.0.0.1")+ if host in ("0.0.0.0", "::", ""):+ host = "127.0.0.1"+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:+ s.settimeout(PORT_PROBE_TIMEOUT_S)+ return s.connect_ex((host, int(settings.get("port", 9090)))) == 0+++_GENERIC_READ = 0x80000000+_OPEN_EXISTING = 3+_ERROR_SHARING_VIOLATION = 32+++def database_in_use(path: Path) -> bool:+ """Whether a process has the database file open, e.g. a server of the template root on another port.++ Windows: an exclusive open fails with a sharing violation while any handle is open. Elsewhere this returns False:+ POSIX opens have no exclusive mode, so on Linux only the port check (`template_server_running`) guards the+ template, and a template server on another port goes unnoticed.+ """+ if sys.platform != "win32":+ return False+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)+ kernel32.CreateFileW.restype = ctypes.c_void_p+ kernel32.CreateFileW.argtypes = [+ ctypes.c_wchar_p,+ ctypes.c_uint32,+ ctypes.c_uint32,+ ctypes.c_void_p,+ ctypes.c_uint32,+ ctypes.c_uint32,+ ctypes.c_void_p,+ ]+ kernel32.CloseHandle.argtypes = [ctypes.c_void_p]+ handle = kernel32.CreateFileW(str(path), _GENERIC_READ, 0, None, _OPEN_EXISTING, 0, None)+ if handle is None or handle == ctypes.c_void_p(-1).value:+ error = ctypes.get_last_error()+ if error == _ERROR_SHARING_VIOLATION:+ return True+ raise ctypes.WinError(error)+ kernel32.CloseHandle(handle)+ return False+++def snapshot_database(source: Path, target: Path) -> None:+ """Writes a consistent snapshot of the database, its WAL included, to `target`; the template stays untouched.++ Opening a database sets its journal mode and checkpoints the WAL on close, which would rewrite the template's+ file. So the files (main file, -wal, -shm) are copied first, which is consistent because no process holds them+ (`database_in_use`), and the copy is opened through the database layer and backed up into `target`.+ """+ # Imported here: the client otherwise imports nothing of invokeai, and this pulls in no torch.+ from invokeai.app.services.shared.database.database import Database++ staging = target.parent / ".snapshot"+ staging.mkdir(parents=True)+ try:+ for suffix in ("", "-wal", "-shm"):+ if source.with_name(source.name + suffix).is_file():+ shutil.copy2(source.with_name(source.name + suffix), staging / (source.name + suffix))+ database = Database.open_sqlite(staging / source.name, logger)+ try:+ database.backup(target)+ finally:+ database.dispose()+ finally:+ shutil.rmtree(staging)+++def free_port() -> int:+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:+ s.bind(("127.0.0.1", 0))+ return s.getsockname()[1]+++def build_scratch_root(+ template_root: Path, scratch_root: Path, log_file: Path, port: int, single_cuda_device: bool = False+) -> None:+ """(Re)creates the scratch root: the template's settings with absolute paths and a snapshot of its database.++ `single_cuda_device`: the server will see one CUDA device only, the runner's pin (`CUDA_VISIBLE_DEVICES`). A+ template that names a CUDA device by index would then refuse to start, so its `device` becomes `cuda:0` and a+ `generation_devices` list with a CUDA device becomes `auto`.+ """+ settings = read_template_settings(template_root)+ template_db = (template_root / settings.get("db_dir", "databases")).resolve() / DB_FILE+ if not template_db.is_file():+ raise ServerError(f"template root has no database at {template_db}")+ if database_in_use(template_db):+ raise ServerError(f"{template_db} is open in another process; stop the template root's server first")++ if scratch_root.exists():+ shutil.rmtree(scratch_root)+ db_dir = scratch_root / SCRATCH_PATHS["db_dir"]+ db_dir.mkdir(parents=True)+ snapshot_database(template_db, db_dir / DB_FILE)++ config = {k: v for k, v in settings.items() if k not in DROPPED_SETTINGS}+ for name, default in TEMPLATE_PATHS.items():+ value = settings.get(name, default)+ if value is not None:+ config[name] = str((template_root / value).resolve())+ for name, relative in SCRATCH_PATHS.items():+ config[name] = str(scratch_root / relative)+ config.update(+ host="127.0.0.1",+ port=port,+ log_handlers=["console", f"file={log_file}"],+ log_format="plain",+ # The residency check reads INFO lines of the model cache.+ log_level="debug" if settings.get("log_level") == "debug" else "info",+ # The index worker embeds every new image on the GPU between runs; a copied queue may hold pending items.+ image_index_enabled=False,+ clear_queue_on_startup=True,+ )+ if single_cuda_device:+ if str(config.get("device", "")).startswith("cuda:"):+ config["device"] = "cuda:0"+ devices = config.get("generation_devices")+ if isinstance(devices, list) and any(str(device).startswith("cuda") for device in devices):+ config["generation_devices"] = "auto"+ (scratch_root / CONFIG_FILE).write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8")+++def server_env(spec: ServerSpec, device_env: dict[str, str] | None = None) -> dict[str, str]:+ """The caller's environment without INVOKEAI_*, then the manifest's env, then `device_env`, which pins the GPU."""+ # INVOKEAI_* variables would override the scratch root's settings; the manifest's env is the place for them.+ env = {k: v for k, v in os.environ.items() if not k.upper().startswith("INVOKEAI_")}+ env["PYTHONPATH"] = str(spec.code_dir)+ env["PYTHONUTF8"] = "1"+ env.update(spec.env)+ env.update(device_env or {})+ return env+++def verify_interpreter(spec: ServerSpec, env: dict[str, str]) -> str:+ """`invokeai.__file__` as the server's interpreter resolves it; must lie in the code directory."""+ result = subprocess.run(+ [str(spec.python), "-c", "import invokeai; print(invokeai.__file__)"],+ cwd=spec.code_dir,+ env=env,+ capture_output=True,+ text=True,+ timeout=INTERPRETER_CHECK_TIMEOUT_S,+ check=False,+ )+ if result.returncode != 0:+ raise ServerError(f"{spec.python} cannot import invokeai:\n{result.stderr[-2000:]}")+ invokeai_file = result.stdout.strip().splitlines()[-1]+ if not Path(invokeai_file).resolve().is_relative_to(spec.code_dir.resolve()):+ raise ServerError(f"{spec.python} imports invokeai from {invokeai_file}, not from {spec.code_dir}")+ return invokeai_file+++def git_state(path: Path) -> tuple[str | None, str | None, bool | None]:+ """(commit, branch, dirty) of the checkout at `path`; dirty counts tracked files only."""++ def git(*args: str) -> str | None:+ try:+ result = subprocess.run(+ ["git", "-C", str(path), *args], capture_output=True, text=True, timeout=GIT_TIMEOUT_S, check=False+ )+ except OSError:+ return None+ return result.stdout.strip() if result.returncode == 0 else None++ status = git("status", "--porcelain", "--untracked-files=no")+ return git("rev-parse", "HEAD"), git("rev-parse", "--abbrev-ref", "HEAD"), None if status is None else bool(status)+++def _serving_process(launched: int, port: int) -> psutil.Process:+ """The process of the launched tree that listens on the port: the interpreter that allocates GPU memory."""+ root = psutil.Process(launched)+ # Per process rather than system-wide: macOS lists other processes' sockets to root only.+ for candidate in [root, *root.children(recursive=True)]:+ try:+ connections = candidate.net_connections(kind="tcp")+ except psutil.Error:+ continue+ if any(c.status == psutil.CONN_LISTEN and c.laddr and c.laddr.port == port for c in connections):+ return candidate+ raise ServerError(f"no process the tool started listens on port {port}")+++def _tail(path: Path, lines: int = 40) -> str:+ try:+ return "\n".join(path.read_text(encoding="utf-8", errors="replace").splitlines()[-lines:])+ except OSError:+ return ""+++class _BasicLimitInformation(ctypes.Structure):+ _fields_ = [+ ("PerProcessUserTimeLimit", ctypes.c_int64),+ ("PerJobUserTimeLimit", ctypes.c_int64),+ ("LimitFlags", ctypes.c_uint32),+ ("MinimumWorkingSetSize", ctypes.c_size_t),+ ("MaximumWorkingSetSize", ctypes.c_size_t),+ ("ActiveProcessLimit", ctypes.c_uint32),+ ("Affinity", ctypes.c_size_t),+ ("PriorityClass", ctypes.c_uint32),+ ("SchedulingClass", ctypes.c_uint32),+ ]+++class _ExtendedLimitInformation(ctypes.Structure):+ _fields_ = [+ ("BasicLimitInformation", _BasicLimitInformation),+ ("IoInfo", ctypes.c_uint64 * 6),+ ("ProcessMemoryLimit", ctypes.c_size_t),+ ("JobMemoryLimit", ctypes.c_size_t),+ ("PeakProcessMemoryUsed", ctypes.c_size_t),+ ("PeakJobMemoryUsed", ctypes.c_size_t),+ ]+++_JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000+_JOB_OBJECT_EXTENDED_LIMIT_INFORMATION = 9+_PROCESS_SET_QUOTA = 0x0100+_PROCESS_TERMINATE = 0x0001+_CREATE_SUSPENDED = 0x00000004+++class KillOnCloseJob:+ """A Windows job object that kills its processes when its handle closes.++ The handle is not inheritable, so it closes at the latest when the process that created the job dies, however it+ dies. Processes started inside the job are in it too, including those in jobs of their own (nested jobs).+ """++ def __init__(self) -> None:+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)+ kernel32.CreateJobObjectW.restype = ctypes.c_void_p+ kernel32.CreateJobObjectW.argtypes = [ctypes.c_void_p, ctypes.c_wchar_p]+ kernel32.SetInformationJobObject.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_uint32]+ kernel32.OpenProcess.restype = ctypes.c_void_p+ kernel32.OpenProcess.argtypes = [ctypes.c_uint32, ctypes.c_int, ctypes.c_uint32]+ kernel32.AssignProcessToJobObject.argtypes = [ctypes.c_void_p, ctypes.c_void_p]+ kernel32.CloseHandle.argtypes = [ctypes.c_void_p]+ self._kernel32 = kernel32+ self._handle: int | None = kernel32.CreateJobObjectW(None, None)+ if not self._handle:+ raise ctypes.WinError(ctypes.get_last_error())+ info = _ExtendedLimitInformation()+ info.BasicLimitInformation.LimitFlags = _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE+ if not kernel32.SetInformationJobObject(+ self._handle, _JOB_OBJECT_EXTENDED_LIMIT_INFORMATION, ctypes.byref(info), ctypes.sizeof(info)+ ):+ error = ctypes.get_last_error()+ self.close()+ raise ctypes.WinError(error)++ def assign(self, pid: int) -> None:+ process = self._kernel32.OpenProcess(_PROCESS_SET_QUOTA | _PROCESS_TERMINATE, 0, pid)+ if not process:+ raise ctypes.WinError(ctypes.get_last_error())+ try:+ if not self._kernel32.AssignProcessToJobObject(self._handle, process):+ raise ctypes.WinError(ctypes.get_last_error())+ finally:+ self._kernel32.CloseHandle(process)++ def close(self) -> None:+ """Kills every process still in the job."""+ if self._handle:+ self._kernel32.CloseHandle(self._handle)+ self._handle = None+++def spawn_in_job(cmd: list[str], **popen_kwargs: Any) -> tuple[subprocess.Popen[bytes], KillOnCloseJob | None]:+ """Starts `cmd` in its own process group; on Windows also in a job that dies with this process.++ The process starts suspended and is resumed only once it is in the job: a venv's python.exe starts the real+ interpreter as a child right away, and a child created before the assignment would escape the job.+ """+ if sys.platform != "win32":+ return subprocess.Popen(cmd, start_new_session=True, **popen_kwargs), None+ job = KillOnCloseJob()+ flags = subprocess.CREATE_NEW_PROCESS_GROUP | _CREATE_SUSPENDED+ try:+ process = subprocess.Popen(cmd, creationflags=flags, **popen_kwargs)+ except BaseException:+ job.close()+ raise+ try:+ job.assign(process.pid)+ psutil.Process(process.pid).resume()+ except BaseException:+ process.kill()+ job.close()+ raise+ return process, job+++def exit_status(process: subprocess.Popen[Any]) -> str | None:+ """How `process` ended, e.g. `exit code 3` (negative for a signal, as in `Popen.returncode`); None while it runs.++ On POSIX the exited process is not reaped: it stays a zombie, so its pid, the id of the group it leads, stays+ reserved until `terminate` has killed that group and reaps it. `Popen.poll()` would reap it. Without+ `os.waitid` (macOS) a zombie tells no exit code before that: `exit code unknown`.+ """+ if sys.platform == "win32" or process.returncode is not None:+ code = process.poll()+ return None if code is None else f"exit code {code}"+ if not hasattr(os, "waitid"):+ try:+ # The child is unreaped, so its pid is still its own.+ if psutil.Process(process.pid).status() != psutil.STATUS_ZOMBIE:+ return None+ except psutil.NoSuchProcess:+ pass+ return "exit code unknown"+ try:+ info = os.waitid(os.P_PID, process.pid, os.WEXITED | os.WNOHANG | os.WNOWAIT)+ except ChildProcessError: # reaped elsewhere+ return f"exit code {process.poll()}"+ if info is None:+ return None+ return f"exit code {info.si_status if info.si_code == os.CLD_EXITED else -info.si_status}"+++def kill_group(pgid: int) -> None:+ """SIGKILL to a process group (POSIX). It reaches a descendant whose parent died, which no walk from parent to+ child finds any more, but which stays in the group.++ The id names this group and no other while its leader is unreaped or any member lives: POSIX hands it out+ again only after that.+ """+ try:+ os.killpg(pgid, signal.SIGKILL)+ except ProcessLookupError:+ pass # the group is empty+ except PermissionError:+ # macOS answers EPERM, not ESRCH, when the only member left is a zombie: the leader, unreaped on purpose.+ # Refused for a living member, the kill really failed.+ if living_members(pgid):+ raise+++def living_members(pgid: int) -> list[int]:+ """The pids of a process group's members that have not exited (POSIX); zombies hold no memory, files or port."""+ living = []+ for pid in psutil.pids():+ try:+ if os.getpgid(pid) == pgid and psutil.Process(pid).status() != psutil.STATUS_ZOMBIE:+ living.append(pid)+ except (OSError, psutil.Error):+ continue # gone, or not visible to this process+ return living+++def terminate(process: subprocess.Popen[Any], job: KillOnCloseJob | None) -> None:+ """Kills a tree started by `spawn_in_job` and waits until every process of it has exited.++ Closing a job kills its processes asynchronously; only an exited process has released its files (the scratch+ database). Neither kill goes by a bare pid: the job holds its processes, and the group the process leads keeps+ its id while it has members or the leader is unreaped. That group is killed even when its leader has exited;+ the server's liveness checks leave an exited leader unreaped (`exit_status`), and it is reaped only after the+ kill. The tree is captured before the kill, from the root Popen still holds.+ """+ try:+ root = psutil.Process(process.pid)+ tree = [root, *root.children(recursive=True)]+ except psutil.Error:+ tree = []+ if job is not None:+ job.close()+ else:+ kill_group(process.pid)+ _, alive = psutil.wait_procs(tree, timeout=STOP_TIMEOUT_S)+ if alive:+ logger.warning("processes still running after the kill: %s", ", ".join(str(p.pid) for p in alive))+ try:+ process.wait(timeout=STOP_TIMEOUT_S)+ except subprocess.TimeoutExpired:+ process.kill()+++def remove_tree(path: Path) -> list[str]:+ """Deletes a directory tree; returns what could still not be deleted after a few attempts.++ Files are named rather than the directories that merely stay non-empty because of them.+ """+ failed: list[str] = []+ for attempt in range(REMOVE_ATTEMPTS):+ failed.clear()+ if not path.exists():+ return []+ shutil.rmtree(path, onexc=lambda _function, failed_path, _error: failed.append(failed_path))+ if not path.exists():+ return []+ if attempt < REMOVE_ATTEMPTS - 1:+ time.sleep(REMOVE_RETRY_S)+ return [p for p in failed if not os.path.isdir(p)] or failed+++@dataclass+class ServerProcess:+ process: subprocess.Popen[bytes]+ console: IO[bytes]+ log_path: Path+ base_url: str+ serving: psutil.Process+ """The interpreter serving the API. On Windows a venv's python.exe is a launcher that runs it as a child."""+ cmd: list[str]+ invokeai_file: str+ job: KillOnCloseJob | None+ """Kills the server tree if the runner dies without stopping it (Windows)."""++ @property+ def pid(self) -> int:+ return self.serving.pid++ def alive(self) -> bool:+ return exit_status(self.process) is None and self.serving.is_running()++ def end_status(self) -> str:+ """How a server that is not alive ended, for an error message; it does not reap the launcher."""+ return exit_status(self.process) or "the serving process is gone"++ def log_size(self) -> int:+ return self.log_path.stat().st_size++ def read_log(self, offset: int) -> str:+ with self.log_path.open("rb") as f:+ f.seek(offset)+ return f.read().decode("utf-8", errors="replace")++ def stop(self) -> None:+ terminate(self.process, self.job)+ self.console.close()+++def launch_server(+ spec: ServerSpec,+ scratch_root: Path,+ log_path: Path,+ console_path: Path,+ device_env: dict[str, str] | None = None,+) -> ServerProcess:+ """Starts the server on a prepared scratch root and waits until its API answers."""+ env = server_env(spec, device_env)+ invokeai_file = verify_interpreter(spec, env)+ cmd = [str(spec.python), str(spec.code_dir / "scripts" / "invokeai-web.py"), "--root", str(scratch_root)]+ log_offset = log_path.stat().st_size if log_path.exists() else 0+ console = console_path.open("ab")+ try:+ process, job = spawn_in_job(+ cmd, cwd=spec.code_dir, env=env, stdin=subprocess.DEVNULL, stdout=console, stderr=subprocess.STDOUT+ )+ except BaseException:+ console.close()+ raise+ try:+ port = _wait_for_port(process, log_path, log_offset, console_path)+ base_url = f"http://127.0.0.1:{port}"+ _wait_for_api(process, base_url, console_path)+ serving = _serving_process(process.pid, port)+ except BaseException:+ terminate(process, job)+ console.close()+ raise+ return ServerProcess(process, console, log_path, base_url, serving, cmd, invokeai_file, job)+++def _check_alive(process: subprocess.Popen[bytes], console_path: Path) -> None:+ status = exit_status(process)+ if status is not None:+ raise ServerError(f"server exited ({status}):\n{_tail(console_path)}")+++def _wait_for_port(process: subprocess.Popen[bytes], log_path: Path, offset: int, console_path: Path) -> int:+ # The server moves to the next free port when the configured one is taken, so the port comes from its log.+ deadline = time.monotonic() + STARTUP_TIMEOUT_S+ while time.monotonic() < deadline:+ _check_alive(process, console_path)+ if log_path.exists():+ with log_path.open("rb") as f:+ f.seek(offset)+ match = RUNNING_LINE.search(f.read().decode("utf-8", errors="replace"))+ if match:+ return int(match.group(1))+ time.sleep(STARTUP_POLL_S)+ raise ServerError(f"server did not log 'Invoke running on' within {STARTUP_TIMEOUT_S:.0f}s:\n{_tail(console_path)}")+++def _wait_for_api(process: subprocess.Popen[bytes], base_url: str, console_path: Path) -> None:+ deadline = time.monotonic() + STARTUP_TIMEOUT_S+ while time.monotonic() < deadline:+ _check_alive(process, console_path)+ try:+ if requests.get(f"{base_url}/api/v1/app/version", timeout=10).ok:+ return+ except requests.RequestException:+ pass+ time.sleep(STARTUP_POLL_S)+ raise ServerError(f"server API at {base_url} did not answer within {STARTUP_TIMEOUT_S:.0f}s")diff --git a/tests/family_e2e/__init__.py b/tests/family_e2e/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/tests/family_e2e/fake_invokeai_server.py b/tests/family_e2e/fake_invokeai_server.pynew file mode 100644index 0000000000..ad8763f66d--- /dev/null+++ b/tests/family_e2e/fake_invokeai_server.py@@ -0,0 +1,203 @@+"""A stand-in for `scripts/invokeai-web.py`: the HTTP routes and socket.io events the family E2E runner uses.++The flow test copies this file to `<code_dir>/scripts/invokeai-web.py`, so the runner launches it exactly as it would+launch InvokeAI. It reads the scratch root's `invokeai.yaml` for its port and log file, logs in InvokeAI's plain+format, and executes a queued graph by walking its nodes: the model loader logs a full load once per cache flush, the+`fake_denoise` node sends preview frames, and the non-intermediate node returns a PNG of its width and height.+When `<code_dir>/crash-at-enqueue` holds N, the server deletes the file and dies while running its N-th queue item.+Self-contained on purpose: it runs in a fresh interpreter with only the code directory on the path.+"""++import argparse+import io+import json+import logging+import os+import re+import socketserver+import threading+import time+from datetime import datetime+from pathlib import Path+from wsgiref.simple_server import WSGIRequestHandler, WSGIServer, make_server++import socketio+import yaml+from PIL import Image++STEP_S = 0.01+CRASH_MARKER = Path(__file__).resolve().parents[1] / "crash-at-enqueue"+MODEL_CONFIG = {+ "key": "fake-model",+ "name": "Fake",+ "base": "fake",+ "type": "main",+ "format": "checkpoint",+ "hash": "blake3:fakehash",+ "path": "/models/fake.safetensors",+ "source": "https://example.com/fake.safetensors?token=fake-token",+ "source_type": "url",+ "default_settings": {},+}+++class _Server(socketserver.ThreadingMixIn, WSGIServer):+ daemon_threads = True+++class _QuietHandler(WSGIRequestHandler):+ def log_message(self, format, *args): # noqa: A002 - stdlib signature+ pass+++class FakeInvoke:+ def __init__(self, logger: logging.Logger) -> None:+ self.logger = logger+ self.sio = socketio.Server(async_mode="threading")+ self.sio.on("subscribe_queue", self.subscribe)+ self.lock = threading.Lock()+ self.items: dict[int, dict] = {}+ self.images: dict[str, bytes] = {}+ self.resident: set[str] = set()+ self.uploads = 0++ def subscribe(self, sid, data):+ self.sio.enter_room(sid, data["queue_id"])++ def emit(self, name: str, data: dict) -> None:+ self.sio.emit(name, {"queue_id": "default", **data}, room="default")++ def execute(self, item_id: int, crash: bool) -> None:+ item = self.items[item_id]+ graph = item["batch"]["graph"]+ item.update(status="in_progress", started_at=str(datetime.now()))+ self.emit("queue_item_status_changed", {"item_id": item_id, "status": "in_progress"})+ if crash:+ time.sleep(STEP_S)+ os._exit(3)+ mapping, results = {}, {}+ for node_id, node in graph["nodes"].items():+ prepared = f"{node_id}-prepared"+ mapping[node_id] = [prepared]+ invocation = {"id": prepared, "type": node["type"]}+ base = {"item_id": item_id, "invocation": invocation, "invocation_source_id": node_id}+ self.emit("invocation_started", base)+ result: dict = {"type": "fake_output"}+ if "model" in node:+ key = node["model"]["key"]+ if key not in self.resident:+ load = {"config": {"key": key}, "submodel_type": "transformer"}+ self.sio.emit("model_load_started", load, room="default")+ time.sleep(STEP_S)+ self.logger.info(+ f"[MODEL CACHE] Loaded model '{key}:transformer' (FakeTransformer) onto cuda device #0 in "+ "0.01s. Total model size: 1024.00MB, VRAM: 1024.00MB (100.0%)"+ )+ self.sio.emit("model_load_complete", load, room="default")+ self.resident.add(key)+ if node["type"] == "fake_denoise":+ for step in range(1, node["steps"] + 1):+ time.sleep(STEP_S)+ frame = {"percentage": step / node["steps"], "message": "Denoising", "image": {"dataURL": "x"}}+ self.emit("invocation_progress", base | frame)+ if not node.get("is_intermediate", False):+ buffer = io.BytesIO()+ Image.new("RGB", (node["width"], node["height"]), (200, 80, 40)).save(buffer, format="PNG")+ name = f"output-{item_id}.png"+ self.images[name] = buffer.getvalue()+ result = {"type": "image_output", "image": {"image_name": name}}+ results[prepared] = result+ time.sleep(STEP_S)+ self.emit("invocation_complete", base | {"result": result})+ item.update(+ status="completed",+ completed_at=str(datetime.now()),+ session={"source_prepared_mapping": mapping, "results": results},+ )+ self.emit("queue_item_status_changed", {"item_id": item_id, "status": "completed"})++ def __call__(self, environ, start_response):+ method, path = environ["REQUEST_METHOD"], environ["PATH_INFO"]+ length = int(environ.get("CONTENT_LENGTH") or 0)+ body = environ["wsgi.input"].read(length) if length else b""++ def reply(payload, status="200 OK", content_type="application/json"):+ data = payload if isinstance(payload, bytes) else json.dumps(payload).encode()+ start_response(status, [("Content-Type", content_type), ("Content-Length", str(len(data)))])+ return [data]++ if path == "/api/v1/app/version":+ return reply({"version": "0.0.0-fake"})+ if path == "/api/v1/app/app_deps":+ return reply({"torch": "fake"})+ if path == "/api/v1/app/runtime_config":+ return reply({"set_fields": [], "config": {"multiuser": False, "fp8_compute": False}})+ if path == "/api/v2/models/":+ return reply({"models": [MODEL_CONFIG]})+ if path == "/api/v2/models/capabilities":+ return reply({"fake": {}})+ if path == "/api/v2/models/empty_model_cache":+ self.logger.info("Emptying model cache.")+ self.resident.clear()+ return reply({"models_cleared": 0, "bytes_freed": 0})+ if path == "/api/v1/images/upload":+ with self.lock:+ self.uploads += 1+ return reply({"image_name": f"upload-{self.uploads}.png"}, status="201 Created")+ if path == "/api/v1/queue/default/enqueue_batch":+ with self.lock:+ item_id = len(self.items) + 1+ self.items[item_id] = {+ "item_id": item_id,+ "status": "pending",+ "batch": json.loads(body)["batch"],+ "session": {},+ }+ crash = CRASH_MARKER.exists() and CRASH_MARKER.read_text() == str(item_id)+ if crash:+ CRASH_MARKER.unlink()+ threading.Thread(target=self.execute, args=(item_id, crash), daemon=True).start()+ return reply({"item_ids": [item_id]}, status="201 Created")+ if path == "/api/v1/queue/default/status":+ states = [item["status"] for item in self.items.values()]+ return reply(+ {+ "queue": {"pending": states.count("pending"), "in_progress": states.count("in_progress")},+ "processor": {},+ }+ )+ if match := re.fullmatch(r"/api/v1/queue/default/i/(\d+)", path):+ item = self.items[int(match[1])]+ return reply({k: v for k, v in item.items() if k != "batch"})+ if match := re.fullmatch(r"/api/v1/images/i/([^/]+)/full", path):+ return reply(self.images[match[1]], content_type="image/png")+ return reply({"detail": f"no route {method} {path}"}, status="404 Not Found")+++def main() -> None:+ parser = argparse.ArgumentParser()+ parser.add_argument("--root", required=True)+ root = Path(parser.parse_args().root)+ config = yaml.safe_load((root / "invokeai.yaml").read_text(encoding="utf-8"))+ log_file = next(h.split("=", 1)[1] for h in config["log_handlers"] if h.startswith("file="))+ handler = logging.FileHandler(log_file, encoding="utf-8")+ handler.setFormatter(logging.Formatter("[%(asctime)s]::[%(name)s]::%(levelname)s --> %(message)s"))+ logger = logging.getLogger("InvokeAI")+ logger.setLevel(logging.INFO)+ logger.addHandler(handler)++ fake = FakeInvoke(logger)+ app = socketio.WSGIApp(fake.sio, fake, socketio_path="/ws/socket.io")+ port = config["port"]+ while True:+ try:+ httpd = make_server("127.0.0.1", port, app, server_class=_Server, handler_class=_QuietHandler)+ break+ except OSError:+ port += 1+ logger.info(f"Invoke running on http://127.0.0.1:{port} (Press CTRL+C to quit)")+ httpd.serve_forever()+++if __name__ == "__main__":+ main()diff --git a/tests/family_e2e/test_bundle.py b/tests/family_e2e/test_bundle.pynew file mode 100644index 0000000000..c61bcda5f5--- /dev/null+++ b/tests/family_e2e/test_bundle.py@@ -0,0 +1,540 @@+"""`bundle`: one zip that opens elsewhere, with what the report shows and nothing of this machine."""++import gzip+import json+import os+import re+import urllib.parse+import zipfile+from dataclasses import dataclass+from datetime import datetime, timedelta, timezone+from pathlib import Path++import numpy as np+import psutil+import pytest+import yaml+from PIL import Image, PngImagePlugin++from scripts.family_e2e.__main__ import main+from scripts.family_e2e.bundle import Root, Sanitizer+from scripts.family_e2e.graphs import model_identifiers+from scripts.family_e2e.records import (+ Environment,+ ForeignProcess,+ ModelIdentity,+ Reference,+ RunInfo,+ load_records,+ load_run_info,+ write_run_info,+)+from scripts.family_e2e.references import accept, load_reference+from scripts.family_e2e.report import write_report+from scripts.family_e2e.runner import HEARTBEAT_FILE, process_identity+from tests.family_e2e.test_records import make_environment, make_record+from tests.family_e2e.test_report import CASE, FIRST, OTHER_CASE, PROFILE, SECOND, _case_records, _write_run++ENV_SECRET = "hf_bundleTestEnvToken"+REFERENCE_SECRET = "civitaiReferenceOnlyToken"+"""A credential of the reference's run only, not of the bundled run."""+CONFIG_SECRET = "sk-unmaskedByAnOlderServer"+QUERY_SECRET = "bundleTestQueryToken"+PROCESS_NAME = "SecretGame.exe"+ALLOC_CONF = "backend:cudaMallocAsync"+"""A setting the manifest's server env sets, no credential: it must not change a verdict."""+IDENTITY = ModelIdentity(+ key="main-key",+ name="Z-Image Turbo",+ base="z-image",+ type="main",+ format="diffusers",+ variant=None,+ hash="blake3:" + "a" * 64,+ source="Tongyi-MAI/Z-Image-Turbo",+)+SHOWN = f"images/{CASE}.default.measure.0.1.png"+"""The image the bundled report shows for this run: the final attempt of the first measure."""+PREVIOUS = f"previous/{FIRST}/images/{CASE}.default.measure.0.0.png"+REFERENCE = f"reference/{CASE}/image.png"+TEXT_CHUNKS = {b"tEXt", b"zTXt", b"iTXt"}+++@dataclass(frozen=True)+class _Bundle:+ data_dir: Path+ run_dir: Path+ root: Path+ """The extracted zip's folder."""+ members: set[str]+ paths: list[Path]+ """This machine's paths the run's files name."""+++def _model(key: str, model_type: str, source: str, source_type: str, **fields: str) -> dict[str, str]:+ return {+ "key": key,+ "hash": "blake3:" + "b" * 64,+ "name": key,+ "base": "z-image",+ "type": model_type,+ "source": source,+ "source_type": source_type,+ **fields,+ }+++def _graph(main_model: dict[str, str]) -> dict:+ encoder = _model(+ "enc-key", "qwen3_encoder", "Qwen/Qwen3-4B", "hf_repo_id", source_url="https://hf.co/Qwen/Qwen3-4B"+ )+ vae = _model("vae-key", "vae", f"https://example.com/vae.safetensors?download_token={QUERY_SECRET}", "url")+ lora = _model("lora-key", "lora", "https://example.com/lora.safetensors", "url")+ lan = _model("lan-key", "lora", "http://cm3588:8090/lan.safetensors", "url")+ nodes = {+ "loader": {"id": "loader", "type": "z_image_model_loader", "model": main_model, "vae_model": vae},+ "encoder": {"id": "encoder", "type": "z_image_text_encoder", "qwen3_encoder_model": encoder},+ "lora": {"id": "lora", "type": "lora_collection_loader", "loras": [{"lora": lora}, {"lora": lan}]},+ }+ return {"graph": {"id": "g", "nodes": nodes, "edges": []}, "data": [], "origin": "o", "destination": "gallery"}+++def _add_metadata(path: Path, text: str) -> None:+ """Re-saves a PNG with the text chunks InvokeAI writes, a private chunk, and a gamma chunk that colours it."""+ info = PngImagePlugin.PngInfo()+ info.add_text("invokeai_metadata", text)+ info.add_text("invokeai_graph", text, zip=True)+ info.add_itxt("Comment", text)+ info.add(b"prVt", text.encode())+ info.add(b"gAMA", (45455).to_bytes(4, "big"))+ with Image.open(path) as image:+ pixels = image.copy()+ pixels.save(path, pnginfo=info)+++def _chunk_types(data: bytes) -> list[bytes]:+ types, offset = [], 8+ while offset < len(data):+ types.append(data[offset + 4 : offset + 8])+ offset += 12 + int.from_bytes(data[offset : offset + 4], "big")+ return types+++def _pixels(path: Path) -> np.ndarray:+ with Image.open(path) as image:+ return np.asarray(image)+++def _snapshot(directory: Path) -> dict[Path, bytes]:+ return {path.relative_to(directory): path.read_bytes() for path in directory.rglob("*") if path.is_file()}+++def _summary_table(summary: str) -> list[str]:+ return [line for line in summary.splitlines() if line.startswith("| ")]+++def bundle(tmp_path: Path) -> _Bundle:+ """A run with a reference and a previous run whose files name this machine's paths, secrets and processes."""+ # Spaces, so a path in free text does not end at the first one.+ data_dir, template_root, code_dir = tmp_path / "e2e data", tmp_path / "template root", tmp_path / "code dir"+ model_dir = tmp_path / "model library" / "z image turbo"+ other_model = tmp_path / "other models" / "flux dev.safetensors"+ metadata = json.dumps(+ {"qwen3_source": {"path": str(model_dir)}, "url": f"https://a.example/x?token={QUERY_SECRET}"}+ )+ data_dir.mkdir()+ manifest = data_dir / "manifest.yaml"+ manifest.write_text(+ yaml.safe_dump(+ {+ "profile": PROFILE,+ "data_dir": ".",+ "gpu": "RTX",+ "server": {"template_root": str(template_root), "python": "python.exe", "code_dir": str(code_dir)},+ "defaults": {"prompt": "a fox"},+ "families": [+ {"family": "z", "cases": [{"id": "zimage-t2i", "model": "m", "steps": 8, "sizes": [[8, 8]]}]}+ ],+ }+ )+ )+ # The reference and previous run, from another checkout. A credential reaches the report through its+ # environment, and its reference.json carries that environment whole.+ base_checkout, base_python = tmp_path / "base checkout", Path.home() / "venvs" / "invoke base" / "python.exe"+ first_environment = make_environment(+ code_dir=str(base_checkout),+ python=str(base_python),+ invokeai_file=str(base_checkout / "invokeai" / "__init__.py"),+ server_cmd=[str(base_python), "--root", str(data_dir / "scratch")],+ extra_env={"HF_TOKEN": ENV_SECRET, "CIVITAI_API_TOKEN": REFERENCE_SECRET},+ runtime_config={+ "set_fields": [],+ "config": {+ "pytorch_cuda_alloc_conf": "backend:native",+ "attention_backend": f"sage-{ENV_SECRET}",+ "models_dir": str(template_root / "models"),+ "image_index_model": f"model-{REFERENCE_SECRET}",+ "external_gemini_base_url": "http://cm3588:8090/v1",+ },+ },+ )+ first = _write_run(data_dir, FIRST, _case_records(FIRST), environment=first_environment)+ for image in (first / "images").iterdir():+ _add_metadata(image, metadata)+ accept(data_dir, first, None)+ # The report notes it skipped this run, naming its records file in the error.+ unreadable = _write_run(data_dir, "20261001-180000-rtx4090", [])+ (unreadable / "records.jsonl").write_text("{\n")++ run_dir = data_dir / "runs" / SECOND+ python = code_dir / ".venv" / "python.exe"+ environment = make_environment(+ code_dir=str(code_dir),+ python=str(python),+ invokeai_file=str(code_dir / "invokeai" / "__init__.py"),+ server_cmd=[str(python), str(code_dir / "scripts" / "invokeai-web.py"), "--root", str(data_dir / "scratch")],+ extra_env={"HF_TOKEN": ENV_SECRET, "INVOKEAI_PYTORCH_CUDA_ALLOC_CONF": ALLOC_CONF},+ runtime_config={+ "set_fields": [],+ "config": {+ "models_dir": str(template_root / "models"),+ "log_handlers": ["console", f"file={run_dir / 'server-default.log'}"],+ "external_openai_api_key": CONFIG_SECRET,+ "external_gemini_base_url": f"https://user:{CONFIG_SECRET}@gemini.example.com/v1?key={QUERY_SECRET}",+ "log_tokenization": True,+ "pytorch_cuda_alloc_conf": ALLOC_CONF,+ "attention_backend": "sage",+ },+ },+ )+ warmup, measure, other, spoiled = _case_records(SECOND)+ crashed = make_record(+ CASE,+ rep=0,+ attempt=0,+ run_id=SECOND,+ status="error",+ image=False,+ error=f"OSError: cannot open '{model_dir / 'vae' / 'diffusion_pytorch_model.safetensors'}' or '{other_model}' "+ f"with {ENV_SECRET} from {Path.home() / 'private-folder' / 'notes.txt'} in {code_dir / 'invokeai'}, "+ f"fetched from https://user:[email protected]/api/download/models/1;session=s?token={QUERY_SECRET}#top",+ invalid_reasons=[f"server crashed, see {run_dir / 'server-default.log'}"],+ )+ resumed = measure.model_copy(update={"attempt": 1, "record_id": f"{CASE}.default.measure.0.1", "image_path": SHOWN})+ assert spoiled.memory is not None+ foreign = ForeignProcess(pid=4321, name=PROCESS_NAME, dedicated_bytes=2**31)+ spoiled = spoiled.model_copy(+ update={+ "valid_timing": False,+ "valid_memory": False,+ "invalid_reasons": [f"foreign GPU load: pid 4321 ({PROCESS_NAME}) 2048 MiB"],+ "memory": spoiled.memory.model_copy(update={"foreign": [foreign]}),+ }+ )+ _write_run(+ data_dir,+ SECOND,+ [warmup, crashed, resumed, other, spoiled],+ environment=environment,+ manifest_path=str(manifest),+ case_models={CASE: [IDENTITY]},+ )+ _add_metadata(run_dir / SHOWN, metadata)+ main_model = _model(+ "main-key",+ "main",+ str(tmp_path / "downloads" / "z image.safetensors"),+ "path",+ name="Z-Image Turbo",+ path=str(model_dir),+ config_path=str(template_root / "configs" / "z.yaml"),+ source_api_response=json.dumps({"downloadUrl": f"https://civitai.com/api/download/1?token={QUERY_SECRET}"}),+ source_url=f"https://example.com/z?ref={QUERY_SECRET}",+ )+ (run_dir / "graphs").mkdir()+ (run_dir / "graphs" / f"{CASE}.json").write_text(json.dumps(_graph(main_model), indent=2))+ # The exporter request lists every model of the server, also those no graph uses.+ (run_dir / "export").mkdir()+ flux = _model("flux-key", "main", str(other_model), "path", name="Flux Dev", path=str(other_model))+ (run_dir / "export" / "export-request.json").write_text(json.dumps({"version": 1, "models": [flux]}))+ (run_dir / "traces").mkdir()+ with gzip.open(run_dir / "traces" / f"{resumed.record_id}.csv.gz", "wt") as trace:+ trace.write("series,t,bytes\ndedicated,0.0,1024\n")+ (run_dir / "inputs").mkdir()+ (run_dir / "inputs" / "[email protected]").write_bytes(b"input")+ for log in ("runner.log", "server-default.log"):+ (run_dir / log).write_text(f"HF_TOKEN={ENV_SECRET} in {template_root}\n")+ (run_dir / HEARTBEAT_FILE).write_text(json.dumps({"runner": None, "step": "done"}))++ before = _snapshot(run_dir)+ output = tmp_path / "out" / "bundle.zip"+ assert main(["bundle", str(run_dir), "--output", str(output)]) == 0+ assert _snapshot(run_dir) == before+ with zipfile.ZipFile(output) as archive:+ archive.extractall(tmp_path / "unzipped")+ members = {name.removeprefix(f"{SECOND}/") for name in archive.namelist()}+ paths = [data_dir, template_root, code_dir, run_dir, model_dir, other_model, Path.home(), tmp_path]+ return _Bundle(data_dir, run_dir, tmp_path / "unzipped" / SECOND, members, paths)+++def test_bundle_holds_the_report_and_the_images_it_shows_with_their_pixels_and_no_logs(bundle: _Bundle) -> None:+ assert bundle.members == {+ "bundle.json",+ "report.html",+ "summary.md",+ "run.json",+ "records.jsonl",+ f"graphs/{CASE}.json",+ f"traces/{CASE}.default.measure.0.1.csv.gz",+ SHOWN,+ REFERENCE,+ f"reference/{CASE}/reference.json",+ PREVIOUS,+ f"diff/{CASE}.png",+ }+ report = (bundle.root / "report.html").read_text(encoding="utf-8")+ links = {urllib.parse.unquote(link) for link in re.findall(r'(?:src|href)="([^"#][^"]*)"', report)}+ assert links == {SHOWN, REFERENCE, PREVIOUS, f"diff/{CASE}.png"}+ sources = {+ SHOWN: bundle.run_dir / SHOWN,+ REFERENCE: bundle.data_dir / "references" / PROFILE / CASE / "image.png",+ PREVIOUS: bundle.data_dir / "runs" / FIRST / "images" / f"{CASE}.default.measure.0.0.png",+ }+ for name, source in sources.items():+ # The same pixels, so a recipient recomputes the PSNR; the colour chunk stays, the metadata goes.+ assert np.array_equal(_pixels(bundle.root / name), _pixels(source)), name+ assert TEXT_CHUNKS < set(_chunk_types(source.read_bytes()))+ bundled = [kind for kind in _chunk_types((bundle.root / name).read_bytes()) if kind != b"IDAT"]+ assert bundled == [b"IHDR", b"gAMA", b"IEND"], name+++def test_bundle_holds_no_path_secret_or_process_name_of_this_machine(bundle: _Bundle) -> None:+ forbidden = {+ ENV_SECRET,+ REFERENCE_SECRET,+ CONFIG_SECRET,+ QUERY_SECRET,+ PROCESS_NAME,+ "private-folder",+ "model library",+ "other models",+ "cm3588",+ }+ for path in bundle.paths:+ forbidden |= {str(path), path.as_posix(), json.dumps(str(path))[1:-1]}+ contents = {}+ for path in bundle.root.rglob("*"):+ if path.is_file():+ data = path.read_bytes()+ contents[path.relative_to(bundle.root).as_posix()] = gzip.decompress(data) if path.suffix == ".gz" else data+ needles = {needle.lower().encode("utf-8") for needle in forbidden}++ assert len(contents) == len(bundle.members)+ found = {name: [n for n in needles if n in data.lower()] for name, data in contents.items()}+ assert found == dict.fromkeys(contents, [])+ # The errors are still there and readable, with placeholders.+ summary = (bundle.root / "summary.md").read_text(encoding="utf-8")+ sep = os.sep+ assert (+ f"cannot open '<model Z-Image Turbo>{sep}vae{sep}diffusion_pytorch_model.safetensors' or '<model Flux Dev>'"+ in (summary)+ )+ assert f"with <HF_TOKEN> from <home>{sep}notes.txt in <code_dir>{sep}invokeai" in summary+ assert "fetched from https://civitai.com/api/download/models/1" in summary+ assert "skipped, unreadable: <data_dir>" in summary+ assert "foreign GPU load: pid 4321 (<process>) 2048 MiB" in summary+++def test_bundled_verdicts_match_the_report_on_disk(bundle: _Bundle) -> None:+ on_disk = write_report(bundle.data_dir, bundle.run_dir).summary_md.read_text(encoding="utf-8")+ bundled = (bundle.root / "summary.md").read_text(encoding="utf-8")++ assert _summary_table(bundled) == _summary_table(on_disk)+ # A setting from the server env is no credential; the credential an earlier environment shows is replaced.+ change = f"pytorch_cuda_alloc_conf backend:native → {ALLOC_CONF}"+ assert f"environment changed vs reference: {change}; attention_backend sage-{ENV_SECRET} → sage" in on_disk+ assert f"environment changed vs reference: {change}; attention_backend sage-<HF_TOKEN> → sage" in bundled+++def test_bundled_run_names_paths_and_variables_only_and_keeps_model_identities(bundle: _Bundle) -> None:+ info = RunInfo.model_validate_json((bundle.root / "run.json").read_bytes())++ environment: Environment = info.environments["default"]+ assert (info.manifest_path, environment.code_dir, environment.python) == ("manifest.yaml", "code dir", "python.exe")+ assert environment.server_cmd == ["python.exe", "invokeai-web.py", "--root", "scratch"]+ assert environment.extra_env == {"HF_TOKEN": "<redacted>", "INVOKEAI_PYTORCH_CUDA_ALLOC_CONF": "<redacted>"}+ assert environment.runtime_config["config"] == {+ "models_dir": "models",+ "log_handlers": ["console", f"file=<run_dir>{os.sep}server-default.log"],+ "external_openai_api_key": "<redacted>",+ "external_gemini_base_url": "https://gemini.example.com/v1",+ "log_tokenization": True,+ "pytorch_cuda_alloc_conf": ALLOC_CONF,+ "attention_backend": "sage",+ }+ foreign = [(p.pid, p.name) for r in load_records(bundle.root) if r.memory for p in r.memory.foreign]+ assert foreign == [(4321, "<process>")]+ assert info.case_models == {CASE: [IDENTITY]}+ assert info.graph_hashes == {CASE: "graph-1"}+++def test_bundled_reference_keeps_what_a_reader_compares_and_names_paths_and_variables_only(bundle: _Bundle) -> None:+ bundled = Reference.model_validate_json((bundle.root / "reference" / CASE / "reference.json").read_bytes())+ loaded = load_reference(bundle.data_dir, PROFILE, CASE)+ assert loaded is not None+ original = loaded[0]++ # Its run, graph hash, medians and the hash of the original image: what tells BASELINE from PASS and drives+ # the comparisons.+ assert bundled.model_dump(exclude={"environment"}) == original.model_dump(exclude={"environment"})+ assert (bundled.source_run_id, bundled.graph_hash) == (FIRST, "graph-1")+ environment = bundled.environment+ assert (environment.code_dir, environment.python, environment.server_cmd) == (+ "base checkout",+ "python.exe",+ ["python.exe", "--root", "scratch"],+ )+ assert environment.extra_env == {"HF_TOKEN": "<redacted>", "CIVITAI_API_TOKEN": "<redacted>"}+ assert environment.runtime_config["config"] == {+ "pytorch_cuda_alloc_conf": "backend:native",+ "attention_backend": "sage-<HF_TOKEN>",+ "models_dir": "models",+ "image_index_model": "model-<CIVITAI_API_TOKEN>",+ "external_gemini_base_url": "http://<local host>/v1",+ }+++def test_only_cases_with_a_readable_reference_carry_its_reference_json(tmp_path: Path) -> None:+ third = "zimage-t2i@16x16"+ records = [*_case_records(FIRST), *_case_records(FIRST, OTHER_CASE), *_case_records(FIRST, third)]+ run_dir = _write_run(tmp_path, FIRST, records)+ accept(tmp_path, run_dir, [CASE, OTHER_CASE])+ (tmp_path / "references" / PROFILE / OTHER_CASE / "reference.json").write_text("{")++ assert main(["bundle", str(run_dir)]) == 0++ with zipfile.ZipFile(run_dir / f"{FIRST}.zip") as archive:+ names = sorted(name.removeprefix(f"{FIRST}/") for name in archive.namelist() if "/reference/" in name)+ assert names == [f"reference/{CASE}/image.png", f"reference/{CASE}/reference.json"]+++def test_bundled_graphs_keep_only_model_sources_anyone_may_see(bundle: _Bundle) -> None:+ graph = json.loads((bundle.root / "graphs" / f"{CASE}.json").read_text(encoding="utf-8"))+ models = {model["key"]: model for model in model_identifiers(graph)}++ assert [key for key, model in models.items() if {"path", "config_path", "source_api_response"} & set(model)] == []+ assert {key: model.get("source") for key, model in models.items()} == {+ "main-key": None, # a local path+ "vae-key": None, # a query that may carry a token+ "lan-key": None, # a host of the local network+ "enc-key": "Qwen/Qwen3-4B",+ "lora-key": "https://example.com/lora.safetensors",+ }+ assert {key: model.get("source_url") for key, model in models.items() if "source_url" in model} == {+ "enc-key": "https://hf.co/Qwen/Qwen3-4B"+ }++[email protected](("status", "shown"), [("stopped", "stopped"), ("running", "interrupted")])+def test_a_run_recorded_before_model_identities_existed_bundles_once_its_runner_is_gone(+ tmp_path: Path, capsys: pytest.CaptureFixture[str], status: str, shown: str+) -> None:+ run_dir = _write_run(tmp_path, FIRST, _case_records(FIRST), status=status)+ old = json.loads((run_dir / "run.json").read_text(encoding="utf-8"))+ del old["case_models"]+ (run_dir / "run.json").write_text(json.dumps(old), encoding="utf-8")+ # The pid of the recorded runner now belongs to another process: the runner is gone.+ identity = [os.getpid(), psutil.Process(os.getpid()).create_time() - 100.0]+ (run_dir / HEARTBEAT_FILE).write_text(json.dumps({"runner": identity}))++ assert main(["report", str(run_dir)]) == 0+ assert main(["bundle", str(run_dir)]) == 0++ zip_path = run_dir / f"{FIRST}.zip"+ assert f"bundle {zip_path}" in capsys.readouterr().out+ with zipfile.ZipFile(zip_path) as archive:+ bundled = RunInfo.model_validate_json(archive.read(f"{FIRST}/run.json"))+ report = archive.read(f"{FIRST}/report.html").decode("utf-8")+ summary = archive.read(f"{FIRST}/summary.md").decode("utf-8")+ assert (bundled.status, bundled.case_models) == (status, {})+ assert "## Models" not in summary+ assert f"run {shown}" in report+ assert f"The run is {shown}; cases it did not reach show as INVALID." in report++[email protected]("tool_commit", ["0123456789abcdef", None])+def test_bundle_describes_its_format_for_the_upload_hub(tmp_path: Path, tool_commit: str | None) -> None:+ run_dir = _write_run(tmp_path, FIRST, _case_records(FIRST))+ write_run_info(run_dir, load_run_info(run_dir).model_copy(update={"tool_commit": tool_commit}))++ # Bracketed by the clock, not waited for; the timestamp has whole seconds.+ before = datetime.now(timezone.utc).replace(microsecond=0)+ assert main(["bundle", str(run_dir)]) == 0+ after = datetime.now(timezone.utc)++ with zipfile.ZipFile(run_dir / f"{FIRST}.zip") as archive:+ description = json.loads(archive.read(f"{FIRST}/bundle.json"))+ created_at = datetime.fromisoformat(description.pop("created_at"))+ assert description == {"format_version": 2, "tool_commit": tool_commit}+ assert created_at.utcoffset() == timedelta(0)+ assert before <= created_at <= after+++def test_a_token_rotated_across_the_compared_runs_is_redacted_in_every_value(tmp_path: Path) -> None:+ # The reference, the previous run and the bundled run each held another HF_TOKEN; the report compares with both.+ reference_token, previous_token, token = "hf_tokenOfTheReferenceRun", "hf_tokenOfThePreviousRun", "hf_tokenNow"+ previous = "20261001-180000-rtx4090"++ def environment(hf_token: str, **settings: str) -> Environment:+ config = {"attention_backend": f"sage-{hf_token}", **settings}+ return make_environment(extra_env={"HF_TOKEN": hf_token}, runtime_config={"set_fields": [], "config": config})++ reference_run = _write_run(tmp_path, FIRST, _case_records(FIRST), environment=environment(reference_token))+ accept(tmp_path, reference_run, None)+ previous_environment = environment(previous_token, pytorch_cuda_alloc_conf="backend:native")+ _write_run(tmp_path, previous, _case_records(previous), environment=previous_environment)+ warmup, measure, *rest = _case_records(SECOND)+ measure = measure.model_copy(update={"error": f"a download sent {token}, the reference's sent {reference_token}"})+ run_dir = _write_run(tmp_path, SECOND, [warmup, measure, *rest], environment=environment(token))++ assert main(["bundle", str(run_dir)]) == 0++ with zipfile.ZipFile(run_dir / f"{SECOND}.zip") as archive:+ contents = {name: archive.read(name) for name in archive.namelist()}+ tokens = [value.encode() for value in (reference_token, previous_token, token)]+ assert [name for name, data in contents.items() if any(value in data for value in tokens)] == []+ assert b"a download sent <HF_TOKEN>, the reference's sent <HF_TOKEN>" in contents[f"{SECOND}/records.jsonl"]+ assert b"sage-<HF_TOKEN>" in contents[f"{SECOND}/reference/{CASE}/reference.json"]+ # The previous run was compared: its other setting shows as a change.+ summary = contents[f"{SECOND}/summary.md"].decode("utf-8")+ assert "environment changed vs previous run: pytorch_cuda_alloc_conf backend:native → —" in summary+++def test_bundle_refuses_while_the_runner_runs(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:+ run_dir = _write_run(tmp_path, FIRST, _case_records(FIRST), status="running")+ (run_dir / HEARTBEAT_FILE).write_text(json.dumps({"runner": process_identity(os.getpid())}))++ assert main(["bundle", str(run_dir)]) == 2++ assert f"the runner of {FIRST} is still running" in capsys.readouterr().err+ assert list(run_dir.glob("*.zip")) == []+++def test_a_posix_path_outside_every_root_keeps_only_its_last_component() -> None:+ """Linux error texts name absolute paths the roots do not cover, e.g. of the server's venv. The tool's own errors+ quote the server's API paths, which name nothing of the machine and must stay readable."""+ sanitizer = Sanitizer([Root("<run_dir>", "/srv/e2e/data/runs/r1", True)], [])+ for api_error in (+ "no output image: GET /api/v1/images/i/abc.png/full -> 404: Not Found",+ "ApiError: POST /api/v1/queue/default/enqueue_batch -> 500: boom",+ ):+ assert sanitizer.text(api_error) == api_error+ text = (+ "OSError: /opt/venvs/prtest/lib/libcudnn.so.9 not found; image /srv/e2e/data/runs/r1/images/a.png; "+ "from https://huggingface.co/org/repo/resolve/main/x.safetensors at 12 MiB/s into traces/x.csv.gz"+ )+ assert sanitizer.text(text) == (+ "OSError: libcudnn.so.9 not found; image <run_dir>/images/a.png; "+ "from https://huggingface.co/org/repo/resolve/main/x.safetensors at 12 MiB/s into traces/x.csv.gz"+ )diff --git a/tests/family_e2e/test_cli.py b/tests/family_e2e/test_cli.pynew file mode 100644index 0000000000..8031024ab2--- /dev/null+++ b/tests/family_e2e/test_cli.py@@ -0,0 +1,282 @@+import json+import socket+import subprocess+import sys+import time+from collections.abc import Iterator+from pathlib import Path++import psutil+import pytest+import yaml++import scripts.family_e2e.__main__ as cli+from scripts.family_e2e import runner, server+from scripts.family_e2e.__main__ import UsageError, _resolve_run, main+from scripts.family_e2e.gpu_memory import Adapter+from scripts.family_e2e.records import RUN_INFO_FILE, RunInfo, load_run_info, write_run_info+from scripts.family_e2e.runner import HEARTBEAT_FILE, now_iso, process_identity++REPO_ROOT = Path(__file__).parents[2]+CHILD_TIMEOUT_S = 60.0+# The runner `start` launches, on a fake GPU, waiting for a line on stdin at its pause: before it begins+# ("unregistered"), or where it opens the GPU, right after its registration ("registered").+STAND_IN_RUNNER = """+import sys+from pathlib import Path++from scripts.family_e2e import runner+from scripts.family_e2e.gpu_memory import Adapter++run_dir, runner.LOCK_DIR, pause = Path(sys.argv[1]), Path(sys.argv[2]), sys.argv[3]+++def wait(at):+ if pause == at:+ print("paused", flush=True)+ sys.stdin.readline()+++def open_gpu(description):+ wait("registered")+ return runner.Gpu(adapter=Adapter(luid=1, description=description), process_usage=dict, sampler=lambda pid: None)+++wait("unregistered")+sys.exit(runner.run(run_dir, gpu_factory=open_gpu))+"""+++def test_runs_resolve_by_directory_id_or_latest_of_the_profile(tmp_path: Path) -> None:+ manifest = tmp_path / "manifest.yaml"+ manifest.write_text(+ yaml.safe_dump(+ {+ "profile": "box",+ "data_dir": "data",+ "gpu": "RTX",+ "server": {"template_root": "t", "python": "p"},+ "defaults": {"prompt": "a fox"},+ "families": [{"family": "f", "cases": [{"id": "a", "model": "m", "steps": 1, "sizes": [[8, 8]]}]}],+ }+ )+ )+ runs = tmp_path / "data" / "runs"+ for name in ("20261016-090000-box", "20261017-080000-box", "20261018-070000-other-box", "20261019-000000-box"):+ (runs / name).mkdir(parents=True)+ if name != "20261019-000000-box": # a run whose start failed before run.json was written+ (runs / name / "run.json").write_text("{}")++ assert _resolve_run(None, manifest) == runs / "20261017-080000-box"+ assert _resolve_run("20261016-090000-box", manifest) == runs / "20261016-090000-box"+ assert _resolve_run(str(runs / "20261016-090000-box"), None) == (runs / "20261016-090000-box").resolve()+ with pytest.raises(UsageError, match="no run 20261001-000000-box"):+ _resolve_run("20261001-000000-box", manifest)+ with pytest.raises(UsageError, match="--manifest"):+ _resolve_run("20261016-090000-box", None)+++def _start_tree(tmp_path: Path) -> tuple[subprocess.Popen[bytes], list[psutil.Process]]:+ """A runner stand-in: a process that starts a sleeping child (its server), plain Popen, no job."""+ pid_file = tmp_path / "child.txt"+ script = tmp_path / "runner.py"+ script.write_text(+ "import os, subprocess, sys, time\n"+ "child = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)'])\n"+ f"open({str(pid_file) + '.tmp'!r}, 'w').write(str(child.pid))\n"+ f"os.replace({str(pid_file) + '.tmp'!r}, {str(pid_file)!r})\n"+ "time.sleep(60)\n"+ )+ process = subprocess.Popen([sys.executable, str(script)])+ deadline = time.monotonic() + 30+ while not pid_file.exists():+ assert process.poll() is None and time.monotonic() < deadline+ time.sleep(0.01)+ return process, [psutil.Process(process.pid), *psutil.Process(process.pid).children(recursive=True)]++[email protected]("first_read", ["readable", "refused"])+def test_stop_kills_the_runner_tree_but_no_process_whose_pid_was_reused(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, first_read: str+) -> None:+ run_id = "20261017-000000-box"+ run_dir = tmp_path / "data" / "runs" / run_id+ run_dir.mkdir(parents=True)+ write_run_info(+ run_dir,+ RunInfo(+ run_id=run_id,+ profile="box",+ created_at="2026-10-17T00:00:00+00:00",+ finished_at=None,+ status="running",+ manifest_path="m.yaml",+ manifest_sha256="0",+ tool_commit=None,+ environments={},+ plan=[],+ case_thresholds={},+ graph_hashes={},+ ),+ )+ scratch = tmp_path / "data" / "scratch-roots" / f"{run_id}-default"+ scratch.mkdir(parents=True)+ (scratch / "invokeai.yaml").write_text("{}")+ # A run of profile "box-x" started in the same second; its scratch root is not this run's.+ other = tmp_path / "data" / "scratch-roots" / f"{run_id}-x-default"+ other.mkdir()++ runner_process, runner_tree = _start_tree(tmp_path)+ unrelated = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])+ try:+ heartbeat = {+ "runner": process_identity(runner_process.pid),+ # The server's recorded pid now belongs to another process: its start time gives it away.+ "server": [unrelated.pid, psutil.Process(unrelated.pid).create_time() - 100.0],+ "server_launcher": None,+ "step": "measure",+ "updated_at": now_iso(),+ }+ (run_dir / HEARTBEAT_FILE).write_text(json.dumps(heartbeat))+ if first_read == "refused":+ # Windows refuses to open the file for a moment while the runner replaces it.+ refusals = [{}]+ monkeypatch.setattr(+ cli, "read_heartbeat", lambda d: refusals.pop() if refusals else runner.read_heartbeat(d)+ )++ assert main(["stop", str(run_dir)]) == 0+ _, alive = psutil.wait_procs(runner_tree, timeout=10)+ assert alive == []+ assert unrelated.poll() is None+ assert load_run_info(run_dir).status == "stopped"+ assert not scratch.exists()+ assert other.exists()+ finally:+ unrelated.kill()+ unrelated.wait()+ runner_process.wait()++[email protected]_independent+def test_the_tool_imports_neither_torch_nor_invokeai() -> None:+ # A CUDA context in the client would land on the GPU it measures. In-process checks prove nothing here: the+ # test session has imported both already.+ code = (+ "import sys, scripts.family_e2e.__main__, scripts.family_e2e.runner; "+ "print(sorted({m.split('.')[0] for m in sys.modules} & {'torch', 'invokeai'}))"+ )+ result = subprocess.run(+ [sys.executable, "-c", code], cwd=REPO_ROOT, capture_output=True, text=True, timeout=120, check=True+ )+ assert result.stdout.strip() == "[]"+++def startable(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ """A manifest that passes `start`'s checks on a fake GPU; its server script is empty and would exit at once."""+ monkeypatch.setattr(runner, "LOCK_DIR", tmp_path / "locks")+ monkeypatch.setattr(server, "PORT_PROBE_TIMEOUT_S", 0.01)+ monkeypatch.setattr(+ cli,+ "open_gpu",+ lambda description: runner.Gpu(+ adapter=Adapter(luid=1, description=description), process_usage=dict, sampler=lambda pid: None+ ),+ )+ with socket.socket() as s:+ s.bind(("127.0.0.1", 0))+ free = s.getsockname()[1]+ (tmp_path / "template").mkdir()+ (tmp_path / "template" / "invokeai.yaml").write_text(yaml.safe_dump({"schema_version": "4.0.3", "port": free}))+ (tmp_path / "code" / "scripts").mkdir(parents=True)+ (tmp_path / "code" / "scripts" / "invokeai-web.py").write_text("")+ manifest = tmp_path / "manifest.yaml"+ manifest.write_text(+ yaml.safe_dump(+ {+ "profile": "box",+ "data_dir": "data",+ "gpu": "Fake",+ "server": {"template_root": "template", "python": sys.executable, "code_dir": "code"},+ "defaults": {"prompt": "a fox"},+ "families": [{"family": "f", "cases": [{"id": "a", "model": "m", "steps": 1, "sizes": [[8, 8]]}]}],+ }+ )+ )+ return manifest+++def stand_ins() -> Iterator[list[subprocess.Popen[bytes]]]:+ """The STAND_IN_RUNNER processes a test starts with `_launch`; what is left of them is killed afterwards."""+ processes: list[subprocess.Popen[bytes]] = []+ yield processes+ for process in processes:+ process.kill()+ process.communicate()+++def _launch(processes: list[subprocess.Popen[bytes]], run_dir: Path, pause: str) -> subprocess.Popen[bytes]:+ process = subprocess.Popen(+ [sys.executable, "-c", STAND_IN_RUNNER, str(run_dir), str(runner.LOCK_DIR), pause],+ cwd=REPO_ROOT,+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ )+ processes.append(process)+ return process+++def test_start_returns_once_its_runner_registered_so_resume_refuses_and_stop_kills_it(+ startable: Path,+ stand_ins: list[subprocess.Popen[bytes]],+ monkeypatch: pytest.MonkeyPatch,+ capsys: pytest.CaptureFixture[str],+) -> None:+ monkeypatch.setattr(cli, "spawn_runner", lambda run_dir: _launch(stand_ins, run_dir, "registered").pid)++ assert main(["start", "--manifest", str(startable)]) == 0+ run_dir = _resolve_run(None, startable)+ [started] = stand_ins+ # The interpreter itself, also where the spawned python is a venv launcher that starts it as its child.+ registered = int(runner.read_heartbeat(run_dir)["runner"][0])+ assert registered in {started.pid, *(child.pid for child in psutil.Process(started.pid).children())}+ assert f"runner pid {registered}," in capsys.readouterr().out++ # The runner has registered but not begun: it waits where it opens the GPU.+ assert main(["resume", str(run_dir)]) == 2+ assert "still running" in capsys.readouterr().err+ assert stand_ins == [started]++ assert main(["stop", str(run_dir)]) == 0+ started.wait(timeout=CHILD_TIMEOUT_S)+ assert load_run_info(run_dir).status == "stopped"+ # Once the runner is gone, stop still ends what is left of the run.+ assert main(["stop", str(run_dir)]) == 0+ assert load_run_info(run_dir).status == "stopped"+++def test_a_runner_that_comes_up_after_stop_leaves_the_stopped_run_untouched(+ startable: Path, stand_ins: list[subprocess.Popen[bytes]]+) -> None:+ run_dir = runner.new_run(startable, [], [])+ late = _launch(stand_ins, run_dir, "unregistered")+ assert late.stdout is not None+ assert late.stdout.readline().strip() == b"paused"++ assert main(["stop", str(run_dir)]) == 0+ stopped = (run_dir / RUN_INFO_FILE).read_bytes()+ assert load_run_info(run_dir).status == "stopped"++ assert late.stdin is not None+ late.stdin.write(b"go\n")+ late.stdin.flush()+ with pytest.raises(runner.RunnerError, match="was stopped before its runner registered"):+ runner.wait_for_runner(run_dir, late.pid, None)+ late.communicate(timeout=CHILD_TIMEOUT_S)+ assert (run_dir / RUN_INFO_FILE).read_bytes() == stopped+ assert not (run_dir / HEARTBEAT_FILE).exists()+ assert sorted(path.name for path in run_dir.iterdir() if path.name.startswith("server-")) == []+ assert not (run_dir.parent.parent / "scratch-roots").exists()diff --git a/tests/family_e2e/test_client.py b/tests/family_e2e/test_client.pynew file mode 100644index 0000000000..c22a1b9791--- /dev/null+++ b/tests/family_e2e/test_client.py@@ -0,0 +1,72 @@+import pytest++from scripts.family_e2e.client import Event, build_timing, per_step_seconds++T0 = 1000.0+++def test_step_time_survives_throttled_frames() -> None:+ # 8 steps of 0.5 s; only steps 1, 3, 6 and 8 sent a frame.+ frames = [(T0 + 0.5 * k, k / 8) for k in (1, 3, 6, 8)]+ assert per_step_seconds(frames) == pytest.approx(0.5)+++def test_step_time_counts_an_initial_zero_frame_as_step_zero() -> None:+ # SD-style loops send a frame before the first step; img2img runs fewer steps than requested (here 6).+ frames = [(T0, 0.0), (T0 + 0.3 * 2, 2 / 6), (T0 + 0.3 * 5, 5 / 6), (T0 + 0.3 * 6, 1.0)]+ assert per_step_seconds(frames) == pytest.approx(0.3)+++def test_frames_on_even_steps_only_need_the_expected_step_count() -> None:+ # 8 steps of 50 ms: the 0.1 s throttle let only every other step's frame through.+ frames = [(T0 + 0.05 * k, k / 8) for k in (0, 2, 4, 6, 8)]+ assert per_step_seconds(frames, expected_steps=8) == pytest.approx(0.05)+ # Inferred, these frames read as 4 steps of 0.1 s; a step that fast cannot rule that out.+ assert per_step_seconds(frames) is None+++def test_expected_step_count_that_does_not_fit_falls_back_to_inference() -> None:+ # The node ran 6 steps although the case asked for 8 (e.g. a preset-driven family); 0.5 s per step.+ frames = [(T0 + 0.5 * k, k / 6) for k in (1, 2, 5, 6)]+ assert per_step_seconds(frames, expected_steps=8) == pytest.approx(0.5)+++def test_step_time_needs_two_distinct_steps() -> None:+ assert per_step_seconds([(T0, 1.0)]) is None+ assert per_step_seconds([(T0, 1.0), (T0 + 1, 1.0)]) is None+++def _invocation(name: str, t: float, node: str, item_id: int = 7, **extra: object) -> Event:+ data = {"item_id": item_id, "invocation": {"id": f"{node}-p", "type": f"{node}_type"}, "invocation_source_id": node}+ return Event(name, t, data | extra)+++def test_timing_is_relative_to_enqueue_and_ignores_other_items() -> None:+ load = {"config": {"key": "m"}, "submodel_type": "transformer"}+ events = [+ # The socket client handles events on separate threads, so the list order can differ from arrival.+ _invocation("invocation_complete", T0 + 0.4, "encode"),+ _invocation("invocation_started", T0 + 0.1, "encode"),+ Event("model_load_started", T0 + 0.15, load),+ Event("model_load_complete", T0 + 0.35, load),+ _invocation("invocation_started", T0 + 0.5, "denoise"),+ *(+ _invocation("invocation_progress", T0 + 0.5 + 0.25 * k, "denoise", percentage=k / 4, has_image=True)+ for k in (1, 2, 4)+ ),+ _invocation("invocation_progress", T0 + 0.6, "denoise", percentage=None, has_image=False),+ _invocation("invocation_started", T0 + 0.2, "other", item_id=8),+ _invocation("invocation_complete", T0 + 1.6, "denoise"),+ ]+ item = {"started_at": "2026-10-17 12:00:00", "completed_at": "2026-10-17 12:00:02"}+ timing = build_timing(events, 7, T0, T0 + 1.7, item)+ assert timing.total_s == pytest.approx(1.7)+ assert [(n.node_id, n.type, round(n.t_start, 3), round(n.t_end, 3)) for n in timing.nodes] == [+ ("encode", "encode_type", 0.1, 0.4),+ ("denoise", "denoise_type", 0.5, 1.6),+ ]+ assert [(m.model, m.submodel, round(m.t_start, 3), round(m.t_end, 3)) for m in timing.model_loads] == [+ ("m", "transformer", 0.15, 0.35)+ ]+ assert timing.per_step_s == pytest.approx(0.25)+ assert (timing.queue_started_at, timing.queue_completed_at) == (item["started_at"], item["completed_at"])diff --git a/tests/family_e2e/test_flow.py b/tests/family_e2e/test_flow.pynew file mode 100644index 0000000000..d026540a46--- /dev/null+++ b/tests/family_e2e/test_flow.py@@ -0,0 +1,332 @@+"""A whole run against a fake server launched the way InvokeAI is launched, with a fake GPU and canned graphs."""++import hashlib+import json+import os+import shutil+import socket+import sqlite3+import sys+import time+from collections.abc import Callable+from pathlib import Path++import pytest+import yaml+from PIL import Image++from scripts.family_e2e import client, runner, server+from scripts.family_e2e.gpu_memory import Adapter, MemoryTrace, ProcessUsage+from scripts.family_e2e.records import (+ RUN_INFO_FILE,+ ModelIdentity,+ Record,+ load_records,+ load_run_info,+ write_run_info,+)++GIB = 2**30+CASE_KEY = "fake-cn@64x48"+FOREIGN_PID = 4_000_000+MODEL = {"key": "fake-model", "hash": "h", "name": "Fake", "base": "fake", "type": "main"}+++class FakeSampler:+ """Memory that rises from 1 GiB to 3 GiB as the run enqueues its item, and falls back when sampling stops.++ The runner reads its enqueue instant just before the enqueue call, and its finish instant from events the server+ sends only after that call, so the rise lies in the measured window however slow the machine is. A rise placed+ by the clock alone, e.g. halfway between start and stop, misses it when the runner's tail outlasts the fake run.+ """++ def __init__(self) -> None:+ self.dedicated: list[tuple[float, int]] = []++ def start(self) -> None:+ self.dedicated = [(time.perf_counter(), GIB)]++ def enqueued(self) -> None:+ self.dedicated.append((time.perf_counter(), 3 * GIB))++ def stop(self) -> MemoryTrace:+ t1 = time.perf_counter()+ return MemoryTrace(+ method="fake",+ interval_ms=3.0,+ dedicated=(*self.dedicated, (t1, GIB)),+ shared=((self.dedicated[0][0], 0), (t1, 0)),+ )+++class FakeGpu:+ """Reports the sampled server process on the adapter once a sampler watched it.++ A foreign process shows up at the end of the fourth sampled run.+ """++ def __init__(self) -> None:+ self.server_pid: int | None = None+ self.adapter = Adapter(luid=0x1234, description="Fake GPU")+ self.samplers = 0+ self.foreign_pending = False+ self.current: FakeSampler | None = None++ def watch_enqueue(self, enqueue: Callable[..., int]) -> Callable[..., int]:+ """Wraps `InvokeClient.enqueue` so the current sampler sees the instant the run submits its item."""++ def enqueue_and_rise(invoke_client: client.InvokeClient, batch: dict) -> int:+ assert self.current is not None+ self.current.enqueued()+ return enqueue(invoke_client, batch)++ return enqueue_and_rise++ def process_usage(self) -> dict[int, ProcessUsage]:+ usage = {} if self.server_pid is None else {self.server_pid: ProcessUsage(dedicated_bytes=GIB, shared_bytes=0)}+ if self.foreign_pending:+ self.foreign_pending = False+ usage[FOREIGN_PID] = ProcessUsage(dedicated_bytes=2 * GIB, shared_bytes=0)+ return usage++ def sampler(self, pid: int) -> FakeSampler:+ self.server_pid = pid+ self.samplers += 1+ self.foreign_pending = self.samplers == 4+ self.current = FakeSampler()+ return self.current++ def gpu(self) -> runner.Gpu:+ return runner.Gpu(adapter=self.adapter, process_usage=self.process_usage, sampler=self.sampler)+++def _graph() -> dict:+ return {+ "id": "fake-graph",+ "nodes": {+ "loader": {"id": "loader", "type": "fake_loader", "is_intermediate": True, "model": MODEL},+ "denoise": {"id": "denoise", "type": "fake_denoise", "is_intermediate": True, "steps": 4},+ "output": {"id": "output", "type": "fake_l2i", "is_intermediate": False, "width": 64, "height": 48},+ },+ "edges": [],+ }+++def isolated_runner(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ monkeypatch.setattr(server, "STARTUP_POLL_S", 0.02)+ monkeypatch.setattr(server, "STARTUP_TIMEOUT_S", 60.0)+ monkeypatch.setattr(client, "POLL_S", 0.05)+ monkeypatch.setattr(runner, "LOCK_DIR", tmp_path / "locks")+++def setup(tmp_path: Path) -> tuple[Path, Path]:+ code_dir = tmp_path / "code"+ (code_dir / "invokeai").mkdir(parents=True)+ (code_dir / "invokeai" / "__init__.py").write_text("")+ (code_dir / "scripts").mkdir()+ shutil.copy(Path(__file__).parent / "fake_invokeai_server.py", code_dir / "scripts" / "invokeai-web.py")++ with socket.socket() as s:+ s.bind(("127.0.0.1", 0))+ template_port = s.getsockname()[1]+ template = tmp_path / "template"+ (template / "databases").mkdir(parents=True)+ sqlite3.connect(template / "databases" / "invokeai.db").close()+ (template / "invokeai.yaml").write_text(yaml.safe_dump({"schema_version": "4.0.3", "port": template_port}))++ data_dir = tmp_path / "data"+ (data_dir / "inputs").mkdir(parents=True)+ Image.new("RGB", (8, 8)).save(data_dir / "inputs" / "fox.png")+ manifest = {+ "profile": "fake",+ "data_dir": "data",+ "gpu": "Fake GPU",+ "server": {"template_root": "template", "python": sys.executable, "code_dir": "code"},+ "defaults": {"warmup": 1, "repeats": 2, "prompt": "a fox"},+ "families": [+ {+ "family": "fake",+ "cases": [+ {+ "id": "fake-cn",+ "model": "fake-model",+ "mode": "controlnet",+ "steps": 4,+ "sizes": [[64, 48]],+ "reference_images": ["fox.png"],+ "control": [{"model": "fake-controlnet", "image": "fox.png"}],+ }+ ],+ }+ ],+ }+ manifest_path = tmp_path / "manifest.yaml"+ manifest_path.write_text(yaml.safe_dump(manifest))+ return manifest_path, data_dir+++def test_run_survives_a_server_crash_retries_foreign_load_and_resumes(+ setup: tuple[Path, Path], isolated_runner: None, monkeypatch: pytest.MonkeyPatch+) -> None:+ manifest_path, data_dir = setup+ # The first server dies in its second queue item, the first measure.+ (manifest_path.parent / "code" / "crash-at-enqueue").write_text("2")+ gpu = FakeGpu()+ monkeypatch.setattr(client.InvokeClient, "enqueue", gpu.watch_enqueue(client.InvokeClient.enqueue))+ requests: list[dict] = []++ def export(request: dict, work_dir: Path) -> dict:+ requests.append(request)+ batch = {"graph": _graph(), "data": [], "origin": "test", "destination": "test"}+ return {"version": 1, "cases": [{"id": request["cases"][0]["id"], "batch": batch, "components": {}}]}++ run_dir = runner.new_run(manifest_path, [], [])+ assert runner.run(run_dir, gpu_factory=lambda _: gpu.gpu(), export=export) == 0++ case = requests[0]["cases"][0]+ assert (case["id"], case["width"], case["height"], case["seed"]) == (CASE_KEY, 64, 48, 1234)+ # Reference images go as they are; a control image is resized to the case size first, as the canvas would.+ assert case["reference_images"] == ["upload-1.png"]+ assert case["control"] == [+ {"model_key": "fake-controlnet", "image_name": "upload-2.png", "weight": 1.0, "begin": 0.0, "end": 1.0}+ ]+ with Image.open(run_dir / "inputs" / "[email protected]") as resized:+ assert resized.size == (64, 48)+ assert [model["key"] for model in requests[0]["models"]] == ["fake-model"]++ records = load_records(run_dir)+ assert [(r.kind, r.rep, r.attempt) for r in records] == [+ ("warmup", 0, 1),+ ("measure", 0, 1),+ ("warmup", 0, 2),+ ("measure", 0, 2),+ ("measure", 0, 3),+ ("measure", 1, 1),+ ]+ # The crashed step has its error record; the new server is warmed up again before the step is repeated.+ crashed = records.pop(1)+ assert crashed.status == "error"+ # Without os.waitid (macOS) the code of the unreaped server is not to be had before it is reaped.+ code = "3" if sys.platform == "win32" or hasattr(os, "waitid") else "unknown"+ assert crashed.invalid_reasons[0].startswith(f"server crashed (exit code {code})"), crashed.invalid_reasons+ assert len(requests) == 2 # each server's uploads need their own export+ # Foreign GPU load spoils time and memory but not the image, and the step is repeated.+ spoiled = records.pop(2)+ assert (spoiled.valid_timing, spoiled.valid_memory, spoiled.valid_psnr) == (False, False, True)+ assert spoiled.invalid_reasons == [f"foreign GPU load: pid {FOREIGN_PID} (?) 2048 MiB"]+ assert [(p.pid, p.dedicated_bytes) for p in spoiled.memory.foreign] == [(FOREIGN_PID, 2 * GIB)]+ for record in records:+ assert record.status == "completed", record.error+ assert (record.valid_timing, record.valid_memory, record.valid_psnr) == (True, True, True), (+ record.invalid_reasons+ )+ assert (record.image_width, record.image_height) == (64, 48)+ image = (run_dir / record.image_path).read_bytes()+ assert hashlib.sha256(image).hexdigest() == record.image_sha256+ assert record.memory.process_baseline_bytes == GIB+ assert record.memory.process_peak_bytes == 3 * GIB+ assert record.memory.foreign == []+ assert (run_dir / record.memory.trace).is_file()+ assert [n.node_id for n in record.timing.nodes] == ["loader", "denoise", "output"]+ assert all(0 <= n.t_start <= n.t_end <= record.timing.total_s for n in record.timing.nodes)+ assert record.timing.per_step_s is not None and record.timing.per_step_s > 0+ assert [(r.model, r.submodel, r.percent) for r in record.residency] == [("fake-model", "transformer", 100.0)]+ # Each server's warm-up loads the model; the measures stay valid on the residency seen since the cache flush.+ assert [len(r.timing.model_loads) for r in records] == [1, 1, 0, 0]++ info = load_run_info(run_dir)+ assert info.status == "completed"+ environment = info.environments["default"]+ assert Path(environment.invokeai_file).is_relative_to(manifest_path.parent / "code")+ assert environment.app_version == {"version": "0.0.0-fake"}+ saved = json.loads((run_dir / "graphs" / f"{CASE_KEY}.json").read_text())+ assert all(node["use_cache"] is False for node in saved["graph"]["nodes"].values())+ assert info.graph_hashes[CASE_KEY] == records[0].graph_hash+ # What names the model elsewhere; neither its path nor a source URL that carries a token.+ assert info.case_models == {+ CASE_KEY: [+ ModelIdentity(+ key="fake-model",+ name="Fake",+ base="fake",+ type="main",+ format="checkpoint",+ variant=None,+ hash="blake3:fakehash",+ source=None,+ )+ ]+ }+ assert not (data_dir / "scratch-roots" / f"{info.run_id}-default").exists()+ assert (run_dir / "report.html").is_file()++ # A runner killed before the last measure: the resumed run warms its new server up before that measure.+ lines = (run_dir / "records.jsonl").read_text().splitlines(keepends=True)+ (run_dir / "records.jsonl").write_text("".join(lines[:5]))+ write_run_info(run_dir, info.model_copy(update={"status": "running"}))+ assert runner.run(run_dir, gpu_factory=lambda _: gpu.gpu(), export=export) == 0++ resumed = load_records(run_dir)[5:]+ assert [(r.kind, r.rep, r.attempt) for r in resumed] == [("warmup", 0, 3), ("measure", 1, 1)]+ assert all(r.valid_timing and r.valid_memory for r in resumed)+ assert resumed[0].graph_hash == records[0].graph_hash+ assert runner.remaining_steps(info.plan, load_records(run_dir)) == []+++def test_a_run_stopped_between_steps_ends_before_the_next_step_and_stays_stopped(+ setup: tuple[Path, Path], isolated_runner: None, monkeypatch: pytest.MonkeyPatch+) -> None:+ manifest_path, data_dir = setup+ gpu = FakeGpu()+ monkeypatch.setattr(client.InvokeClient, "enqueue", gpu.watch_enqueue(client.InvokeClient.enqueue))++ def export(request: dict, work_dir: Path) -> dict:+ batch = {"graph": _graph(), "data": [], "origin": "test", "destination": "test"}+ return {"version": 1, "cases": [{"id": request["cases"][0]["id"], "batch": batch, "components": {}}]}++ run_dir = runner.new_run(manifest_path, [], [])+ store = runner._Session.store+ stopped: list[bytes] = []++ def store_then_stop(session: runner._Session, record: Record) -> None:+ store(session, record)+ if not stopped:+ # `stop` marks the run after the first record, and the kill does not reach the runner.+ info = load_run_info(run_dir)+ write_run_info(run_dir, info.model_copy(update={"status": "stopped", "finished_at": "2026-10-25T01:00:00"}))+ stopped.append((run_dir / RUN_INFO_FILE).read_bytes())++ monkeypatch.setattr(runner._Session, "store", store_then_stop)+ with pytest.raises(runner.RunStopped):+ runner.run(run_dir, gpu_factory=lambda _: gpu.gpu(), export=export)++ assert [(r.kind, r.rep) for r in load_records(run_dir)] == [("warmup", 0)]+ assert (run_dir / RUN_INFO_FILE).read_bytes() == stopped[0]+ assert not runner.is_alive(runner.read_heartbeat(run_dir)["server"])+ assert not (data_dir / "scratch-roots" / f"{run_dir.name}-default").exists()+ assert not (run_dir / "report.html").exists()+++def test_a_run_stopped_during_the_graph_export_is_not_put_back_to_running(+ setup: tuple[Path, Path], isolated_runner: None+) -> None:+ manifest_path, data_dir = setup+ gpu = FakeGpu()+ run_dir = runner.new_run(manifest_path, [], [])+ stopped: list[bytes] = []++ def export(request: dict, work_dir: Path) -> dict:+ # `stop` marks the run during the export, which takes tens of seconds, and its kill misses the runner.+ assert runner.finish_run(run_dir, "stopped")+ stopped.append((run_dir / RUN_INFO_FILE).read_bytes())+ batch = {"graph": _graph(), "data": [], "origin": "test", "destination": "test"}+ return {"version": 1, "cases": [{"id": request["cases"][0]["id"], "batch": batch, "components": {}}]}++ with pytest.raises(runner.RunStopped):+ runner.run(run_dir, gpu_factory=lambda _: gpu.gpu(), export=export)++ assert (run_dir / RUN_INFO_FILE).read_bytes() == stopped[0]+ assert load_records(run_dir) == []+ assert not (data_dir / "scratch-roots" / f"{run_dir.name}-default").exists()diff --git a/tests/family_e2e/test_gpu_memory.py b/tests/family_e2e/test_gpu_memory.pynew file mode 100644index 0000000000..ac4c2c037e--- /dev/null+++ b/tests/family_e2e/test_gpu_memory.py@@ -0,0 +1,248 @@+import subprocess+import sys+import time++import pytest++from scripts.family_e2e import gpu_memory+from scripts.family_e2e.gpu_memory import (+ Adapter,+ MemoryTrace,+ ProcessMemorySampler,+ UnsupportedPlatformError,+ find_adapter,+ list_adapters,+ process_usage_on_adapter,+)++windows_only = pytest.mark.skipif(sys.platform != "win32", reason="the sampler reads WDDM, which only Windows has")+++def _trace(*samples: tuple[float, int]) -> MemoryTrace:+ return MemoryTrace(method="d3dkmt", interval_ms=3.0, dedicated=samples, shared=())+++STEPS = _trace((1.0, 10), (2.0, 30), (3.0, 20))+++def test_empty_trace_has_no_level_or_peak() -> None:+ trace = _trace()+ assert trace.at(1.0) is None+ assert trace.peak() is None+ assert trace.peak(0.0, 1.0) is None++[email protected](("t", "expected"), [(0.5, None), (1.0, 10), (1.99, 10), (2.0, 30), (10.0, 20)])+def test_at_holds_the_last_sample_at_or_before_t(t: float, expected: int | None) -> None:+ assert STEPS.at(t) == expected+++ ("t0", "t1", "expected"),+ [+ (None, None, 30),+ (None, 1.5, 10),+ (2.0, None, 30),+ (1.5, 2.0, 30), # the end is inclusive+ (2.2, 2.4, 30), # no sample inside: the value in effect at t0+ (2.5, 3.0, 30), # the value in effect at t0 counts ...+ (3.0, 4.0, 20), # ... unless a sample at exactly t0 supersedes it+ (4.0, 5.0, 20), # after the last sample its value holds+ (0.0, 0.5, None), # before the first sample+ ],+)+def test_peak_is_the_highest_level_in_the_window(t0: float | None, t1: float | None, expected: int | None) -> None:+ assert STEPS.peak(t0, t1) == expected+++def test_samples_sharing_a_timestamp_all_count() -> None:+ # Samples taken within one tick of a coarse clock share a timestamp; all of them belong to that instant.+ trace = _trace((1.0, 10), (1.0, 50), (1.0, 20), (2.0, 5))+ assert trace.at(1.0) == 20+ assert trace.peak(1.0, 1.0) == 50+ assert trace.peak(1.5, 1.6) == 20+ assert trace.peak(2.0, 3.0) == 5+++def test_peak_rejects_a_window_that_ends_before_it_starts() -> None:+ with pytest.raises(ValueError):+ STEPS.peak(2.0, 1.0)+++ ("name", "expected"),+ [+ ("pid_50992_luid_0x00000000_0x00022A61_phys_0", (50992, 0x22A61)),+ ("pid_7_luid_0x00000001_0x0000beef_phys_0", (7, (1 << 32) | 0xBEEF)),+ ("pid_7_luid_0x00000000_0x00022A61_phys_1", None), # second physical GPU of a linked adapter+ ("pid_7_luid_0x22A61_phys_0", None),+ ("_Total", None),+ ],+)+def test_pdh_instance_names_parse_to_pid_and_luid(name: str, expected: tuple[int, int] | None) -> None:+ assert gpu_memory._parse_instance(name) == expected++[email protected]("luid", [0x22A61, (1 << 32) | 0xBEEF, (0x80000000 << 32) | 1])+def test_luid_survives_the_d3dkmt_struct_and_matches_the_pdh_spelling(luid: int) -> None:+ # HighPart is a signed LONG; a set top bit must not turn the LUID negative.+ assert gpu_memory._luid_value(gpu_memory._luid_struct(luid)) == luid+ pdh_name = f"pid_1_luid_0x{luid >> 32:08X}_0x{luid & 0xFFFFFFFF:08X}_phys_0"+ assert gpu_memory._parse_instance(pdh_name) == (1, luid)+++ ("packed", "expected"),+ [+ # As D3DKMT reports the RTX 4090 and RX 9060 XT drivers, next to what Device Manager shows for them.+ (0x0020000000100417, "32.0.16.1047"),+ (0x00200000794103EC, "32.0.31041.1004"),+ (0xFFFF000100020003, "65535.1.2.3"),+ (0, None), # an unset version is unknown, not "0.0.0.0"+ ],+)+def test_driver_version_reads_as_device_manager_shows_it(packed: int, expected: str | None) -> None:+ assert gpu_memory._format_driver_version(packed) == expected+++ADAPTERS = [+ Adapter(luid=0x29ADC, description="AMD Radeon(TM) Graphics"),+ Adapter(luid=0x25CBD, description="AMD Radeon RX 9060 XT"),+ Adapter(luid=0x22A61, description="NVIDIA GeForce RTX 4090"),+]+++def test_adapter_is_selected_by_case_insensitive_substring() -> None:+ assert gpu_memory._select_adapter(ADAPTERS, "rx 9060") == ADAPTERS[1]+++ ("adapters", "needle", "message"),+ [+ (ADAPTERS, "Radeon", "2 adapters match 'Radeon'"),+ (ADAPTERS, "Arc", "No adapter matches 'Arc'"),+ ([], "4090", "Adapters: none"),+ ],+)+def test_adapter_selection_needs_exactly_one_match(adapters: list[Adapter], needle: str, message: str) -> None:+ with pytest.raises(LookupError) as error:+ gpu_memory._select_adapter(adapters, needle)+ assert message in str(error.value)+ # The message lists what is there, so the caller can pick a better substring.+ for adapter in adapters:+ assert adapter.description in str(error.value)+++def test_an_adapter_has_exactly_one_identity() -> None:+ # The identity names the lock file; a WDDM adapter has a LUID, an NVML device a UUID.+ with pytest.raises(ValueError):+ Adapter(luid=None, description="NVIDIA RTX 6000 Ada Generation")+ with pytest.raises(ValueError):+ Adapter(luid=0x22A61, uuid="GPU-5f1c2e3a-1111", description="NVIDIA GeForce RTX 4090")+++def test_other_platforms_are_refused(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(sys, "platform", "linux")+ with pytest.raises(UnsupportedPlatformError):+ list_adapters()+ with pytest.raises(UnsupportedPlatformError):+ find_adapter("4090")+ with pytest.raises(UnsupportedPlatformError):+ process_usage_on_adapter(ADAPTERS[2])+ with pytest.raises(UnsupportedPlatformError):+ ProcessMemorySampler(1234, ADAPTERS[2])+++@windows_only+def test_stop_without_start_returns_one_empty_trace() -> None:+ sampler = ProcessMemorySampler(1234, ADAPTERS[2], interval_s=0.005)+ trace = sampler.stop()+ assert trace == MemoryTrace(method="d3dkmt", interval_ms=5.0, dedicated=(), shared=())+ assert sampler.stop() is trace+++@windows_only+def test_start_refuses_a_process_that_has_exited() -> None:+ process = subprocess.Popen(["cmd.exe", "/c", "exit 0"])+ process.wait()+ # Popen still holds its handle, so the pid cannot have been reused by another process.+ sampler = ProcessMemorySampler(process.pid, ADAPTERS[2])+ with pytest.raises(ProcessLookupError, match="has exited"):+ sampler.start()+ assert sampler.stop().dedicated == ()+++_CUDA_CHILD = """+import os, sys, torch+if not torch.cuda.is_available():+ print("unavailable", flush=True)+ sys.exit()+torch.zeros(1, device="cuda")+torch.cuda.synchronize()+print(os.getpid(), flush=True)+sys.stdin.readline()+x = torch.empty(2**28, dtype=torch.float32, device="cuda")+x.fill_(1)+torch.cuda.synchronize()+print("allocated", flush=True)+sys.stdin.readline()+del x+torch.cuda.empty_cache()+torch.cuda.synchronize()+print("freed", flush=True)+sys.stdin.readline()+"""+++@windows_only+def test_sampler_follows_a_cuda_allocation_in_another_process() -> None:+ """Needs exactly one NVIDIA adapter and torch with CUDA. The child prints its own pid: under a venv launcher,+ ``Popen.pid`` is the launcher, not the interpreter that allocates."""+ try:+ adapter = find_adapter("NVIDIA")+ except LookupError as error:+ pytest.skip(str(error))+ child = subprocess.Popen(+ [sys.executable, "-c", _CUDA_CHILD], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True+ )+ assert child.stdin is not None and child.stdout is not None+ sampler = None+ try:+ first = child.stdout.readline().strip()+ if not first.isdigit():+ pytest.skip(f"no CUDA in the child: {first!r}")+ sampler = ProcessMemorySampler(int(first), adapter)+ sampler.start()++ def step(expected: str) -> float:+ """Trigger the child's next step; the instant just before it, read against the trace afterwards."""+ t = time.perf_counter()+ child.stdin.write("\n")+ child.stdin.flush()+ assert child.stdout.readline().strip() == expected+ # Let samples land after the step before anything else changes.+ time.sleep(0.05)+ return t++ # Each instant is taken immediately before the next change, so the level read there must not show it yet.+ t_before_allocation = step("allocated")+ t_before_free = step("freed")+ t_end = time.perf_counter()+ trace = sampler.stop()+ finally:+ if sampler is not None:+ sampler.stop()+ child.communicate("\n", timeout=60)++ gib = 2**30+ context = trace.at(t_before_allocation)+ allocated = trace.at(t_before_free)+ assert context is not None and allocated is not None+ assert context > 0+ assert abs(allocated - context - gib) < gib / 16+ peak = trace.peak(t_before_allocation, t_before_free)+ assert peak is not None and 0 <= peak - allocated < gib / 16+ # The CUDA caching allocator hands the block back to the driver on empty_cache().+ freed = trace.at(t_end)+ assert freed is not None and freed < allocated - gib * 15 / 16diff --git a/tests/family_e2e/test_graphs.py b/tests/family_e2e/test_graphs.pynew file mode 100644index 0000000000..5703c95c29--- /dev/null+++ b/tests/family_e2e/test_graphs.py@@ -0,0 +1,146 @@+import pytest++from scripts.family_e2e.graphs import build_export_request, output_image_name, prepare_batch, shareable_source+from scripts.family_e2e.manifest import CaseSpec, ResolvedCase+from scripts.family_e2e.records import Thresholds++MAIN = {"key": "main-key", "hash": "h", "name": "Main", "base": "sdxl", "type": "main"}+LORA = {"key": "lora-key", "hash": "h", "name": "Lora", "base": "sdxl", "type": "lora"}+++def _batch(image_name: str = "upload-1.png", seed: int = 1234, reverse: bool = False) -> dict:+ nodes = {+ "model": {"id": "model", "type": "main_model_loader", "model": MAIN, "is_intermediate": True},+ "loras": {"id": "loras", "type": "lora_collection_loader", "loras": [{"lora": LORA, "weight": 0.8}]},+ "init": {"id": "init", "type": "i2l", "image": {"image_name": image_name}, "is_intermediate": True},+ "output": {"id": "output", "type": "l2i", "is_intermediate": False},+ }+ if reverse:+ nodes = {k: dict(reversed(v.items())) for k, v in reversed(nodes.items())}+ data = [[{"node_path": "noise", "field_name": "seed", "items": [seed]}]]+ return {"graph": {"id": "g", "nodes": nodes, "edges": []}, "data": data, "origin": "o", "destination": "gallery"}+++def test_prepare_disables_the_cache_on_every_node_and_runs_once() -> None:+ original = _batch()+ prepared = prepare_batch(original, {"vae": "vae-key"}, {})+ assert all(node["use_cache"] is False for node in prepared.batch["graph"]["nodes"].values())+ assert prepared.batch["runs"] == 1+ assert "use_cache" not in original["graph"]["nodes"]["model"]+ assert prepared.model_keys == {"main-key", "lora-key"}+ assert prepared.components == {"vae": "vae-key"}+++def test_hash_ignores_key_order_and_upload_names_but_not_inputs_or_data() -> None:+ first = prepare_batch(_batch("upload-1.png"), {}, {"upload-1.png": "input:abc"})+ reordered = prepare_batch(_batch("upload-7.png", reverse=True), {}, {"upload-7.png": "input:abc"})+ assert first.graph_hash == reordered.graph_hash+ other_input = prepare_batch(_batch("upload-1.png"), {}, {"upload-1.png": "input:def"})+ other_seed = prepare_batch(_batch("upload-1.png", seed=5), {}, {"upload-1.png": "input:abc"})+ assert len({first.graph_hash, other_input.graph_hash, other_seed.graph_hash}) == 3+++def _session(results: dict) -> dict:+ return {+ "source_prepared_mapping": {node: [f"{node}-p"] for node in results},+ "results": {f"{k}-p": v for k, v in results.items()},+ }+++def test_output_image_comes_from_the_one_non_intermediate_image_node() -> None:+ graph = _batch()["graph"]+ session = _session(+ {+ "init": {"type": "latents_output"},+ "output": {"type": "image_output", "image": {"image_name": "final.png"}},+ }+ )+ assert output_image_name(graph, session) == "final.png"+ # A node without the field is not intermediate, as on the server.+ del graph["nodes"]["init"]["is_intermediate"]+ session = _session(+ {+ "init": {"type": "image_output", "image": {"image_name": "other.png"}},+ "output": {"type": "image_output", "image": {"image_name": "final.png"}},+ }+ )+ with pytest.raises(ValueError, match="found 2"):+ output_image_name(graph, session)+ with pytest.raises(ValueError, match="found 0"):+ output_image_name(graph, _session({}))+++def test_export_request_carries_each_case_with_its_uploaded_images() -> None:+ spec = CaseSpec.model_validate(+ {+ "id": "sdxl-cn",+ "model": "main-key",+ "mode": "controlnet",+ "steps": 25,+ "sizes": [[1024, 768]],+ "loras": [{"key": "lora-key", "weight": 0.5}],+ "reference_images": ["ref.png"],+ "control": [{"model": "cn-key", "image": "canny.png", "weight": 0.7, "end": 0.8}],+ "settings": {"scheduler": "euler"},+ }+ )+ case = ResolvedCase(+ case_key="sdxl-cn@1024x768",+ family="sdxl",+ spec=spec,+ width=1024,+ height=768,+ seed=3,+ prompt="a fox",+ negative_prompt="blurry",+ thresholds=Thresholds(psnr_min_db=30, time_tolerance=0.1, peak_tolerance_mb=256),+ )+ names = {"sdxl-cn@1024x768": {("ref.png", False): "upload-1.png", ("canny.png", True): "upload-2.png"}}+ request = build_export_request([case], [MAIN], {"sdxl": {}}, names)+ assert request["version"] == 1+ assert (request["models"], request["capabilities"]) == ([MAIN], {"sdxl": {}})+ assert request["cases"] == [+ {+ "id": "sdxl-cn@1024x768",+ "mode": "controlnet",+ "model_key": "main-key",+ "components": {},+ "width": 1024,+ "height": 768,+ "steps": 25,+ "seed": 3,+ "positive_prompt": "a fox",+ "negative_prompt": "blurry",+ "loras": [{"key": "lora-key", "weight": 0.5}],+ "reference_images": ["upload-1.png"],+ "init_image": None,+ "control": [{"model_key": "cn-key", "image_name": "upload-2.png", "weight": 0.7, "begin": 0.0, "end": 0.8}],+ "settings": {"scheduler": "euler"},+ }+ ]+++ ("source", "source_type", "shareable"),+ [+ ("Tongyi-MAI/Z-Image-Turbo", "hf_repo_id", True),+ ("https://huggingface.co/x/y/resolve/main/y.safetensors", "url", True),+ ("http://8.8.8.8/y.safetensors", "url", True),+ ("S:/model_library/y.safetensors", "path", False),+ ("https://civitai.com/api/download/models/1?token=abc", "url", False),+ ("https://civitai.com/api/download/models/1#token", "url", False),+ ("https://civitai.com/api/download/models/1;jsessionid=abc", "url", False),+ ("https://user:[email protected]/y.safetensors", "url", False),+ ("http://cm3588:8090/y.safetensors", "url", False),+ ("http://localhost/y.safetensors", "url", False),+ ("http://nas.local/y.safetensors", "url", False),+ ("http://192.168.1.5/y.safetensors", "url", False),+ ("http://127.0.0.1:9090/y.safetensors", "url", False),+ ("http://[fe80::1]/y.safetensors", "url", False),+ ("file:///S:/y.safetensors", "url", False),+ ],+)+def test_a_source_is_shareable_when_it_names_the_model_for_anyone(+ source: str, source_type: str, shareable: bool+) -> None:+ assert shareable_source({"source": source, "source_type": source_type}) == (source if shareable else None)diff --git a/tests/family_e2e/test_manifest.py b/tests/family_e2e/test_manifest.pynew file mode 100644index 0000000000..8c46784fa9--- /dev/null+++ b/tests/family_e2e/test_manifest.py@@ -0,0 +1,142 @@+from pathlib import Path+from typing import Any++import pytest+import yaml++from scripts.family_e2e.manifest import ManifestError, load_manifest, plan_steps, resolve_cases++EXAMPLE = Path(__file__).parents[2] / "scripts" / "family_e2e" / "manifest.example.yaml"+++def _case(case_id: str, **fields: Any) -> dict[str, Any]:+ return {"id": case_id, "model": "m", "steps": 4, "sizes": [[64, 64]], **fields}+++def _write(tmp_path: Path, families: list[dict[str, Any]], inputs: tuple[str, ...] = (), **top: Any) -> Path:+ for name in inputs:+ (tmp_path / "data" / "inputs" / name).parent.mkdir(parents=True, exist_ok=True)+ (tmp_path / "data" / "inputs" / name).write_bytes(b"png")+ manifest = {+ "profile": "box",+ "data_dir": "data",+ "gpu": "RTX",+ "server": {"template_root": "template", "python": "venv/python.exe"},+ "defaults": {"prompt": "a fox", "seed": 7, "warmup": 1, "repeats": 2},+ "families": families,+ **top,+ }+ path = tmp_path / "manifest.yaml"+ path.write_text(yaml.safe_dump(manifest))+ return path+++def test_relative_paths_resolve_against_the_manifest_directory(tmp_path: Path) -> None:+ manifest = load_manifest(_write(tmp_path, [{"family": "f", "cases": [_case("a")]}]))+ assert manifest.data_dir == tmp_path / "data"+ assert manifest.server.template_root == tmp_path / "template"+ assert manifest.server.python == tmp_path / "venv" / "python.exe"+++def test_plan_follows_family_case_and_size_order_with_warmups_first(tmp_path: Path) -> None:+ families = [+ {"family": "second", "cases": [_case("b", sizes=[[128, 64], [64, 128]]), _case("c")]},+ {"family": "first", "cases": [_case("a")]},+ ]+ manifest = load_manifest(_write(tmp_path, families))+ steps = plan_steps(resolve_cases(manifest), manifest.defaults.warmup, manifest.defaults.repeats)+ assert [(s.family, s.case_key, s.kind, s.rep) for s in steps] == [+ ("second", "b@128x64", "warmup", 0),+ ("second", "b@128x64", "measure", 0),+ ("second", "b@128x64", "measure", 1),+ ("second", "b@64x128", "warmup", 0),+ ("second", "b@64x128", "measure", 0),+ ("second", "b@64x128", "measure", 1),+ ("second", "c@64x64", "warmup", 0),+ ("second", "c@64x64", "measure", 0),+ ("second", "c@64x64", "measure", 1),+ ("first", "a@64x64", "warmup", 0),+ ("first", "a@64x64", "measure", 0),+ ("first", "a@64x64", "measure", 1),+ ]+ assert {s.arm for s in steps} == {"default"}+++def test_filters_select_by_family_and_case_and_reject_unknown_names(tmp_path: Path) -> None:+ families = [{"family": "x", "cases": [_case("a"), _case("b")]}, {"family": "y", "cases": [_case("c")]}]+ manifest = load_manifest(_write(tmp_path, families))+ assert [c.case_key for c in resolve_cases(manifest, families=["y"])] == ["c@64x64"]+ assert [c.case_key for c in resolve_cases(manifest, case_ids=["b", "c"])] == ["b@64x64", "c@64x64"]+ with pytest.raises(ManifestError, match="no case"):+ resolve_cases(manifest, families=["x"], case_ids=["c"])+ with pytest.raises(ManifestError, match="unknown family or case: z"):+ resolve_cases(manifest, families=["z"])+++def test_case_values_fall_back_to_the_defaults(tmp_path: Path) -> None:+ b_spec = _case("b", seed=99, prompt="a cat", psnr_min_db=40, expect="changed")+ a, b = resolve_cases(load_manifest(_write(tmp_path, [{"family": "f", "cases": [_case("a"), b_spec]}])))+ assert (a.seed, a.prompt, a.thresholds.psnr_min_db, a.thresholds.peak_tolerance_mb) == (7, "a fox", 30.0, 256.0)+ assert (b.seed, b.prompt, b.thresholds.psnr_min_db, b.thresholds.time_tolerance) == (99, "a cat", 40.0, 0.10)+ assert (a.thresholds.expect, b.thresholds.expect) == ("unchanged", "changed")+++ ("case", "message"),+ [+ (_case("a", mode="img2img"), "init_image is required"),+ (_case("a", init_image={"path": "i.png", "strength": 0.5}), "init_image is required"),+ (_case("a", mode="controlnet"), "control is required"),+ (_case("a", control=[{"model": "cn", "image": "i.png"}]), "control is required"),+ (_case("a", sizes=[[64, 60]]), "multiples of 8"),+ (_case("a", sizes=[[64, 64], [64, 64]]), "unique"),+ (_case("a.b"), "id"),+ (_case("a", unknown=1), "unknown"),+ (_case("a", expect="better"), "expect"),+ ],+)+def test_invalid_cases_are_rejected(tmp_path: Path, case: dict[str, Any], message: str) -> None:+ with pytest.raises(ManifestError, match=message):+ load_manifest(_write(tmp_path, [{"family": "f", "cases": [case]}], inputs=("i.png",)))+++def test_case_ids_must_be_unique_across_families(tmp_path: Path) -> None:+ families = [{"family": "x", "cases": [_case("a")]}, {"family": "y", "cases": [_case("a")]}]+ with pytest.raises(ManifestError, match="unique across the manifest: a"):+ load_manifest(_write(tmp_path, families))+++def test_inputs_must_exist_under_the_inputs_directory(tmp_path: Path) -> None:+ case = _case("a", mode="img2img", init_image={"path": "missing.png", "strength": 0.5})+ with pytest.raises(ManifestError, match="a: missing.png"):+ load_manifest(_write(tmp_path, [{"family": "f", "cases": [case]}]))++ (tmp_path / "data").mkdir(exist_ok=True)+ (tmp_path / "data" / "outside.png").write_bytes(b"png")+ escaping = _case("a", reference_images=["../outside.png"])+ with pytest.raises(ManifestError, match="outside"):+ load_manifest(_write(tmp_path, [{"family": "f", "cases": [escaping]}]))++ nested = _case("a", reference_images=["refs/fox.png"])+ manifest = load_manifest(_write(tmp_path, [{"family": "f", "cases": [nested]}], inputs=("refs/fox.png",)))+ assert manifest.input_file("refs/fox.png") == (tmp_path / "data" / "inputs" / "refs" / "fox.png").resolve()+++def test_example_manifest_is_valid(tmp_path: Path) -> None:+ raw = yaml.safe_load(EXAMPLE.read_text(encoding="utf-8"))+ raw["data_dir"] = str(tmp_path)+ for family in raw["families"]:+ for case in family["cases"]:+ for name in case.get("reference_images", []) + [c["image"] for c in case.get("control", [])]:+ (tmp_path / "inputs").mkdir(exist_ok=True)+ (tmp_path / "inputs" / name).write_bytes(b"png")+ if case.get("init_image"):+ (tmp_path / "inputs").mkdir(exist_ok=True)+ (tmp_path / "inputs" / case["init_image"]["path"]).write_bytes(b"png")+ path = tmp_path / "manifest.yaml"+ path.write_text(yaml.safe_dump(raw))+ manifest = load_manifest(path)+ cases = resolve_cases(manifest)+ assert {c.family for c in cases} == {"z-image", "flux2", "krea2", "sdxl"}+ assert {c.spec.mode for c in cases} == {"txt2img", "img2img", "controlnet"}+ assert any(len(c.spec.sizes) > 1 for c in cases)diff --git a/tests/family_e2e/test_metrics.py b/tests/family_e2e/test_metrics.pynew file mode 100644index 0000000000..829428d0c0--- /dev/null+++ b/tests/family_e2e/test_metrics.py@@ -0,0 +1,116 @@+import math+from pathlib import Path++import numpy as np+import pytest++from scripts.family_e2e.metrics import (+ ImageSizeMismatchError,+ compare_peak,+ compare_time,+ load_rgb,+ mad,+ measured_values,+ median,+ psnr,+ write_diff_image,+)+from tests.family_e2e.test_records import MB, make_record, write_png+++def _image(value: int, width: int = 8, height: int = 8) -> np.ndarray:+ return np.full((height, width, 3), value, dtype=np.uint8)+++def test_identical_images_have_infinite_psnr() -> None:+ assert psnr(_image(100), _image(100)) == math.inf+++def test_off_by_one_in_every_channel_gives_20_log10_255() -> None:+ assert psnr(_image(100), _image(101)) == pytest.approx(48.1308, abs=1e-4)+++def test_single_saturated_channel_gives_psnr_from_its_share_of_the_error() -> None:+ a = _image(0, width=4, height=4)+ b = a.copy()+ b[2, 1, 0] = 255+ # MSE = 255² / 48 values, so PSNR = 10·log10(48).+ assert psnr(a, b) == pytest.approx(16.8124, abs=1e-4)+++def test_size_mismatch_is_an_explicit_error() -> None:+ with pytest.raises(ImageSizeMismatchError, match="size mismatch: 8x8 vs 8x4"):+ psnr(_image(0), _image(0, width=8, height=4))+++def test_alpha_is_ignored_when_loading(tmp_path: Path) -> None:+ rgba = np.zeros((4, 4, 4), dtype=np.uint8)+ rgba[..., :3] = 77+ rgba[..., 3] = 10+ write_png(tmp_path / "rgba.png", rgba)+ write_png(tmp_path / "rgb.png", _image(77, 4, 4))++ assert psnr(load_rgb(tmp_path / "rgba.png"), load_rgb(tmp_path / "rgb.png")) == math.inf+++def test_diff_image_amplifies_and_saturates(tmp_path: Path) -> None:+ a = _image(100, 2, 1)+ b = a.copy()+ b[0, 0] = (101, 100, 70)++ write_diff_image(a, b, tmp_path / "diff" / "case.png")++ assert load_rgb(tmp_path / "diff" / "case.png").tolist() == [[[10, 0, 255], [0, 0, 0]]]+++def test_median_and_mad_resist_a_single_extreme_value() -> None:+ values = [1.0, 2.0, 3.0, 4.0, 100.0]+ assert median(values) == 3.0+ assert mad(values) == 1.0+ assert median([]) is None and mad([]) is None+++ ("values", "tolerance", "outlier"),+ [+ ([11.0, 11.0, 11.0], 0.05, True), # MAD 0: the 10 % deviation exceeds 5 %+ ([11.0, 11.0, 11.0], 0.15, False), # within tolerance+ ([9.0, 12.0, 15.0], 0.05, False), # +20 %, but within 3×MAD = 9 s of noise+ ([20.0, 21.0, 22.0], 0.05, True), # +110 %, beyond 3×MAD = 3 s+ ([5.0, 5.0, 5.0], 0.10, True), # a sudden speed-up is flagged too+ ],+)+def test_time_outlier_needs_tolerance_and_noise_exceeded(values: list[float], tolerance: float, outlier: bool) -> None:+ delta = compare_time(values, 10.0, tolerance)++ assert delta is not None+ assert delta.outlier is outlier+ assert delta.delta == median(values) - 10.0++[email protected](("baseline_mb", "outlier"), [(900, False), (600, True), (1300, True)])+def test_peak_outlier_uses_an_absolute_tolerance(baseline_mb: int, outlier: bool) -> None:+ delta = compare_peak([1000.0 * MB] * 3, baseline_mb * MB, tolerance_mb=256)++ assert delta is not None and delta.outlier is outlier+++def test_comparison_without_current_values_is_none() -> None:+ assert compare_time([], 10.0, 0.1) is None+ assert compare_peak([], 10.0, 256) is None+++def test_measured_values_use_each_metric_only_from_valid_completed_measurements() -> None:+ records = [+ make_record(rep=0, total_s=10.0, peak_bytes=100),+ make_record(rep=1, total_s=11.0, peak_bytes=200, valid_memory=False),+ make_record(rep=2, total_s=50.0, peak_bytes=300, valid_timing=False),+ make_record("zimage-t2i@8x8", "warmup", total_s=90.0, peak_bytes=900),+ make_record(rep=3, attempt=1, status="failed", total_s=70.0, peak_bytes=700),+ ]++ values = measured_values(records)++ assert values.total_s == [10.0, 11.0]+ assert values.process_peak_bytes == [100, 300]+ assert dict(values.node_peak_bytes) == {"denoise": [100, 300]}diff --git a/tests/family_e2e/test_nvml_memory.py b/tests/family_e2e/test_nvml_memory.pynew file mode 100644index 0000000000..f8b260d905--- /dev/null+++ b/tests/family_e2e/test_nvml_memory.py@@ -0,0 +1,577 @@+"""The Linux NVML sampler against a scripted stand-in for libnvidia-ml.++The stand-in holds the module to its declared prototypes: every entry point converts its arguments through the+argtypes the module declares, as a ctypes function does, and process entries are written as raw bytes at NVML's ABI+offsets, so the module's entry struct must match the driver's layout. The real library, its calling convention and+the restypes are exercised only by the hardware test at the end, which needs Linux, an NVIDIA GPU and torch with CUDA.+"""++import ctypes+import logging+import os+import statistics+import struct+import subprocess+import sys+import threading+import time+from collections.abc import Callable, Iterator+from pathlib import Path+from typing import Any++import pytest++from scripts.family_e2e import nvml_memory, runner+from scripts.family_e2e.gpu_memory import Adapter, MemoryTrace, ProcessUsage, UnsupportedPlatformError+from scripts.family_e2e.nvml_memory import ProcessMemorySampler, find_adapter, list_adapters, process_usage_on_adapter++GIB = 2**30+MIB = 2**20+NOT_AVAILABLE = 0xFFFFFFFFFFFFFFFF+DRIVER = "580.95.05"+RTX_6000 = ("NVIDIA RTX 6000 Ada Generation", "GPU-5f1c2e3a-1111-4000-8000-000000000001")+L4 = ("NVIDIA L4", "GPU-9b8a7c6d-2222-4000-8000-000000000002")+RTX_6000_ADAPTER = Adapter(luid=None, uuid=RTX_6000[1], description=RTX_6000[0], driver_version=DRIVER)+# NVML's codes for the failures scripted here.+NOT_SUPPORTED = 3+NO_PERMISSION = 4+NOT_FOUND = 6+INSUFFICIENT_SIZE = 7+GPU_IS_LOST = 15+LIB_RM_VERSION_MISMATCH = 18+# nvmlProcessInfo_t as the driver writes it: pid, padding, usedGpuMemory, gpuInstanceId, computeInstanceId.+PROCESS_ENTRY = struct.Struct("=I4xQII")++linux_only = pytest.mark.skipif(sys.platform != "linux", reason="the NVML sampler is the Linux backend")+++class _Declared:+ """An entry point of the fake. Like a ctypes function it takes the argtypes and restype the module declares, and+ converts each argument through its argtype, so a call ctypes would refuse fails here too."""++ def __init__(self, implementation: Callable[..., Any]) -> None:+ self._implementation = implementation+ self.argtypes: list[Any] | None = None+ self.restype: Any = None++ def __call__(self, *args: Any) -> Any:+ name = self._implementation.__name__+ assert self.argtypes is not None and self.restype is not None, f"{name} is called without a declared prototype"+ assert len(args) == len(self.argtypes), f"{name} takes {len(self.argtypes)} arguments, got {len(args)}"+ for argtype, arg in zip(self.argtypes, args, strict=True):+ argtype.from_param(arg)+ return self._implementation(*args)+++class _FakeNvml:+ """Devices as (name, uuid). `processes` and `graphics` map a device's uuid to its compute and graphics processes+ as [(pid, used bytes)]; `failing` holds device indices whose handle lookup NVML refuses.++ While a sampler runs, tests change what NVML answers through `change` and `wait_until_listed`.+ """++ def __init__(self, *devices: tuple[str, str], init_status: int = 0) -> None:+ self.devices = list(devices)+ self.processes: dict[str, list[tuple[int, int]]] = {uuid: [] for _, uuid in devices}+ self.graphics: dict[str, list[tuple[int, int]]] = {uuid: [] for _, uuid in devices}+ self.failing: set[int] = set()+ self.init_status = init_status+ self.inits = 0+ self.list_status = 0+ """Returned by every process listing while not 0."""+ self.graphics_status = 0+ """Returned by every graphics process listing while not 0."""+ self.before_list: Callable[[], None] | None = None+ """Runs at the start of every process listing."""+ self._listed = threading.Condition()+ self._version = 0+ self._served = 0+ for name in dir(self):+ if name.startswith("nvml"):+ setattr(self, name, _Declared(getattr(self, name)))++ def nvmlInit_v2(self) -> int:+ self.inits += 1+ return self.init_status++ def nvmlErrorString(self, status: int) -> bytes:+ texts = {NO_PERMISSION: b"Insufficient Permissions", NOT_FOUND: b"Not Found", GPU_IS_LOST: b"GPU is lost"}+ return texts.get(status, b"Unknown Error")++ def nvmlSystemGetDriverVersion(self, buffer, length: int) -> int:+ buffer.value = DRIVER.encode()+ return 0++ def nvmlDeviceGetCount_v2(self, count_ref) -> int:+ count_ref._obj.value = len(self.devices)+ return 0++ def nvmlDeviceGetHandleByIndex_v2(self, index: int, handle_ref) -> int:+ if index in self.failing:+ return NO_PERMISSION+ handle_ref._obj.value = index + 1 # a device handle is a non-null pointer+ return 0++ def nvmlDeviceGetHandleByUUID(self, uuid: bytes, handle_ref) -> int:+ uuids = [device_uuid.encode() for _, device_uuid in self.devices]+ if uuid not in uuids:+ return NOT_FOUND+ handle_ref._obj.value = uuids.index(uuid) + 1+ return 0++ def nvmlDeviceGetName(self, handle: ctypes.c_void_p, buffer, length: int) -> int:+ buffer.value = self.devices[handle.value - 1][0].encode()+ return 0++ def nvmlDeviceGetUUID(self, handle: ctypes.c_void_p, buffer, length: int) -> int:+ buffer.value = self.devices[handle.value - 1][1].encode()+ return 0++ def nvmlDeviceGetComputeRunningProcesses_v3(self, handle: ctypes.c_void_p, count_ref, entries) -> int:+ return self._list(self.processes, handle, count_ref, entries)++ def nvmlDeviceGetGraphicsRunningProcesses_v3(self, handle: ctypes.c_void_p, count_ref, entries) -> int:+ return self.graphics_status or self._list(self.graphics, handle, count_ref, entries)++ def _list(self, table: dict[str, list[tuple[int, int]]], handle: ctypes.c_void_p, count_ref, entries) -> int:+ if self.before_list is not None:+ self.before_list()+ with self._listed:+ version, status = self._version, self.list_status+ processes = list(table[self.devices[handle.value - 1][1]])+ try:+ if status:+ return status+ count = count_ref._obj+ if entries is None or count.value < len(processes):+ count.value = len(processes)+ return INSUFFICIENT_SIZE if processes else 0+ for index, (pid, used) in enumerate(processes):+ PROCESS_ENTRY.pack_into(entries, index * PROCESS_ENTRY.size, pid, used, 0, 0)+ count.value = len(processes)+ return 0+ finally:+ with self._listed:+ self._served = max(self._served, version)+ self._listed.notify_all()++ def change(self, uuid: str, processes: list[tuple[int, int]] | None = None, list_status: int | None = None) -> None:+ """What later listings of the device answer: its compute processes, or a failure status (0 for none)."""+ with self._listed:+ if processes is not None:+ self.processes[uuid] = processes+ if list_status is not None:+ self.list_status = list_status+ self._version += 1++ def wait_until_listed(self) -> None:+ """Blocks until a listing has answered with the state of the last `change`. A sampler stores what it read+ there before its `stop()` returns."""+ with self._listed:+ target = self._version+ assert self._listed.wait_for(lambda: self._served >= target, timeout=30), "the sampler stopped listing"+++def install(monkeypatch: pytest.MonkeyPatch) -> Iterator[Callable[[_FakeNvml], _FakeNvml]]:+ """Replaces libnvidia-ml with a fake; the module's NVML init is reset around each test."""+ nvml_memory._nvml.cache_clear()++ def installer(fake: _FakeNvml) -> _FakeNvml:+ monkeypatch.setattr(nvml_memory, "_open_library", lambda: fake)+ return fake++ yield installer+ nvml_memory._nvml.cache_clear()+++def _exited_child() -> subprocess.Popen[bytes]:+ child = subprocess.Popen([sys.executable, "-c", "pass"])+ child.wait()+ return child+++def test_adapters_are_named_by_nvml_with_their_uuid_and_the_driver(install) -> None:+ fake = install(_FakeNvml(RTX_6000, L4))++ assert list_adapters() == [+ RTX_6000_ADAPTER,+ Adapter(luid=None, uuid=L4[1], description=L4[0], driver_version=DRIVER),+ ]+ assert list_adapters()[0].key == RTX_6000[1]+ assert fake.inits == 1, "NVML is initialised once per process"+++def test_a_gpu_nvml_cannot_query_is_left_out_with_a_warning(install, caplog: pytest.LogCaptureFixture) -> None:+ fake = install(_FakeNvml(L4, RTX_6000))+ fake.failing = {0}++ with caplog.at_level(logging.WARNING, logger=nvml_memory.__name__):+ assert list_adapters() == [RTX_6000_ADAPTER]+ assert find_adapter("6000") == RTX_6000_ADAPTER+ assert any(+ "NVIDIA GPU 0 left out" in r.getMessage() and "Insufficient Permissions" in r.getMessage()+ for r in caplog.records+ )+++def test_an_adapter_is_found_by_name_and_a_miss_lists_the_gpus_and_notes_amd(install) -> None:+ install(_FakeNvml(RTX_6000, L4))++ assert find_adapter("rtx 6000") == RTX_6000_ADAPTER+ with pytest.raises(LookupError) as miss:+ find_adapter("Radeon")+ assert "No adapter matches 'Radeon'" in str(miss.value)+ assert f"{RTX_6000[0]} ({RTX_6000[1]})" in str(miss.value)+ assert "AMD (ROCm) GPUs on Linux are not supported yet" in str(miss.value)+ with pytest.raises(LookupError) as several:+ find_adapter("NVIDIA")+ assert "2 adapters match 'NVIDIA'" in str(several.value)+ assert "AMD" not in str(several.value)+++def test_identical_gpus_are_told_apart_by_their_uuid(install) -> None:+ name = "NVIDIA RTX PRO 6000 Blackwell Server Edition"+ first, second = (+ (name, "GPU-aaaaaaaa-1111-4000-8000-000000000001"),+ (name, "GPU-bbbbbbbb-2222-4000-8000-000000000002"),+ )+ install(_FakeNvml(first, second))++ assert find_adapter(second[1]).uuid == second[1]+ assert find_adapter(first[1].upper()).uuid == first[1]+ with pytest.raises(LookupError) as ambiguous:+ find_adapter("RTX PRO 6000")+ message = str(ambiguous.value)+ assert "2 adapters match 'RTX PRO 6000'" in message+ assert f"{name} ({first[1]})" in message and f"{name} ({second[1]})" in message+ assert "set gpu to the UUID of one of them; the runner pins the server to that GPU" in message+++def test_open_gpu_on_linux_reads_memory_and_samples_through_nvml(+ install, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ fake = install(_FakeNvml(RTX_6000))+ me = os.getpid()+ fake.processes[RTX_6000[1]] = [(me, GIB)]+ monkeypatch.setattr(sys, "platform", "linux")+ monkeypatch.setattr(runner, "WSL_KERNEL_RELEASE", tmp_path / "absent")++ gpu = runner.open_gpu("6000")++ assert gpu.adapter == RTX_6000_ADAPTER+ assert gpu.process_usage() == {me: ProcessUsage(dedicated_bytes=GIB, shared_bytes=0)}+ sampler = gpu.sampler(me)+ sampler.start()+ trace = sampler.stop()+ assert trace.method == "nvml" and trace.dedicated and trace.dedicated[0][1] == GIB+ with pytest.raises(runner.RunnerError, match="AMD"):+ runner.open_gpu("Radeon")+++def test_open_gpu_refuses_linux_under_wsl(install, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ install(_FakeNvml(RTX_6000))+ release = tmp_path / "osrelease"+ release.write_text("5.15.167.4-microsoft-standard-WSL2\n", encoding="utf-8")+ monkeypatch.setattr(sys, "platform", "linux")+ monkeypatch.setattr(runner, "WSL_KERNEL_RELEASE", release)++ with pytest.raises(UnsupportedPlatformError, match="WSL.*run the tool on Windows"):+ runner.open_gpu("6000")+++def test_without_the_nvml_library_sampling_is_unsupported(install, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(nvml_memory, "_LIBRARY_NAMES", ("libnvidia-ml-absent.so.1",))+ with pytest.raises(UnsupportedPlatformError, match=r"reads NVML.*AMD \(ROCm\) GPUs on Linux are not supported"):+ list_adapters()+++def test_a_driver_and_library_version_mismatch_asks_for_a_reboot(install) -> None:+ install(_FakeNvml(RTX_6000, init_status=LIB_RM_VERSION_MISMATCH))+ with pytest.raises(UnsupportedPlatformError, match="driver upgrade.*reboot"):+ list_adapters()+++def test_process_usage_merges_compute_and_graphics_processes_of_that_gpu_only(install) -> None:+ fake = install(_FakeNvml(RTX_6000, L4))+ fake.processes[RTX_6000[1]] = [(10, GIB), (11, 2 * GIB)]+ # 11 has both kinds of context and is listed in both; 14's memory is not attributed and cannot count.+ fake.graphics[RTX_6000[1]] = [(11, 2 * GIB), (13, 512 * MIB), (14, NOT_AVAILABLE)]+ fake.processes[L4[1]] = [(12, 3 * GIB)]++ assert process_usage_on_adapter(RTX_6000_ADAPTER) == {+ 10: ProcessUsage(dedicated_bytes=GIB, shared_bytes=0),+ 11: ProcessUsage(dedicated_bytes=2 * GIB, shared_bytes=0),+ 13: ProcessUsage(dedicated_bytes=512 * MIB, shared_bytes=0),+ }+++def test_a_gpu_without_graphics_process_listing_reports_its_compute_processes(install) -> None:+ fake = install(_FakeNvml(RTX_6000))+ fake.processes[RTX_6000[1]] = [(10, GIB)]+ fake.graphics_status = NOT_SUPPORTED++ assert process_usage_on_adapter(RTX_6000_ADAPTER) == {10: ProcessUsage(dedicated_bytes=GIB, shared_bytes=0)}+++def test_a_process_list_that_grows_while_it_is_read_is_read_again(install) -> None:+ fake = install(_FakeNvml(RTX_6000))+ processes = fake.processes[RTX_6000[1]]+ calls = 0++ def thirty_more_on_the_first_two_calls() -> None:+ # More than the spare entries each time, so each answer outgrows the room the previous one made.+ nonlocal calls+ calls += 1+ if calls <= 2:+ start = 100 + len(processes)+ processes.extend((pid, GIB + pid) for pid in range(start, start + 30))++ fake.before_list = thirty_more_on_the_first_two_calls++ usage = process_usage_on_adapter(RTX_6000_ADAPTER)++ assert len(usage) == 60+ assert {pid: value.dedicated_bytes for pid, value in usage.items()} == dict(processes)+++def test_a_process_list_that_never_settles_fails_instead_of_looping(install) -> None:+ fake = install(_FakeNvml(RTX_6000))+ processes = fake.processes[RTX_6000[1]]+ new_pids = iter(range(100, 100_000))+ fake.before_list = lambda: processes.extend((next(new_pids), GIB) for _ in range(100))++ with pytest.raises(OSError, match="kept growing"):+ process_usage_on_adapter(RTX_6000_ADAPTER)+++def test_memory_the_driver_does_not_attribute_is_refused(install) -> None:+ fake = install(_FakeNvml(RTX_6000))+ fake.processes[RTX_6000[1]] = [(os.getpid(), NOT_AVAILABLE)]++ with pytest.raises(UnsupportedPlatformError, match="does not attribute memory to processes"):+ process_usage_on_adapter(RTX_6000_ADAPTER)+ sampler = ProcessMemorySampler(os.getpid(), RTX_6000_ADAPTER)+ with pytest.raises(UnsupportedPlatformError, match="does not attribute memory to processes"):+ sampler.start()+ assert sampler.stop().dedicated == ()+++def test_sampler_reads_its_process_and_zero_while_nvml_does_not_list_it(install) -> None:+ fake = install(_FakeNvml(RTX_6000))+ me, other = os.getpid(), 4_000_001+ fake.processes[RTX_6000[1]] = [(other, 5 * GIB)]+ sampler = ProcessMemorySampler(me, RTX_6000_ADAPTER)+ sampler.start()+ try:+ fake.change(RTX_6000[1], processes=[(other, 5 * GIB), (me, 3 * GIB)])+ fake.wait_until_listed()+ finally:+ trace = sampler.stop()++ values = [value for _, value in trace.dedicated]+ assert values[0] == 0 and values[-1] == 3 * GIB+ assert set(values) == {0, 3 * GIB}, "only the sampled process counts"+ assert (trace.method, trace.shared) == ("nvml", ())+ assert sampler.stop() is trace+++def test_sampler_stops_when_its_process_exits(install) -> None:+ fake = install(_FakeNvml(RTX_6000))+ child = subprocess.Popen([sys.executable, "-c", "import sys; sys.stdin.read()"], stdin=subprocess.PIPE)+ assert child.stdin is not None+ fake.processes[RTX_6000[1]] = [(child.pid, GIB)]+ sampler = ProcessMemorySampler(child.pid, RTX_6000_ADAPTER)+ try:+ sampler.start()+ finally:+ child.stdin.close()+ child.wait(timeout=60)+ try:+ fake.change(RTX_6000[1], processes=[])+ fake.wait_until_listed()+ finally:+ trace = sampler.stop()++ # A process that is gone ends the trace; it does not read as zero from then on.+ assert trace.dedicated and {value for _, value in trace.dedicated} == {GIB}+++def test_start_refuses_a_process_that_has_exited(install) -> None:+ install(_FakeNvml(RTX_6000))+ sampler = ProcessMemorySampler(_exited_child().pid, RTX_6000_ADAPTER)+ with pytest.raises(ProcessLookupError):+ sampler.start()+ assert sampler.stop().dedicated == ()+++def test_nvml_failures_fail_start_and_only_skip_samples_once_running(install, caplog: pytest.LogCaptureFixture) -> None:+ fake = install(_FakeNvml(RTX_6000))+ me = os.getpid()+ fake.list_status = GPU_IS_LOST+ with pytest.raises(OSError, match="GPU is lost"):+ ProcessMemorySampler(me, RTX_6000_ADAPTER).start()++ fake.list_status = 0+ sampler = ProcessMemorySampler(me, RTX_6000_ADAPTER)+ with caplog.at_level(logging.WARNING, logger=nvml_memory.__name__):+ sampler.start()+ try:+ # Twice, so at least two listings fail.+ for _ in range(2):+ fake.change(RTX_6000[1], list_status=GPU_IS_LOST)+ fake.wait_until_listed()+ fake.change(RTX_6000[1], processes=[(me, 2 * GIB)], list_status=0)+ fake.wait_until_listed()+ finally:+ trace = sampler.stop()++ assert trace.dedicated[0][1] == 0 and trace.dedicated[-1][1] == 2 * GIB+ assert sum("GPU is lost" in record.getMessage() for record in caplog.records) == 1+++def test_stop_without_start_returns_one_empty_trace() -> None:+ sampler = ProcessMemorySampler(1234, RTX_6000_ADAPTER)+ trace = sampler.stop()+ assert trace == MemoryTrace(method="nvml", interval_ms=5.0, dedicated=(), shared=())+ assert sampler.stop() is trace+++def test_the_process_entry_matches_the_nvml_layout() -> None:+ """The driver writes entries by offset: a shifted field or stride reads a neighbour's bytes, it does not fail."""+ assert nvml_memory._ProcessInfo.usedGpuMemory.offset == 8+ assert ctypes.sizeof(nvml_memory._ProcessInfo) == PROCESS_ENTRY.size == 24+++_CUDA_CHILD = """+import os, sys, torch+if not torch.cuda.is_available():+ print("unavailable", flush=True)+ sys.exit()+torch.zeros(1, device="cuda")+torch.cuda.synchronize()+# CUDA device 0 after CUDA_VISIBLE_DEVICES, spelled as NVML spells its UUID.+print(os.getpid(), "GPU-" + str(torch.cuda.get_device_properties(0).uuid), flush=True)+sys.stdin.readline()+x = torch.empty(int(sys.argv[1]), dtype=torch.uint8, device="cuda")+x.fill_(1)+torch.cuda.synchronize()+print("allocated", flush=True)+sys.stdin.readline()+"""+++def _end_child(child: subprocess.Popen[str]) -> None:+ """Lets the child finish, or kills it. Raises nothing, so a failure of the test itself stays the one reported."""+ try:+ child.communicate("\n", timeout=60)+ except Exception:+ child.kill()+ child.wait()+++def _tail(path: Path, lines: int = 20) -> str:+ return "\n".join(path.read_text(encoding="utf-8", errors="replace").splitlines()[-lines:])+++@linux_only+def test_two_cuda_processes_are_each_charged_their_own_memory(+ record_property: Callable[[str, object], None], tmp_path: Path+) -> None:+ """Needs NVML and torch with CUDA. Two processes at once, with different allocations: an entry stride that does+ not match the driver's would hand one process the other's memory, or garbage.++ The GPU is the children's CUDA device 0, by its UUID, so the test honours CUDA_VISIBLE_DEVICES on a machine with+ several GPUs. This process stays without a CUDA context, like the tool."""+ if runner._under_wsl():+ pytest.skip("the tool refuses WSL: NVML there reports no per-process memory")+ try:+ list_adapters()+ except UnsupportedPlatformError as error:+ pytest.skip(str(error))+ # NVML's own error text comes back through nvmlErrorString's declared restype.+ absent = Adapter(luid=None, uuid="GPU-00000000-0000-0000-0000-000000000000", description="no such GPU")+ with pytest.raises(OSError, match=r"nvmlDeviceGetHandleByUUID .* failed: (?!unknown error).+ \(NVML error \d+\)"):+ nvml_memory._ProcessTable(absent)+ sizes = (GIB, 2 * GIB)+ # stderr into files, not pipes: torch's warnings could fill a pipe nobody reads and block the child.+ logs = [tmp_path / f"child-{index}.log" for index in range(len(sizes))]+ children = []+ for size, log in zip(sizes, logs, strict=True):+ with log.open("wb") as stderr:+ children.append(+ subprocess.Popen(+ [sys.executable, "-c", _CUDA_CHILD, str(size)],+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=stderr,+ text=True,+ )+ )+ sampler = None+ try:+ pids, uuids = [], set()+ for child, log in zip(children, logs, strict=True):+ assert child.stdout is not None+ first = child.stdout.readline().split()+ if first == ["unavailable"]:+ pytest.skip("torch in this environment has no CUDA")+ if len(first) != 2 or not first[0].isdigit():+ pytest.fail(f"the CUDA child failed (stdout {first!r}); its stderr ends with:\n{_tail(log)}")+ pids.append(int(first[0]))+ uuids.add(first[1])+ assert len(uuids) == 1, f"the children run on different GPUs: {uuids}"+ # Not caught: a UUID NVML does not list is a failure, not a reason to skip.+ adapter = find_adapter(uuids.pop())+ sampler = ProcessMemorySampler(pids[1], adapter)+ sampler.start()+ contexts = process_usage_on_adapter(adapter)++ def allocate(child: subprocess.Popen[str]) -> float:+ """Let the child allocate; the instant just before it, read against the trace afterwards."""+ assert child.stdin is not None and child.stdout is not None+ t = time.perf_counter()+ child.stdin.write("\n")+ child.stdin.flush()+ assert child.stdout.readline().strip() == "allocated"+ # Let samples land after the allocation before anything else changes.+ time.sleep(0.05)+ return t++ t_before_first = allocate(children[0])+ t_before_second = allocate(children[1])+ t_end = time.perf_counter()+ allocated = process_usage_on_adapter(adapter)++ table = nvml_memory._ProcessTable(adapter)+ latencies = []+ for _ in range(2000):+ t0 = time.perf_counter()+ table.read()+ latencies.append(time.perf_counter() - t0)+ trace = sampler.stop()+ finally:+ if sampler is not None:+ sampler.stop()+ for child in children:+ _end_child(child)++ tolerance = GIB / 16+ for pid, size in zip(pids, sizes, strict=True):+ assert contexts[pid].dedicated_bytes > 0, "a CUDA context holds memory"+ assert abs(allocated[pid].dedicated_bytes - contexts[pid].dedicated_bytes - size) < tolerance+ second_context, before_second, after_second = (trace.at(t) for t in (t_before_first, t_before_second, t_end))+ assert second_context is not None and before_second is not None and after_second is not None+ assert abs(before_second - second_context) < tolerance, "the first child's allocation is not the second's"+ assert abs(after_second - second_context - sizes[1]) < tolerance++ cuts = statistics.quantiles(latencies, n=100)+ p50_us, p99_us = cuts[49] * 1e6, cuts[98] * 1e6+ record_property("nvml_process_list_p50_us", round(p50_us, 1))+ record_property("nvml_process_list_p99_us", round(p99_us, 1))+ record_property("sampler_interval_ms", round(trace.interval_ms, 3))+ print(+ f"NVML process listing over {len(latencies)} calls: p50 {p50_us:.0f} us, p99 {p99_us:.0f} us; "+ f"sampler interval {trace.interval_ms:.2f} ms"+ )diff --git a/tests/family_e2e/test_records.py b/tests/family_e2e/test_records.pynew file mode 100644index 0000000000..d79ccc739f--- /dev/null+++ b/tests/family_e2e/test_records.py@@ -0,0 +1,305 @@+import json+import sys+import threading+from pathlib import Path+from typing import Any++import numpy as np+import pytest+from PIL import Image++from scripts.family_e2e import records as records_module+from scripts.family_e2e.records import (+ RECORDS_FILE,+ RUN_INFO_FILE,+ Environment,+ Memory,+ ModelIdentity,+ NodeMemory,+ NodeTiming,+ PlannedStep,+ Record,+ Reference,+ RunInfo,+ Thresholds,+ Timing,+ append_record,+ load_records,+ load_run_info,+ write_run_info,+)++MB = 2**20+++def make_environment(**overrides: Any) -> Environment:+ fields: dict[str, Any] = {+ "code_dir": "D:/code/InvokeAI",+ "git_commit": "0123456789abcdef",+ "git_branch": "main",+ "git_dirty": False,+ "python": "D:/code/InvokeAI/.venv/Scripts/python.exe",+ "invokeai_file": "D:/code/InvokeAI/invokeai/__init__.py",+ "app_version": {"version": "7.0.0"},+ "app_deps": {"torch": "2.8.0+cu128", "CUDA": "12.8", "numpy": "1.26.4"},+ "runtime_config": {+ "set_fields": [],+ "config": {"pytorch_cuda_alloc_conf": "backend:cudaMallocAsync", "enable_partial_loading": False},+ },+ "gpu_description": "NVIDIA GeForce RTX 4090",+ "gpu_luid": 0x1234,+ "gpu_driver": "32.0.15.6094",+ "server_cmd": ["python", "-m", "invokeai.app.run_app"],+ "extra_env": {},+ }+ fields.update(overrides)+ return Environment(**fields)+++def make_record(+ case_key: str = "zimage-t2i@8x8",+ kind: str = "measure",+ rep: int = 0,+ attempt: int = 0,+ *,+ run_id: str = "20261001-120000-rtx4090",+ arm: str = "default",+ status: str = "completed",+ total_s: float = 10.0,+ per_step_s: float | None = 1.0,+ peak_bytes: int | None = 8000 * MB,+ node_peaks: dict[str, int] | None = None,+ image: bool = True,+ image_size: tuple[int, int] | None = None,+ image_sha256: str = "sha-a",+ graph_hash: str = "graph-1",+ valid_timing: bool = True,+ valid_memory: bool = True,+ valid_psnr: bool = True,+ invalid_reasons: list[str] | None = None,+ error: str | None = None,+) -> Record:+ case_id, size = case_key.split("@")+ width, height = (int(v) for v in size.split("x"))+ record_id = f"{case_key}.{arm}.{kind}.{rep}.{attempt}"+ nodes = node_peaks if node_peaks is not None else {"denoise": peak_bytes or 0}+ image_width, image_height = image_size or (width, height)+ return Record(+ record_id=record_id,+ run_id=run_id,+ arm=arm,+ case_id=case_id,+ case_key=case_key,+ family="z-image",+ width=width,+ height=height,+ steps=8,+ seed=1234,+ kind=kind, # type: ignore[arg-type]+ rep=rep,+ attempt=attempt,+ queue_item_id=1,+ graph_hash=graph_hash,+ status=status, # type: ignore[arg-type]+ error=error,+ image_path=f"images/{record_id}.png" if image else None,+ image_sha256=image_sha256 if image else None,+ image_width=image_width if image else None,+ image_height=image_height if image else None,+ timing=Timing(+ total_s=total_s,+ nodes=[+ NodeTiming(node_id=node_id, type="z_image_denoise", t_start=1.0, t_end=total_s) for node_id in nodes+ ],+ model_loads=[],+ per_step_s=per_step_s,+ queue_started_at=None,+ queue_completed_at=None,+ ),+ memory=Memory(+ method="d3dkmt",+ interval_ms=3.0,+ process_baseline_bytes=1000 * MB,+ process_peak_bytes=peak_bytes,+ nodes=[NodeMemory(node_id=n, baseline_bytes=1000 * MB, peak_bytes=p) for n, p in nodes.items()],+ shared_max_delta_bytes=0,+ foreign=[],+ trace=f"traces/{record_id}.csv.gz",+ ),+ residency=[],+ uses_fp8=False,+ valid_timing=valid_timing,+ valid_memory=valid_memory,+ valid_psnr=valid_psnr,+ invalid_reasons=invalid_reasons or [],+ )+++def make_run_info(+ run_id: str = "20261001-120000-rtx4090",+ *,+ profile: str = "rtx4090",+ case_keys: tuple[str, ...] = ("zimage-t2i@8x8",),+ arms: tuple[str, ...] = ("default",),+ environment: Environment | None = None,+ graph_hash: str = "graph-1",+ thresholds: Thresholds | None = None,+ status: str = "completed",+ manifest_path: str = "D:/e2e/manifest.rtx4090.yaml",+ case_models: dict[str, list[ModelIdentity]] | None = None,+) -> RunInfo:+ plan = [+ PlannedStep(case_key=key, case_id=key.split("@")[0], family="z-image", arm=arm, kind=kind, rep=rep) # type: ignore[arg-type]+ for arm in arms+ for key in case_keys+ for kind, rep in (("warmup", 0), ("measure", 0), ("measure", 1), ("measure", 2))+ ]+ return RunInfo(+ run_id=run_id,+ profile=profile,+ created_at="2026-10-01T12:00:00+00:00",+ finished_at=None,+ status=status, # type: ignore[arg-type]+ manifest_path=manifest_path,+ manifest_sha256="f" * 64,+ tool_commit="abc",+ environments={arm: environment or make_environment() for arm in arms},+ plan=plan,+ case_thresholds={+ key: thresholds or Thresholds(psnr_min_db=30.0, time_tolerance=0.10, peak_tolerance_mb=256.0)+ for key in case_keys+ },+ graph_hashes=dict.fromkeys(case_keys, graph_hash),+ case_models=case_models or {},+ )+++def write_png(path: Path, pixels: np.ndarray) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ Image.fromarray(pixels.astype(np.uint8)).save(path)+++def test_records_round_trip_in_append_order(tmp_path: Path) -> None:+ written = [make_record(rep=rep, total_s=10.0 + rep) for rep in range(3)]+ for record in written:+ append_record(tmp_path, record)++ assert load_records(tmp_path) == written+++def test_run_without_records_file_has_no_records(tmp_path: Path) -> None:+ assert load_records(tmp_path) == []+++def test_truncated_last_line_from_a_killed_writer_is_skipped(tmp_path: Path) -> None:+ complete = [make_record(rep=0), make_record(rep=1)]+ for record in complete:+ append_record(tmp_path, record)+ partial = make_record(rep=2).model_dump_json()[:57]+ with open(tmp_path / RECORDS_FILE, "ab") as f:+ f.write(partial.encode())++ assert load_records(tmp_path) == complete++[email protected]("malformed_at_end", [False, True], ids=["middle", "terminated-last-line"])+def test_malformed_complete_line_raises(tmp_path: Path, malformed_at_end: bool) -> None:+ good = make_record().model_dump_json()+ lines = [good, '{"record_id": "x"}'] if malformed_at_end else ['{"record_id": "x"}', good]+ (tmp_path / RECORDS_FILE).write_bytes(("\n".join(lines) + "\n").encode())++ with pytest.raises(ValueError, match="line 2" if malformed_at_end else "line 1"):+ load_records(tmp_path)+++def test_append_after_a_killed_writer_drops_the_partial_line(tmp_path: Path) -> None:+ append_record(tmp_path, make_record(rep=0))+ with open(tmp_path / RECORDS_FILE, "ab") as f:+ f.write(make_record(rep=1).model_dump_json()[:40].encode())++ append_record(tmp_path, make_record(rep=1, attempt=1))++ assert [(r.rep, r.attempt) for r in load_records(tmp_path)] == [(0, 0), (1, 1)]+++def test_append_keeps_a_complete_record_that_lacks_only_its_line_end(tmp_path: Path) -> None:+ (tmp_path / RECORDS_FILE).write_bytes(make_record(rep=0).model_dump_json().encode())++ append_record(tmp_path, make_record(rep=1))++ assert [r.rep for r in load_records(tmp_path)] == [0, 1]+++def test_run_info_rewrite_replaces_the_file_and_leaves_no_temp_files(tmp_path: Path) -> None:+ info = make_run_info(status="running")+ write_run_info(tmp_path, info)+ finished = info.model_copy(update={"status": "completed", "finished_at": "2026-10-01T13:00:00+00:00"})++ write_run_info(tmp_path, finished)++ assert load_run_info(tmp_path) == finished+ assert [p.name for p in tmp_path.iterdir()] == [RUN_INFO_FILE]+++def test_run_info_of_a_linux_gpu_without_a_luid_round_trips(tmp_path: Path) -> None:+ linux = make_environment(gpu_description="NVIDIA RTX 6000 Ada Generation", gpu_luid=None, gpu_driver="580.95.05")+ info = make_run_info(environment=linux)++ write_run_info(tmp_path, info)++ assert load_run_info(tmp_path) == info+++def test_run_info_and_reference_written_before_newer_fields_existed_still_load(tmp_path: Path) -> None:+ old = make_run_info().model_dump(mode="json")+ del old["environments"]["default"]["gpu_driver"]+ del old["case_models"]+ del old["case_thresholds"]["zimage-t2i@8x8"]["expect"]+ (tmp_path / RUN_INFO_FILE).write_text(json.dumps(old))+ reference = {+ "profile": "rtx4090",+ "case_key": "zimage-t2i@8x8",+ "source_run_id": old["run_id"],+ "accepted_at": "2026-10-01T13:00:00+00:00",+ "image_sha256": "a" * 64,+ "graph_hash": "graph-1",+ "environment": old["environments"]["default"],+ "total_s_median": 10.0,+ "per_step_s_median": None,+ "process_peak_bytes_median": None,+ "node_peak_bytes_median": {},+ }++ info = load_run_info(tmp_path)+ assert info.environments["default"].gpu_driver is None+ assert info.case_models == {}+ assert info.case_thresholds["zimage-t2i@8x8"].expect == "unchanged"+ assert Reference.model_validate_json(json.dumps(reference)).environment.gpu_driver is None++[email protected](sys.platform != "win32", reason="only Windows refuses to replace a file another handle holds")+def test_run_info_write_waits_for_a_brief_concurrent_reader(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(records_module, "REPLACE_RETRY_DELAY_S", 0.005)+ write_run_info(tmp_path, make_run_info(status="running"))+ reader = open(tmp_path / RUN_INFO_FILE, "rb")+ timer = threading.Timer(0.02, reader.close)+ timer.start()+ try:+ write_run_info(tmp_path, make_run_info(status="stopped"))+ finally:+ timer.join()++ assert load_run_info(tmp_path).status == "stopped"++[email protected](sys.platform != "win32", reason="only Windows refuses to replace a file another handle holds")+def test_failed_run_info_write_keeps_the_old_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(records_module, "REPLACE_ATTEMPTS", 2)+ monkeypatch.setattr(records_module, "REPLACE_RETRY_DELAY_S", 0.0)+ write_run_info(tmp_path, make_run_info(status="running"))++ with open(tmp_path / RUN_INFO_FILE, "rb"), pytest.raises(PermissionError):+ write_run_info(tmp_path, make_run_info(status="stopped"))++ assert load_run_info(tmp_path).status == "running"+ assert [p.name for p in tmp_path.iterdir()] == [RUN_INFO_FILE]diff --git a/tests/family_e2e/test_references.py b/tests/family_e2e/test_references.pynew file mode 100644index 0000000000..ebb1f2caa0--- /dev/null+++ b/tests/family_e2e/test_references.py@@ -0,0 +1,117 @@+import hashlib+import logging+from pathlib import Path++import numpy as np+import pytest++from scripts.family_e2e.records import Record, append_record, write_run_info+from scripts.family_e2e.references import AcceptError, accept, load_reference+from tests.family_e2e.test_records import MB, make_record, make_run_info, write_png++RUN_ID = "20261001-120000-rtx4090"+CASE = "zimage-t2i@8x8"+OTHER_CASE = "zimage-i2i@8x8"+++def _run(data_dir: Path, records: list[Record], *, arms: tuple[str, ...] = ("default",)) -> Path:+ run_dir = data_dir / "runs" / RUN_ID+ run_dir.mkdir(parents=True)+ write_run_info(+ run_dir, make_run_info(RUN_ID, case_keys=tuple(dict.fromkeys(r.case_key for r in records)), arms=arms)+ )+ for index, record in enumerate(records):+ if record.image_path:+ write_png(run_dir / record.image_path, np.full((8, 8, 3), index * 20, dtype=np.uint8))+ append_record(run_dir, record)+ return run_dir+++def test_accept_uses_first_psnr_valid_image_and_medians_of_valid_records(tmp_path: Path) -> None:+ records = [+ make_record(CASE, "warmup", total_s=90.0, peak_bytes=9000 * MB),+ make_record(CASE, rep=0, total_s=10.0, per_step_s=1.0, peak_bytes=4000 * MB, valid_psnr=False),+ make_record(CASE, rep=1, total_s=11.0, per_step_s=1.2, peak_bytes=5000 * MB, valid_memory=False),+ make_record(CASE, rep=2, total_s=40.0, per_step_s=4.0, peak_bytes=6000 * MB, valid_timing=False),+ make_record(CASE, rep=3, status="failed", total_s=1.0, peak_bytes=1 * MB, error="boom"),+ ]+ run_dir = _run(tmp_path, records)++ [reference] = accept(tmp_path, run_dir, None)++ loaded = load_reference(tmp_path, "rtx4090", CASE)+ assert loaded is not None and loaded[0] == reference+ image_bytes = (run_dir / f"images/{CASE}.default.measure.1.0.png").read_bytes()+ assert loaded[1].read_bytes() == image_bytes+ assert reference.image_sha256 == hashlib.sha256(image_bytes).hexdigest()+ assert reference.source_run_id == RUN_ID+ assert reference.total_s_median == 10.5+ assert reference.per_step_s_median == pytest.approx(1.1)+ assert reference.process_peak_bytes_median == 5000 * MB+ assert reference.node_peak_bytes_median == {"denoise": 5000 * MB}+++def test_accept_refuses_runs_with_ab_arms(tmp_path: Path) -> None:+ records = [make_record(CASE, rep=0, arm="A"), make_record(CASE, rep=0, arm="B")]+ run_dir = _run(tmp_path, records, arms=("A", "B"))++ with pytest.raises(AcceptError, match="arms A, B"):+ accept(tmp_path, run_dir, None)+ assert not (tmp_path / "references").exists()+++def test_accept_writes_nothing_when_one_requested_case_has_no_valid_image(tmp_path: Path) -> None:+ records = [+ make_record(CASE, rep=0),+ make_record(OTHER_CASE, rep=0, valid_psnr=False, invalid_reasons=["residency 80 %"]),+ make_record(OTHER_CASE, rep=1, status="error", error="CUDA out of memory"),+ ]+ run_dir = _run(tmp_path, records)++ with pytest.raises(AcceptError, match=f"{OTHER_CASE}: no completed measured record"):+ accept(tmp_path, run_dir, [CASE, OTHER_CASE])+ assert not (tmp_path / "references").exists()+++def test_accept_refuses_an_image_of_the_wrong_size(tmp_path: Path) -> None:+ run_dir = _run(tmp_path, [make_record(CASE, rep=0, image_size=(8, 4))])++ with pytest.raises(AcceptError, match="8x4 is not the requested 8x8"):+ accept(tmp_path, run_dir, None)+++def test_accept_only_the_requested_case(tmp_path: Path) -> None:+ run_dir = _run(tmp_path, [make_record(CASE, rep=0), make_record(OTHER_CASE, rep=0)])++ accepted = accept(tmp_path, run_dir, [OTHER_CASE])++ assert [r.case_key for r in accepted] == [OTHER_CASE]+ assert load_reference(tmp_path, "rtx4090", CASE) is None+ assert load_reference(tmp_path, "rtx4090", OTHER_CASE) is not None+++def test_accept_reports_differing_measured_images(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:+ records = [+ make_record(CASE, rep=0, image_sha256="one"),+ make_record(CASE, rep=1, image_sha256="two"),+ ]+ run_dir = _run(tmp_path, records)++ with caplog.at_level(logging.WARNING):+ accepted = accept(tmp_path, run_dir, None)++ assert len(accepted) == 1+ assert f"{CASE}: the 2 measured images are not identical" in caplog.text+++def test_reaccept_replaces_the_reference(tmp_path: Path) -> None:+ run_dir = _run(tmp_path, [make_record(CASE, rep=0, total_s=10.0)])+ accept(tmp_path, run_dir, None)+ (run_dir / "records.jsonl").unlink()+ append_record(run_dir, make_record(CASE, rep=0, total_s=20.0))++ accept(tmp_path, run_dir, None)++ loaded = load_reference(tmp_path, "rtx4090", CASE)+ assert loaded is not None and loaded[0].total_s_median == 20.0+ assert sorted(p.name for p in loaded[1].parent.iterdir()) == ["image.png", "reference.json"]diff --git a/tests/family_e2e/test_report.py b/tests/family_e2e/test_report.pynew file mode 100644index 0000000000..0ed154f563--- /dev/null+++ b/tests/family_e2e/test_report.py@@ -0,0 +1,436 @@+import json+import re+import urllib.parse+from pathlib import Path+from typing import Any++import numpy as np+import pytest++from scripts.family_e2e.__main__ import main+from scripts.family_e2e.records import (+ Environment,+ ModelIdentity,+ Record,+ Residency,+ Thresholds,+ append_record,+ write_run_info,+)+from scripts.family_e2e.references import accept+from scripts.family_e2e.report import ReportResult, _residency_text, write_report+from tests.family_e2e.test_records import make_environment, make_record, make_run_info, write_png++PROFILE = "rtx4090"+CASE = "zimage-t2i@8x8"+OTHER_CASE = "zimage-i2i@8x8"+FIRST = "20261001-120000-rtx4090"+SECOND = "20261002-120000-rtx4090"+++def _case_records(+ run_id: str, case: str = CASE, totals: tuple[float, ...] = (10.0, 10.0, 10.0), **kw: Any+) -> list[Record]:+ warmup = make_record(case, "warmup", run_id=run_id, total_s=90.0, **kw)+ return [warmup] + [make_record(case, rep=rep, run_id=run_id, total_s=t, **kw) for rep, t in enumerate(totals)]+++def _write_run(+ data_dir: Path,+ run_id: str,+ records: list[Record],+ *,+ fills: dict[str, int] | None = None,+ profile: str = PROFILE,+ **run_info: Any,+) -> Path:+ """Writes a run whose images are uniform 8-bit fills (100 unless `fills` maps the record_id elsewhere)."""+ run_dir = data_dir / "runs" / run_id+ run_dir.mkdir(parents=True)+ case_keys = tuple(dict.fromkeys(r.case_key for r in records))+ write_run_info(run_dir, make_run_info(run_id, profile=profile, case_keys=case_keys, **run_info))+ for record in records:+ if record.image_path:+ assert record.image_width is not None and record.image_height is not None+ fill = (fills or {}).get(record.record_id, 100)+ write_png(run_dir / record.image_path, np.full((record.image_height, record.image_width, 3), fill))+ append_record(run_dir, record)+ return run_dir+++def _summary(result: ReportResult) -> dict[str, list[str]]:+ """Summary table rows by case label: status, min PSNR, time, vs ref, vs prev, peak, vs ref, vs prev."""+ rows = {}+ for line in result.summary_md.read_text(encoding="utf-8").splitlines():+ if line.startswith("| ") and not line.startswith(("| Case", "| ---")):+ cells = [cell.strip() for cell in line.strip("|").split("|")]+ rows[cells[0]] = cells[1:]+ return rows+++def _attention(result: ReportResult) -> list[str]:+ return [line for line in result.summary_md.read_text(encoding="utf-8").splitlines() if line.startswith("- ")]+++def test_identical_rerun_passes_and_links_all_images(tmp_path: Path) -> None:+ accept(tmp_path, _write_run(tmp_path, FIRST, _case_records(FIRST)), None)+ run_dir = _write_run(tmp_path, SECOND, _case_records(SECOND))+ (run_dir / "graphs").mkdir()+ (run_dir / "graphs" / f"{CASE}.json").write_text(+ json.dumps({"graph": {"id": "g", "nodes": {"denoise": {"id": "denoise", "type": "z_image_denoise"}}}})+ )++ result = write_report(tmp_path, run_dir)++ assert (result.failures, result.outliers, result.invalid) == (0, 0, 0)+ status, min_psnr, time, time_vs_ref, time_vs_prev, *_ = _summary(result)[CASE]+ assert (status, min_psnr, time, time_vs_ref, time_vs_prev) == ("PASS", "∞", "10.00 s", "+0.0%", "+0.0%")+ report = result.report_html.read_text(encoding="utf-8")+ assert "z_image_denoise · denoise" in report+ sources = re.findall(r'<img src="([^"]+)"', report)+ assert len(sources) == 4 # reference, this run, previous run, difference+ assert all((run_dir / urllib.parse.unquote(src)).is_file() for src in sources)+++def test_quality_regression_fails_on_the_worst_measured_image(tmp_path: Path) -> None:+ accept(tmp_path, _write_run(tmp_path, FIRST, _case_records(FIRST)), None)+ records = _case_records(SECOND)+ # A uniform offset of 40 levels: MSE 1600, PSNR = 10·log10(255² / 1600) ≈ 16.09 dB.+ run_dir = _write_run(tmp_path, SECOND, records, fills={records[2].record_id: 140})++ result = write_report(tmp_path, run_dir)++ assert result.failures == 1+ assert _summary(result)[CASE][:2] == ["FAIL", "16.09 dB"]+ assert f"- FAIL {CASE}: min PSNR 16.09 dB is below 30 dB" in _attention(result)+ worst = urllib.parse.quote(f"images/{records[2].record_id}.png")+ assert f'<img src="{worst}"' in result.report_html.read_text(encoding="utf-8")+++ ("fill", "status", "reason", "exit_code"),+ [+ # A uniform offset of 40 levels: PSNR ≈ 16.09 dB.+ (140, "CHANGED", "differs from reference as expected (min PSNR 16.09 dB)", 0),+ (100, "FAIL", "expected a change, but the output matches the reference (min PSNR ∞)", 1),+ ],+)+def test_a_case_expected_to_change_passes_only_when_it_changed(+ tmp_path: Path, capsys: pytest.CaptureFixture[str], fill: int, status: str, reason: str, exit_code: int+) -> None:+ accept(tmp_path, _write_run(tmp_path, FIRST, _case_records(FIRST)), None)+ records = _case_records(SECOND)+ expect_change = Thresholds(psnr_min_db=30.0, time_tolerance=0.10, peak_tolerance_mb=256.0, expect="changed")+ fills = {r.record_id: fill for r in records}+ run_dir = _write_run(tmp_path, SECOND, records, fills=fills, thresholds=expect_change)++ assert main(["report", str(run_dir)]) == exit_code++ changed = int(status == "CHANGED")+ counts = f"{1 - changed} failures, 0 outliers, 0 invalid, {changed} changed as expected, 0 baseline"+ assert counts in capsys.readouterr().out+ summary = (run_dir / "summary.md").read_text(encoding="utf-8")+ assert f"run completed: 1 {status}, 0 with outliers" in summary+ assert f"- {status} {CASE}: {reason}" in summary.splitlines()+++def test_a_run_judged_against_the_reference_it_set_is_a_baseline_unless_it_failed(+ tmp_path: Path, capsys: pytest.CaptureFixture[str]+) -> None:+ records = [*_case_records(FIRST), *_case_records(FIRST, OTHER_CASE)[:-1]]+ records.append(make_record(OTHER_CASE, rep=2, run_id=FIRST, status="error", image=False, error="out of memory"))+ run_dir = _write_run(tmp_path, FIRST, records)+ accept(tmp_path, run_dir, None)++ assert main(["report", str(run_dir)]) == 1+ assert "1 failures, 0 outliers, 0 invalid, 0 changed as expected, 1 baseline" in capsys.readouterr().out++ result = write_report(tmp_path, run_dir)+ # Against its own medians there is nothing to compare.+ assert _summary(result)[CASE] == ["BASELINE", "∞", "10.00 s", "—", "—", "8,000 MB", "—", "—"]+ assert _summary(result)[OTHER_CASE][0] == "ERROR"+ assert f"- BASELINE {CASE}: reference set from this run" in _attention(result)+ assert "accepted from this run" in result.report_html.read_text(encoding="utf-8")+++def test_image_of_the_wrong_size_fails(tmp_path: Path) -> None:+ accept(tmp_path, _write_run(tmp_path, FIRST, _case_records(FIRST)), None)+ run_dir = _write_run(tmp_path, SECOND, _case_records(SECOND, image_size=(8, 4)))++ result = write_report(tmp_path, run_dir)++ assert result.failures == 1+ assert _summary(result)[CASE][0] == "FAIL"+ assert f"- FAIL {CASE}: {CASE}.default.measure.0.0: image is 8x4, requested 8x8" in _attention(result)+++def test_failed_generation_is_an_error(tmp_path: Path) -> None:+ records = _case_records(FIRST)+ records[1] = make_record(CASE, rep=0, run_id=FIRST, status="error", image=False, error="CUDA out of memory")+ run_dir = _write_run(tmp_path, FIRST, records)++ result = write_report(tmp_path, run_dir)++ assert result.failures == 1+ assert _summary(result)[CASE][0] == "ERROR"+ assert f"- ERROR {CASE}: {CASE}.default.measure.0.0: error: CUDA out of memory" in _attention(result)+++def test_a_step_that_failed_and_then_succeeded_on_resume_is_judged_by_its_final_attempt(tmp_path: Path) -> None:+ accept(tmp_path, _write_run(tmp_path, FIRST, _case_records(FIRST)), None)+ records = _case_records(SECOND)+ crashed = make_record(CASE, rep=0, attempt=0, run_id=SECOND, status="error", image=False, error="server died")+ resumed = records[1].model_copy(update={"attempt": 1, "record_id": f"{CASE}.default.measure.0.1"})+ resumed = resumed.model_copy(update={"image_path": f"images/{resumed.record_id}.png"})+ run_dir = _write_run(tmp_path, SECOND, [records[0], crashed, resumed, *records[2:]])++ result = write_report(tmp_path, run_dir)++ assert result.failures == 0+ assert _summary(result)[CASE][0] == "PASS"+ assert f"- FLAG {CASE}: earlier attempt {CASE}.default.measure.0.0 error: server died" in _attention(result)+++def test_case_without_valid_measurements_is_invalid_with_reasons(tmp_path: Path) -> None:+ reason = "model residency 80 % < 100 %"+ run_dir = _write_run(tmp_path, FIRST, _case_records(FIRST, valid_psnr=False, invalid_reasons=[reason]))++ result = write_report(tmp_path, run_dir)++ assert (result.failures, result.invalid) == (0, 1)+ assert _summary(result)[CASE][0] == "INVALID"+ attention = _attention(result)+ assert f"- INVALID {CASE}: no measured image is valid for PSNR" in attention+ assert f"- INVALID METRICS {CASE}: PSNR invalid: {reason} (3 of 3 measured)" in attention+++def test_partial_residency_marks_time_and_vram_invalid_but_keeps_the_psnr_verdict(tmp_path: Path) -> None:+ # The shape of a real forced-partial-loading run: residency spoils time and memory, the image stays rated.+ reasons = [+ "residency: te:text_encoder loaded with 33.2% of its weights in VRAM",+ "residency: tr:transformer loaded with 41.7% of its weights in VRAM",+ ]+ shape = {"valid_timing": False, "valid_memory": False, "valid_psnr": True, "invalid_reasons": reasons}+ records = [make_record(CASE, "warmup", run_id=FIRST, **shape)]+ records += [make_record(CASE, rep=rep, run_id=FIRST, **shape) for rep in range(2)]+ run_dir = _write_run(tmp_path, FIRST, records)++ result = write_report(tmp_path, run_dir)++ assert (result.failures, result.invalid) == (0, 1)+ status, _, time, _, _, peak, *_ = _summary(result)[CASE]+ assert (status, time, peak) == ("NO-REFERENCE", "invalid", "invalid")+ summary = result.summary_md.read_text(encoding="utf-8")+ assert "1 NO-REFERENCE, 0 with outliers, 1 with invalid metrics." in summary+ attention = _attention(result)+ for reason in reasons:+ assert f"- INVALID METRICS {CASE}: time and VRAM invalid: {reason} (2 of 2 measured)" in attention+ assert f'title="{reasons[0]}; {reasons[1]}">invalid</td>' in result.report_html.read_text(encoding="utf-8")+++def test_a_retried_attempt_does_not_make_metrics_invalid(tmp_path: Path) -> None:+ spoiled = make_record(+ CASE,+ rep=0,+ attempt=1,+ run_id=FIRST,+ total_s=30.0,+ valid_timing=False,+ valid_memory=False,+ invalid_reasons=["foreign queue item 17 ran during the measurement"],+ )+ retried = [make_record(CASE, rep=0, attempt=2, run_id=FIRST)]+ retried += [make_record(CASE, rep=rep, attempt=1, run_id=FIRST) for rep in (1, 2)]+ run_dir = _write_run(tmp_path, FIRST, [spoiled, *retried])++ result = write_report(tmp_path, run_dir)++ assert result.invalid == 0+ assert _summary(result)[CASE][2] == "10.00 s"+ assert not any("INVALID METRICS" in line for line in _attention(result))+ assert "retried as attempt 2" in result.report_html.read_text(encoding="utf-8")+++def test_report_without_reference_never_creates_one(tmp_path: Path) -> None:+ run_dir = _write_run(tmp_path, FIRST, _case_records(FIRST))++ result = write_report(tmp_path, run_dir)++ assert _summary(result)[CASE][0] == "NO-REFERENCE"+ assert result.failures == 0+ assert not (tmp_path / "references").exists()+++def test_graph_and_environment_changes_against_the_reference_are_flagged(tmp_path: Path) -> None:+ accept(tmp_path, _write_run(tmp_path, FIRST, _case_records(FIRST)), None)+ changed = make_environment(+ app_deps={"torch": "2.9.0+cu130", "CUDA": "13.0"},+ gpu_driver="32.0.15.7680",+ runtime_config={+ "config": {"pytorch_cuda_alloc_conf": "backend:cudaMallocAsync", "enable_partial_loading": True}+ },+ )+ records = _case_records(SECOND, graph_hash="graph-2")+ run_dir = _write_run(tmp_path, SECOND, records, environment=changed, graph_hash="graph-2")++ result = write_report(tmp_path, run_dir)++ assert _summary(result)[CASE][0] == "PASS"+ attention = _attention(result)+ assert f"- FLAG {CASE}: graph changed vs reference" in attention+ assert (+ f"- FLAG {CASE}: environment changed vs reference: torch 2.8.0+cu128 → 2.9.0+cu130; CUDA 12.8 → 13.0; "+ "GPU driver 32.0.15.6094 → 32.0.15.7680; enable_partial_loading False → True"+ ) in attention+++def test_working_memory_attention_and_int8_settings_count_as_environment_changes(tmp_path: Path) -> None:+ def environment(**config: object) -> Environment:+ settings = {"device_working_mem_gb": 3, "attention_type": "auto", "attention_backend": "auto", **config}+ return make_environment(runtime_config={"set_fields": [], "config": settings})++ accept(tmp_path, _write_run(tmp_path, FIRST, _case_records(FIRST), environment=environment()), None)+ changed = environment(+ device_working_mem_gb=6, attention_backend="sage", rocm_aotriton_experimental="on", int8_compute=True+ )+ run_dir = _write_run(tmp_path, SECOND, _case_records(SECOND), environment=changed)++ result = write_report(tmp_path, run_dir)++ assert (+ f"- FLAG {CASE}: environment changed vs reference: device_working_mem_gb 3 → 6; "+ "attention_backend auto → sage; rocm_aotriton_experimental — → on; int8_compute — → True"+ ) in _attention(result)+++ ("totals", "outliers", "shown"),+ [+ ((12.0, 12.1, 11.9), 1, "**+20.0%**"), # beyond the 10 % tolerance and 3×MAD = 0.3 s+ ((10.5, 10.4, 10.6), 0, "+5.0%"), # within tolerance+ ((10.0, 12.0, 14.0), 0, "+20.0%"), # beyond tolerance, but within 3×MAD = 6 s of this run's noise+ ],+)+def test_time_outlier_against_the_previous_run(+ tmp_path: Path, totals: tuple[float, ...], outliers: int, shown: str+) -> None:+ _write_run(tmp_path, FIRST, _case_records(FIRST))+ run_dir = _write_run(tmp_path, SECOND, _case_records(SECOND, totals=totals))++ result = write_report(tmp_path, run_dir)++ assert result.outliers == outliers+ assert _summary(result)[CASE][4] == shown+ assert any(line.startswith(f"- OUTLIER {CASE}: Total time vs previous run") for line in _attention(result)) is bool(+ outliers+ )+++def test_previous_run_is_the_latest_earlier_one_of_the_profile_with_the_case(tmp_path: Path) -> None:+ current = "20261003-000000-rtx4090"+ _write_run(tmp_path, "20261001-000000-rtx4090", _case_records("20261001-000000-rtx4090", totals=(20.0,) * 3))+ _write_run(tmp_path, "20261002-000000-rtx4090", _case_records("20261002-000000-rtx4090", OTHER_CASE))+ failed = [make_record(CASE, rep=0, run_id="20261002-060000-rtx4090", status="failed", image=False)]+ _write_run(tmp_path, "20261002-060000-rtx4090", failed)+ _write_run(tmp_path, "20261002-120000-amd", _case_records("20261002-120000-amd", totals=(5.0,) * 3), profile="amd")+ run_dir = _write_run(tmp_path, current, _case_records(current))+ _write_run(tmp_path, "20261004-000000-rtx4090", _case_records("20261004-000000-rtx4090", totals=(40.0,) * 3))++ result = write_report(tmp_path, run_dir)++ assert _summary(result)[CASE][4] == "**-50.0%**"+ report = result.report_html.read_text(encoding="utf-8")+ assert "20261001-000000-rtx4090" in report+ assert not any(run_id in report for run_id in ("20261002-", "20261004-"))+++def test_runs_of_other_profiles_are_never_read_but_an_unreadable_run_of_this_one_is_noted(tmp_path: Path) -> None:+ current = "20261003-000000-rtx4090"+ _write_run(tmp_path, "20261001-000000-rtx4090", _case_records("20261001-000000-rtx4090", totals=(20.0,) * 3))+ # run.json files of another version of the tool, with a field this one does not know. The first profile only+ # starts like this run's.+ for run_id in ("20261002-000000-rtx4090-vae", "20261002-060000-rtx4090"):+ (tmp_path / "runs" / run_id).mkdir()+ (tmp_path / "runs" / run_id / "run.json").write_text(json.dumps({"calibrate": False}))+ run_dir = _write_run(tmp_path, current, _case_records(current))++ result = write_report(tmp_path, run_dir)++ assert _summary(result)[CASE][4] == "**-50.0%**"+ notes = [line for line in _attention(result) if line.startswith("- NOTE")]+ assert len(notes) == 1+ assert notes[0].startswith("- NOTE Earlier run 20261002-060000-rtx4090 skipped, unreadable: ")+++def test_broken_inputs_of_one_case_do_not_hide_the_others(tmp_path: Path) -> None:+ first = _write_run(tmp_path, FIRST, _case_records(FIRST) + _case_records(FIRST, OTHER_CASE))+ accept(tmp_path, first, None)+ (tmp_path / "references" / PROFILE / CASE / "reference.json").write_text("{")+ records = _case_records(SECOND) + _case_records(SECOND, OTHER_CASE)+ run_dir = _write_run(tmp_path, SECOND, records)+ (run_dir / records[-1].image_path).unlink() # type: ignore[operator]++ result = write_report(tmp_path, run_dir)++ summary = _summary(result)+ assert summary[CASE][0] == "NO-REFERENCE"+ assert any(line.startswith(f"- NO-REFERENCE {CASE}: reference.json unreadable") for line in _attention(result))+ assert summary[OTHER_CASE][0] == "FAIL"+ assert f"- FAIL {OTHER_CASE}: {records[-1].record_id}: image missing" in _attention(result)+++def test_ab_run_renders_each_arm(tmp_path: Path) -> None:+ records = [r for arm in ("A", "B") for r in _case_records(FIRST, arm=arm)]+ run_dir = _write_run(tmp_path, FIRST, records, arms=("A", "B"))++ result = write_report(tmp_path, run_dir)++ assert {label: cells[0] for label, cells in _summary(result).items()} == {+ f"{CASE} [A]": "NO-REFERENCE",+ f"{CASE} [B]": "NO-REFERENCE",+ }+++def test_each_case_names_its_models_with_a_short_hash(tmp_path: Path) -> None:+ main = ModelIdentity(+ key="k1",+ name="Z-Image Turbo",+ base="z-image",+ type="main",+ format="diffusers",+ variant=None,+ hash="blake3:" + "0123456789abcdef" * 4,+ source="Tongyi-MAI/Z-Image-Turbo",+ )+ encoder = main.model_copy(+ update={"key": "k2", "name": "Qwen3 4B", "type": "qwen3_encoder", "hash": "sha256:" + "f" * 64}+ )+ third = "zimage-t2i@16x16"+ records = [*_case_records(FIRST), *_case_records(FIRST, OTHER_CASE), *_case_records(FIRST, third)]+ models = {CASE: [main, encoder], OTHER_CASE: [main], third: [main, encoder]}+ run_dir = _write_run(tmp_path, FIRST, records, case_models=models)++ result = write_report(tmp_path, run_dir)++ # Sizes of a case share its models, so the summary lists each distinct set once.+ assert (+ "\n## Models\n\n"+ f"- {CASE}, {third}: Z-Image Turbo (main, blake3:0123456789ab); Qwen3 4B (qwen3_encoder, sha256:ffffffffffff)\n"+ f"- {OTHER_CASE}: Z-Image Turbo (main, blake3:0123456789ab)\n"+ ) in result.summary_md.read_text(encoding="utf-8")+ report = result.report_html.read_text(encoding="utf-8")+ assert f'Qwen3 4B <span class="muted">qwen3_encoder · <span title="{encoder.hash}">sha256:ffffffffffff' in report+++def test_the_residency_column_names_the_least_resident_weighted_load() -> None:+ tokenizer = Residency(model="te", submodel="tokenizer_2", vram_mb=0.0, total_mb=0.03, percent=0.0)+ encoder = Residency(model="te", submodel="text_encoder_2", vram_mb=7600.0, total_mb=7600.0, percent=100.0)+ transformer = Residency(model="tr", submodel="transformer", vram_mb=9000.0, total_mb=12000.0, percent=75.0)++ assert _residency_text(make_record().model_copy(update={"residency": [tokenizer]})) == "unknown"+ assert _residency_text(make_record().model_copy(update={"residency": [tokenizer, encoder]})) == "100 %"+ partial = make_record().model_copy(update={"residency": [tokenizer, encoder, transformer]})+ assert _residency_text(partial) == "75 % (tr/transformer)"+ # A record written before sizes were kept cannot be weightless: its 0.0 % is a load without weights in VRAM.+ old = Residency(model="tr", submodel="transformer", vram_mb=0.0, percent=0.0)+ assert _residency_text(make_record().model_copy(update={"residency": [old]})) == "0 % (tr/transformer)"diff --git a/tests/family_e2e/test_residency.py b/tests/family_e2e/test_residency.pynew file mode 100644index 0000000000..643d6188fc--- /dev/null+++ b/tests/family_e2e/test_residency.py@@ -0,0 +1,124 @@+from scripts.family_e2e.records import Residency+from scripts.family_e2e.residency import ResidencyTracker, parse_log, resident, weightless++PREFIX = "[2026-10-17 12:00:00,000]::[ModelManagerService]::INFO --> [MODEL CACHE] "+MODEL = "6dc7b49c-2a39-4901-a38b-4b291320b42f"+VAE = "4d85e528-e888-4e72-9539-41612778409b"+++def loaded(key: str, fraction: float, device: str = "cuda device #0", total_mb: float = 7600.0) -> str:+ # The format of ModelCache._load_locked_model, including its percent formatting.+ return (+ f"{PREFIX}Loaded model '{key}' (Krea2Transformer2DModel) onto {device} in 3.21s. "+ f"Total model size: {total_mb:.2f}MB, VRAM: {total_mb * fraction:.2f}MB ({fraction:.1%})\n"+ )+++def short(key: str) -> str:+ return (+ "[2026-10-17 12:00:00,000]::[ModelManagerService]::WARNING --> [MODEL CACHE] "+ f"VRAM budget for '{key}' is short by 812MB even after offloading (working memory reservation: 3072MB); "+ "the model will run with minimum weights resident. Other models still in VRAM: none.\n"+ )+++def test_load_lines_parse_into_model_submodel_and_percent() -> None:+ text = (+ loaded(f"{MODEL}:transformer", 1.0)+ + f"{PREFIX}Loaded model '{VAE}' (AutoencoderKL) onto cpu device (cpu_only); skipping VRAM load\n"+ + loaded(VAE, 0.5, device="cuda device", total_mb=160.0)+ + short(f"{MODEL}:transformer")+ )+ window = parse_log(text)+ assert [(r.model, r.submodel, r.vram_mb, r.total_mb, r.percent) for r in window.loads] == [+ (MODEL, "transformer", 7600.0, 7600.0, 100.0),+ (VAE, None, 80.0, 160.0, 50.0),+ ]+ assert window.short == [f"{MODEL}:transformer"]+++def test_warm_runs_without_load_lines_stay_valid_after_a_full_load() -> None:+ tracker = ResidencyTracker()+ residency, reasons = tracker.observe(parse_log(loaded(f"{MODEL}:transformer", 1.0)), [MODEL])+ assert reasons == []+ residency, reasons = tracker.observe(parse_log("nothing about models\n"), [MODEL])+ assert reasons == []+ assert [(r.model, r.percent) for r in residency] == [(MODEL, 100.0)]+++def test_partial_load_invalidates_this_run_and_later_runs_without_a_new_line() -> None:+ tracker = ResidencyTracker()+ _, reasons = tracker.observe(parse_log(loaded(f"{MODEL}:transformer", 0.874)), [MODEL])+ assert reasons == [f"residency: {MODEL}:transformer loaded with 87.4% of its weights in VRAM"]+ _, reasons = tracker.observe(parse_log(""), [MODEL])+ assert reasons == [f"residency: {MODEL}:transformer at 87.4% since an earlier run"]+ _, reasons = tracker.observe(parse_log(loaded(f"{MODEL}:transformer", 1.0)), [MODEL])+ assert reasons == []+++def test_rounding_to_one_decimal_counts_as_full_only_at_100_0() -> None:+ tracker = ResidencyTracker()+ assert tracker.observe(parse_log(loaded(MODEL, 0.99951)), [MODEL])[1] == []+ assert tracker.observe(parse_log(loaded(MODEL, 0.9994)), [MODEL])[1] != []+++def test_a_weightless_tokenizer_load_is_resident_but_a_partial_weighted_load_is_not() -> None:+ # The lines of a FLUX.1 dev (int8) run: its T5 encoder's tokenizer has no weights, the cache logs it at 0.0 %.+ tokenizer = (+ f"{PREFIX}Loaded model '{MODEL}:tokenizer_2' (T5Tokenizer) onto cuda device #0 in 0.00s. "+ "Total model size: 0.03MB, VRAM: 0.00MB (0.0%)\n"+ )+ tracker = ResidencyTracker()++ residency, reasons = tracker.observe(parse_log(tokenizer + loaded(f"{MODEL}:text_encoder_2", 1.0)), [MODEL])+ assert reasons == []+ # The record keeps what the cache logged.+ assert [(r.submodel, r.total_mb, r.percent) for r in residency] == [+ ("tokenizer_2", 0.03, 0.0),+ ("text_encoder_2", 7600.0, 100.0),+ ]++ _, reasons = tracker.observe(parse_log(tokenizer + loaded(VAE, 0.5, total_mb=160.0)), [MODEL])+ assert reasons == [f"residency: {VAE} loaded with 50.0% of its weights in VRAM"]+++def test_a_record_written_before_sizes_were_kept_is_never_weightless() -> None:+ # Without a logged size a 0.0 % load cannot be told from weights left entirely in RAM.+ old = Residency(model=MODEL, submodel="transformer", vram_mb=0.0, total_mb=None, percent=0.0)+ assert not weightless(old)+ assert not resident(old)+++def test_a_weightless_load_alone_leaves_residency_unknown() -> None:+ tokenizer = (+ f"{PREFIX}Loaded model '{MODEL}:tokenizer_2' (T5Tokenizer) onto cuda device #0 in 0.00s. "+ "Total model size: 0.03MB, VRAM: 0.00MB (0.0%)\n"+ )+ _, reasons = ResidencyTracker().observe(parse_log(tokenizer), [MODEL])+ assert reasons == ["residency unknown: no load with weights for the graph's models since the last cache flush"]+++def test_short_budget_warning_invalidates_even_with_full_lines() -> None:+ tracker = ResidencyTracker()+ text = short(f"{MODEL}:transformer") + loaded(f"{MODEL}:transformer", 1.0)+ _, reasons = tracker.observe(parse_log(text), [MODEL])+ assert reasons == [f"residency: VRAM budget short for {MODEL}:transformer"]+++def test_without_any_line_for_the_graphs_models_residency_is_unknown() -> None:+ tracker = ResidencyTracker()+ unknown = "residency unknown: no load with weights for the graph's models since the last cache flush"+ assert tracker.observe(parse_log(""), [MODEL])[1] == [unknown]+ # Another model's full load says nothing about this graph's models.+ assert tracker.observe(parse_log(loaded(VAE, 1.0)), [MODEL])[1] == [unknown]+ tracker.observe(parse_log(loaded(f"{MODEL}:transformer", 1.0)), [MODEL])+ tracker.reset()+ assert tracker.observe(parse_log(""), [MODEL])[1] == [unknown]+++def test_partial_load_of_a_model_outside_the_graph_still_invalidates_the_run() -> None:+ tracker = ResidencyTracker()+ text = loaded(f"{MODEL}:transformer", 1.0) + loaded(VAE, 0.3)+ residency, reasons = tracker.observe(parse_log(text), [MODEL])+ assert [r.model for r in residency] == [MODEL]+ assert reasons == [f"residency: {VAE} loaded with 30.0% of its weights in VRAM"]diff --git a/tests/family_e2e/test_runner.py b/tests/family_e2e/test_runner.pynew file mode 100644index 0000000000..3680e298c9--- /dev/null+++ b/tests/family_e2e/test_runner.py@@ -0,0 +1,612 @@+import errno+import json+import os+import socket+import subprocess+import sys+import time+from collections.abc import Callable, Iterator+from contextlib import contextmanager+from pathlib import Path++import psutil+import pytest+import yaml++from scripts.family_e2e import runner, server+from scripts.family_e2e.__main__ import main+from scripts.family_e2e.gpu_memory import Adapter, MemoryTrace, ProcessUsage, UnsupportedPlatformError+from scripts.family_e2e.manifest import DEFAULT_ARM, Manifest+from scripts.family_e2e.records import (+ RUN_INFO_FILE,+ NodeTiming,+ PlannedStep,+ Record,+ RunInfo,+ Timing,+ append_record,+ load_records,+ load_run_info,+ write_run_info,+)+from scripts.family_e2e.runner import (+ FOREIGN_GPU_LOAD,+ HEARTBEAT_FILE,+ SERVER_CRASHED,+ SERVER_ROLES,+ Gpu,+ RunnerError,+ build_memory,+ device_env,+ foreign_processes,+ gpu_lock,+ model_identities,+ preflight,+ remaining_steps,+ uses_fp8,+)++MIB = 2**20+GIB = 2**30+# Waiting for a helper process to report that it is ready.+CHILD_POLL_S = 0.01+CHILD_TIMEOUT_S = 30.0+++def _plan() -> list[PlannedStep]:+ return [+ PlannedStep(case_key="a@64x64", case_id="a", family="f", arm="default", kind=kind, rep=rep)+ for kind, rep in (("warmup", 0), ("measure", 0), ("measure", 1), ("measure", 2))+ ]+++def _record(step: PlannedStep, attempt: int, status: str = "completed", reasons: tuple[str, ...] = ()) -> Record:+ return Record(+ record_id=f"{step.case_key}.{step.arm}.{step.kind}.{step.rep}.{attempt}",+ run_id="r",+ arm=step.arm,+ case_id=step.case_id,+ case_key=step.case_key,+ family=step.family,+ width=64,+ height=64,+ steps=4,+ seed=1,+ kind=step.kind,+ rep=step.rep,+ attempt=attempt,+ queue_item_id=attempt,+ graph_hash="h",+ status=status,+ error=None,+ image_path=None,+ image_sha256=None,+ image_width=None,+ image_height=None,+ timing=None,+ memory=None,+ residency=[],+ uses_fp8=False,+ valid_timing=not reasons,+ valid_memory=not reasons,+ valid_psnr=True,+ invalid_reasons=list(reasons),+ )+++def test_resume_skips_final_steps_and_tolerates_a_truncated_last_line(tmp_path: Path) -> None:+ warmup, m0, m1, m2 = _plan()+ foreign = (f"{FOREIGN_GPU_LOAD}: pid 4 (chrome.exe) 2048 MiB",)+ append_record(tmp_path, _record(warmup, 1))+ append_record(tmp_path, _record(m0, 1, reasons=foreign)) # a retry was due+ append_record(tmp_path, _record(m1, 1, status="failed"))+ with open(tmp_path / "records.jsonl", "ab") as f:+ f.write(_record(m2, 1).model_dump_json().encode()[:40]) # the runner died while writing+ assert [(s.kind, s.rep) for s in remaining_steps(_plan(), load_records(tmp_path))] == [+ ("measure", 0),+ ("measure", 1),+ ("measure", 2),+ ]++ append_record(tmp_path, _record(m0, 2, reasons=foreign))+ append_record(tmp_path, _record(m0, 3, reasons=foreign)) # retries used up: final, though invalid+ append_record(tmp_path, _record(m1, 2))+ assert [(s.kind, s.rep) for s in remaining_steps(_plan(), load_records(tmp_path))] == [("measure", 2)]+++def test_a_case_that_keeps_crashing_the_server_is_given_up() -> None:+ warmup, m0, m1, m2 = _plan()+ crash = (f"{SERVER_CRASHED} (exit code 3): ConnectionError: refused",)+ records = [_record(warmup, 1), _record(m0, 1, status="error", reasons=crash)]+ assert [(s.kind, s.rep) for s in remaining_steps(_plan(), records)] == [+ ("measure", 0),+ ("measure", 1),+ ("measure", 2),+ ]+ # The restarted server repeats the warm-up, which crashes it again: the case stops counting as remaining.+ records.append(_record(warmup, 2, status="error", reasons=crash))+ assert remaining_steps(_plan(), records) == []+++def test_foreign_processes_are_large_or_growing_others() -> None:+ before = {+ 1: ProcessUsage(dedicated_bytes=8 * GIB, shared_bytes=0), # the server itself+ 2: ProcessUsage(dedicated_bytes=2 * GIB, shared_bytes=0), # large from the start+ 3: ProcessUsage(dedicated_bytes=300 * MIB, shared_bytes=0), # grows by 400 MiB+ 4: ProcessUsage(dedicated_bytes=500 * MIB, shared_bytes=0), # stable and small+ }+ after = dict(before)+ after[3] = ProcessUsage(dedicated_bytes=700 * MIB, shared_bytes=0)+ after[5] = ProcessUsage(dedicated_bytes=200 * MIB, shared_bytes=0) # new but small+ found = foreign_processes(before, after, own={1})+ assert [(p.pid, p.dedicated_bytes) for p in found] == [(2, 2 * GIB), (3, 700 * MIB)]+++def test_fp8_comes_from_storage_settings_or_runtime_compute() -> None:+ configs = {+ "plain": {"default_settings": {"fp8_storage": False}},+ "fp8": {"default_settings": {"fp8_storage": True}},+ }+ assert not uses_fp8(frozenset({"plain", "lora-without-config"}), configs, fp8_compute=False)+ assert uses_fp8(frozenset({"plain", "fp8"}), configs, fp8_compute=False)+ assert uses_fp8(frozenset({"plain"}), configs, fp8_compute=True)+++def test_a_cases_models_start_with_its_main_model_even_beside_another_main_model() -> None:+ # Z-Image takes its text encoder from a second diffusers main model.+ configs = {+ key: {"key": key, "name": name, "base": "z-image", "type": model_type, "path": f"S:/{name}"}+ for key, name, model_type in (+ ("vae", "ae", "vae"),+ ("source", "A Z-Image source", "main"),+ ("turbo", "Z-Image Turbo", "main"),+ )+ }++ identities = model_identities(frozenset(configs), "turbo", configs)++ assert [m.name for m in identities] == ["Z-Image Turbo", "A Z-Image source", "ae"]+++def test_memory_is_split_per_node_and_shared_growth_is_measured_from_enqueue() -> None:+ t0 = 100.0+ trace = MemoryTrace(+ method="d3dkmt",+ interval_ms=3.0,+ dedicated=((t0 - 0.01, GIB), (t0 + 0.2, 4 * GIB), (t0 + 0.4, 2 * GIB), (t0 + 0.6, 6 * GIB), (t0 + 0.9, GIB)),+ shared=((t0 - 0.05, 100 * MIB), (t0 + 0.5, 500 * MIB), (t0 + 2.0, 900 * MIB)),+ )+ nodes = [+ NodeTiming(node_id="encode", type="e", t_start=0.1, t_end=0.3),+ NodeTiming(node_id="denoise", type="d", t_start=0.5, t_end=None),+ ]+ timing = Timing(+ total_s=1.0, nodes=nodes, model_loads=[], per_step_s=None, queue_started_at=None, queue_completed_at=None+ )+ memory = build_memory(trace, timing, t0, t0 + 1.0, [], "traces/x.csv.gz")+ assert (memory.process_baseline_bytes, memory.process_peak_bytes) == (GIB, 6 * GIB)+ assert [(n.node_id, n.baseline_bytes, n.peak_bytes) for n in memory.nodes] == [+ ("encode", GIB, 4 * GIB),+ ("denoise", 2 * GIB, 6 * GIB),+ ]+ # The sample after the window does not count.+ assert memory.shared_max_delta_bytes == 400 * MIB+++ ("adapter", "lock_file"),+ [+ (Adapter(luid=0xABC, description="Fake GPU"), "abc.lock"),+ (Adapter(luid=None, uuid="GPU-5f1c2e3a-1111", description="Fake GPU"), "GPU-5f1c2e3a-1111.lock"),+ ],+ ids=["wddm-luid", "nvml-uuid"],+)+def test_second_runner_on_the_same_gpu_fails_fast(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, adapter: Adapter, lock_file: str+) -> None:+ monkeypatch.setattr(runner, "LOCK_DIR", tmp_path / "locks")+ with gpu_lock(adapter):+ assert [path.name for path in (tmp_path / "locks").iterdir()] == [lock_file]+ with pytest.raises(RunnerError, match="another runner"):+ with gpu_lock(adapter):+ pass+ with gpu_lock(adapter):+ pass+++def test_runners_on_two_gpus_of_one_machine_do_not_block_each_other(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(runner, "LOCK_DIR", tmp_path / "locks")+ name = "NVIDIA RTX PRO 6000 Blackwell Server Edition"+ with gpu_lock(Adapter(luid=None, uuid="GPU-aaaaaaaa", description=name)):+ with gpu_lock(Adapter(luid=None, uuid="GPU-bbbbbbbb", description=name)):+ pass+++def test_the_server_is_pinned_to_the_selected_nvml_gpu_and_a_conflicting_pin_is_refused() -> None:+ uuid = "GPU-aaaaaaaa-1111-4000-8000-000000000001"+ nvml = Adapter(luid=None, uuid=uuid, description="NVIDIA RTX PRO 6000 Blackwell Server Edition")++ assert device_env(nvml, {}) == {"CUDA_VISIBLE_DEVICES": uuid}+ assert device_env(nvml, {"CUDA_VISIBLE_DEVICES": uuid.upper()}) == {"CUDA_VISIBLE_DEVICES": uuid}+ with pytest.raises(RunnerError, match="CUDA_VISIBLE_DEVICES=1, but gpu selects .*GPU-aaaaaaaa"):+ device_env(nvml, {"CUDA_VISIBLE_DEVICES": "1"})+ # WDDM adapters have no device selector; the manifest's env pins the server there.+ assert device_env(Adapter(luid=0x22A61, description="NVIDIA GeForce RTX 4090"), {"CUDA_VISIBLE_DEVICES": "1"}) == {}+++def test_open_gpu_refuses_a_platform_without_a_sampler(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(sys, "platform", "darwin")+ with pytest.raises(UnsupportedPlatformError, match="not for darwin"):+ runner.open_gpu("M3")+++def test_preflight_refuses_a_template_with_an_unfinished_model_install(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(server, "PORT_PROBE_TIMEOUT_S", 0.01)+ with socket.socket() as s:+ s.bind(("127.0.0.1", 0))+ free = s.getsockname()[1]+ template = tmp_path / "template"+ (template / "my-models").mkdir(parents=True)+ (template / "invokeai.yaml").write_text(+ yaml.safe_dump({"schema_version": "4.0.3", "port": free, "models_dir": "my-models"})+ )+ code_dir = tmp_path / "code"+ (code_dir / "scripts").mkdir(parents=True)+ (code_dir / "scripts" / "invokeai-web.py").write_text("")+ manifest = Manifest.model_validate(+ {+ "profile": "box",+ "data_dir": str(tmp_path / "data"),+ "gpu": "Fake",+ "server": {"template_root": str(template), "python": sys.executable, "code_dir": str(code_dir)},+ "defaults": {"prompt": "a fox"},+ "families": [{"family": "f", "cases": [{"id": "a", "model": "m", "steps": 1, "sizes": [[8, 8]]}]}],+ }+ )+ gpu = Gpu(adapter=Adapter(luid=1, description="Fake"), process_usage=dict, sampler=lambda pid: None)++ (template / "my-models" / "tmpinstall_k2j3").mkdir()+ with pytest.raises(RunnerError, match="tmpinstall_k2j3.*finish or cancel the pending model install"):+ preflight(manifest, gpu)+ (template / "my-models" / "tmpinstall_k2j3").rmdir()+ preflight(manifest, gpu)++[email protected](sys.platform == "win32", reason="POSIX process groups; on Windows the job object holds the tree")+def test_stop_kills_a_descendant_whose_parent_died(tmp_path: Path) -> None:+ # The launcher's child starts a grandchild and exits: the grandchild is in no tree any more, but in the group+ # the launcher leads, as with a server launched by spawn_in_job.+ grandchild_file, ready = tmp_path / "grandchild.txt", tmp_path / "ready"+ middle = (+ "import subprocess, sys\n"+ "grandchild = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)'])\n"+ f"with open({str(grandchild_file)!r}, 'w') as f:\n"+ " f.write(str(grandchild.pid))\n"+ )+ script = tmp_path / "launcher.py"+ script.write_text(+ "import subprocess, sys, time\n"+ f"subprocess.run([sys.executable, '-c', {middle!r}], check=True)\n"+ f"open({str(ready)!r}, 'w').close()\n"+ "time.sleep(60)\n"+ )+ process, _ = server.spawn_in_job([sys.executable, str(script)])+ grandchild: psutil.Process | None = None+ try:+ deadline = time.monotonic() + CHILD_TIMEOUT_S+ while not ready.exists():+ assert process.poll() is None and time.monotonic() < deadline+ time.sleep(CHILD_POLL_S)+ grandchild = psutil.Process(int(grandchild_file.read_text()))+ assert grandchild.pid not in {p.pid for p in psutil.Process(process.pid).children(recursive=True)}++ assert runner.kill_identified(runner.process_identity(process.pid))++ _, alive = psutil.wait_procs([grandchild], timeout=CHILD_TIMEOUT_S)+ assert alive == []+ finally:+ if grandchild is not None and grandchild.is_running():+ grandchild.kill()+ process.kill()+ process.wait()+++RUN_ID = "20261025-000000-box"+++def _fake_gpu(description: str) -> Gpu:+ return Gpu(adapter=Adapter(luid=1, description=description), process_usage=dict, sampler=lambda pid: None)+++def killed_run(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ """The run directory of a runner that was killed: a step is left, and its scratch root is still there.++ The template's port is free, so a new session of the run would pass preflight and go on to rebuild that root. Its+ server script is empty: a server it launched would exit at once.+ """+ monkeypatch.setattr(runner, "LOCK_DIR", tmp_path / "locks")+ monkeypatch.setattr(server, "PORT_PROBE_TIMEOUT_S", 0.01)+ (tmp_path / "code" / "scripts").mkdir(parents=True)+ (tmp_path / "code" / "scripts" / "invokeai-web.py").write_text("")+ with socket.socket() as s:+ s.bind(("127.0.0.1", 0))+ free = s.getsockname()[1]+ (tmp_path / "template").mkdir()+ (tmp_path / "template" / "invokeai.yaml").write_text(yaml.safe_dump({"schema_version": "4.0.3", "port": free}))+ manifest = tmp_path / "manifest.yaml"+ manifest.write_text(+ yaml.safe_dump(+ {+ "profile": "box",+ "data_dir": "data",+ "gpu": "Fake",+ "server": {"template_root": "template", "python": sys.executable, "code_dir": "code"},+ "defaults": {"prompt": "a fox"},+ "families": [{"family": "f", "cases": [{"id": "a", "model": "m", "steps": 1, "sizes": [[8, 8]]}]}],+ }+ )+ )+ run_dir = tmp_path / "data" / "runs" / RUN_ID+ run_dir.mkdir(parents=True)+ step = PlannedStep(case_key="a@8x8", case_id="a", family="f", arm=DEFAULT_ARM, kind="warmup", rep=0)+ write_run_info(+ run_dir,+ RunInfo(+ run_id=RUN_ID,+ profile="box",+ created_at="2026-10-25T00:00:00+00:00",+ finished_at=None,+ status="running",+ manifest_path=str(manifest),+ manifest_sha256=runner.file_sha256(manifest),+ tool_commit=None,+ environments={},+ plan=[step],+ case_thresholds={},+ graph_hashes={},+ ),+ )+ scratch = runner.scratch_root(tmp_path / "data", RUN_ID, DEFAULT_ARM)+ scratch.mkdir(parents=True)+ (scratch / "invokeai.yaml").write_text("left by the killed runner")+ return run_dir+++def _scratch_file(run_dir: Path) -> Path:+ return runner.scratch_root(run_dir.parent.parent, RUN_ID, DEFAULT_ARM) / "invokeai.yaml"+++def _write_heartbeat(run_dir: Path, **identities: list[float]) -> None:+ data = {"runner": None, "server": None, "server_launcher": None, "step": "a@8x8 warmup 0 attempt 1"}+ (run_dir / HEARTBEAT_FILE).write_text(json.dumps({**data, **identities, "updated_at": runner.now_iso()}))+++def surviving_server() -> Iterator[list[float]]:+ """The identity of a server whose runner was killed: a process in a group (on Windows a job) of its own."""+ process, job = server.spawn_in_job([sys.executable, "-c", "import time; time.sleep(60)"])+ identity = runner.process_identity(process.pid)+ assert identity is not None+ try:+ yield identity+ finally:+ if job is not None:+ job.close()+ runner.kill_identified(identity)+ process.wait()+++class _FirstHeartbeat(Exception):+ pass+++def _trap_first_replacing_write(+ monkeypatch: pytest.MonkeyPatch, run_dir: Path, check: Callable[[Path], object]+) -> list[object]:+ """Lets the runner's writes through until the first one that replaces the server entries of the heartbeat (its+ registration keeps them); records `check(path)` there and raises _FirstHeartbeat."""+ recorded = {role: runner.read_heartbeat(run_dir).get(role) for role in SERVER_ROLES}+ write_bytes_atomic = runner.write_bytes_atomic+ seen: list[object] = []++ def write(path: Path, data: bytes) -> None:+ if path.name == HEARTBEAT_FILE and {role: json.loads(data).get(role) for role in SERVER_ROLES} == recorded:+ return write_bytes_atomic(path, data)+ seen.append(check(path))+ raise _FirstHeartbeat++ monkeypatch.setattr(runner, "write_bytes_atomic", write)+ return seen++[email protected]("role", SERVER_ROLES)+def test_a_runner_stops_the_server_a_killed_runner_left_before_it_replaces_the_heartbeat(+ killed_run: Path, surviving_server: list[float], monkeypatch: pytest.MonkeyPatch, role: str+) -> None:+ # The other entry's pid now belongs to an unrelated process: its start time gives it away.+ unrelated = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])+ try:+ reused = [unrelated.pid, psutil.Process(unrelated.pid).create_time() - 100.0]+ other = next(r for r in SERVER_ROLES if r != role)+ _write_heartbeat(killed_run, **{role: surviving_server, other: reused})+ # The scratch root is rebuilt only after that write.+ seen = _trap_first_replacing_write(+ monkeypatch,+ killed_run,+ lambda path: (path.name, runner.is_alive(surviving_server), _scratch_file(killed_run).is_file()),+ )+ with pytest.raises(_FirstHeartbeat):+ runner.run(killed_run, gpu_factory=_fake_gpu)++ assert seen == [(HEARTBEAT_FILE, False, True)]+ assert unrelated.poll() is None+ finally:+ unrelated.kill()+ unrelated.wait()++[email protected]("failure", ["survives the kill", "kill refused"])+def test_a_runner_refuses_and_keeps_heartbeat_and_scratch_root_while_a_left_server_cannot_be_stopped(+ killed_run: Path, surviving_server: list[float], monkeypatch: pytest.MonkeyPatch, failure: str+) -> None:+ # A process stuck in the GPU driver outlives SIGKILL until it leaves the kernel; another user's refuses it.+ _write_heartbeat(killed_run, server=surviving_server, server_launcher=surviving_server)++ def kill_process(process: psutil.Process) -> None:+ if failure == "kill refused":+ raise psutil.AccessDenied(process.pid)++ def killpg(pgid: int, sig: int) -> None:+ if failure == "kill refused":+ raise PermissionError(errno.EPERM, "Operation not permitted")++ with monkeypatch.context() as m:+ m.setattr(runner, "KILL_WAIT_S", 0.05)+ m.setattr(psutil.Process, "kill", kill_process)+ if sys.platform != "win32":+ m.setattr(os, "killpg", killpg)+ with pytest.raises(RunnerError, match=rf"cannot be stopped: pid {int(surviving_server[0])} \("):+ runner.run(killed_run, gpu_factory=_fake_gpu)++ # What names the server for `stop`; the refusing runner adds only itself.+ heartbeat = runner.read_heartbeat(killed_run)+ assert {role: heartbeat[role] for role in SERVER_ROLES} == dict.fromkeys(SERVER_ROLES, surviving_server)+ assert _scratch_file(killed_run).read_text() == "left by the killed runner"+ assert runner.is_alive(surviving_server)+++def _gone(process: psutil.Process) -> bool:+ try:+ return not process.is_running() or process.status() == psutil.STATUS_ZOMBIE+ except psutil.NoSuchProcess:+ return True+++@contextmanager+def _unreaped_launcher(tmp_path: Path, orphan: bool) -> Iterator[tuple[list[float], psutil.Process | None]]:+ """A server launcher that exited but is not reaped: its parent lives on without waiting for it, as a container's+ PID 1 that reaps nothing does. With `orphan`, a worker it started runs on in its group. Yields the launcher's+ identity and the worker."""++ def publish(path: Path, value: str) -> str:+ # Written whole and renamed into place, so whatever the name holds once it exists is complete.+ tmp = str(path) + ".tmp"+ return f"with open({tmp!r}, 'w') as f: f.write({value})\nos.replace({tmp!r}, {str(path)!r})\n"++ launcher_file, worker_file = tmp_path / "launcher.txt", tmp_path / "worker.txt"+ launcher_code = "import os, subprocess, sys\n"+ if orphan:+ launcher_code += "worker = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)'])\n"+ launcher_code += publish(worker_file, "str(worker.pid)")+ parent = subprocess.Popen(+ [+ sys.executable,+ "-c",+ "import os, subprocess, sys, time\n"+ f"launcher = subprocess.Popen([sys.executable, '-c', {launcher_code!r}], start_new_session=True)\n"+ + publish(launcher_file, "str(launcher.pid)")+ + "time.sleep(60)\n",+ ]+ )+ worker: psutil.Process | None = None+ try:+ deadline = time.monotonic() + CHILD_TIMEOUT_S+ while not launcher_file.exists():+ assert parent.poll() is None and time.monotonic() < deadline+ time.sleep(CHILD_POLL_S)+ launcher = psutil.Process(int(launcher_file.read_text()))+ while launcher.status() != psutil.STATUS_ZOMBIE:+ assert time.monotonic() < deadline+ time.sleep(CHILD_POLL_S)+ if orphan:+ worker = psutil.Process(int(worker_file.read_text()))+ assert worker.status() != psutil.STATUS_ZOMBIE+ yield [launcher.pid, launcher.create_time()], worker+ finally:+ if worker is not None and not _gone(worker):+ worker.kill()+ parent.kill() # its init reaps the launcher then+ parent.wait()++[email protected](sys.platform == "win32", reason="POSIX zombies; Windows keeps no exited process for its parent")[email protected]("orphan", [False, True], ids=["alone", "orphaned-worker"])[email protected]("command", ["resume", "stop"])+def test_an_unreaped_server_counts_as_gone_but_a_worker_left_in_its_group_is_killed(+ killed_run: Path,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ capsys: pytest.CaptureFixture[str],+ command: str,+ orphan: bool,+) -> None:+ # Bounds what a regression would wait for the zombie to exit.+ monkeypatch.setattr(runner, "KILL_WAIT_S", 1.0)+ with _unreaped_launcher(tmp_path, orphan) as (identity, worker):+ assert not runner.is_alive(identity)+ _write_heartbeat(killed_run, server=identity, server_launcher=identity)+ if command == "resume":+ worker_running = _trap_first_replacing_write(+ monkeypatch, killed_run, lambda path: worker is not None and not _gone(worker)+ )+ with pytest.raises(_FirstHeartbeat): # not refused+ runner.run(killed_run, gpu_factory=_fake_gpu)+ assert worker_running == [False]+ else:+ capsys.readouterr()+ assert main(["stop", str(killed_run)]) == 0+ # A zombie alone has nothing to kill; a worker in its group is killed through it.+ assert ("killed server_launcher" in capsys.readouterr().out) == orphan+ assert worker is None or _gone(worker)+++STOPPED_AT = "2026-10-25T01:00:00+00:00"+++def _mark_stopped(run_dir: Path) -> bytes:+ """What `stop` writes before it kills the runner; returns run.json as it is then."""+ info = load_run_info(run_dir)+ write_run_info(run_dir, info.model_copy(update={"status": "stopped", "finished_at": STOPPED_AT}))+ return (run_dir / RUN_INFO_FILE).read_bytes()+++def test_a_runner_stopped_after_it_registered_leaves_before_the_server_and_keeps_the_run_stopped(+ killed_run: Path,+) -> None:+ # `stop` marked the run after the runner registered, and the kill did not reach the runner.+ stopped: list[bytes] = []++ def open_gpu(description: str) -> Gpu:+ stopped.append(_mark_stopped(killed_run))+ return _fake_gpu(description)++ with pytest.raises(runner.RunStopped):+ runner.run(killed_run, gpu_factory=open_gpu)++ assert (killed_run / RUN_INFO_FILE).read_bytes() == stopped[0]+ assert runner.read_heartbeat(killed_run).get("server") is None+ assert not (killed_run / "server-default.log").exists()+ assert _scratch_file(killed_run).read_text() == "left by the killed runner" # `stop` removes it+ assert not (killed_run / "report.html").exists()+++def test_a_runner_that_finishes_after_a_stop_keeps_the_run_stopped(+ killed_run: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ append_record(killed_run, _record(load_run_info(killed_run).plan[0], 1)) # nothing left to run+ stop_surviving_server = runner.stop_surviving_server++ def stop_arrives(run_dir: Path) -> None:+ stop_surviving_server(run_dir)+ _mark_stopped(run_dir)++ monkeypatch.setattr(runner, "stop_surviving_server", stop_arrives)+ runner.run(killed_run, gpu_factory=_fake_gpu)++ info = load_run_info(killed_run)+ assert (info.status, info.finished_at) == ("stopped", STOPPED_AT)diff --git a/tests/family_e2e/test_server.py b/tests/family_e2e/test_server.pynew file mode 100644index 0000000000..4ddd654330--- /dev/null+++ b/tests/family_e2e/test_server.py@@ -0,0 +1,458 @@+import errno+import os+import shutil+import socket+import sqlite3+import subprocess+import sys+import time+import typing+from contextlib import closing+from pathlib import Path++import psutil+import pytest+import yaml++from invokeai.app.services.config.config_default import InvokeAIAppConfig+from scripts.family_e2e import server+from scripts.family_e2e.manifest import ServerSpec+from scripts.family_e2e.server import (+ DROPPED_SETTINGS,+ SCRATCH_PATHS,+ TEMPLATE_PATHS,+ ServerError,+ ServerProcess,+ build_scratch_root,+ server_env,+ spawn_in_job,+ template_server_running,+ verify_interpreter,+)++# Waiting for a helper process to report that it is ready.+CHILD_POLL_S = 0.01+CHILD_TIMEOUT_S = 30.0+++def _rows(database: str | Path, uri: bool = False) -> list[str]:+ with closing(sqlite3.connect(database, uri=uri)) as conn:+ return [row[0] for row in conn.execute("SELECT name FROM models ORDER BY name")]+++def _template(tmp_path: Path, settings: dict) -> Path:+ root = tmp_path / "template"+ (root / "databases").mkdir(parents=True)+ conn = sqlite3.connect(root / "databases" / "invokeai.db")+ conn.execute("CREATE TABLE models (name TEXT)")+ conn.execute("INSERT INTO models VALUES ('flux')")+ conn.commit()+ conn.close()+ (root / "databases" / "invokeai_backup_1.db").write_bytes(b"old")+ (root / "invokeai.yaml").write_text(yaml.safe_dump({"schema_version": "4.0.3", **settings}))+ return root+++def test_scratch_root_points_back_at_the_template_and_keeps_run_output_local(tmp_path: Path) -> None:+ elsewhere = tmp_path / "nodes-elsewhere"+ template = _template(+ tmp_path,+ {+ "models_dir": "my-models",+ "custom_nodes_dir": str(elsewhere),+ "outputs_dir": "out",+ "fonts_storage_dir": "uploaded",+ "port": 9090,+ "host": "0.0.0.0",+ "log_level": "warning",+ "ssl_certfile": "cert.pem",+ "device_working_mem_gb": 6,+ "enable_partial_loading": False,+ },+ )+ scratch = tmp_path / "scratch"+ log_file = tmp_path / "run" / "server-default.log"+ build_scratch_root(template, scratch, log_file, port=9321)++ config = yaml.safe_load((scratch / "invokeai.yaml").read_text())+ assert config["models_dir"] == str((template / "my-models").resolve())+ assert config["download_cache_dir"] == str((template / "models/.download_cache").resolve())+ assert config["custom_nodes_dir"] == str(elsewhere.resolve())+ # Stores the database owns are reconciled with the scratch database, so they must not be the template's.+ for name, relative in (+ ("outputs_dir", "outputs"),+ ("db_dir", "databases"),+ ("fonts_storage_dir", "fonts-uploaded"),+ ("style_presets_dir", "style_presets"),+ ("workflow_thumbnails_dir", "workflow_thumbnails"),+ ):+ assert config[name] == str(scratch / relative), name+ assert (config["host"], config["port"]) == ("127.0.0.1", 9321)+ assert config["log_handlers"] == ["console", f"file={log_file}"]+ assert (config["log_format"], config["log_level"]) == ("plain", "info")+ assert (config["image_index_enabled"], config["clear_queue_on_startup"]) == (False, True)+ assert "ssl_certfile" not in config+ # Memory settings decide residency and peaks; they must reach the scratch server unchanged.+ assert (config["device_working_mem_gb"], config["enable_partial_loading"]) == (6, False)+ assert [p.name for p in (scratch / "databases").iterdir()] == ["invokeai.db"]+ assert _rows(scratch / "databases" / "invokeai.db") == ["flux"]+ # The template's database was read immutable: SQLite left no -wal/-shm beside it.+ assert sorted(p.name for p in (template / "databases").iterdir()) == ["invokeai.db", "invokeai_backup_1.db"]+++def test_snapshot_includes_the_wal_of_an_unclean_stop_without_changing_it(tmp_path: Path) -> None:+ template = _template(tmp_path, {})+ db_dir = template / "databases"+ live = tmp_path / "live"+ live.mkdir()+ shutil.copy(db_dir / "invokeai.db", live / "invokeai.db")+ conn = sqlite3.connect(live / "invokeai.db")+ conn.execute("PRAGMA journal_mode=WAL")+ conn.execute("INSERT INTO models VALUES ('sdxl')")+ conn.commit()+ # A server killed at this point leaves the committed row in the WAL only.+ for name in ("invokeai.db", "invokeai.db-wal", "invokeai.db-shm"):+ shutil.copy(live / name, db_dir / name)+ conn.close()+ before = {name: (db_dir / name).read_bytes() for name in ("invokeai.db", "invokeai.db-wal")}+ assert _rows(f"{(db_dir / 'invokeai.db').as_uri()}?immutable=1", uri=True) == ["flux"] # the main file alone++ build_scratch_root(template, tmp_path / "scratch", tmp_path / "a.log", port=1)+ assert _rows(tmp_path / "scratch" / "databases" / "invokeai.db") == ["flux", "sdxl"]+ assert {name: (db_dir / name).read_bytes() for name in before} == before++[email protected](sys.platform != "win32", reason="open-file detection is Windows-only")+def test_database_open_in_another_process_is_refused(tmp_path: Path) -> None:+ template = _template(tmp_path, {})+ conn = sqlite3.connect(template / "databases" / "invokeai.db")+ try:+ conn.execute("SELECT 1").fetchall()+ with pytest.raises(ServerError, match="open in another process"):+ build_scratch_root(template, tmp_path / "scratch", tmp_path / "a.log", port=1)+ finally:+ conn.close()+ build_scratch_root(template, tmp_path / "scratch", tmp_path / "a.log", port=1)+++def test_scratch_root_is_rebuilt_from_scratch(tmp_path: Path) -> None:+ template = _template(tmp_path, {})+ scratch = tmp_path / "scratch"+ build_scratch_root(template, scratch, tmp_path / "a.log", port=1)+ (scratch / "outputs").mkdir()+ (scratch / "outputs" / "stale.png").write_bytes(b"x")+ build_scratch_root(template, scratch, tmp_path / "a.log", port=2)+ assert not (scratch / "outputs").exists()+ assert yaml.safe_load((scratch / "invokeai.yaml").read_text())["models_dir"] == str((template / "models").resolve())+++ ("settings", "message"),+ [+ ({"db_url": "mariadb+pymysql://u:p@db/invokeai"}, "only a SQLite database"),+ ({"schema_version": "3.0.0"}, "start its server once"),+ ],+)+def test_templates_the_tool_cannot_copy_are_refused(tmp_path: Path, settings: dict, message: str) -> None:+ template = _template(tmp_path, settings)+ with pytest.raises(ServerError, match=message):+ build_scratch_root(template, tmp_path / "scratch", tmp_path / "a.log", port=1)+ assert not (tmp_path / "scratch").exists()+++def test_template_without_database_is_refused(tmp_path: Path) -> None:+ template = _template(tmp_path, {})+ (template / "databases" / "invokeai.db").unlink()+ with pytest.raises(ServerError, match="no database"):+ build_scratch_root(template, tmp_path / "scratch", tmp_path / "a.log", port=1)+++def test_path_settings_cover_every_path_field_of_the_app_config() -> None:+ # A new path setting must be classified: left relative, it would resolve against the scratch root.+ path_fields = {+ name: field.default+ for name, field in InvokeAIAppConfig.model_fields.items()+ if Path in (field.annotation, *typing.get_args(field.annotation))+ }+ assert set(path_fields) == set(TEMPLATE_PATHS) | set(SCRATCH_PATHS) | {"ssl_certfile", "ssl_keyfile"}+ for name, default in TEMPLATE_PATHS.items():+ assert path_fields[name] == (None if default is None else Path(default)), name+ for name, relative in SCRATCH_PATHS.items():+ assert path_fields[name] == Path(relative), name+ assert set(DROPPED_SETTINGS) <= set(InvokeAIAppConfig.model_fields)+++def test_template_port_in_use_is_detected() -> None:+ with socket.socket() as listener:+ listener.bind(("127.0.0.1", 0))+ listener.listen()+ port = listener.getsockname()[1]+ assert template_server_running({"port": port, "host": "0.0.0.0"})+++def test_server_env_drops_inherited_invokeai_settings(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("INVOKEAI_PORT", "9090")+ monkeypatch.setenv("FAMILY_E2E_TEST_KEEP", "1")+ spec = ServerSpec(template_root=tmp_path, python=Path(sys.executable), code_dir=tmp_path, env={"INVOKEAI_X": "y"})+ env = server_env(spec)+ assert "INVOKEAI_PORT" not in env+ assert (env["FAMILY_E2E_TEST_KEEP"], env["INVOKEAI_X"], env["PYTHONPATH"]) == ("1", "y", str(tmp_path))+++ ("settings", "expected"),+ [+ ({"device": "cuda:1"}, {"device": "cuda:0"}),+ ({"generation_devices": ["cuda:0", "cuda:1"]}, {"generation_devices": "auto"}),+ ({"device": "cuda:1", "generation_devices": ["cuda:1"]}, {"device": "cuda:0", "generation_devices": "auto"}),+ ({"device": "cpu", "generation_devices": ["cpu"]}, {"device": "cpu", "generation_devices": ["cpu"]}),+ ],+)+def test_a_server_pinned_to_one_cuda_device_gets_no_other_cuda_index(+ tmp_path: Path, settings: dict, expected: dict+) -> None:+ template = _template(tmp_path, settings)++ build_scratch_root(template, tmp_path / "pinned", tmp_path / "a.log", port=1, single_cuda_device=True)+ build_scratch_root(template, tmp_path / "unpinned", tmp_path / "a.log", port=1)++ pinned = yaml.safe_load((tmp_path / "pinned" / "invokeai.yaml").read_text())+ assert {key: pinned[key] for key in expected} == expected+ unpinned = yaml.safe_load((tmp_path / "unpinned" / "invokeai.yaml").read_text())+ assert {key: unpinned[key] for key in settings} == settings+++def test_the_device_pin_overrides_the_inherited_cuda_visible_devices(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "0,1")+ spec = ServerSpec(template_root=tmp_path, python=Path(sys.executable), code_dir=tmp_path)+ env = server_env(spec, {"CUDA_VISIBLE_DEVICES": "GPU-aaaaaaaa"})+ assert env["CUDA_VISIBLE_DEVICES"] == "GPU-aaaaaaaa"+++def test_interpreter_must_import_invokeai_from_the_code_dir(tmp_path: Path) -> None:+ code_dir = tmp_path / "code"+ code_dir.mkdir()+ spec = ServerSpec(template_root=tmp_path, python=Path(sys.executable), code_dir=code_dir)+ # Nothing to import in code_dir: the interpreter finds the installed package elsewhere, or none.+ with pytest.raises(ServerError):+ verify_interpreter(spec, server.server_env(spec))+ (code_dir / "invokeai").mkdir()+ (code_dir / "invokeai" / "__init__.py").write_text("")+ assert Path(verify_interpreter(spec, server.server_env(spec))).is_relative_to(code_dir)+++def _spawn_tree(tmp_path: Path) -> tuple[subprocess.Popen[bytes], server.KillOnCloseJob | None, list[psutil.Process]]:+ """A process that starts a sleeping child, like a venv launcher and the server it runs; returns the whole tree."""+ pid_file = tmp_path / "pids.txt"+ script = tmp_path / "tree.py"+ # Written whole and closed before the rename, so whatever the name holds once readable is complete.+ script.write_text(+ "import os, subprocess, sys, time\n"+ "child = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)'])\n"+ f"tmp = {str(pid_file) + '.tmp'!r}\n"+ "with open(tmp, 'w') as f:\n"+ " f.write(f'{os.getpid()} {child.pid}')\n"+ f"os.replace(tmp, {str(pid_file)!r})\n"+ "time.sleep(60)\n"+ )+ process, job = spawn_in_job([sys.executable, str(script)])+ deadline = time.monotonic() + CHILD_TIMEOUT_S+ while True:+ assert process.poll() is None and time.monotonic() < deadline+ try:+ # Windows can refuse to open a file right after it was renamed into place, e.g. while a scanner holds it.+ text = pid_file.read_text()+ break+ except OSError:+ time.sleep(CHILD_POLL_S)+ interpreter, grandchild = (int(pid) for pid in text.split())+ tree = [psutil.Process(process.pid), *psutil.Process(process.pid).children(recursive=True)]+ assert {interpreter, grandchild} <= {p.pid for p in tree}+ return process, job, tree++[email protected](sys.platform != "win32", reason="job objects are Windows-only")+def test_closing_the_job_kills_the_whole_server_tree(tmp_path: Path) -> None:+ # What the runner's death does to its server: the job handle closes.+ process, job, tree = _spawn_tree(tmp_path)+ assert job is not None+ job.close()+ _, alive = psutil.wait_procs(tree, timeout=10)+ assert alive == []+ process.wait(timeout=10)+++def test_stop_kills_the_server_tree_and_never_a_process_by_its_recorded_pid(tmp_path: Path) -> None:+ process, job, tree = _spawn_tree(tmp_path)+ # The serving pid recorded at launch now belongs to an unrelated process (pid reuse).+ unrelated = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])+ try:+ console = (tmp_path / "console.log").open("ab")+ stopped = ServerProcess(+ process=process,+ console=console,+ log_path=tmp_path / "server.log",+ base_url="http://127.0.0.1:1",+ serving=psutil.Process(unrelated.pid),+ cmd=[],+ invokeai_file="",+ job=job,+ )+ stopped.stop()+ _, alive = psutil.wait_procs(tree, timeout=10)+ assert alive == []+ assert unrelated.poll() is None+ finally:+ unrelated.kill()+ unrelated.wait()+++def _gone(process: psutil.Process) -> bool:+ try:+ return process.status() == psutil.STATUS_ZOMBIE+ except psutil.NoSuchProcess:+ return True++[email protected](sys.platform == "win32", reason="POSIX process groups; on Windows the job object holds the tree")[email protected]("reaped", [False, True], ids=["leader-exited", "leader-reaped"])+def test_terminate_kills_the_group_even_after_its_leader_exited(tmp_path: Path, reaped: bool) -> None:+ # A launcher whose child outlives it: the child is in no tree any more, but still in the launcher's group.+ pid_file = tmp_path / "child.txt"+ script = tmp_path / "launcher.py"+ script.write_text(+ "import os, subprocess, sys\n"+ "child = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)'])\n"+ f"tmp = {str(pid_file) + '.tmp'!r}\n"+ "with open(tmp, 'w') as f:\n"+ " f.write(str(child.pid))\n"+ f"os.replace(tmp, {str(pid_file)!r})\n"+ )+ process, job = spawn_in_job([sys.executable, str(script)])+ leader = psutil.Process(process.pid)+ deadline = time.monotonic() + CHILD_TIMEOUT_S+ # Exited but not reaped, as the runner first meets a crashed launcher.+ while leader.status() != psutil.STATUS_ZOMBIE:+ assert time.monotonic() < deadline+ time.sleep(CHILD_POLL_S)+ child = psutil.Process(int(pid_file.read_text()))+ if reaped: # as ServerProcess.alive() or Popen.communicate() may have done before+ assert process.poll() is not None+ try:+ server.terminate(process, job)+ _, alive = psutil.wait_procs([child], timeout=CHILD_TIMEOUT_S)+ assert alive == []+ finally:+ if not _gone(child):+ child.kill()++[email protected](sys.platform == "win32", reason="POSIX zombies; Windows does not reap")[email protected]("waitid", [True, False], ids=["waitid", "no-waitid"])+def test_a_dead_server_reads_as_dead_but_stays_unreaped_until_terminate(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, waitid: bool+) -> None:+ # Its pid is its group's id: reaped before terminate() killed the group, the id could pass to another group.+ if waitid and not hasattr(os, "waitid"):+ pytest.skip("this platform has no os.waitid (macOS)")+ if not waitid:+ monkeypatch.delattr(os, "waitid", raising=False) # as on macOS, also where it exists+ process, job = spawn_in_job([sys.executable, "-c", "import sys; sys.exit(3)"])+ leader = psutil.Process(process.pid)+ deadline = time.monotonic() + CHILD_TIMEOUT_S+ while leader.status() != psutil.STATUS_ZOMBIE:+ assert time.monotonic() < deadline+ time.sleep(CHILD_POLL_S)+ dead = ServerProcess(+ process=process,+ console=(tmp_path / "console.log").open("ab"),+ log_path=tmp_path / "server.log",+ base_url="http://127.0.0.1:1",+ serving=leader,+ cmd=[],+ invokeai_file="",+ job=job,+ )++ assert not dead.alive()+ # Without waitid the code of an unreaped process is not to be had.+ assert dead.end_status() == ("exit code 3" if waitid else "exit code unknown")+ assert leader.status() == psutil.STATUS_ZOMBIE++ dead.stop()+ assert not leader.is_running()++[email protected](sys.platform == "win32", reason="POSIX process groups")[email protected]("member", ["zombie", "living"])+def test_a_refused_group_kill_fails_only_while_a_member_lives(monkeypatch: pytest.MonkeyPatch, member: str) -> None:+ # macOS refuses (EPERM) to signal a group whose only member is a zombie; then there is nothing to kill.+ code = "pass" if member == "zombie" else "import time; time.sleep(60)"+ process, _ = spawn_in_job([sys.executable, "-c", code]) # it leads a group of its own+ leader = psutil.Process(process.pid)+ try:+ deadline = time.monotonic() + CHILD_TIMEOUT_S+ while member == "zombie" and leader.status() != psutil.STATUS_ZOMBIE:+ assert time.monotonic() < deadline+ time.sleep(CHILD_POLL_S)++ def refuse(pgid: int, sig: int) -> None:+ raise PermissionError(errno.EPERM, "Operation not permitted")++ monkeypatch.setattr(os, "killpg", refuse)+ if member == "zombie":+ server.kill_group(process.pid)+ else:+ with pytest.raises(PermissionError):+ server.kill_group(process.pid)+ finally:+ process.kill()+ process.wait()+++def test_terminate_waits_until_the_tree_released_the_scratch_root(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ # The server and a process it started hold the scratch database open, as SQLite does. Windows refuses to delete+ # an open file, so a single removal attempt right after terminate() succeeds only if it waited for the tree.+ monkeypatch.setattr(server, "REMOVE_ATTEMPTS", 1)+ root = tmp_path / "scratch"+ (root / "databases").mkdir(parents=True)+ ready = tmp_path / "ready"+ wal = root / "databases" / "invokeai.db-wal"+ child = tmp_path / "child.py"+ child.write_text(f"import time\nwal = open({str(wal)!r}, 'w')\ntime.sleep(60)\n")+ script = tmp_path / "holder.py"+ script.write_text(+ "import os, subprocess, sys, time\n"+ f"db = open({str(root / 'databases' / 'invokeai.db')!r}, 'w')\n"+ f"subprocess.Popen([sys.executable, {str(child)!r}])\n"+ f"while not os.path.exists({str(wal)!r}): time.sleep(0.01)\n"+ f"open({str(ready)!r}, 'w').close()\n"+ "time.sleep(60)\n"+ )+ process, job = spawn_in_job([sys.executable, str(script)])+ deadline = time.monotonic() + CHILD_TIMEOUT_S+ while not ready.exists():+ assert process.poll() is None and time.monotonic() < deadline+ time.sleep(CHILD_POLL_S)++ tree = [psutil.Process(process.pid), *psutil.Process(process.pid).children(recursive=True)]+ server.terminate(process, job)+ assert [p.pid for p in tree if p.is_running()] == []+ assert server.remove_tree(root) == []+ assert not root.exists()++[email protected](sys.platform != "win32", reason="only Windows refuses to delete an open file")+def test_files_that_cannot_be_removed_are_reported(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(server, "REMOVE_ATTEMPTS", 2)+ monkeypatch.setattr(server, "REMOVE_RETRY_S", 0.0)+ root = tmp_path / "scratch"+ (root / "databases").mkdir(parents=True)+ held = root / "databases" / "invokeai.db"+ with held.open("w"):+ assert server.remove_tree(root) == [str(held)]+ assert server.remove_tree(root) == []