Skip to content

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.

fix(tests): keep the guards the slow marker would have removed

Alexander Eichhorn90a8979de62a
diff --git a/.github/workflows/python-tests.yml b/.github/workflows/python-tests.yml
index 3b47bef370..6fbaf82680 100644
--- a/.github/workflows/python-tests.yml
+++ b/.github/workflows/python-tests.yml
@@ -109,4 +109,4 @@ jobs:
# `logical`, not `auto`: xdist's `auto` asks psutil for *physical* cores, which is half
# the vCPUs a standard runner exposes. Much of the suite waits on timers and polls, so
# one worker per vCPU is the right level.
- run: uv run --no-sync pytest -n logical
+ run: uv run --no-sync pytest -n logical --max-worker-restart=0
diff --git a/AGENTS.md b/AGENTS.md
index cfca97e803..a4f58493e8 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -65,7 +65,7 @@ If the environment cannot spawn subagents, perform separate self-review passes w
- Use **pnpm 10**, never npm/yarn, for frontends and docs. Each package owns its lockfile. Use `pnpm -C <package> ...`; `.nvmrc` records the development Node version. Read the package scripts instead of assuming root Makefile frontend commands target webv2.
- Use the existing Python environment and `uv.lock`. For a fresh test environment: `uv sync --locked --extra test`; do not replace a configured accelerator environment with a different backend as routine setup.
- From the root: `uv tool run [email protected] check <paths>` and `uv tool run [email protected] format --check <paths>`. Python uses 120-column formatting and absolute imports. Respect configured vendored-code exclusions.
-- Run focused Python tests with `uv run --no-sync pytest <test-paths>`; the full CI suite is `uv run --no-sync pytest -n logical` (xdist; each file's tests stay on a single worker). Slow tests are excluded by default; hardware validation is separate.
+- Run focused Python tests with `uv run --no-sync pytest <test-paths>`; the full CI suite is `uv run --no-sync pytest -n logical` (xdist; each file's tests stay on a single worker). Slow tests are excluded by default and no job runs them, so marking a test `slow` removes it from automated protection; hardware validation is separate.
- `uv run --no-sync mypy scripts/invokeai-web.py` is an additional diagnostic using the current exclusions, not an enforced CI gate. Do not describe it as comprehensive type coverage.
- Choose checks by changed behavior. Broaden to the milestone's required gates before review; do not repeatedly rerun unchanged checks without a reason.
- Install local hooks with `uv run --no-sync pre-commit install` after test dependencies are available. Hook installation is local to each checkout and is not implied by committing the configuration.
diff --git a/tests/AGENTS.md b/tests/AGENTS.md
index e0543565b0..3b2a90f5ca 100644
--- a/tests/AGENTS.md
+++ b/tests/AGENTS.md
@@ -7,7 +7,7 @@
- Prefer real temporary SQLite/filesystem/tensor operations when they establish the behavior. Mock external services, expensive models, or unavailable hardware at an appropriate interface; never mock away the transaction, authorization, concurrency, or numerical behavior being checked.
- Isolate filesystem paths, databases, account identities, clocks, random seeds, environment changes, and network behavior. Clean up subprocesses, listeners, patches, and resources. Never use production model/database/output directories.
- Exercise rollback, revisions, cross-user isolation, retries, cancellation, resource bounds, and cleanup when affected. Frontend IndexedDB, Web Locks, focus, and rendering belong in webv2's real-browser tests.
-- Run `uv run --no-sync pytest <test-paths>` from the root for focused checks; CI uses `uv run --no-sync pytest -n logical`, which runs the suite across xdist workers (one per vCPU). Configuration excludes `slow` by default. Use `-m slow` for selected slow tests or `-m ""` to include them deliberately.
+- Run `uv run --no-sync pytest <test-paths>` from the root for focused checks; CI uses `uv run --no-sync pytest -n logical`, which runs the suite across xdist workers (one per vCPU). Configuration excludes `slow` by default and no job runs `-m slow`, so the marker removes a test from automated protection rather than moving it to a slower tier. Use `-m slow` for selected slow tests or `-m ""` to include them deliberately.
- Tests must pass under parallel execution, in any file order. `--dist loadfile` (set in `addopts`) keeps a file's tests on one worker, but which files a worker gets is arbitrary: a file must establish its own process-global state (the JWT secret, for example) instead of inheriting it from a file that happens to run earlier. Verify a new file passes when run on its own.
-- Assert behavior, not wall-clock duration or throughput. Such thresholds measure the runner once workers share its cores; mark an unavoidable benchmark `slow` rather than tuning its threshold.
+- Assert behavior, not throughput or latency: those measure the runner once workers share its cores. A generous ceiling that separates "finishes" from "hangs" is fine, and CPU time survives contention where wall clock does not. Where a measurement is unavoidably a benchmark, mark it `slow` -- knowing that nothing will run it -- rather than tuning its threshold.
- Hardware tests need explicit prerequisites and honest reporting of skips/unavailable devices. Passing mocked or CPU tests does not establish CUDA/ROCm/MPS/XPU behavior.
diff --git a/tests/app/services/auth/test_password_utils.py b/tests/app/services/auth/test_password_utils.py
index a8a9ec4aa2..4f080c442d 100644
--- a/tests/app/services/auth/test_password_utils.py
+++ b/tests/app/services/auth/test_password_utils.py
@@ -333,3 +333,15 @@ class TestPasswordSecurityProperties:
assert hashed.startswith("$2")
# Bcrypt hashes are 60 characters long
assert len(hashed) == 60
+
+ def test_hashing_cost_stays_at_a_defensible_work_factor(self):
+ """The cost factor is what makes a stolen hash expensive to attack.
+
+ Read from the hash rather than timed: a passlib default drift or an explicit
+ `bcrypt__rounds` low enough to make hashing trivial is invisible to every other assertion
+ here -- the `$2`, length and round-trip checks all hold at cost factor 4 -- and a timing
+ threshold could not run alongside the rest of the suite on a shared CI core anyway.
+ """
+ rounds = int(hash_password("TestPassword123").split("$")[2])
+
+ assert rounds >= 12, f"bcrypt cost factor dropped to {rounds}"
diff --git a/tests/app/services/shared/test_for_scheduler_performance.py b/tests/app/services/shared/test_for_scheduler_performance.py
index 40ec8c8346..1fe48825d6 100644
--- a/tests/app/services/shared/test_for_scheduler_performance.py
+++ b/tests/app/services/shared/test_for_scheduler_performance.py
@@ -1,12 +1,9 @@
"""Scheduler behavior and overhead for trivial loop bodies.
-The two overhead tests assert wall-clock budgets and per-item ratios, so they are marked `slow`
-and excluded from the default run: once CI spreads the suite over xdist workers sharing the
-runner's cores, those numbers measure the runner. Run them with
-`pytest -m slow tests/app/services/shared/test_for_scheduler_performance.py`.
-
-The completion-state tests below them are not benchmarks -- they assert `GraphExecutionState`
-invariants in milliseconds and keep running by default.
+`test_loop_scheduler_overhead_is_linear` measures CPU time, not wall clock: it compares per-item
+cost at two sizes, and CPU time is not inflated when xdist workers share the runner's cores. The
+absolute budget below it is machine-dependent and stays `slow`, as does the sibling
+`test_graph_execution_performance.py`. The completion-state tests are not benchmarks at all.
"""
import time
@@ -36,21 +33,21 @@ def _run_trivial_loop(loop_type: str, count: int) -> float:
graph.add_edge(create_edge("body", "value", "collect", "item"))
state = GraphExecutionState(graph=graph)
context = Mock()
- started = time.perf_counter()
+ started = time.process_time()
while (node := state.next()) is not None:
state.complete(node.id, node.invoke(context))
assert state.is_complete()
- return time.perf_counter() - started
+ return time.process_time() - started
@pytest.mark.parametrize("loop_type", ["iterate", "for"])
def test_loop_scheduler_overhead_is_linear(loop_type: str) -> None:
timings = {count: [] for count in (300, 1200)}
for _ in range(3):
for count in (1200, 300):
- # perf_counter, not process_time: the latter ticks at ~15ms on Windows, so a 300-item
- # loop measures as 0.0 and the ratio below is compared against zero.
+ # CPU time, so a worker losing the core to a sibling does not read as scheduler cost.
+ # Both sizes take hundreds of milliseconds, well clear of the ~15ms clock granularity
+ # that made this measurement unusable when the loops were cheaper.
timings[count].append(_run_trivial_loop(loop_type, count) / count)
# Best-of-N is the noise-tolerant estimator for a lower bound: shared CI hosts inflate any
# single sample (a GC pause or a scheduler hiccup), and the median of three still fell over
diff --git a/tests/backend/model_manager/load/state_dicts/utils.py b/tests/backend/model_manager/load/state_dicts/utils.py
index f751490f19..575570e2ea 100644
--- a/tests/backend/model_manager/load/state_dicts/utils.py
+++ b/tests/backend/model_manager/load/state_dicts/utils.py
@@ -11,3 +11,16 @@ import torch
def keys_to_mock_state_dict(keys: dict[str, list[int]]) -> dict[str, torch.Tensor]:
"""Build a state dict of empty tensors from a {key: shape} mapping."""
return {k: torch.empty(shape) for k, shape in keys.items()}
+
+
+def token_extents(shape: list[int]) -> list[int]:
+ """Shrink a captured shape to token extents, keeping its rank.
+
+ A fixture whose tests read key names, dtypes, values and rank does not need the real extents,
+ and the real ones are ruinous: the FLUX.2 mixed-fp8 layout alone is 2.3 billion elements, more
+ memory than a CI runner has once the suite runs across several processes. Use this only where
+ no assertion and no code path under test reads a size -- where the layout has to stay exact
+ (a fused qkv that gets split into thirds, say), expand a single element to the full shape
+ instead.
+ """
+ return [min(extent, 4) for extent in shape]
diff --git a/tests/backend/model_manager/load/test_anima_scaled_fp8_keys.py b/tests/backend/model_manager/load/test_anima_scaled_fp8_keys.py
index cd0412f9b1..7cd1c3c194 100644
--- a/tests/backend/model_manager/load/test_anima_scaled_fp8_keys.py
+++ b/tests/backend/model_manager/load/test_anima_scaled_fp8_keys.py
@@ -32,19 +32,11 @@ from tests.backend.model_manager.load.state_dicts.anima_transformer_scaled_fp8_k
from tests.backend.model_manager.load.state_dicts.anima_transformer_scaled_fp8_keys import (
state_dict_keys as anima_keys,
)
+from tests.backend.model_manager.load.state_dicts.utils import token_extents
_DTYPES = {"F8_E4M3": FP8_DTYPE, "F32": torch.float32, "BF16": torch.bfloat16, "U8": torch.uint8}
-def _capped(shape: list[int]) -> list[int]:
- """Token extents for a captured layout.
-
- Only key names, dtypes, values and rank are asserted here, never a size, so the real extents
- buy nothing and cost GBs -- more than parallel CI test processes can hold at once.
- """
- return [min(extent, 4) for extent in shape]
-
-
def _build_state_dict() -> dict[str, torch.Tensor]:
"""Rebuild the checkpoint. `comfy_quant` markers are real JSON blobs, not placeholders.
@@ -61,12 +53,12 @@ def _build_state_dict() -> dict[str, torch.Tensor]:
# parses the blob. Python's `False` would not parse and the flag would vanish.
sd[key] = torch.frombuffer(bytearray(json.dumps(blob).encode()), dtype=torch.uint8).clone()
elif torch_dtype is FP8_DTYPE:
- sd[key] = torch.zeros(_capped(shape), dtype=FP8_DTYPE)
+ sd[key] = torch.zeros(token_extents(shape), dtype=FP8_DTYPE)
elif key.endswith((".weight_scale", ".input_scale")):
# 1.0 is the placeholder `_usable_input_scale` rejects, so it must not be used here.
- sd[key] = torch.full(_capped(shape), 2.5, dtype=torch_dtype)
+ sd[key] = torch.full(token_extents(shape), 2.5, dtype=torch_dtype)
else:
- sd[key] = torch.zeros(_capped(shape), dtype=torch_dtype)
+ sd[key] = torch.zeros(token_extents(shape), dtype=torch_dtype)
return _filter_non_model_keys(_strip_anima_bundle_prefix(sd))
diff --git a/tests/backend/model_manager/load/test_flux1_scaled_fp8_keys.py b/tests/backend/model_manager/load/test_flux1_scaled_fp8_keys.py
index 98abe792e3..23ddac02ef 100644
--- a/tests/backend/model_manager/load/test_flux1_scaled_fp8_keys.py
+++ b/tests/backend/model_manager/load/test_flux1_scaled_fp8_keys.py
@@ -21,31 +21,23 @@ from invokeai.backend.quantization.fp8_scaled import (
from tests.backend.model_manager.load.state_dicts.flux1_transformer_scaled_fp8_keys import (
state_dict_keys as scaled_keys,
)
+from tests.backend.model_manager.load.state_dicts.utils import token_extents
_DTYPES = {"F8_E4M3": FP8_DTYPE, "F32": torch.float32, "BF16": torch.bfloat16}
-def _capped(shape: list[int]) -> list[int]:
- """Token extents for a captured layout.
-
- Only key names, dtypes, values and rank are asserted here, never a size, so the real extents
- buy nothing and cost GBs -- more than parallel CI test processes can hold at once.
- """
- return [min(extent, 4) for extent in shape]
-
-
def _build_state_dict() -> dict[str, torch.Tensor]:
sd: dict[str, torch.Tensor] = {}
for key, (shape, dtype) in scaled_keys.items():
torch_dtype = _DTYPES[dtype]
if torch_dtype is FP8_DTYPE:
- sd[key] = torch.zeros(_capped(shape), dtype=FP8_DTYPE)
+ sd[key] = torch.zeros(token_extents(shape), dtype=FP8_DTYPE)
elif key.endswith((".scale_weight", ".scale_input")):
# Real checkpoints carry calibrated scales; 1.0 is the placeholder value that
# `_usable_input_scale` deliberately rejects, so it must not be used here.
- sd[key] = torch.full(_capped(shape), 2.5, dtype=torch_dtype)
+ sd[key] = torch.full(token_extents(shape), 2.5, dtype=torch_dtype)
else:
- sd[key] = torch.zeros(_capped(shape), dtype=torch_dtype)
+ sd[key] = torch.zeros(token_extents(shape), dtype=torch_dtype)
return sd
@@ -140,9 +132,9 @@ def test_bundle_conversion_keeps_the_scales_at_full_precision() -> None:
"model.diffusion_model.double_blocks.0.img_attn.norm.key_norm.scale": torch.ones(128, dtype=torch.float32),
"model.diffusion_model.double_blocks.0.img_attn.qkv.weight_scale": torch.full((), 2.5, dtype=torch.float32),
"model.diffusion_model.double_blocks.0.img_attn.qkv.scale_weight": torch.full((), 2.5, dtype=torch.float32),
- "model.diffusion_model.double_blocks.0.img_attn.qkv.weight": torch.zeros(9216, 3072, dtype=torch.float32).to(
- FP8_DTYPE
- ),
+ # Allocated as fp8 directly: the float32 round trip this once took is four bytes per
+ # element for a result that holds one.
+ "model.diffusion_model.double_blocks.0.img_attn.qkv.weight": torch.zeros(9216, 3072, dtype=FP8_DTYPE),
}
converted = convert_bundle_to_flux_transformer_checkpoint(sd)
diff --git a/tests/backend/model_manager/load/test_flux2_fp8mixed_keys.py b/tests/backend/model_manager/load/test_flux2_fp8mixed_keys.py
index 9653c5fe6a..bbf9fb3de4 100644
--- a/tests/backend/model_manager/load/test_flux2_fp8mixed_keys.py
+++ b/tests/backend/model_manager/load/test_flux2_fp8mixed_keys.py
@@ -14,6 +14,7 @@ from invokeai.backend.quantization.fp8_scaled import FP8_DTYPE, is_scale_metadat
from tests.backend.model_manager.load.state_dicts.flux2_transformer_fp8mixed_keys import (
state_dict_keys as mixed_keys,
)
+from tests.backend.model_manager.load.state_dicts.utils import token_extents
_DTYPES = {"F8_E4M3": FP8_DTYPE, "F32": torch.float32, "BF16": torch.bfloat16}
@@ -24,17 +25,16 @@ def _mock_state_dict() -> dict[str, torch.Tensor]:
"""Builds the captured layout at a token size.
The assertions below read key names, dtypes, values and -- in one case -- rank; none reads an
- extent. Materializing the real extents means 2.3 billion elements, which peaks at ~15GB per
- call and cannot be afforded once CI runs several test processes at once, so every dimension is
- capped while rank and dtype are kept exactly as captured.
+ extent. Materializing the real extents means 2.3 billion elements: ~5GB for one call, and a
+ ~15GB peak across this file, which cannot be afforded once CI runs several test processes at
+ once. Every dimension is capped while rank and dtype are kept exactly as captured.
"""
sd: dict[str, torch.Tensor] = {}
for key, (shape, dtype) in mixed_keys.items():
if key.endswith((".weight_scale", ".input_scale")):
sd[key] = torch.tensor(SCALE_VALUE, dtype=torch.float32)
else:
- token_shape = [min(extent, 4) for extent in shape]
- sd[key] = torch.ones(token_shape, dtype=_DTYPES[dtype])
+ sd[key] = torch.ones(token_extents(shape), dtype=_DTYPES[dtype])
return sd
diff --git a/tests/backend/model_manager/load/test_flux2_scaled_fp8_keys.py b/tests/backend/model_manager/load/test_flux2_scaled_fp8_keys.py
index 1acd3c7275..3f8422d4c8 100644
--- a/tests/backend/model_manager/load/test_flux2_scaled_fp8_keys.py
+++ b/tests/backend/model_manager/load/test_flux2_scaled_fp8_keys.py
@@ -20,16 +20,22 @@ _DTYPES = {"F8_E4M3": FP8_DTYPE, "F32": torch.float32, "BF16": torch.bfloat16}
def _build_state_dict() -> dict[str, torch.Tensor]:
+ """Builds the captured layout at exact extents but almost no storage.
+
+ The extents matter here -- the fused qkv is split into thirds, so they cannot be capped the
+ way the sibling fixtures are -- but the values do not, so each tensor is one element expanded
+ to its full shape. Materializing 5.6e8 elements instead costs ~2GB, which is more than the
+ CI test processes can hold alongside one another.
+ """
sd: dict[str, torch.Tensor] = {}
for key, (shape, dtype) in klein_keys.items():
torch_dtype = _DTYPES[dtype]
- if torch_dtype is FP8_DTYPE:
- sd[key] = torch.zeros(shape, dtype=torch.float32).to(FP8_DTYPE)
- elif key.endswith((".weight_scale", ".input_scale")):
+ if key.endswith((".weight_scale", ".input_scale")):
# 1.0 is the placeholder `_usable_input_scale` rejects, so it must not be used here.
- sd[key] = torch.full(shape, 2.5, dtype=torch_dtype)
+ fill = 2.5
else:
- sd[key] = torch.zeros(shape, dtype=torch_dtype)
+ fill = 0.0
+ sd[key] = torch.full((), fill, dtype=torch_dtype).expand(shape)
return sd
diff --git a/tests/backend/model_manager/load/test_z_image_scaled_fp8_keys.py b/tests/backend/model_manager/load/test_z_image_scaled_fp8_keys.py
index 2d02104012..8403c39252 100644
--- a/tests/backend/model_manager/load/test_z_image_scaled_fp8_keys.py
+++ b/tests/backend/model_manager/load/test_z_image_scaled_fp8_keys.py
@@ -17,6 +17,7 @@ from invokeai.backend.quantization.fp8_scaled import (
extract_comfy_quant_hints,
extract_fp8_scaled_layers,
)
+from tests.backend.model_manager.load.state_dicts.utils import token_extents
from tests.backend.model_manager.load.state_dicts.z_image_transformer_scaled_fp8_keys import (
state_dict_keys as scaled_keys,
)
@@ -24,22 +25,13 @@ from tests.backend.model_manager.load.state_dicts.z_image_transformer_scaled_fp8
_DTYPES = {"F8_E4M3": FP8_DTYPE, "F32": torch.float32, "BF16": torch.bfloat16}
-def _capped(shape: list[int]) -> list[int]:
- """Token extents for a captured layout.
-
- Only key names, dtypes, values and rank are asserted here, never a size, so the real extents
- buy nothing and cost GBs -- more than parallel CI test processes can hold at once.
- """
- return [min(extent, 4) for extent in shape]
-
-
def _mock_state_dict(scale_value: float = 4.0) -> dict[str, torch.Tensor]:
sd: dict[str, torch.Tensor] = {}
for key, (shape, dtype) in scaled_keys.items():
if key.endswith(".scale_weight"):
- sd[key] = torch.full(_capped(shape), scale_value, dtype=torch.float32)
+ sd[key] = torch.full(token_extents(shape), scale_value, dtype=torch.float32)
else:
- sd[key] = torch.ones(_capped(shape), dtype=_DTYPES[dtype])
+ sd[key] = torch.ones(token_extents(shape), dtype=_DTYPES[dtype])
return sd
diff --git a/tests/conftest.py b/tests/conftest.py
index dc7de96b48..ea386ff898 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -6,6 +6,7 @@
# play well with fixtures (F401 and F811), so this is cleaner than importing in all files that use these fixtures.
import logging
import shutil
+import sys
from pathlib import Path
import pytest
@@ -109,3 +110,49 @@ def invokeai_root_dir(tmp_path_factory) -> Path:
temp_dir: Path = tmp_path_factory.mktemp("data") / "invokeai_root"
shutil.copytree(root_template, temp_dir)
return temp_dir
+
+
+# --- Peak memory reporting -------------------------------------------------------------------
+#
+# Running the suite across xdist workers multiplies its memory footprint, and the failure mode is
+# silent: the runner is killed mid-run, so there is no summary, no failing test and no clue which
+# file was responsible. Reporting each worker's peak turns a future blow-up into a number that
+# moves in the CI log before it takes a runner down. `--max-worker-restart=0` in the workflow
+# makes the death itself fail the run immediately rather than after sixteen restarts.
+
+_worker_peak_rss: dict[str, int] = {}
+
+
+def _peak_rss_bytes() -> int:
+ if sys.platform == "win32":
+ import psutil
+
+ return psutil.Process().memory_info().peak_wset
+ import resource
+
+ peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
+ # ru_maxrss is bytes on macOS and kilobytes on Linux.
+ return peak if sys.platform == "darwin" else peak * 1024
+
+
+def pytest_sessionfinish(session: pytest.Session) -> None:
+ """Hands this worker's peak to the controller; `workeroutput` exists only in a worker."""
+ output = getattr(session.config, "workeroutput", None)
+ if output is not None:
+ output["peak_rss_bytes"] = _peak_rss_bytes()
+
+
+def pytest_testnodedown(node, error) -> None: # noqa: ANN001 # xdist types are not exported
+ peak = getattr(node, "workeroutput", {}).get("peak_rss_bytes")
+ if peak is not None:
+ _worker_peak_rss[node.gateway.id] = peak
+
+
+def pytest_terminal_summary(terminalreporter) -> None: # noqa: ANN001
+ if not _worker_peak_rss:
+ return
+ peaks = _worker_peak_rss.values()
+ terminalreporter.write_line(
+ f"peak RSS: {max(peaks) / 2**30:.2f}GB worst worker, "
+ f"{sum(peaks) / 2**30:.2f}GB summed over {len(_worker_peak_rss)} workers"
+ )