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
fix(calibration): enforce attempt exclusivity for retries (#10077)
Guishi Wang503528cde12c
diff --git a/docs/src/content/docs/development/Architecture/model-manager.mdx b/docs/src/content/docs/development/Architecture/model-manager.mdxindex 4478428a03..12f246215e 100644--- a/docs/src/content/docs/development/Architecture/model-manager.mdx+++ b/docs/src/content/docs/development/Architecture/model-manager.mdx@@ -1136,7 +1136,7 @@ A calibration run measures one model's operations on this machine's GPU; estimat1. `POST /api/v2/models/i/{key}/working_memory/calibrate` takes a client-built graph, the identities of the models it names (`graph_models`), batch data, an optional `idempotency_key`, and an optional `attempt_id` with its `attempt_steps`. The server turns off `use_cache` on every node, sets `is_intermediate` on every node and clears the `board` of every `WithBoard` node (a node saves its images with its own flag and that board), sets `runs=1`, sets the graph's id to the run id, and sets the origin to `invokeai:wm-calibration:<run_id>` and the destination to `invokeai:wm-calibration`. It records the run, enqueues the batch as the requesting admin, then records the run's items.- An `attempt_id` (1–64 of letters, digits, `_ - . :`) groups the runs one owner enqueues for one calibration attempt (two owners that send one id start two attempts), and `attempt_steps` (1–256) says how many runs the attempt queues. They come together or not at all (422); the server does not read a count out of the id. Both are stored on the run (and left out of the file when absent, so older readers keep reading such runs) and returned in the run summaries of the status and the model summary. Every run of an attempt sends the same `attempt_steps`: a run that sends another count than the attempt's runs already stored, or a repeat of a keyed request that changes it, is refused with 409 (checked under the store file's lock, so two such runs cannot both be recorded).- - One attempt runs on a device class at a time: its steps measure the GPU back to back, each on what the last one left, and another attempt's items between them would measure neither. A run of an attempt is refused with 409 and `detail` `{"code": "calibration_running", "message": "Another calibration is still running on this GPU. Wait until it has finished, or stop it, then calibrate again."}` while the queue holds an item that is pending, in progress or waiting of another attempt's run in the device class's file (`get_unfinished_origins`, read under the file's lock, which the queue takes only outside its transactions), and, with the message `Another calibration on this GPU is between its steps. Try again in a moment, or once it has finished.` under the same code, while another owner's attempt is open: between its steps, short of `attempt_steps` runs, not aborted (no other run since its first included), its model as its runs recorded it, and active within `ATTEMPT_IDLE_GRACE` (two minutes) of its newest run's creation or the latest observation of one of its items. The client posts the next step as soon as the last one finished; a step that runs long is running, and its last observation starts the wait. An attempt idle for longer is taken for abandoned: it blocks nothing, and, short of steps, never feeds. The grace is measured on the stored times against the clock now, so a jump of the wall clock lengthens or shortens it once. The owner's own open attempt blocks nothing while none of its runs is running: an open attempt is almost always one whose submission stopped partway (a full queue, a lost connection, a closed tab), and the owner's new attempt replaces it; the replaced one stays short, so aborted, and a later step of it is refused as interleaved. The attempt's own next steps pass, and so does a repeat of a keyed request that finds its run. A later step of an attempt after any other run of the device class was created since the attempt's first run, another attempt's or one without an attempt (a script's, the family E2E tool's: it measured the GPU in between too), is refused with 409 and `detail` `{"code": "calibration_interleaved", "message": "Another calibration ran on this GPU after this calibration started, so its measurements can no longer be combined. Calibrate again."}`: it would measure the GPU after that calibration, not after its own earlier steps. The attempt then stays short and is aborted; an attempt another run was created between the first and the last run of is aborted too, should a store hold one (`_interleaved_attempts`). Two clients that start attempts at once cannot both pass: every creation of an attempt's run holds one OS file lock, `<db_dir>/working_memory/creations/attempts.lock`, from finding or recording the run to recording its items, in every process serving the root, so the later creation finds the earlier one's items queued. The creation takes it before its run's creation lock (below), and it is a file of its own: on a file they shared, the second lock would wait for the first. A run without an `attempt_id` takes neither the lock nor the check.+ - One attempt runs on a device class at a time: its steps measure the GPU back to back, each on what the last one left, and another attempt's items between them would measure neither. A run of an attempt is refused with 409 and `detail` `{"code": "calibration_running", "message": "Another calibration is still running on this GPU. Wait until it has finished, or stop it, then calibrate again."}` while the queue holds an item that is pending, in progress or waiting of another attempt's run in the device class's file (`get_unfinished_origins`, read under the file's lock, which the queue takes only outside its transactions), and, with the message `Another calibration on this GPU is between its steps. Try again in a moment, or once it has finished.` under the same code, while another owner's attempt is open: between its steps, short of `attempt_steps` runs, not aborted (no other run since its first included), its model as its runs recorded it, and active within `ATTEMPT_IDLE_GRACE` (two minutes) of its newest run's creation or the latest observation of one of its items. The client posts the next step as soon as the last one finished; a step that runs long is running, and its last observation starts the wait. An attempt idle for longer is taken for abandoned: it blocks nothing, and, short of steps, never feeds. The grace is measured on the stored times against the clock now, so a jump of the wall clock lengthens or shortens it once. The owner's own open attempt blocks nothing while none of its runs is running: an open attempt is almost always one whose submission stopped partway (a full queue, a lost connection, a closed tab), and the owner's new attempt replaces it; the replaced one stays short, so aborted, and a later step of it is refused as interleaved. The attempt's own next steps pass, and so does a repeat of a keyed request that finds its run. A later step of an attempt after any other run of the device class was created since the attempt's first run, another attempt's or one without an attempt (a script's, the family E2E tool's: it measured the GPU in between too), is refused with 409 and `detail` `{"code": "calibration_interleaved", "message": "Another calibration ran on this GPU after this calibration started, so its measurements can no longer be combined. Calibrate again."}`: it would measure the GPU after that calibration, not after its own earlier steps. The attempt then stays short and is aborted; an attempt another run was created between the first and the last run of is aborted too, should a store hold one (`_interleaved_attempts`). Two clients that start attempts at once cannot both pass: every creation of an attempt's run holds one OS file lock, `<db_dir>/working_memory/creations/attempts.lock`, from finding or recording the run to recording its items, in every process serving the root, so the later creation finds the earlier one's items queued. The creation takes it before its run's creation lock (below), and it is a file of its own: on a file they shared, the second lock would wait for the first. A run without an `attempt_id` takes neither the lock nor the check. A retry of calibration items from the queue (`retry_items_by_id`) is held to the same rule, and holds the same lock from its check through its commit (`retry_admission`): it is refused under `calibration_interleaved` once another run began on the device class since the first run of its item's attempt, and under `calibration_running` while another attempt runs or is open between its steps (for an item of a run without an attempt, its owner's attempt too), with messages of its own that say to retry later or to calibrate again. The whole request is refused, its other items included. A retry of a run without an attempt measures the GPU after every attempt begun before it, as a run created then would: the run notes when it began (`retried_at`), and it cuts those attempts off the same way, so neither a later step nor a retry of a step of theirs is accepted. An attempt whose last step failed is complete, so not open, and such a retry may begin; the step's own retry is then refused rather than measuring after it.- The graph names each model it loads as the client compiled it (`ModelIdentifierField`: key, hash, name, base, type), in a node's field or inside one, such as the LoRAs of a collection loader, or as a mapping of that shape in an untyped field, such as a metadata node's record of a model (`graph_model_identifiers`): in the graph's JSON a client cannot tell the two apart. The request states the identity of each of those models as the record the graph was compiled over had it, in `graph_models`: per model key its `hash`, `base`, `type`, `format` and `variant` (`CalibrationCompiledModel`), every one of them required (`format` and `variant` null when the record has none; `hash`, `base` and `type` never null). It names exactly the graph's models; a missing or extra key or an unstated fact is refused with 422. The identities come from the records the graph was compiled over, never from a read at posting time, which would carry the change the comparison has to catch. Under the run's creation locks (below), the creation reads each model's record once and compares it with the graph's identifier and with its `graph_models` entry. A model whose record differs in any of those facts, or that was removed, refuses the request with 409 and `detail` `{"code": "model_changed", "message": "<name> changed after this calibration was planned (<facts>). Calibrate again."}`, the facts among `hash`, `base`, `type`, `format` and `variant`, or with the message `<name> was removed after this calibration was planned. Calibrate again.` So a run always measures the configuration its graph was compiled for. The run records the identity of its model as that comparison read it: `model_hash`, and `model_identity` (base, type, format and variant); and that of every model the graph names, with its hash (`graph_models`), which equals what the client compiled against. A change after that is caught at admission. The run id does not derive from `graph_models`, so a keyed repeat that finds its run without items and has to enqueue its batch also compares its `graph_models` with what the run recorded (an entry the run lacks, or a recorded entry without a hash, compares only what it has); a difference is refused with the same coded 409, since the item would fail at admission on what the run recorded. A later run of an attempt is refused the same way when its model differs from what an earlier run of the attempt recorded for it, or a model its graph names differs from what an earlier run recorded for that model, the hash included (a graph compiled after a reinstall names the new hash): the attempt would measure two versions of a model, and, short of that step, it never feeds a fit. The message names the model that changed.- The queue takes all of the batch's items or none (`enqueue_batch(..., all_or_none=True)`, checked under its admission lock): a run with only some of its cases would measure only some of them. Without room for all of them nothing is enqueued, the key stays unused, and the run is removed if this request recorded it.- With a key, the run id is derived from the owner, the key, the request's fingerprint (the model key, the graph without its id, and the batch data) and the `attempt_id` if given. A client that sends no graph id would otherwise get a fresh one each time and could never repeat a request. A repeated request finds its run and gets the same response; nothing new is enqueued, even after the queue collected the key's receipt. A key therefore names one run. Once a reset removed the run, a repeat is refused (404) whether or not the queue still keeps the receipt: the store keeps the ids of removed runs, so the run is never started again and its queued items keep failing at admission. Another request that reuses the key (another model, graph, batch data or `attempt_id`) gets another run id and so another origin. While the key's receipt exists, that request is refused (409) and the first run stays; the receipt is checked before the request's model, so an unknown model does not turn the refusal into a 404. Once the queue has collected the acknowledged receipt, the request starts a run of its own. Clients make each key unique per run of an attempt, for example from the attempt id and the step. Acknowledge the key through `POST /api/v1/queue/{queue_id}/enqueue_batch/acknowledge`.@@ -1161,7 +1161,7 @@ A calibration run measures one model's operations on this machine's GPU; estimatThe store has one JSON file per device class at `<db_dir>/working_memory/<device_class_id>.json` (`CalibrationStoreFile`, `schema_version` 1). It is machine data, so it lives next to the database rather than inside it. It holds:- the device class, with its id;-- the runs: model key, the model's hash and identity at creation (`model_hash`, `model_identity`), owner, environment and its soft facts at creation, queue items, whether an enqueue of the run's batch may have committed (`enqueue_attempted`), and for each item the last status the runner saw, why admission failed it (`error_code`), and every retry of an item, recorded pending as the queue commits it until the runner sees it; how many of the queue's retry operations that retry items of the run are in flight, however many items each retries (`retries_in_flight`); the models the graph names as they were then (`graph_models`); the soft facts, the `model_identity`, the `graph_models`, the `retries_in_flight`, the `error_code`, the `attempt_id` and the `attempt_steps` are left out when absent (or 0), so runs stored without them still load and older readers still read runs that lack them;+- the runs: model key, the model's hash and identity at creation (`model_hash`, `model_identity`), owner, environment and its soft facts at creation, queue items, whether an enqueue of the run's batch may have committed (`enqueue_attempted`), and for each item the last status the runner saw, why admission failed it (`error_code`), and every retry of an item, recorded pending as the queue commits it until the runner sees it; how many of the queue's retry operations that retry items of the run are in flight, however many items each retries (`retries_in_flight`); for a run without an attempt, when a retry of its items last began (`retried_at`); the models the graph names as they were then (`graph_models`); the soft facts, the `model_identity`, the `graph_models`, the `retries_in_flight`, the `retried_at`, the `error_code`, the `attempt_id` and the `attempt_steps` are left out when absent (or 0), so runs stored without them still load and older readers still read runs that lack them;- the points: `MeasuredWindow` plus `env_id`;- the environments those reference;- the ids of the runs with a retry key that a reset removed (`removed_run_ids`), so that a repeat of the request that started one cannot start it again. They are kept for good, about 40 bytes per removed run. A run without a key gets a fresh id and is never repeated, so its id is not kept;diff --git a/invokeai/app/api/routers/session_queue.py b/invokeai/app/api/routers/session_queue.pyindex 4b8f010c79..c44722590d 100644--- a/invokeai/app/api/routers/session_queue.py+++ b/invokeai/app/api/routers/session_queue.py@@ -9,6 +9,7 @@ from pydantic import BaseModelfrom invokeai.app.api.auth_dependencies import AdminUserOrDefault, CurrentUserOrDefaultfrom invokeai.app.api.dependencies import ApiDependenciesfrom invokeai.app.api.routers.image_move_maintenance import assert_image_move_maintenance_inactive+from invokeai.app.api.routers.working_memory import coded_conflictfrom invokeai.app.invocations.fields import ImageField, VideoFieldfrom invokeai.app.services.progress_previews.progress_previews_common import ProgressPreviewDTOfrom invokeai.app.services.session_processor.session_processor_common import SessionProcessorStatus@@ -43,6 +44,8 @@ from invokeai.app.services.shared.pagination import SQLiteDirectionfrom invokeai.app.services.video_records.video_records_common import VideoRecordNotFoundExceptionfrom invokeai.app.services.working_memory_calibration.working_memory_calibration_common import (CALIBRATION_ORIGIN_PREFIX,+ CalibrationAttemptBusyError,+ CalibrationAttemptInterleavedError,CalibrationStoreError,is_reserved_origin,)@@ -625,6 +628,13 @@ def cancel_by_destination(operation_id="retry_items_by_id",responses={200: {"model": RetryItemsResult},+ 409: {+ "description": "The items include a working-memory calibration's whose retry would break attempt "+ "exclusivity on its GPU: no item is retried, the request's other items included. Carries a code, as "+ '`{"code": ..., "message": ...}` in `detail`: `calibration_running`, another calibration attempt still '+ "runs on that GPU or is between its steps (also for an item of a calibration without an attempt); "+ "`calibration_interleaved`, another calibration ran on that GPU since the item's attempt began"+ },503: {"description": "The items include a working-memory calibration's, and its store cannot be written now ""(unwritable root, lock timeout): no item is retried, the request's other items included"@@ -639,7 +649,10 @@ def retry_items_by_id("""Retries the given queue items. Users can only retry their own items unless they are an admin.A calibration item's retry is recorded in the calibration store as it commits. When that store cannot be written,- the request retries nothing, also its items that are no calibration's (503); retry again once it can."""+ the request retries nothing, also its items that are no calibration's (503); retry again once it can. A calibration+ item whose retry would measure between another calibration attempt's steps, or after another calibration cut its+ own attempt off, refuses the whole request too, generations included (409 with a code). The web UI retries one+ item per request; an API client that retries several at once should retry its calibration items on their own."""try:# Check queue membership for all items and ownership for non-admins.valid_item_ids: list[int] = []@@ -669,6 +682,8 @@ def retry_items_by_id()except HTTPException:raise+ except (CalibrationAttemptBusyError, CalibrationAttemptInterleavedError) as error:+ raise coded_conflict(error) from errorexcept CalibrationStoreError:# The error names the store's path on the server.raise HTTPException(diff --git a/invokeai/app/api/routers/working_memory.py b/invokeai/app/api/routers/working_memory.pyindex d1477ac479..694f9a7002 100644--- a/invokeai/app/api/routers/working_memory.py+++ b/invokeai/app/api/routers/working_memory.py@@ -67,12 +67,20 @@ def _service() -> WorkingMemoryCalibrationServiceBase:return service+def coded_conflict(+ error: CalibrationAttemptBusyError | CalibrationAttemptInterleavedError | CalibrationModelChangedError,+) -> HTTPException:+ """The 409 of a calibration refusal a client acts on: coded, as other routes' refusals a client acts on are, as+ `{"code": ..., "message": ...}` in `detail`, which tells these 409s from the others. Also the queue's retry+ route's, which refuses a retry of calibration items that would break attempt exclusivity."""+ return HTTPException(status_code=409, detail={"code": error.code, "message": str(error)})++def _http_error(error: Exception) -> HTTPException:if isinstance(error, (CalibrationAttemptBusyError, CalibrationAttemptInterleavedError, CalibrationModelChangedError)):- # Coded, as other routes' refusals a client acts on are: it tells these 409s from the others.- return HTTPException(status_code=409, detail={"code": error.code, "message": str(error)})+ return coded_conflict(error)if isinstance(error, (CalibrationRunNotFoundError, UnknownModelException)):return HTTPException(status_code=404, detail=str(error))if isinstance(error, CalibrationGraphError):diff --git a/invokeai/app/services/session_queue/session_queue_default.py b/invokeai/app/services/session_queue/session_queue_default.pyindex 95ba79b2fe..78c05f23c3 100644--- a/invokeai/app/services/session_queue/session_queue_default.py+++ b/invokeai/app/services/session_queue/session_queue_default.py@@ -2,6 +2,7 @@ import asyncioimport hashlibimport jsonimport math+from contextlib import nullcontextfrom datetime import datetime, timedelta, timezonefrom typing import Any, Literal, Optional, cast@@ -1286,21 +1287,26 @@ class SessionQueue(SessionQueueBase):# pruned before anything else saw it. Announcing a retry cannot promise that: the server may stop before the# announcement is handled. So the store counts the retries in flight before they commit and records them# after, and a count left over keeps the attempt out.+ # The store also refuses a retry that would measure between another calibration attempt's steps, or after+ # another calibration cut its own attempt off. Its check and the commit hold the lock every attempt's creation+ # holds through its enqueue (`retry_admission`): no attempt starts between them.calibration = self.__invoker.services.working_memory_calibrationin_flight = None+ sources: dict[int, tuple[Optional[str], int]] = {}if calibration is not None:origin_at, retried_from_at = ITEM_COLUMNS.index("origin"), ITEM_COLUMNS.index("retried_from_item_id")- in_flight = calibration.retries_starting(- {root_item_id: (values[origin_at], values[retried_from_at]) for root_item_id, _, values in clones}- )- try:- admitted = self._queries.run(admit)- except Exception:- if calibration is not None and in_flight is not None:- # A failure once `admit` ended can be the commit's own, which may have committed all the same (a lost- # connection to MySQL or MariaDB): which retries exist is unknown, and the count stays.- calibration.retries_committed(in_flight, None if admit_ended else [])- raise+ sources = {root_item_id: (values[origin_at], values[retried_from_at]) for root_item_id, _, values in clones}+ with calibration.retry_admission(sources) if calibration is not None else nullcontext():+ if calibration is not None:+ in_flight = calibration.retries_starting(sources)+ try:+ admitted = self._queries.run(admit)+ except Exception:+ if calibration is not None and in_flight is not None:+ # A failure once `admit` ended can be the commit's own, which may have committed all the same (a+ # lost connection to MySQL or MariaDB): which retries exist is unknown, and the count stays.+ calibration.retries_committed(in_flight, None if admit_ended else [])+ raiseif calibration is not None and in_flight is not None:calibration.retries_committed(in_flight,diff --git a/invokeai/app/services/working_memory_calibration/working_memory_calibration_base.py b/invokeai/app/services/working_memory_calibration/working_memory_calibration_base.pyindex 076350b243..799153d073 100644--- a/invokeai/app/services/working_memory_calibration/working_memory_calibration_base.py+++ b/invokeai/app/services/working_memory_calibration/working_memory_calibration_base.py@@ -1,5 +1,6 @@from abc import ABC, abstractmethodfrom collections.abc import Iterable, Mapping+from contextlib import AbstractContextManagerfrom typing import Optionalfrom invokeai.app.services.session_queue.session_queue_common import RetriedQueueItem, SessionQueueItem@@ -32,13 +33,23 @@ class WorkingMemoryCalibrationServiceBase(ABC):def admit(self, queue_item: SessionQueueItem, run_id: str) -> Optional[str]:"""Called by the session runner before a calibration item runs: None to run it, or why it must fail."""+ @abstractmethod+ def retry_admission(self, sources: Mapping[int, tuple[Optional[str], int]]) -> AbstractContextManager[None]:+ """Held by the session queue from `retries_starting` through the commit of the retries, `sources` as there:+ when an item is a calibration's, the lock every calibration attempt's creation holds from its checks through+ its enqueue, so that no attempt is created between a retry's checks and its commit. A retry of generations+ alone takes nothing. Raises `CalibrationStoreError` when the lock cannot be taken: the queue retries nothing."""+@abstractmethoddef retries_starting(self, sources: Mapping[int, tuple[Optional[str], int]]) -> Optional[RetriesInFlight]:"""Called by the session queue before it commits retries: per item a retry is made of, that item's origin andthe item its lineage started from. Counts the retries in flight on the runs of the calibration items amongthem, in the store, so that a retry the store then fails to record keeps its attempt from feeding a fit. None- when no item is a calibration's, which touches no store file. Raises `CalibrationStoreError` when the store- cannot be written: the queue then retries nothing."""+ when no item is a calibration's, which touches no store file. Raises `CalibrationAttemptBusyError` or+ `CalibrationAttemptInterleavedError` when retrying one of the calibration items would break attempt exclusivity+ (also an item of a run without an attempt, retried between another attempt's steps), and+ `CalibrationStoreError` when the store cannot be written: the queue then retries nothing, the request's other+ items included."""@abstractmethoddef retries_committed(self, in_flight: RetriesInFlight, retried: Optional[Iterable[RetriedQueueItem]]) -> None:diff --git a/invokeai/app/services/working_memory_calibration/working_memory_calibration_common.py b/invokeai/app/services/working_memory_calibration/working_memory_calibration_common.pyindex cee7d02cc0..b93d8502c4 100644--- a/invokeai/app/services/working_memory_calibration/working_memory_calibration_common.py+++ b/invokeai/app/services/working_memory_calibration/working_memory_calibration_common.py@@ -268,6 +268,14 @@ class CalibrationRun(_StoreModel):"record: a retry may exist that the run does not record, so the run's attempt never feeds a fit until a reset ""removes the run",)+ retried_at: Optional[datetime.datetime] = Field(+ default=None,+ description="Only for a run without an attempt: when the queue last began a retry of items of it, as the "+ "retry was checked and counted (`retries_starting`), before it committed. Such a retry measures the GPU "+ "after the runs created before it, as a run created then would, so it cuts off an attempt begun before it "+ "the same way: a later step or retry of that attempt is refused. Kept also when the retry then committed "+ "nothing. Absent until a retry of the run began",+ )@model_validator(mode="after")def _steps_belong_to_an_attempt(self) -> "CalibrationRun":@@ -279,7 +287,7 @@ class CalibrationRun(_StoreModel):def _omit_absent_fields(self, handler: SerializerFunctionWrapHandler) -> dict:# Written only when set: a run without them stays readable by a version that forbids the unknown fields.data = handler(self)- for name in ("attempt_id", "attempt_steps", "soft", "model_identity"):+ for name in ("attempt_id", "attempt_steps", "soft", "model_identity", "retried_at"):if data.get(name) is None:data.pop(name, None)if not data.get("graph_models"):diff --git a/invokeai/app/services/working_memory_calibration/working_memory_calibration_default.py b/invokeai/app/services/working_memory_calibration/working_memory_calibration_default.pyindex 01df4f433f..992bda51f9 100644--- a/invokeai/app/services/working_memory_calibration/working_memory_calibration_default.py+++ b/invokeai/app/services/working_memory_calibration/working_memory_calibration_default.py@@ -7,14 +7,14 @@ import threadingimport uuidimport weakreffrom bisect import bisect_left, bisect_right-from collections.abc import AsyncIterator, Callable, Iterable, Mapping-from contextlib import AbstractContextManager, ExitStack, asynccontextmanager+from collections.abc import AsyncIterator, Callable, Iterable, Iterator, Mapping+from contextlib import AbstractContextManager, ExitStack, asynccontextmanager, contextmanagerfrom dataclasses import dataclassfrom functools import partialfrom itertools import chainfrom pathlib import Pathfrom types import SimpleNamespace-from typing import TYPE_CHECKING, Any, Final, NamedTuple, Optional+from typing import TYPE_CHECKING, Any, Final, Literal, NamedTuple, Optionalimport torch@@ -143,19 +143,36 @@ finished, within seconds; a step that runs long (a large model's largest decode)observation, as the runner settles them, starts the wait. Past it the attempt is taken for abandoned: a client thatwent away. It no longer blocks another attempt, and it never feeds a fit, being short of steps."""-_RUNNING_ELSEWHERE: Final = (- "Another calibration is still running on this GPU. Wait until it has finished, or stop it, then calibrate again."-)--_BETWEEN_STEPS: Final = (- "Another calibration on this GPU is between its steps. Try again in a moment, or once it has finished."-)+_Busy = Literal["running", "between_steps"]+"""Why another attempt holds the device class (`_attempt_blocks`): one of its runs is running, or it is open between+its steps."""++_BUSY: Final[Mapping[_Busy, str]] = {+ "running": "Another calibration is still running on this GPU. Wait until it has finished, or stop it, then "+ "calibrate again.",+ "between_steps": "Another calibration on this GPU is between its steps. Try again in a moment, or once it has "+ "finished.",+}+"""The refusals of a new run of an attempt (`create_run`), by why another attempt holds the device class."""++_RETRY_BUSY: Final[Mapping[_Busy, str]] = {+ "running": "Another calibration is still running on this GPU, and this item would measure in the middle of it. "+ "Retry it once that calibration has finished, or stop it.",+ "between_steps": "Another calibration on this GPU is between its steps, and this item would measure in the middle "+ "of it. Retry it once that calibration has finished.",+}+"""The refusals of a retry of calibration items (`retries_starting`), shown where the queue's retry failed."""_INTERLEAVED: Final = ("Another calibration ran on this GPU after this calibration started, so its measurements can no longer be ""combined. Calibrate again.")+_RETRY_INTERLEAVED: Final = (+ "Another calibration ran on this GPU after this item's calibration started, so a retry could no longer be "+ "combined with that calibration's measurements. Calibrate the model again instead."+)+_ATTEMPTS_LOCK: Final = "calibration-attempts""""This process's gate in front of the lock every attempt's creation takes (`_attempt_lock`)."""@@ -373,11 +390,15 @@ def _lineage_outcomes(def _count_retries(run_ids: frozenset[str], file: CalibrationStoreFile) -> tuple[bool, frozenset[str]]:- """A store change: count one more retry in flight on each run of `run_ids` the file holds. Returns those."""+ """A store change: count one more retry in flight on each run of `run_ids` the file holds, and note on each of+ them without an attempt that a retry of it began now (`retried_at`, `_started_at`). Returns those."""counted = frozenset(run.run_id for run in file.runs if run.run_id in run_ids)+ now = _now()for run in file.runs:if run.run_id in counted:run.retries_in_flight += 1+ if run.attempt_id is None:+ run.retried_at = nowreturn bool(counted), counted@@ -411,19 +432,33 @@ def _last_activity(runs: Iterable[CalibrationRun]) -> datetime.datetime:)+def _started_at(run: CalibrationRun) -> datetime.datetime:+ """When the run last began to measure the GPU on its own account: its creation, or for a run without an attempt+ the latest retry of its items that began since (`retried_at`). A retry of an attempt's run needs no such note: it+ is refused once another run began after the attempt's first (`_cut_off`), and an attempt begun after it is cut+ off by its own first run."""+ return max(run.created_at, run.retried_at) if run.retried_at is not None else run.created_at++def _cut_off(file: CalibrationStoreFile, key: AttemptKey) -> bool:- """Whether another run (another attempt's, or one without an attempt: a script, the family E2E tool) was created- on the device class after the first run of attempt `key`: a later step of it would measure the GPU after that run,- so none is accepted (`CalibrationAttemptInterleavedError`)."""+ """Whether another run (another attempt's, or one without an attempt: a script, the family E2E tool) began on the+ device class after the first run of attempt `key`, created or, without an attempt, retried (`_started_at`): a+ later step of it, or a retry of one of its steps, would measure the GPU after that run, so none is accepted+ (`CalibrationAttemptInterleavedError`)."""own = [run.created_at for run in file.runs if _attempt_key(run) == key]- return bool(own) and any(_attempt_key(run) != key and run.created_at > min(own) for run in file.runs)+ return bool(own) and any(_attempt_key(run) != key and _started_at(run) > min(own) for run in file.runs)def _interleaved_attempts(file: CalibrationStoreFile) -> set[AttemptKey]:- """The attempts another run was created between the first and the last run of: their later steps measured the GPU- after that run, not after their own earlier steps. The calibrate route refuses such a step- (`CalibrationAttemptInterleavedError`), so only a store written otherwise holds one."""- created = sorted(run.created_at for run in file.runs)+ """The attempts another run was created, or retried without an attempt (`retried_at`), between the first and the+ last run of: their later steps measured the GPU after that run, not after their own earlier steps. The calibrate+ route refuses such a step (`CalibrationAttemptInterleavedError`), so only a store written otherwise holds one."""+ created = sorted(+ chain(+ (run.created_at for run in file.runs),+ (run.retried_at for run in file.runs if run.attempt_id is None and run.retried_at is not None),+ )+ )spans: dict[AttemptKey, list[datetime.datetime]] = {}for run in file.runs:if (key := _attempt_key(run)) is not None:@@ -711,7 +746,8 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):"""For a run of an attempt, hold the lock every attempt's creation takes, from the run's record through itsenqueue to the record of its items, in every process serving the root: the next attempt's creation finds theitems of the last one in the queue, and refuses while they run (`CalibrationAttemptBusyError`). The runs of one- attempt are posted one after the other, so they barely wait. A run without an attempt takes no lock."""+ attempt are posted one after the other, so they barely wait. A run without an attempt takes no lock. A retry of+ calibration items holds it too, from its checks through its commit (`retry_admission`)."""if request.attempt_id is None:yieldreturn@@ -928,7 +964,7 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):raise CalibrationAttemptInterleavedError(_INTERLEAVED)# The queue is read under the file's lock; the queue takes it only outside its transactions.if (busy := self._attempt_blocks(file, key)) is not None:- raise CalibrationAttemptBusyError(busy)+ raise CalibrationAttemptBusyError(_BUSY[busy])# The attempt's earlier steps measured the models as they were then: the model calibrated, and every# model their graphs named, hash included, which a graph compiled since names as it is now.for known in file.runs:@@ -963,12 +999,16 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):self._run_files[run_id] = device_class.idreturn _Enqueue(batch, device_class.id, created=created, marks=created)- def _attempt_blocks(self, file: CalibrationStoreFile, key: AttemptKey) -> Optional[str]:+ def _attempt_blocks(self, file: CalibrationStoreFile, key: Optional[AttemptKey]) -> Optional[_Busy]:"""Why another attempt than `key` holds the device class, or None: one of its runs is running (an item pending,in progress or waiting), or another owner's attempt is open. One attempt runs on a device class at a time: itsruns measure the GPU back to back, each step on what the last one left, and another attempt's items in betweenwould measure neither.+ `key` None judges a retry of a run without an attempt (a script's, the family E2E tool's): every attempt counts+ then, its owner's too. The retry would measure between the open attempt's steps and cut it off (`retried_at`,+ `_cut_off`), where its owner's client means to go on with it.+Open: between its steps, short of `attempt_steps` runs (those resets removed included), not aborted (no itemof it canceled or failed for a changed model, no reset that stopped it, no other run since its first), itsmodel as its runs recorded it (`_can_continue`: a later step would be refused otherwise), and active within@@ -979,7 +1019,9 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):aborted, and a later step of it is refused (`_cut_off`).The grace is measured on the stored times against the clock now: a jump of the wall clock lengthens or- shortens it once."""+ shortens it once.++ Called under `_fits_lock` (`_canceled_runs`), and the file's lock."""origins = self._services.session_queue.get_unfinished_origins(DEFAULT_QUEUE_ID, CALIBRATION_ORIGIN_PREFIX)running = {run_id for origin in origins if (run_id := calibration_run_id(origin)) is not None}attempts: dict[AttemptKey, list[CalibrationRun]] = {}@@ -992,11 +1034,11 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):between_steps: list[list[CalibrationRun]] = []for other, runs in attempts.items():if any(run.run_id in running for run in runs):- return _RUNNING_ELSEWHERE+ return "running"removed = notes.get(other)queued, planned = _queued_runs(runs, removed)if (- other[0] == key[0]+ (key is not None and other[0] == key[0])or queued >= plannedor (removed is not None and removed.aborted)or other in interleaved@@ -1010,9 +1052,9 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):canceled, started = self._canceled_runs([run for runs in between_steps for run in runs])for runs in between_steps:if any(run.run_id in started for run in runs):- return _RUNNING_ELSEWHERE+ return "running"if not any(run.run_id in canceled for run in runs):- return _BETWEEN_STEPS+ return "between_steps"return Nonedef _can_continue(self, runs: list[CalibrationRun]) -> bool:@@ -1247,10 +1289,36 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):),)+ @contextmanager+ def retry_admission(self, sources: Mapping[int, tuple[Optional[str], int]]) -> Iterator[None]:+ """While a retry of calibration items is checked (`retries_starting`) and committed, hold the lock every+ attempt's creation holds from its checks through its enqueue (`_attempt_lock`), in every process serving the+ root: a creation then finds the retry queued and refuses while it runs, or the retry finds the run created and+ is refused as `retries_starting` says. A retry of generations alone takes no lock. Raises+ `CalibrationStoreError` when the lock cannot be taken (an unwritable root, a timeout)."""+ if not any(calibration_run_id(origin) is not None for origin, _ in sources.values()):+ yield+ return+ with self._store.attempts_lock():+ yield+def retries_starting(self, sources: Mapping[int, tuple[Optional[str], int]]) -> Optional[RetriesInFlight]:"""Count a retry in flight on each run one of whose items the queue is about to retry, before it commits theretries: the store then records every retry of a calibration item, or keeps its attempt out of every fit.+ Refuse the whole retry when one of its runs no longer owns an exclusive measurement sequence on the device+ class: the run's attempt was cut off by another run created since its first+ (`CalibrationAttemptInterleavedError`), or another attempt holds the device class+ (`CalibrationAttemptBusyError`, `_attempt_blocks`), which also refuses the retry of a run without an attempt+ between another attempt's steps. A count left over in `retries_in_flight` refuses nothing: it would refuse for+ good. The queue calls this under `retry_admission`.++ A run without an attempt notes that a retry of it began (`retried_at`), as it is counted: the retry measures+ the GPU after every attempt begun before it, so it cuts those off as a run created now would (`_cut_off`), and+ a later step or retry of theirs is refused. An attempt whose last step failed is not open, and its own retry+ is the only thing that would go on with it: without the note, a script's retry admitted first, then that+ retry, would let the attempt feed a window measured after the script's.+A retry inherits its source's origin, which names the run: a recreated or restored database that gave arecorded id to an unrelated item cannot make that item's retry the run's, and a bulk retry of generationstouches no store file. A run no usable file holds (a reset removed it) is not counted; its retries fail at@@ -1264,10 +1332,24 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):return Nonerun_ids = frozenset(run_id for run_id, _ in lineages.values())counted: dict[str, frozenset[str]] = {}++ def count(file: CalibrationStoreFile) -> tuple[bool, frozenset[str]]:+ # Every run retried, in the file's order; None stands for the runs without an attempt.+ keys = dict.fromkeys(_attempt_key(run) for run in file.runs if run.run_id in run_ids)+ for key in keys:+ if key is not None and _cut_off(file, key):+ raise CalibrationAttemptInterleavedError(_RETRY_INTERLEAVED)+ if (busy := self._attempt_blocks(file, key)) is not None:+ raise CalibrationAttemptBusyError(_RETRY_BUSY[busy])+ return _count_retries(run_ids, file)+try:for device_class_id in self._store.device_class_ids():try:- marked = self._store.change(device_class_id, partial(_count_retries, run_ids))+ # The attempt check judges other runs' items (`_attempt_blocks`) under the lock that orders those+ # judgements with removals, taken before the file's lock as every holder of both takes them.+ with self._fits_lock:+ marked = self._store.change(device_class_id, count)except CalibrationStoreUnusableError:# Kept as it is and never written: it holds no run a calibration item can be admitted for.continuediff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.jsonindex 49b829af89..cd118f9af6 100644--- a/invokeai/frontend/api/openapi.json+++ b/invokeai/frontend/api/openapi.json@@ -14692,7 +14692,7 @@"put": {"tags": ["queue"],"summary": "Retry Items By Id",- "description": "Retries the given queue items. Users can only retry their own items unless they are an admin.\n\nA calibration item's retry is recorded in the calibration store as it commits. When that store cannot be written,\nthe request retries nothing, also its items that are no calibration's (503); retry again once it can.",+ "description": "Retries the given queue items. Users can only retry their own items unless they are an admin.\n\nA calibration item's retry is recorded in the calibration store as it commits. When that store cannot be written,\nthe request retries nothing, also its items that are no calibration's (503); retry again once it can. A calibration\nitem whose retry would measure between another calibration attempt's steps, or after another calibration cut its\nown attempt off, refuses the whole request too, generations included (409 with a code). The web UI retries one\nitem per request; an API client that retries several at once should retry its calibration items on their own.","operationId": "retry_items_by_id","security": [{@@ -14738,6 +14738,9 @@}}},+ "409": {+ "description": "The items include a working-memory calibration's whose retry would break attempt exclusivity on its GPU: no item is retried, the request's other items included. Carries a code, as `{\"code\": ..., \"message\": ...}` in `detail`: `calibration_running`, another calibration attempt still runs on that GPU or is between its steps (also for an item of a calibration without an attempt); `calibration_interleaved`, another calibration ran on that GPU since the item's attempt began"+ },"503": {"description": "The items include a working-memory calibration's, and its store cannot be written now (unwritable root, lock timeout): no item is retried, the request's other items included"},diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.tsindex 66d531c929..fc0c4bb6d3 100644--- a/invokeai/frontend/api/schema.ts+++ b/invokeai/frontend/api/schema.ts@@ -3530,7 +3530,10 @@ export type paths = {* @description Retries the given queue items. Users can only retry their own items unless they are an admin.** A calibration item's retry is recorded in the calibration store as it commits. When that store cannot be written,- * the request retries nothing, also its items that are no calibration's (503); retry again once it can.+ * the request retries nothing, also its items that are no calibration's (503); retry again once it can. A calibration+ * item whose retry would measure between another calibration attempt's steps, or after another calibration cut its+ * own attempt off, refuses the whole request too, generations included (409 with a code). The web UI retries one+ * item per request; an API client that retries several at once should retry its calibration items on their own.*/put: operations["retry_items_by_id"];post?: never;@@ -68486,6 +68489,13 @@ export interface operations {"application/json": components["schemas"]["RetryItemsResult"];};};+ /** @description The items include a working-memory calibration's whose retry would break attempt exclusivity on its GPU: no item is retried, the request's other items included. Carries a code, as `{"code": ..., "message": ...}` in `detail`: `calibration_running`, another calibration attempt still runs on that GPU or is between its steps (also for an item of a calibration without an attempt); `calibration_interleaved`, another calibration ran on that GPU since the item's attempt began */+ 409: {+ headers: {+ [name: string]: unknown;+ };+ content?: never;+ };/** @description Validation Error */422: {headers: {diff --git a/tests/app/routers/test_working_memory_calibration.py b/tests/app/routers/test_working_memory_calibration.pyindex 1f7cbb83e3..7ba5f55be9 100644--- a/tests/app/routers/test_working_memory_calibration.py+++ b/tests/app/routers/test_working_memory_calibration.py@@ -1,5 +1,6 @@"""The calibration routes and the reserved origin, against a real SQLite queue and a store on a temporary root."""+import asyncioimport threadingfrom pathlib import Pathfrom types import SimpleNamespace@@ -18,6 +19,7 @@ from invokeai.app.invocations.model import LoRACollectionLoader, LoRAField, Modefrom invokeai.app.invocations.sd.sdxl import SDXLModelLoaderInvocationfrom invokeai.app.services.invoker import Invokerfrom invokeai.app.services.model_records import UnknownModelException+from invokeai.app.services.session_queue.session_queue_common import Batchfrom invokeai.app.services.session_queue.session_queue_default import SessionQueuefrom invokeai.app.services.shared.database.database import Databasefrom invokeai.app.services.shared.graph import Graph@@ -255,6 +257,64 @@ def test_a_retry_the_calibration_store_cannot_count_is_refused_with_503_naming_nassert queue.dequeue() is None+def test_a_retry_that_would_break_attempt_exclusivity_is_refused_with_a_coded_409(+ client: TestClient, admin_token: str, calibration+) -> None:+ """A's step failed, and another calibration ran since: A's retry would measure after it. The whole request is+ refused, the generation it also retries included, with the code the calibrate route uses."""+ queue, _ = calibration+ step = {"graph": _graph(), "attempt_id": "model-tab", "attempt_steps": 2}+ [item_id] = _calibrate(client, admin_token, step).json()["item_ids"]+ queue.dequeue()+ queue.fail_queue_item(item_id, "OutOfMemoryError", "out of memory", "")+ [other] = _calibrate(client, admin_token).json()["item_ids"]+ queue.dequeue()+ queue.complete_queue_item(other)+ [generation] = asyncio.run(+ queue.enqueue_batch("default", Batch(graph=Graph.model_validate(_graph()), origin="canvas"), prepend=False)+ ).item_ids+ queue.dequeue()+ queue.fail_queue_item(generation, "ValueError", "failed", "")+ before = queue.get_queue_item_ids("default").item_ids++ response = client.put(+ "/api/v1/queue/default/retry_items_by_id", json=[generation, item_id], headers=_auth(admin_token)+ )++ assert response.status_code == 409, response.text+ assert response.json()["detail"] == {+ "code": "calibration_interleaved",+ "message": "Another calibration ran on this GPU after this item's calibration started, so a retry could no "+ "longer be combined with that calibration's measurements. Calibrate the model again instead.",+ }+ assert queue.get_queue_item_ids("default").item_ids == before+++def test_a_retry_between_another_attempts_steps_is_refused_with_a_coded_409(+ client: TestClient, admin_token: str, calibration+) -> None:+ """A script's run failed; then an attempt started and is between its steps. The script run's retry would measure+ between them."""+ queue, _ = calibration+ [item_id] = _calibrate(client, admin_token).json()["item_ids"]+ queue.dequeue()+ queue.fail_queue_item(item_id, "OutOfMemoryError", "out of memory", "")+ [step] = _calibrate(client, admin_token, {"graph": _graph(), "attempt_id": "tab", "attempt_steps": 2}).json()[+ "item_ids"+ ]+ queue.dequeue()+ queue.complete_queue_item(step)++ response = client.put("/api/v1/queue/default/retry_items_by_id", json=[item_id], headers=_auth(admin_token))++ assert response.status_code == 409, response.text+ assert response.json()["detail"] == {+ "code": "calibration_running",+ "message": "Another calibration on this GPU is between its steps, and this item would measure in the middle "+ "of it. Retry it once that calibration has finished.",+ }++def test_status_reset_and_export_for_admins(client: TestClient, admin_token: str, calibration) -> None:_, service = calibrationrun_id = _calibrate(client, admin_token).json()["run_id"]diff --git a/tests/app/services/working_memory_calibration/test_working_memory_calibration_user_fits.py b/tests/app/services/working_memory_calibration/test_working_memory_calibration_user_fits.pyindex ee5e17017c..045382603e 100644--- a/tests/app/services/working_memory_calibration/test_working_memory_calibration_user_fits.py+++ b/tests/app/services/working_memory_calibration/test_working_memory_calibration_user_fits.py@@ -5,7 +5,8 @@ import builtinsimport datetimeimport jsonimport os-from collections.abc import Iterator, Mapping+import threading+from collections.abc import Callable, Iterator, Mappingfrom contextlib import asynccontextmanagerfrom pathlib import Pathfrom types import SimpleNamespace@@ -56,6 +57,8 @@ from invokeai.backend.working_memory.probe import CounterDelta, MeasuredWindowfrom invokeai.backend.z_image.denoise_working_memory import Z_IMAGE_DENOISE_SPECfrom tests.fixtures.working_memory_calibration import (GPU,+ GPU_CLASS,+ OTHER_CLASS,HeldEnqueue,calibration_service,fake_environment,@@ -822,11 +825,12 @@ def test_each_reset_forgets_what_the_service_kept_of_the_runs_it_removed(tmp_patdef test_every_judgement_of_item_outcomes_holds_the_lock_removals_hold(tmp_path: Path, started, monkeypatch) -> None:"""A removal drops its runs' outcomes under the fits' lock, in the same hold as its store change. Every other- judgement of the store's items (the summary, a new attempt's check of an attempt between its steps, a reset's hold- reasons) reads the queue under it too: none can write back an outcome of a run a removal just dropped, or find- one dropped between checking and reading it."""+ judgement of the store's items (the summary, a new attempt's check of an attempt between its steps, a retry's+ check of it, a reset's hold reasons) reads the queue under it too: none can write back an outcome of a run a+ removal just dropped, or find one dropped between checking and reading it."""service = started(tmp_path)queue = service._services.session_queue+ script = _failed(service, None)settled = _create(service, attempt_id="settled", attempt_steps=1)request = WorkingMemoryCalibrationRequest(graph_models={}, graph=_add_graph(), attempt_id="between-steps", attempt_steps=2@@ -848,11 +852,15 @@ def test_every_judgement_of_item_outcomes_holds_the_lock_removals_hold(tmp_path:service._item_outcomes.clear()with pytest.raises(CalibrationAttemptBusyError):_create(service, attempt_id="next", attempt_steps=1)+ phase = "retry check"+ service._item_outcomes.clear()+ with pytest.raises(CalibrationAttemptBusyError):+ queue.retry_items_by_id("default", script.item_ids)phase = "reset"service._item_outcomes.clear()service.reset_run(settled)- assert held == {"summary": [True], "attempt check": [True], "reset": [True]}+ assert held == {"summary": [True], "attempt check": [True], "retry check": [True], "reset": [True]}def _renumber(tmp_path: Path, run_id: str, item_ids: list[int]) -> None:@@ -1016,25 +1024,61 @@ def test_a_run_whose_items_were_never_recorded_aborts_its_attempt(assert _estimate() == _shipped()-def test_a_retry_queued_between_the_two_queue_reads_holds_its_attempt_back(+def _retry_held_after_its_check(+ monkeypatch: pytest.MonkeyPatch, service: WorkingMemoryCalibrationService, item_ids: list[int], retried: list[int]+) -> Callable[[], None]:+ """Retry `item_ids` in another thread, held once the store checked and counted it (`retries_starting`), as a retry+ whose commit is slow. The function returned lets it commit, the first time it is called, and waits for its end;+ `retried` then holds the retries' ids."""+ queue = service._services.session_queue+ checked, release = threading.Event(), threading.Event()+ starting = service.retries_starting++ def checked_then_held(sources):+ in_flight = starting(sources)+ checked.set()+ assert release.wait(10)+ return in_flight++ monkeypatch.setattr(service, "retries_starting", checked_then_held)+ retrying = threading.Thread(+ target=lambda: retried.extend(+ item.item_id for item in queue.retry_items_by_id("default", item_ids).retried_items+ )+ )+ retrying.start()+ assert checked.wait(10)++ def commit() -> None:+ if not release.is_set():+ release.set()+ retrying.join(10)+ assert not retrying.is_alive()++ return commit+++def test_a_retry_committed_during_a_refresh_holds_its_attempt_back(tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch) -> None:- """The stopped step is retried after the read for running items and before the items are read by id: the refresh- judges the store it read, in which the step ended canceled, so the attempt feeds nothing; the next one finds the- retry running, and the attempt feeds once it completed."""+ """The stopped step's retry was checked and counted before the refresh took the fits' lock, which the check takes+ too, and commits after the refresh read the queue for running items. The refresh judges the store it read: the+ count keeps the attempt out, so it feeds nothing, and no read by id can find the step ended canceled while its+ retry is queued. The next refresh finds the retry running, and the attempt feeds once it completed."""service = started(tmp_path)- _, stopped = _queue_attempt(service, "retried-between-reads", 2)+ _, stopped = _queue_attempt(service, "retried-during-a-refresh", 2)queue = service._services.session_queuequeue.cancel_queue_item(stopped.item_ids[0])- read_by_id = queue.get_queue_item_summaries_by_ids+ read_running = queue.get_unfinished_originsretries: list[int] = []+ commit = _retry_held_after_its_check(monkeypatch, service, stopped.item_ids, retries)- def retry_then_read(*args, **kwargs):- if not retries:- retries.extend(item.item_id for item in queue.retry_items_by_id("default", stopped.item_ids).retried_items)- return read_by_id(*args, **kwargs)+ def read_then_commit(*args, **kwargs):+ origins = read_running(*args, **kwargs)+ commit()+ return origins- monkeypatch.setattr(queue, "get_queue_item_summaries_by_ids", retry_then_read)+ monkeypatch.setattr(queue, "get_unfinished_origins", read_then_commit)service.refresh_user_fits()assert retries and _estimate() == _shipped()@@ -1375,7 +1419,8 @@ def test_a_retry_queued_as_a_reset_takes_the_files_lock_still_stops_the_attempt(tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch, reset: str) -> None:"""The failed step's retry is queued by the time the reset reads the queue, under the file's lock: the reset finds- the attempt running and stops it for good. Resetting the model is what the UI does."""+ the attempt running and stops it for good. Resetting the model is what the UI does. The retry was checked before+ the reset took the fits' lock, which its check takes too, and commits while the reset holds it."""service = started(tmp_path)queue = service._services.session_queue_, failed = _queue_attempt(service, "retried-while-reset", 2)@@ -1384,12 +1429,10 @@ def test_a_retry_queued_as_a_reset_takes_the_files_lock_still_stops_the_attempt(assert _estimate() == _user_bytes(1024)change = service._store.changeretried: list[int] = []+ commit = _retry_held_after_its_check(monkeypatch, service, failed.item_ids, retried)def retry_then_change(*args, **kwargs):- if not retried:- # Marked first: the retry's own changes of the file pass.- retried.append(-1)- retried.extend(item.item_id for item in queue.retry_items_by_id("default", failed.item_ids).retried_items)+ commit()return change(*args, **kwargs)monkeypatch.setattr(service._store, "change", retry_then_change)@@ -1738,6 +1781,308 @@ def test_a_calibration_between_two_steps_of_an_attempt_refuses_its_next_step(tmpassert runs[first.run_id] == "aborted_attempt"[email protected]("other_status", ["completed", "running"])+def test_a_retry_after_another_attempt_started_is_refused(tmp_path: Path, started, other_status: str) -> None:+ service = started(tmp_path)+ queue = service._services.session_queue+ request_a = WorkingMemoryCalibrationRequest(+ graph_models={}, graph=_add_graph(), attempt_id="tab-a", attempt_steps=2+ )+ failed = asyncio.run(service.create_run("model-a", request_a, "system"))+ _settle_as_the_runner(service, failed.run_id, failed.item_ids, "failed")++ request_b = WorkingMemoryCalibrationRequest(+ graph_models={}, graph=_add_graph(), attempt_id="tab-b", attempt_steps=2+ )+ other = asyncio.run(service.create_run("model-a", request_b, "system"))+ if other_status == "completed":+ _settle_as_the_runner(service, other.run_id, other.item_ids, "completed")++ before = queue.get_queue_item_ids("default").item_ids+ with pytest.raises(CalibrationAttemptInterleavedError):+ queue.retry_items_by_id("default", failed.item_ids)++ assert queue.get_queue_item_ids("default").item_ids == before+ failed_record = _stored_run(tmp_path, failed.run_id)+ assert failed_record.get("retries_in_flight", 0) == 0+++def _failed(+ service: WorkingMemoryCalibrationService,+ attempt_id: Optional[str],+ owner: str = "system",+ steps: int = 2,+ *,+ model_key: str = "model-a",+):+ """One run (a step of an attempt, or a run without one) whose item ran out of memory, as the runner saw it."""+ request = WorkingMemoryCalibrationRequest(+ graph_models={},+ graph=_add_graph(),+ attempt_id=attempt_id,+ attempt_steps=steps if attempt_id is not None else None,+ )+ created = asyncio.run(service.create_run(model_key, request, owner))+ _settle_as_the_runner(service, created.run_id, created.item_ids, "failed")+ return created+++def _unchanged_by_a_refused_retry(tmp_path: Path, queue: SessionQueue, before: list[int], *runs) -> None:+ assert queue.get_queue_item_ids("default").item_ids == before+ for created in runs:+ assert "retries_in_flight" not in _stored_run(tmp_path, created.run_id)++[email protected]("between", ["running", "between steps"])+def test_a_retry_of_a_run_without_an_attempt_between_another_attempts_steps_is_refused(+ tmp_path: Path, started, between: str+) -> None:+ """A script's run failed before A started. Retrying it while A runs, or is between its steps, would measure+ between A's steps without cutting A off as a new run would: refused, also for A's own owner. Once A finished, the+ retry is admitted."""+ service = started(tmp_path)+ queue = service._services.session_queue+ script = _failed(service, None)+ first = asyncio.run(service.create_run("model-a", _steps("tab-a", 2), "system"))+ if between == "between steps":+ _settle_as_the_runner(service, first.run_id, first.item_ids, "completed")+ before = queue.get_queue_item_ids("default").item_ids++ with pytest.raises(CalibrationAttemptBusyError) as refused:+ queue.retry_items_by_id("default", script.item_ids)++ assert refused.value.code == "calibration_running"+ _unchanged_by_a_refused_retry(tmp_path, queue, before, script, first)+ if between == "running":+ _settle_as_the_runner(service, first.run_id, first.item_ids, "completed")+ _step(service, "tab-a")+ assert [retry.source_item_id for retry in queue.retry_items_by_id("default", script.item_ids).retried_items] == (+ script.item_ids+ )++[email protected]("first", ["the script's retry", "the attempt's retry"])+def test_a_script_retry_between_a_failed_last_step_and_its_retry(tmp_path: Path, started, first: str) -> None:+ """A script's run failed; then A ran, its first step measured the line and its last step ran out of memory. A is+ complete, so not open: the script's run may be retried, and its retry measures the GPU after A's steps. A's last+ step's retry would then measure after it: refused, and A feeds only what it measured before. Retried first, A's+ step runs while the script's retry is refused; once it finished, the script's run may be retried."""+ service = started(tmp_path)+ queue = service._services.session_queue+ script = _failed(service, None)+ largest = _failed_largest_step(service, "tab-a")++ if first == "the script's retry":+ [script_retry] = queue.retry_items_by_id("default", script.item_ids).retried_items+ before = queue.get_queue_item_ids("default").item_ids+ with pytest.raises(CalibrationAttemptInterleavedError) as refused:+ queue.retry_items_by_id("default", largest.item_ids)+ assert refused.value.code == "calibration_interleaved"+ _unchanged_by_a_refused_retry(tmp_path, queue, before, largest)+ _settle_as_the_runner(service, script.run_id, [script_retry.item_id], "completed")+ else:+ [step_retry] = queue.retry_items_by_id("default", largest.item_ids).retried_items+ before = queue.get_queue_item_ids("default").item_ids+ with pytest.raises(CalibrationAttemptBusyError):+ queue.retry_items_by_id("default", script.item_ids)+ _unchanged_by_a_refused_retry(tmp_path, queue, before, script)+ _settle_as_the_runner(service, largest.run_id, [step_retry.item_id], "failed")+ assert len(queue.retry_items_by_id("default", script.item_ids).retried_items) == 1+ service.refresh_user_fits()++ assert _estimate() == _user_bytes(1024)+ assert {run.held_back for run in service.get_model_summary("model-a").runs if run.run_id != script.run_id} == {None}+++def test_a_script_retry_past_an_idle_attempts_grace_refuses_its_next_step(+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A's client went away after its first step. Past `ATTEMPT_IDLE_GRACE` a script's run may be retried; A's next+ step, posted after all, would measure after the retry: refused, as after a script's new run, and A never feeds."""+ service = started(tmp_path)+ queue = service._services.session_queue+ script = _failed(service, None)+ first = _step(service, "tab-a")+ service.record_windows(first.run_id, _on_the_line(first.run_id))+ _idle(monkeypatch)++ assert len(queue.retry_items_by_id("default", script.item_ids).retried_items) == 1+ assert "retried_at" in _stored_run(tmp_path, script.run_id)+ with pytest.raises(CalibrationAttemptInterleavedError):+ _step(service, "tab-a")+ service.refresh_user_fits()+ runs = {run.run_id: run.held_back for run in service.get_model_summary("model-a").runs}+ assert runs[first.run_id] == "aborted_attempt"+++def test_a_retry_while_another_attempt_runs_is_refused_though_it_started_before_on_the_clock(+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The wall clock stepped back before B was created: A's first step looks created after B, so nothing cut A off.+ B's item still waits in the queue, and A's retry would measure around it: refused as B runs (`_attempt_blocks`)."""+ service = started(tmp_path)+ queue = service._services.session_queue+ failed = _failed(service, "tab-a")+ clock = calibration_default._now+ monkeypatch.setattr(calibration_default, "_now", lambda: clock() - datetime.timedelta(hours=1))+ running = asyncio.run(service.create_run("model-a", _steps("tab-b", 2), "system"))+ monkeypatch.setattr(calibration_default, "_now", clock)+ before = queue.get_queue_item_ids("default").item_ids++ with pytest.raises(CalibrationAttemptBusyError) as refused:+ queue.retry_items_by_id("default", failed.item_ids)++ assert str(refused.value) == (+ "Another calibration is still running on this GPU, and this item would measure in the middle of it. Retry it "+ "once that calibration has finished, or stop it."+ )+ _unchanged_by_a_refused_retry(tmp_path, queue, before, failed, running)+++def test_a_retry_count_left_over_blocks_neither_a_retry_nor_another_attempt(+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A's retry was committed and its record failed: the count stays on A's run for good, keeping A out of every+ fit. It must not hold the device class too: A's item can be retried again, and another administrator's attempt+ may start once nothing of A runs."""+ service = started(tmp_path)+ queue = service._services.session_queue+ failed = _failed(service, "tab-a", steps=1)+ _refuse_the_record(monkeypatch, service, [CalibrationStoreError("Cannot write the file")])+ [lost] = queue.retry_items_by_id("default", failed.item_ids).retried_items+ queue.cancel_queue_item(lost.item_id)+ assert _stored_run(tmp_path, failed.run_id)["retries_in_flight"] == 1++ [again] = queue.retry_items_by_id("default", failed.item_ids).retried_items+ queue.cancel_queue_item(again.item_id)+ _step(service, "tab-b", "other-admin")++ assert _stored_run(tmp_path, failed.run_id)["retries_in_flight"] == 1+ service.refresh_user_fits()+ held = {run.run_id: run.held_back for run in service.get_model_summary("model-a").runs}+ assert held[failed.run_id] == "aborted_attempt"++[email protected]("order", ["script first", "attempt first"])+def test_a_bulk_retry_is_refused_when_any_of_its_runs_is_cut_off(tmp_path: Path, started, order: str) -> None:+ """The script's run, before A, may be retried on its own; A's step was cut off by a later run. Retried together,+ in either order, the queue retries neither."""+ service = started(tmp_path)+ queue = service._services.session_queue+ script = _failed(service, None)+ cut_off = _failed(service, "tab-a")+ _step(service, None)+ item_ids = script.item_ids + cut_off.item_ids+ before = queue.get_queue_item_ids("default").item_ids++ with pytest.raises(CalibrationAttemptInterleavedError):+ queue.retry_items_by_id("default", item_ids if order == "script first" else item_ids[::-1])++ _unchanged_by_a_refused_retry(tmp_path, queue, before, script, cut_off)+ assert len(queue.retry_items_by_id("default", script.item_ids).retried_items) == 1++[email protected]("failure", ["refused", "unexpected"])+def test_a_retry_refused_on_one_device_class_counts_nothing_on_another(+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch, failure: str+) -> None:+ """A bulk retry of runs on two device classes' files: the first file counted its run before the second refused+ (a cut-off attempt) or failed (any error): the first count is taken back, and nothing is retried."""+ counted_class, failing_class = sorted([GPU_CLASS, OTHER_CLASS], key=lambda device_class: device_class.id)+ counted_service = started(tmp_path, device_class=counted_class)+ counted = _failed(counted_service, "tab-a")+ failing_service = started(tmp_path, device_class=failing_class)+ failing = _failed(failing_service, "tab-b")+ if failure == "refused":+ _step(failing_service, None)+ else:+ change = failing_service._store.change++ def fail_on_the_second_file(device_class_id, apply, **kwargs):+ if device_class_id == failing_class.id:+ raise RuntimeError("unexpected")+ return change(device_class_id, apply, **kwargs)++ monkeypatch.setattr(failing_service._store, "change", fail_on_the_second_file)+ queue = failing_service._services.session_queue+ before = queue.get_queue_item_ids("default").item_ids++ with pytest.raises(CalibrationAttemptInterleavedError if failure == "refused" else RuntimeError):+ queue.retry_items_by_id("default", counted.item_ids + failing.item_ids)++ _unchanged_by_a_refused_retry(tmp_path, queue, before)+ for device_class in (counted_class, failing_class):+ stored = json.loads((tmp_path / "working_memory" / f"{device_class.id}.json").read_bytes())+ assert [run.get("retries_in_flight", 0) for run in stored["runs"]] == [0] * len(stored["runs"])++[email protected]("b_starts", ["at the check", "at the commit"])+def test_no_attempt_starts_between_a_retrys_check_and_its_commit(+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch, b_starts: str+) -> None:+ """A's one-step attempt failed, and nothing runs: its retry passes the check. Before the queue commits it, another+ administrator starts B, whose check would find nothing running yet: inside the check, or once it returned, as the+ queue begins the commit (`admit`). The retry holds the attempts' lock from its check through its commit: B waits+ for it, then finds A's retry queued and is refused. Were the lock given back after the check, B would start at the+ commit and A's retry would commit after it, between B's steps."""+ service = started(tmp_path)+ queue = service._services.session_queue+ failed = _failed(service, "tab-a", steps=1)+ lock = service._file_lock+ arrived = threading.Event()++ @asynccontextmanager+ async def watched(name: str, os_lock):+ if name == _ATTEMPTS_LOCK:+ arrived.set()+ async with lock(name, os_lock):+ yield++ monkeypatch.setattr(service, "_file_lock", watched)+ outcome: list = []++ def start_b() -> None:+ try:+ outcome.append(asyncio.run(service.create_run("model-a", _steps("tab-b", 2), "other-admin")))+ except Exception as error:+ outcome.append(error)++ other = threading.Thread(target=start_b)++ def b_starts_now() -> None:+ other.start()+ assert arrived.wait(10)+ # Time for B to pass the retry, were nothing to hold it.+ other.join(timeout=0.5)++ if b_starts == "at the check":+ checked = service.retries_starting++ def checked_then_b_starts(sources):+ in_flight = checked(sources)+ b_starts_now()+ return in_flight++ monkeypatch.setattr(service, "retries_starting", checked_then_b_starts)+ else:+ run = queue._queries.run++ def b_starts_then_commit(work, *, read_only: bool = False):+ # The retry's commit; B's own enqueue, once B started, runs a work of that name too.+ if work.__name__ == "admit" and other.ident is None:+ b_starts_now()+ return run(work, read_only=read_only)++ monkeypatch.setattr(queue._queries, "run", b_starts_then_commit)+ [retried] = queue.retry_items_by_id("default", failed.item_ids).retried_items+ other.join(timeout=10)++ [refused] = outcome+ assert isinstance(refused, CalibrationAttemptBusyError), refused+ assert sorted(queue.get_queue_item_ids("default").item_ids) == sorted(failed.item_ids + [retried.item_id])+ assert [run.attempt_id for run in service.get_status().device_classes[0].runs] == ["tab-a"]++def test_another_attempt_waits_while_one_is_between_its_steps(tmp_path: Path, started, monkeypatch) -> None:"""A's first step finished a moment ago, and its client is about to post the next: B, another administrator's,is refused, A's next step is not, and once A finished B may start."""@@ -1815,6 +2160,34 @@ def test_an_attempt_whose_steps_another_calibration_ran_between_never_feeds(assert held[first.run_id] == "aborted_attempt"+def test_an_attempt_a_script_was_retried_between_the_steps_of_never_feeds(+ tmp_path: Path, started, mock_invoker: Invoker+) -> None:+ """A store that holds such an attempt all the same: the script's run was created before A, and its retry began+ between A's two steps (`retried_at`). Complete, every step finished, and still aborted."""+ service = started(tmp_path)+ script = _failed(service, None)+ first, second = _step(service, "tab-a"), _step(service, "tab-a")+ service.record_windows(first.run_id, _on_the_line(first.run_id))+ service.stop(mock_invoker)+ path = next((tmp_path / "working_memory").glob("*.json"))+ stored = json.loads(path.read_bytes())+ start = datetime.datetime(2026, 10, 27, 12, tzinfo=datetime.timezone.utc)+ offsets = {script.run_id: 0, first.run_id: 10, second.run_id: 20}+ for run in stored["runs"]:+ run["created_at"] = (start + datetime.timedelta(seconds=offsets[run["run_id"]])).isoformat()+ if run["run_id"] == script.run_id:+ run["retried_at"] = (start + datetime.timedelta(seconds=15)).isoformat()+ path.write_text(json.dumps(stored))++ reread = started(tmp_path)+ reread.refresh_user_fits()++ assert _estimate() == _shipped()+ held = {run.run_id: run.held_back for run in reread.get_model_summary("model-a").runs}+ assert held[first.run_id] == "aborted_attempt"++def test_another_attempt_started_as_the_next_step_of_one_is_posted_is_refused(tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch) -> None: