feat: schedule image-list items on bounded serverless slots

This commit is contained in:
Robert Wojciechowski
2026-10-14 00:16:54 +00:00
parent 1fb4d4a284
commit e9c95bf110
8 changed files with 1619 additions and 58 deletions
+2
View File
@@ -171,6 +171,8 @@ class ServerlessManager:
for rid in done[:-200]:
self.tasks.pop(rid, None)
self.runs.pop(rid, None)
# Additive ownership handle for item schedulers; legacy callers ignore it.
return [record_id for record_id, _run, _semaphore in new_runs]
def is_pending(self, collector_job_id, participant_id):
return any(not task.done() and run["worker"]["id"] == participant_id and
+15 -20
View File
@@ -38,7 +38,7 @@ from .orchestration.prompt_transform import (
WORKER_SINK_CLASS,
_resolve_direct_workers_for_image_list,
)
from ..image_list.runtime import validate_image_list_regions
from ..image_list.runtime import validate_image_list_regions, _has_selected_serverless_workers
from ..image_list.execution_plan import prepare_image_list_execution
@@ -361,23 +361,16 @@ async def orchestrate_distributed_execution(
"DistributedMediaCollector or Ultimate SD Upscale nodes in one prompt"
)
validate_image_list_regions(prompt_obj, explicit_targets=True)
configured_serverless = [
str(worker.get("id")) for worker in config.get("workers", [])
if worker.get("enabled", False)
and str(worker.get("type") or "local").lower() == "serverless"
and (requested_ids is None or str(worker.get("id")) in {str(x) for x in requested_ids})
]
if configured_serverless:
trace_debug(
execution_trace_id,
"Image List v1 explicitly excludes unsupported serverless pools: "
+ ", ".join(configured_serverless),
)
workers = _resolve_direct_workers_for_image_list(config, requested_ids)
if _has_selected_serverless_workers(config, requested_ids):
from ..image_list.serverless import resolve_serverless_workers
# Pool identity is retained once, never expanded by Images per run.
# Validate profiles before reachability can hide an invalid selection.
workers += resolve_serverless_workers(config, requested_ids)
if not workers and delegate_master:
raise RuntimeError(
"Distributed Image List in orchestrator-only mode requires a selected direct worker; "
"serverless pools are unsupported"
"Distributed Image List in orchestrator-only mode requires a selected direct worker "
"or comfy-media-v1 serverless pool"
)
else:
if typed_media_mode and requested_ids is not None:
@@ -425,13 +418,15 @@ async def orchestrate_distributed_execution(
from .orchestration.dispatch import preflight_image_list_workers
if not active_workers and delegate_master:
raise RuntimeError(
"No selected direct worker is reachable for Distributed Image List in orchestrator-only mode"
"No selected worker is reachable for Distributed Image List in orchestrator-only mode"
)
idle_ids = (await preflight_image_list_workers(active_workers, require_idle=delegate_master)
if active_workers else {})
active_workers = [worker for worker in active_workers if worker["id"] in idle_ids]
direct_workers = [worker for worker in active_workers if worker.get("type") != "serverless"]
idle_ids = (await preflight_image_list_workers(direct_workers, require_idle=delegate_master)
if direct_workers else {})
active_workers = [worker for worker in active_workers
if worker.get("type") == "serverless" or worker["id"] in idle_ids]
if not active_workers and delegate_master:
raise RuntimeError("No feature-compatible direct worker is idle in orchestrator-only mode")
raise RuntimeError("No feature-compatible worker is available in orchestrator-only mode")
else:
delegate_master = selected_delegate_master
+65 -13
View File
@@ -1,8 +1,8 @@
# Dynamic image-list queue
Process a list of images across the master and direct local or remote ComfyUI workers without assigning fixed chunks to each participant.
Process a list of images across the master, direct local or remote ComfyUI workers, and compatible Runpod serverless pools without assigning fixed chunks to each participant.
The master evaluates the input list once. By default, the master and each selected idle worker receive one image job at a time; when a participant finishes, it gets the next unassigned image. Faster participants can therefore process more images. The master restores input order before running downstream nodes.
The master evaluates the input list once. By default, the master and each selected direct worker receive one image job at a time; a serverless pool contributes bounded concurrent slots. All slots share the same queue: when a participant finishes, it gets the next unassigned image. Faster participants can therefore process more images. Each source frame is assigned once, and the master restores input order before running downstream nodes.
The existing **Orchestrator Only** setting (`settings.master_delegate_only`) excludes the master from per-image processing. The master still creates the input list and runs downstream nodes. API callers can override the setting for a run with `delegate_master`. There is no second image-list-specific toggle.
@@ -23,8 +23,8 @@ Distributed Image List Start -------- context ---------+
Preview / Save / next stage
```
1. Install the same feature-capable version of Distributed on the master and every selected worker. Workers on an older image-list protocol fail preflight before any work is sent. Restart those instances and refresh the frontend after installation.
2. Enable Distributed and select the **direct** workers to use. The master also participates unless **Orchestrator Only** is enabled. With the master participating, an empty worker selection runs locally through the same image-list scheduler; orchestrator-only mode requires at least one reachable, idle direct worker. The master must be reachable from remote workers at its configured callback address.
1. Install the same feature-capable version of Distributed on the master and every selected direct worker. Direct workers on an older image-list protocol fail preflight before any work is sent. Restart those instances and refresh the frontend after installation. Serverless endpoints instead need the compatible media bridge and supervision described below.
2. Enable Distributed and select direct workers and/or **Typed media v1** serverless pools. The master also participates unless **Orchestrator Only** is enabled. With the master participating, an empty worker selection runs locally through the same image-list scheduler; orchestrator-only mode requires at least one eligible direct worker or compatible serverless pool. Serverless-only selection is supported. The master must be reachable from direct remote workers at its configured callback address; serverless jobs do not use this callback.
3. Feed your image list or tensor batch into **Distributed Image List Start → images**.
4. Connect its `image` output through the per-image processing nodes to **Distributed Image List End → images**.
5. Connect Start's **context** directly to End's **context**. This is a dedicated `DISTRIBUTED_IMAGE_LIST_CONTEXT` socket, not editable text.
@@ -60,24 +60,69 @@ Per-image data must pass through Start; do not bypass it with upstream images, l
End's optional `texts` is a connection-only socket. For workflows saved before this socket became connection-only, recreate End and reconnect its wires if an old text widget or literal `texts: ""` remains in the compiled prompt. Arbitrary text literals are not accepted at End.
File-based dependencies keep ComfyUI's `[output]` / `[temp]` root annotations and are read on the master. Their worker copies use separate content-addressed paths under `input/distributed-media/`; each worker's rewritten prompt is reused across items without reusing item tokens.
File-based dependencies keep ComfyUI's `[output]` / `[temp]` root annotations and are read on the master. Direct-worker copies use separate content-addressed paths under `input/distributed-media/`; each direct worker's rewritten prompt is reused across items without reusing item tokens. Cloud requests use the PR2 bounded file-input adapters instead.
## Serverless pools and bounded capacity
Select `media_profile: "comfy-media-v1"` for each cloud pool. The endpoint must
include the [standalone PR2 media bridge](../serverless_bridge/README.md), route
typed requests through its executor, and provide the required supervisor. Merely
installing the bridge nodes or choosing the profile is not sufficient. The
endpoint needs the workflow's models and custom nodes, but not the full
Distributed extension. A selected `legacy-image-v1` pool fails before the master
prompt is queued; it is not silently skipped in favor of local execution.
Provider health/authentication probing does not verify bridge/model installation.
- Each pool is selected once by its configured pool ID. **Images per run
(`jobs_per_run`) does not multiply input images or set image-list parallelism.**
An assigned cloud job processes exactly one source item and its paired values.
- Cloud slots are bounded by the existing **16 outstanding jobs per pool** cap,
available manager capacity (**64 pending jobs** across pools), reservations,
and the source item count. Unresolved submissions and unconfirmed cancellations
still consume capacity. Selecting more items does not enqueue all of them as
provider jobs at once. Endpoint-side worker limits can reduce actual concurrency.
- Cloud slots, direct workers and the optional master pull from the same queue;
no region is cloned once per Images-per-run setting. Results are restored to
source order even when participants finish out of order.
- Each cloud request uses the standard media-v1 envelope and existing durable
serverless job lifecycle. The private item graph replaces Start/End with typed
inputs and explicit exporter roots, not independent all-output execution.
IMAGE/MASK tensor data and text are preserved by the typed codecs. There is no
image-list-specific endpoint protocol or new visible node socket.
- Cloud `value_N` tensors must have native IMAGE `[B,H,W,C]` or MASK `[B,H,W]`
shapes, not arbitrary rank-one/rank-two tensor payloads. Typed tensors must be
finite; connected masks must match their image grid. Unsupported values fail
rather than being resized, flattened or converted to lossy images.
- Inputs are inline and the **complete serialized Runpod request is capped at
10,000,000 bytes**, including workflow and base64. Default inline result JSON
has the same cap. The PR2 contract's larger artifact ceilings do not remove
these inline limits; larger outputs need an operator-provided artifact publisher.
There is no built-in large-input uploader. See [typed media limits](serverless-media.md#size-and-operational-limits).
- Missing/duplicate/mismatched results or provider failures fail the region.
Cancellation closes only this region's owned cloud jobs and collector queues,
including jobs whose dispatch was cancelled before returning a handle. It does
not clear unrelated pool work. No failed or ambiguous job is retried automatically.
- A provider cancellation or timeout is **not proof that endpoint ComfyUI stopped**.
The PR2 supervisor must quarantine/reconcile or terminate an uncertain endpoint
before reuse. Preserve its retained files until execution and readers are known
to have stopped; see the [bridge uncertainty policy](../serverless_bridge/README.md).
## Scope and failure behavior
- This version supports the master and direct workers, not Runpod serverless pools. Unsupported pools are excluded without contacting the provider for this job.
- Worker eligibility is determined before execution and checked again before dispatch. Busy or transiently unreachable workers are excluded; healthy candidates can continue. Malformed capability/queue responses and incompatible versions fail explicitly. Workers joining later are not added to an already-running region.
- Omitted worker IDs select enabled direct workers. Explicit IDs select the named configured direct workers, including disabled ones; an empty list stays empty, unknown IDs fail, and serverless workers are excluded. Local workers use the master's loopback callback; remote workers use its configured public address.
- Only the enclosed processing is distributed. List creation and downstream saving run on the master in both modes. With participation enabled, the master is a normal scheduler participant and can run alone when no direct workers are available. **Orchestrator-only mode never silently falls back to master processing.** Failed items are not reassigned automatically.
- This version supports master, direct workers and `comfy-media-v1` serverless pools in one image-list region. Direct capability/idle HTTP probes are never sent to serverless pools; pool probing uses the existing serverless health/authentication path.
- Worker eligibility is determined before execution and checked again before dispatch. Direct workers must be idle in orchestrator-only mode; master-participating mode can use reachable compatible peers without requiring an empty queue. Transiently unreachable workers are excluded; healthy candidates can continue. Malformed capability/queue responses and incompatible versions fail explicitly. Workers joining later are not added to an already-running region.
- Omitted worker IDs select enabled direct workers and compatible serverless pools. Explicit IDs select the named configured workers/pools, including disabled ones; an empty list stays empty and unknown IDs fail. Pool IDs are retained in Start's hidden selection metadata, not expanded participant IDs. Local direct workers use the master's loopback callback; remote direct workers use its configured public address.
- Only the enclosed processing is distributed. List creation and downstream saving run on the master in both modes. With participation enabled, the master is a normal scheduler participant and can run alone when no workers are selected or reachable. **Orchestrator-only mode never silently falls back to master processing.** Failed items are not reassigned automatically.
- Local items execute while the enclosing master prompt waits; they are not queued behind that prompt on the master's `/prompt` queue. The enclosed branch is not also evaluated as a full list by the outer prompt.
- Start/End regions may be chained sequentially and share model-loader dependencies. Nested/overlapping per-image regions and data escaping a region without End are rejected. Collector and distributed-upscaler nodes cannot be mixed into the same prompt in this first version.
- Queue preparation works on an execution copy, leaving the saved canvas unchanged. Unused per-item preview/save branches are pruned by dependency reachability, not node names. Required computational utilities marked `OUTPUT_NODE` stay in the graph; explicit `partial_execution_targets` prevent them from also becoming independent outer-master roots. End and legitimate post-End or unrelated outputs are retained. Bypass/rejoin branches still fail boundary validation rather than being silently removed.
- Every selected worker must advertise `execution_targets: true` as well as the existing image-list protocol. Older workers fail preflight before dispatch. Both HTTP and WebSocket item submissions target End only; the participating master uses its existing End-only local executor. Submit through `/distributed/queue`: an ordinary all-output `/prompt` request does not receive this relaxation.
- Every selected direct worker must advertise `execution_targets: true` as well as the existing image-list protocol. Older workers fail preflight before dispatch. Both HTTP and WebSocket item submissions target End only; the participating master uses its existing End-only local executor. Cloud jobs use explicit media exporter roots. Submit through `/distributed/queue`: an ordinary all-output `/prompt` request does not receive this relaxation.
- **Target selection is not a sandbox.** A required utility still runs its own save, preview or other side effects when it executes for an item. Keep intentional final saving after End.
- The entire input list is materialized before scheduling; this is not streaming input. The limit is 4,096 frames. Remote transport preserves floating-point tensor dtype and values rather than encoding to lossy images. Each transported tensor is limited to 50 MiB, and the complete JSON/base64 HTTP request to 101 MiB; image/mask/value combinations can hit the aggregate request limit first. In-process master items use tensors directly and are not subject to those HTTP limits.
- The entire input list is materialized before scheduling; this is not streaming input. The limit is 4,096 frames. Direct-worker transport preserves floating-point tensor dtype and values rather than encoding to lossy images. Each direct-worker tensor is limited to 50 MiB, and the complete JSON/base64 HTTP request to 101 MiB; image/mask/value combinations can hit the aggregate request limit first. Serverless inline limits are smaller, as described above. In-process master items use tensors directly and are not subject to those HTTP limits.
- Results are accepted once per item using assignment tokens. Missing, duplicate, malformed and wrong-index results fail rather than silently returning a partial list. No failed or ambiguous submission is retried automatically.
- Worker errors fail the region. The worker timeout measures loss of evidence for the owned prompt ID, not maximum render duration. Pending/running evidence refreshes liveness; unrelated busy jobs and failed polls do not. Healthy cold loads and long renders can continue.
- Worker errors fail the region. For direct workers, the worker timeout measures loss of evidence for the owned prompt ID, not maximum render duration. Pending/running evidence refreshes liveness; unrelated busy jobs and failed polls do not. Healthy cold loads and long renders can continue. Serverless jobs instead use their configured serverless timeout and durable manager lifecycle; they are excluded from direct-history/liveness polling.
- User interruption is checked during submission and result waiting. Cleanup targets only this region's acknowledged prompt IDs and staged input tokens. Submission may wait briefly for an acknowledgement before cancellation; remote transport and cleanup have finite time limits. Local cleanup stops at node/progress boundaries and waits for its execution thread to finish before the parent prompt can resume. A synchronous node that does not cooperate with cancellation can delay this beyond the configured deadline. Lost acknowledgements are ambiguous, never retried automatically. Unreachable cleanup is logged as unconfirmed and may require checking the worker manually; cancellation does not guarantee remote termination through a broken network.
- State is in memory. Restarting the master does not resume an interrupted region. Abandoned master contexts and expired worker staging are actively swept on the server loop; active/queued master work is protected from age-only expiry. End also removes its context on success, failure or interruption. This releases feature-owned references, not ComfyUI's separate execution cache.
- Image-list ordering/context state is in memory. Restarting the master does not resume an interrupted region. Cloud job IDs and uncertainty state remain in the existing durable serverless ledger for reconciliation, not automatic list resumption. Abandoned master contexts and expired direct-worker staging are actively swept on the server loop; active/queued master work is protected from age-only expiry. End also removes its context on success, failure or interruption. This releases feature-owned references, not ComfyUI's separate execution cache.
### Time and size limits
@@ -93,6 +138,13 @@ Use trusted workers and trusted workflows, as with the existing ComfyUI API. Cap
The generic acceptance helper starts two isolated loopback workers using real ComfyUI HTTP handlers, `PromptQueue` records and CPU `PromptExecutor` instances. Production queue preparation, list nodes, graph extraction, HTTP item/result routes, dynamic scheduling, float transport, ordering and cancellation are exercised. The harness checks orchestrator-only, mixed master/worker and master-only execution, including exact-once required output utilities, discarded previews, unchanged source graphs, End-only worker roots, post-End capture, source-once materialization and cached local model-loader dependencies. WebSocket target propagation is covered by focused route/dispatch tests. No managed ComfyUI service or model is started.
Offline cloud integration tests additionally cover mixed-role and cloud-only
scheduling, out-of-order image/mask/text pairing, one job per source item regardless
of Images per run, profile/selection rejection before queueing, exact cleanup on
setup/dispatch/result failures, and the real CPU ComfyUI `processing_interrupted`
signal while awaiting a mocked cloud result. Provider calls are mocked: this is
not live Runpod, endpoint-supervisor or GPU-workflow acceptance.
```bash
COMFYUI_SOURCE_ROOT=/path/to/ComfyUI /path/to/ComfyUI/.venv/bin/python -m pytest tests -q
bash scripts/test-web.sh
+69 -22
View File
@@ -383,7 +383,7 @@ def create_master_job(start_id: str, end_id: str, prompt: dict[str, Any], items:
if not isinstance(master_participates, bool):
raise ValueError("master_participates must be a boolean")
if not worker_ids and not master_participates:
raise RuntimeError("Distributed Image List requires at least one preflighted direct worker; master fallback is disabled")
raise RuntimeError("Distributed Image List requires at least one selected worker; master fallback is disabled")
# Only the target-controlled Start caller may relax the outer prompt guard.
regions = validate_image_list_regions(prompt, explicit_targets=explicit_targets is True)
if not any(region["start_id"] == str(start_id) and region["end_id"] == str(end_id)
@@ -794,7 +794,7 @@ def _collect_output_lists(results: list[dict[str, Any]]) -> tuple[list[Any], lis
async def run_image_list_job(context_id: str, *, model_callback=None) -> tuple[list[Any], list[Any], list[Any]]:
"""Schedule a shared queue across the optional master and direct workers."""
"""Schedule one queue across master, direct peers and bounded cloud slots."""
state = get_master_job(context_id)
if state is None:
raise RuntimeError("Distributed Image List context is missing or expired")
@@ -820,34 +820,64 @@ async def run_image_list_job(context_id: str, *, model_callback=None) -> tuple[l
remove_master_job(context_id)
def _has_selected_serverless_workers(config, requested_ids):
"""Keep direct/master-only execution free of optional cloud adapter imports.
This is only an import guard, not validation. The adapter validates original
pool IDs/configuration without repairing them, before any cloud work starts.
"""
requested = None if requested_ids is None else {str(value) for value in requested_ids}
return any(
str(worker.get("type") or "local").strip().lower() == "serverless"
and (worker.get("enabled", False) if requested is None
else str(worker.get("id") or "").strip() in requested)
for worker in config.get("workers", [])
)
async def _run_image_list_job(state: ImageListJob):
context_id = state.context_id
state.event = asyncio.Event()
state.event_loop = asyncio.get_running_loop()
from ..api.orchestration.dispatch import (
preflight_image_list_workers, dispatch_worker_prompt,
)
from ..api.orchestration.prompt_transform import _resolve_direct_workers_for_image_list
from ..utils.config import load_config, get_worker_timeout_seconds
from ..utils.network import build_master_callback_url, build_worker_url, get_client_session
from ..utils.logging import log
import aiohttp
from ..utils.config import load_config
config = load_config()
workers = _resolve_direct_workers_for_image_list(config, state.worker_ids)
if not workers and not state.master_participates:
raise RuntimeError("Distributed Image List requires enabled direct workers; serverless pools are unsupported")
# Recheck worker capability and idle state immediately before the first item.
worker_statuses = await preflight_image_list_workers(workers, require_idle=not state.master_participates) if workers else {}
workers = [worker for worker in workers if worker["id"] in worker_statuses]
if not workers and not state.master_participates:
raise RuntimeError("No free, reachable, feature-compatible direct workers are available; master execution is disabled")
session = await get_client_session() if workers else None
# Both item paths below select End explicitly, never all OUTPUT_NODE roots.
# Every item path selects End explicitly, never all OUTPUT_NODE roots.
regions = validate_image_list_regions(state.original_prompt, explicit_targets=True)
region = next((entry for entry in regions if entry["start_id"] == state.start_id and entry["end_id"] == state.end_id), None)
if region is None:
raise RuntimeError("Image-list region no longer matches the submitted prompt")
controller = None
try:
if _has_selected_serverless_workers(config, state.worker_ids):
from .serverless import create_serverless_slots
controller = await create_serverless_slots(state, region, config, state.event)
return await _run_image_list_slots(state, config, workers, region, controller)
finally:
# Own cloud jobs even if direct preflight/local setup fails, or dispatch
# is cancelled before returning an acknowledged handle to the scheduler.
if controller is not None:
await controller.close()
async def _run_image_list_slots(state, config, workers, region, controller):
context_id = state.context_id
from ..api.orchestration.dispatch import (
preflight_image_list_workers, dispatch_worker_prompt,
)
from ..utils.config import get_worker_timeout_seconds
from ..utils.network import build_master_callback_url, build_worker_url, get_client_session
from ..utils.logging import log
import aiohttp
serverless_slots = list(controller.slots) if controller is not None else []
# Direct capability/idle probes must never be sent to a serverless pool.
worker_statuses = await preflight_image_list_workers(workers, require_idle=not state.master_participates) if workers else {}
workers = [worker for worker in workers if worker["id"] in worker_statuses]
if not workers and not serverless_slots and not state.master_participates:
raise RuntimeError("No reachable, feature-compatible image-list workers are available; master execution is disabled")
session = await get_client_session() if workers else None
timeout_seconds = max(5.0, float(get_worker_timeout_seconds()))
use_websocket = bool((config.get("settings", {}) or {}).get("websocket_orchestration", False))
prepared_worker_prompts: dict[str, dict[str, Any]] = {}
@@ -862,6 +892,8 @@ async def _run_image_list_job(state: ImageListJob):
local_executor = LocalExecutionSlot(model_callback=state.local_model_callback)
async def dispatch(worker_id: Any, index: int) -> dict[str, Any]:
if worker_id in serverless_slots:
return await controller.dispatch(worker_id, index)
if worker_id is master_slot:
assert local_executor is not None
token = create_worker_task_token()
@@ -926,6 +958,10 @@ async def _run_image_list_job(state: ImageListJob):
state.event.clear()
if state.failed:
raise RuntimeError(state.failed)
if controller is not None:
completed = controller.poll(inflight)
if completed is not None:
return completed
local = inflight.get(master_slot)
if local is not None and local["future"].done():
# A posted result does not release this slot until execution has
@@ -975,10 +1011,15 @@ async def _run_image_list_job(state: ImageListJob):
return None
return None
errors = await asyncio.gather(*(history_status(wid, handle) for wid, handle in inflight.items()
if wid is not master_slot))
if wid is not master_slot and wid not in serverless_slots))
failure = next((error for error in errors if isinstance(error, str)), None)
if failure:
raise RuntimeError(failure)
# A cloud manager task may finish during direct HTTP history waits.
if controller is not None:
completed = controller.poll(inflight)
if completed is not None:
return completed
completed = next((entry for entry in errors if isinstance(entry, tuple)), None)
if completed is not None:
# The callback precedes the worker prompt finishing. Wait for its
@@ -989,7 +1030,8 @@ async def _run_image_list_job(state: ImageListJob):
return completed
now = time.monotonic()
expired = [f"{wid}/item {handle['index']}" for wid, handle in inflight.items()
if wid is not master_slot and now - handle["last_seen"] > timeout_seconds]
if wid is not master_slot and wid not in serverless_slots
and now - handle["last_seen"] > timeout_seconds]
if expired:
raise TimeoutError(f"Image-list owned-prompt liveness timeout after {timeout_seconds:.1f}s: {', '.join(expired)}")
try:
@@ -998,6 +1040,10 @@ async def _run_image_list_job(state: ImageListJob):
pass
async def cleanup(worker_id: Any, handle: dict[str, Any]) -> None:
if worker_id in serverless_slots:
# The controller owns exact manager records, including dispatches
# that never returned a handle. Close it once in the outer finally.
return
if worker_id is master_slot:
# The outer finally owns the non-abandonable stop/join. The generic
# scheduler's bounded remote cleanup must never detach local work.
@@ -1038,7 +1084,8 @@ async def _run_image_list_job(state: ImageListJob):
return False
try:
slots = ([master_slot] if local_executor is not None else []) + [worker["id"] for worker in workers]
slots = (([master_slot] if local_executor is not None else [])
+ [worker["id"] for worker in workers] + serverless_slots)
results = await dynamic_schedule(len(state.items), slots,
dispatch, wait_next, cleanup, interrupted)
return _collect_output_lists(results)
+407
View File
@@ -0,0 +1,407 @@
"""Image-list items on explicitly selected comfy-media-v1 pools.
Only graph/media adaptation lives here. The shared manager owns admission,
provider submission, durable reservations, cancellation and atomic decoding.
A provider terminal state is not proof that an arbitrary endpoint stopped its
local Comfy prompt: the selected profile must honour its supervision contract.
"""
from __future__ import annotations
import asyncio
import copy
import hashlib
import uuid
from . import runtime
from ..api.orchestration.runpod_client import serialize_request
from ..api.orchestration.serverless_media_prompt import compile_media_prompt
from ..api.orchestration.serverless_runtime import PER_WORKER_JOB_LIMIT, get_manager
from ..api.orchestration.serverless_typed_inputs import prepare_media_inputs, _artifact_id
from ..serverless_bridge import codec, contract
from ..utils.serverless_config import validate_serverless_worker
def _identity(value):
contract.identifier(value)
if any(part in ("", ".", "..") for part in value.split("/")):
raise ValueError("Unsafe image-list media identifier")
return value
def resolve_serverless_workers(config, requested_ids):
"""Return pool configurations, never jobs_per_run-expanded participants.
None means enabled defaults; an explicit selection includes disabled pools.
Direct worker IDs may coexist in that selection and are left to their own
resolver. Unknown, duplicate configured and malformed identities fail closed.
"""
workers = (config or {}).get("workers", [])
indexed = {}
for worker in workers:
wid = worker.get("id")
if not isinstance(wid, str) or not wid or wid != wid.strip():
raise ValueError("Invalid configured image-list worker ID")
if wid in indexed:
raise ValueError("Duplicate configured image-list worker ID")
indexed[wid] = worker
requested = None
if requested_ids is not None:
if not isinstance(requested_ids, (list, tuple, set)):
raise ValueError("Image-list worker selection must be a list of exact IDs")
if any(not isinstance(wid, str) or not wid or wid != wid.strip() for wid in requested_ids):
raise ValueError("Invalid selected image-list worker ID")
requested = set(requested_ids)
if requested - indexed.keys():
raise ValueError("Unknown explicitly selected image-list worker ID(s)")
result = []
for wid, worker in indexed.items():
if requested is None:
if worker.get("enabled", False) is not True:
continue
elif wid not in requested:
continue
if str(worker.get("type") or "").strip().lower() != "serverless":
continue
clean = validate_serverless_worker(worker)
_identity(wid)
if clean.get("media_profile") != contract.PROFILE:
raise ValueError(f"Image-list serverless pool {wid!r} requires comfy-media-v1")
# Pool IDs, not virtual legacy participant IDs, own capacity and secrets.
if "pool_id" in clean and clean["pool_id"] != wid:
raise ValueError("Image-list selection requires a pool, not an expanded participant")
clean["pool_id"] = wid
result.append(clean)
return result
def _link(value, prompt):
if not isinstance(value, (list, tuple)):
return None
if (len(value) != 2 or not isinstance(value[0], str)
or type(value[1]) is not int or value[1] < 0):
raise ValueError("Invalid image-list graph link")
_identity(value[0])
if value[0] not in prompt:
raise ValueError("Image-list graph link source is missing")
return value[0], value[1]
def _new_node_id(graph, label):
base = "image-list:input:" + label
candidate, suffix = base, 0
while candidate in graph:
suffix += 1
candidate = f"{base}:{suffix}"
return candidate
def _merge_artifacts(*groups):
indexed = {}
for group in groups:
for artifact in group:
contract.validate_artifact(artifact)
aid = artifact["id"]
if aid in indexed and indexed[aid] != artifact:
raise ValueError("Conflicting image-list input artifact identity")
indexed[aid] = artifact
if (len(indexed) > contract.MAX_ARTIFACTS or
sum(a["byte_length"] for a in indexed.values()) > contract.MAX_TOTAL_BYTES):
raise ValueError("Image-list media inputs exceed artifact limits")
return [indexed[aid] for aid in sorted(indexed)]
async def prepare_serverless_item(prompt, region, item, worker, *, request_id, job_id):
"""Compile one immutable Start/End region to an endpoint-native media job.
Tensor Start outputs use exact codec artifacts and references to existing
consumer inputs. PrimitiveString placeholders keep exporter sockets linked
until the endpoint handler injects MediaImportV1 and prunes unused ancestors.
Scalar values remain typed literals, except exported text stays linked.
"""
_identity(request_id)
_identity(job_id)
worker = validate_serverless_worker(worker)
_identity(worker["id"])
if worker.get("media_profile") != contract.PROFILE:
raise ValueError("Image-list serverless execution requires comfy-media-v1")
if not isinstance(prompt, dict) or not prompt:
raise ValueError("Image-list prompt must be an API graph")
# Check original tokens before looking them up or pruning any nodes. Do not
# let int/bool IDs or slots become valid through string/int normalization.
for node_id, node in prompt.items():
_identity(node_id)
if not isinstance(node, dict) or not isinstance(node.get("inputs", {}), dict):
raise ValueError("Invalid image-list prompt node")
for name, value in node.get("inputs", {}).items():
_identity(name)
_link(value, prompt)
start, end = region["start_id"], region["end_id"]
_identity(start)
_identity(end)
if (prompt[start].get("class_type") != runtime.START_CLASS or
prompt[end].get("class_type") != runtime.END_CLASS):
raise ValueError("Image-list region has mismatched Start/End identities")
if _link(prompt[end].get("inputs", {}).get("context"), prompt) != (start, runtime.CONTEXT_OUT):
raise ValueError("Image-list End context must reference its exact Start")
ids = region["node_ids"]
for node_id in ids:
_identity(node_id)
if not {start, end} <= set(ids):
raise ValueError("Image-list region is missing its boundary nodes")
graph = {nid: copy.deepcopy(prompt[nid]) for nid in sorted(ids)}
end_inputs = graph[end].get("inputs", {})
if "images" not in end_inputs:
raise ValueError("Image-list End requires images")
graph[end] = {"class_type": "DistributedMediaCollector", "inputs": {
**{key: end_inputs[key] for key in ("images", "masks", "texts") if key in end_inputs},
"multi_job_id": job_id, "worker_id": worker["id"]}}
del graph[start]
if type(item.get("index")) is not int or item["index"] < 0:
raise ValueError("Image-list item index must be a nonnegative integer")
image = item.get("image")
if (not isinstance(image, runtime._torch().Tensor) or image.ndim != 4
or image.shape[0] != 1 or image.shape[-1] not in (3, 4)):
raise ValueError("Image-list item must contain exactly one RGB/RGBA image frame")
values = item.get("values", {})
if not isinstance(values, dict) or any(name not in runtime.VALUE_NAMES for name in values):
raise ValueError("Invalid image-list value_N slots")
materialized, artifacts = {}, {}
placeholders = {}
def replacement(slot):
if slot in materialized:
return copy.deepcopy(materialized[slot])
if slot == runtime.IMAGE_OUT:
value, kind = image, "IMAGE"
elif slot == runtime.MASK_OUT:
value, kind = item.get("mask"), "MASK"
elif slot == runtime.INDEX_OUT:
value, kind = item["index"], "INT"
elif runtime.VALUE_OUT_BASE <= slot < runtime.VALUE_OUT_BASE + runtime.MAX_VALUE_SLOTS:
name = runtime.VALUE_NAMES[slot - runtime.VALUE_OUT_BASE]
value = values.get(name)
kind = runtime.value_kind(value, name)
if kind == "TENSOR":
if value.ndim == 4:
kind = "IMAGE"
elif value.ndim == 3:
kind = "MASK"
else:
raise ValueError(f"{name} serverless tensor requires IMAGE [B,H,W,C] or MASK [B,H,W]")
else:
raise ValueError("Unsupported Start context/control output in endpoint computation")
if value is None:
raise ValueError("Connected Start output is empty; None cannot be submitted")
if kind in ("IMAGE", "MASK"):
if kind == "MASK" and slot == runtime.MASK_OUT:
if value.ndim != 3 or value.shape[0] != 1 or value.shape[1:3] != image.shape[1:3]:
raise ValueError("Image-list item mask must be paired with its image grid")
if value.numel() * value.element_size() > contract.MAX_ARTIFACT_BYTES:
raise ValueError("Image-list tensor exceeds media artifact byte limit")
descriptor, payload = codec.encode_payload(kind, value.detach().to("cpu"),
max_bytes=contract.MAX_ARTIFACT_BYTES)
aid = _artifact_id(kind, descriptor, payload)
if aid not in artifacts and (len(artifacts) >= contract.MAX_ARTIFACTS or
len(payload) + sum(a["byte_length"] for a in artifacts.values()) > contract.MAX_TOTAL_BYTES):
raise ValueError("Image-list media inputs exceed artifact limits")
artifacts[aid] = contract.artifact_from_payload(aid, kind, descriptor, payload)
placeholder = _new_node_id(graph, str(slot))
graph[placeholder] = {"class_type": "PrimitiveString", "inputs": {"value": ""}}
placeholders[placeholder] = aid
output = [placeholder, 0]
else:
# value_kind rejects objects/None/nonfinite values and bool remains bool.
runtime.value_kind(value, "Start output")
output = value
materialized[slot] = output
return copy.deepcopy(output)
for node_id in list(graph):
inputs = graph[node_id].setdefault("inputs", {})
for name, value in list(inputs.items()):
link = _link(value, prompt)
if link and link[0] == start:
inputs[name] = replacement(link[1])
elif link:
inputs[name] = list(link)
# Start text/index/generic scalar substitutions may have removed End's link.
text = graph[end]["inputs"].get("texts")
if "texts" in graph[end]["inputs"] and not isinstance(text, list):
if not isinstance(text, str):
raise ValueError("Image-list End texts must be STRING")
nid = _new_node_id(graph, "text")
graph[nid] = {"class_type": "PrimitiveString", "inputs": {"value": text}}
graph[end]["inputs"]["texts"] = [nid, 0]
workflow, manifest = compile_media_prompt(graph, request_id)
refs = []
for nid, node in workflow.items():
for name, value in node["inputs"].items():
if isinstance(value, list) and value[0] in placeholders:
refs.append({"node_id": nid, "input_name": name, "artifact_id": placeholders[value[0]]})
# Only actual surviving consumer slots count as uses of an input artifact.
used = {ref["artifact_id"] for ref in refs}
images, fixed_artifacts, fixed_refs = await prepare_media_inputs(workflow)
merged = _merge_artifacts([artifacts[aid] for aid in used], fixed_artifacts)
refs.extend(fixed_refs)
media = {"version": contract.VERSION, "profile": contract.PROFILE,
"request_id": request_id, "artifacts": merged,
"inputs": sorted(refs, key=lambda ref: (ref["node_id"], ref["input_name"])),
"outputs": manifest}
# Includes handler identity/link/ref validation and aggregate + exact JSON caps.
serialize_request(workflow, images, worker["timeout_seconds"], media=media)
return {"worker": worker, "workflow": workflow, "images": images,
"manifest": manifest, "media": media}
class ServerlessSlots:
"""Nonblocking slot adapter; completion means the manager task has drained."""
def __init__(self, state, region, workers, manager, event):
self.state, self.region, self.manager, self.event = state, region, manager, event
self.workers = {worker["id"]: worker for worker in workers}
# The manager remains the atomic authority at start(). Bound this local
# scheduler too, including other callers' currently pending tasks.
available = max(0, 64 - sum(not task.done() for task in manager.tasks.values())) if manager else 0
self.slots = [("serverless", worker["id"], index)
for index in range(PER_WORKER_JOB_LIMIT) for worker in workers][:available]
if workers and not self.slots:
raise ValueError("Distributed already has too many pending serverless jobs (limit 64)")
digest = hashlib.sha256(state.context_id.encode()).hexdigest()
self._scope = f"image-list:{digest}:{uuid.uuid4().hex}"
self._active = {}
self._queues = {}
self._executions = set()
self._assigned = set()
self._submissions = set()
self._closed = False
self._close_task = None
async def dispatch(self, slot, index):
if self._closed:
raise RuntimeError("Image-list serverless controller is closed")
if slot not in self.slots or slot in self._active:
raise RuntimeError("Unknown or occupied serverless image-list slot")
if type(index) is not int or not 0 <= index < len(self.state.items) or index in self._assigned:
raise ValueError("Invalid or duplicate serverless image-list index")
if self.state.items[index].get("index") != index:
raise ValueError("Serverless image-list item index mismatch")
self._assigned.add(index)
identity = f"{self._scope}:{index}"
handle = {"index": index, "execution_id": identity, "job_id": identity,
"worker_id": slot[1], "task": None}
self._active[slot] = handle
# Own execution identity BEFORE start, even if its caller loses the handle.
self._executions.add(identity)
task = asyncio.create_task(self._submit(handle))
self._submissions.add(task)
try:
await asyncio.shield(task)
return handle
except BaseException:
if not task.done():
task.cancel()
await asyncio.gather(task, return_exceptions=True)
self._remove_queue(handle["job_id"])
await self.manager.cancel(execution_id=identity)
raise
finally:
self._submissions.discard(task)
async def _submit(self, handle):
job = await prepare_serverless_item(
self.state.original_prompt, self.region, self.state.items[handle["index"]],
self.workers[handle["worker_id"]], request_id=handle["execution_id"], job_id=handle["job_id"])
if self._closed:
raise RuntimeError("Image-list serverless controller closed during preparation")
self.manager.ensure_capacity(1)
queue = asyncio.Queue()
async with self.manager.server.distributed_jobs_lock:
if self._closed:
raise RuntimeError("Image-list serverless controller is closed")
if handle["job_id"] in self.manager.server.distributed_pending_jobs:
raise RuntimeError("Duplicate serverless image-list queue identity")
self._queues[handle["job_id"]] = queue
self.manager.server.distributed_pending_jobs[handle["job_id"]] = queue
handle["sockets"] = {binding["socket"] for binding in job["manifest"]}
record_ids = await self.manager.start(handle["execution_id"], self.state.prompt_id, [job])
if len(record_ids) != 1 or record_ids[0] not in self.manager.tasks:
raise RuntimeError("Missing serverless image-list lifecycle task")
handle["task"] = self.manager.tasks[record_ids[0]]
handle["task"].add_done_callback(lambda _: self.event.set())
def _remove_queue(self, job_id):
queue = self._queues.pop(job_id, None)
# Same event-loop turn, without an await: never delete a replacement queue.
if queue is not None and self.manager.server.distributed_pending_jobs.get(job_id) is queue:
del self.manager.server.distributed_pending_jobs[job_id]
def poll(self, inflight):
if self._closed:
raise RuntimeError("Image-list serverless controller is closed")
for slot, handle in inflight.items():
if slot not in self.slots:
continue # Direct/master slots belong to the surrounding scheduler.
if self._active.get(slot) is not handle:
raise RuntimeError("Mismatched or duplicate serverless image-list completion handle")
task = handle["task"]
if task is None or not task.done():
continue
if task.cancelled():
raise RuntimeError("Serverless image-list task was cancelled")
if task.exception() is not None:
raise RuntimeError("Serverless image-list lifecycle task failed") from task.exception()
queue = self._queues.get(handle["job_id"])
if queue is None or self.manager.server.distributed_pending_jobs.get(handle["job_id"]) is not queue:
raise RuntimeError("Missing serverless image-list result queue")
if queue.qsize() != 1:
raise RuntimeError("Missing or duplicate serverless image-list terminal result")
message = queue.get_nowait()
if (not isinstance(message, dict) or message.get("worker_id") != handle["worker_id"]
or message.get("is_last") is not True):
raise RuntimeError("Mismatched serverless image-list result identity")
if "serverless_error" in message:
raise RuntimeError(f"Serverless image-list item {handle['index']} failed: {message['serverless_error']}")
media = message.get("media")
if not isinstance(media, dict) or set(media) != handle["sockets"]:
raise RuntimeError("Missing or unexpected serverless image-list result sockets")
if any(not isinstance(values, list) or len(values) != 1 or values[0] is None
for values in media.values()):
raise RuntimeError("Serverless image-list result requires exactly one value per socket")
result = runtime.normalize_worker_result(media["images"], media.get("masks"), media.get("texts"))
if result["mask"] is not None and result["mask"].shape[1:3] != result["image"].shape[1:3]:
raise ValueError("Serverless image-list result mask is not paired with the image grid")
self._remove_queue(handle["job_id"])
del self._active[slot]
return slot, handle["index"], result
return None
async def _close(self):
# Stop preparation/start before cancellation discovery, then retire exact
# destinations before manager callbacks can publish cancellation errors.
submissions = tuple(self._submissions)
for task in submissions:
if not task.done():
task.cancel()
await asyncio.gather(*submissions, return_exceptions=True)
for job_id in list(self._queues):
self._remove_queue(job_id)
await asyncio.gather(*(self.manager.cancel(execution_id=eid) for eid in self._executions))
self._active.clear()
async def close(self):
if self._close_task is None:
self._closed = True
self._close_task = asyncio.create_task(self._close())
cancelled = False
while not self._close_task.done():
try:
await asyncio.shield(self._close_task)
except asyncio.CancelledError:
cancelled = True
self._close_task.result()
if cancelled:
raise asyncio.CancelledError
async def create_serverless_slots(state, region, config, event):
workers = resolve_serverless_workers(config, state.worker_ids)
return ServerlessSlots(state, region, workers, get_manager() if workers else None, event)
+19 -3
View File
@@ -117,12 +117,28 @@ class MasterSelectionTests(unittest.IsolatedAsyncioTestCase):
await self.queue()
self.q.queue_prompt_payload.assert_not_awaited()
async def test_serverless_only_uses_master_without_provider_dispatch(self):
self.config["workers"] = [{"id": "pool", "type": "serverless", "enabled": True}]
async def test_serverless_pool_is_retained_with_participating_master(self):
self.config["workers"] = [{
"id": "pool", "name": "Cloud", "type": "serverless", "enabled": True,
"endpoint_id": "endpoint", "media_profile": "comfy-media-v1",
}]
result = await self.queue()
self.assertIs(self.prepared_inputs()["image_list_master_participates"], True)
self.assertEqual(result[2], 0)
self.assertEqual(json.loads(self.prepared_inputs()["image_list_enabled_worker_ids"]), ["pool"])
self.assertEqual(result[2], 1)
self.preflight.assert_not_awaited()
self.q.dispatch_worker_prompt.assert_not_awaited()
self.assertEqual(self.ps.distributed_pending_jobs, {})
async def test_legacy_serverless_pool_is_rejected_not_silently_ignored(self):
self.config["workers"] = [{
"id": "pool", "name": "Cloud", "type": "serverless", "enabled": True,
"endpoint_id": "endpoint",
}]
with self.assertRaisesRegex(ValueError, "comfy-media-v1"):
await self.queue()
self.q.queue_prompt_payload.assert_not_awaited()
self.preflight.assert_not_awaited()
async def test_incompatible_worker_is_not_silently_hidden_by_master(self):
self.preflight.side_effect = RuntimeError("upgrade worker")
+683
View File
@@ -0,0 +1,683 @@
"""CPU-only image-list compilation and lifecycle tests; providers are mocked."""
import asyncio
import base64
import copy
import importlib
import json
import sys
import tempfile
import types
import unittest
from pathlib import Path
from unittest.mock import AsyncMock, patch
import pytest
import torch
ROOT = Path(__file__).resolve().parents[1]
PACKAGE = "_image_list_serverless_tests"
for suffix in ("", ".api", ".api.orchestration", ".image_list", ".serverless_bridge"):
module = types.ModuleType(PACKAGE + suffix)
module.__path__ = [str(ROOT.joinpath(*suffix.strip(".").split(".")))] if suffix else [str(ROOT)]
sys.modules[module.__name__] = module
adapter = importlib.import_module(PACKAGE + ".image_list.serverless")
runtime = adapter.runtime
manager_module = importlib.import_module(PACKAGE + ".api.orchestration.serverless_runtime")
handler = importlib.import_module(PACKAGE + ".serverless_bridge.handler")
codec, contract = adapter.codec, adapter.contract
def node(kind, **inputs):
return {"class_type": kind, "inputs": inputs}
def pool(wid="pool", jobs=1, enabled=True, **overrides):
return dict(id=wid, type="serverless", endpoint_id="ep", timeout_seconds=30,
jobs_per_run=jobs, enabled=enabled, media_profile=contract.PROFILE, **overrides)
def source():
return {
"upstream": node("LoadImage", image="never-read.png"),
"ns/start": node(runtime.START_CLASS, images=["upstream", 0]),
"model": node("CheckpointLoaderSimple", ckpt_name="fixed.safetensors"),
"process": node("Process", image=["ns/start", 0], mask=["ns/start", 1],
index=["ns/start", 2], text=["ns/start", 4], integer=["ns/start", 5],
floating=["ns/start", 6], boolean=["ns/start", 7], model=["model", 0]),
"ns/end": node(runtime.END_CLASS, context=["ns/start", 3], images=["process", 0],
masks=["process", 1], texts=["ns/start", 4], worker_result_token="drop-me"),
"downstream": node("SaveImage", images=["ns/end", 0]),
}
def region(prompt=None):
return {"start_id": "ns/start", "end_id": "ns/end",
"node_ids": set(prompt or source()) - {"upstream", "downstream"}}
def item(index=0, dtype=torch.float32):
return {"index": index, "image": torch.arange(24, dtype=dtype).reshape(1, 2, 3, 4) / 24,
"mask": torch.arange(6, dtype=dtype).reshape(1, 2, 3) / 6,
"values": {"value_1": " \n雪", "value_2": 123, "value_3": 0.25, "value_4": False}}
async def prepare(prompt=None, value=None, worker=None):
prompt = prompt or source()
return await adapter.prepare_serverless_item(prompt, region(prompt), value or item(), worker or pool(),
request_id="request:1", job_id="queue:1")
async def decoded_inputs(job):
return {artifact["id"]: codec.decode_payload(artifact["kind"], artifact["descriptor"],
await contract.resolve_artifact(artifact)) for artifact in job["media"]["artifacts"]}
def test_selection_is_exact_no_expansion_or_profile_fallback():
a, b = pool("a", jobs=16), pool("b", enabled=False)
direct = {"id": "direct", "type": "remote", "enabled": True}
config = {"workers": [a, b, direct]}
assert [w["id"] for w in adapter.resolve_serverless_workers(config, None)] == ["a"]
resolved = adapter.resolve_serverless_workers(config, ["b", "direct"])
assert [w["id"] for w in resolved] == ["b"]
assert resolved[0]["pool_id"] == "b"
resolved[0]["jobs_per_run"] = 2
assert b["jobs_per_run"] == 1
assert adapter.resolve_serverless_workers(config, []) == []
legacy = pool("legacy", enabled=False)
legacy.pop("media_profile")
config["workers"].append(legacy)
assert [w["id"] for w in adapter.resolve_serverless_workers(config, None)] == ["a"]
with pytest.raises(ValueError, match="comfy-media-v1"):
adapter.resolve_serverless_workers(config, ["legacy"])
with pytest.raises(ValueError, match="Unknown"):
adapter.resolve_serverless_workers(config, ["a:1"])
with pytest.raises(ValueError, match="Invalid"):
adapter.resolve_serverless_workers(config, [" a"])
with pytest.raises(ValueError, match="Duplicate"):
adapter.resolve_serverless_workers({"workers": [a, a]}, ["a"])
@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16, torch.float32, torch.float64])
def test_deterministic_graph_exact_codecs_and_source_immutable(dtype):
async def check():
prompt, value = source(), item(dtype=dtype)
original, saved_image = copy.deepcopy(prompt), value["image"].clone()
one = await prepare(prompt, value)
two = await prepare(dict(reversed(list(prompt.items()))), value)
assert one == two
assert prompt == original and torch.equal(value["image"], saved_image)
assert "upstream" not in one["workflow"] and "downstream" not in one["workflow"]
assert one["workflow"]["model"] == prompt["model"]
assert not any("distributed" in n["class_type"].lower() for n in one["workflow"].values())
proc = one["workflow"]["process"]["inputs"]
for name, expected in [("index", 0), ("integer", 123), ("floating", 0.25), ("boolean", False), ("text", " \n雪")]:
assert proc[name] == expected and type(proc[name]) is type(expected)
output = next(b for b in one["manifest"] if b["socket"] == "texts")
text_source = one["workflow"][output["node_id"]]["inputs"]["texts"][0]
assert one["workflow"][text_source] == node("PrimitiveString", value=" \n雪")
values = await decoded_inputs(one)
for ref in one["media"]["inputs"]:
result = values[ref["artifact_id"]]
assert result.dtype == dtype
assert torch.equal(result, value[ref["input_name"]])
assert len(values) == 2
handler._validate_request({key: one[key] for key in ("workflow", "images", "media")})
asyncio.run(check())
def test_direct_passthrough_exports_and_tensor_generic_values_deduplicate():
async def check():
prompt, value = source(), item()
prompt["process"]["inputs"]["reference"] = ["ns/start", 8]
prompt["process"]["inputs"]["reference_mask"] = ["ns/start", 9]
value["values"].update(value_5=value["image"], value_6=value["mask"])
prompt["ns/end"]["inputs"]["images"] = ["ns/start", 0]
job = await prepare(prompt, value)
assert "process" in job["workflow"] # mask still depends on processing
assert len(job["media"]["artifacts"]) == 2
refs = job["media"]["inputs"]
assert len(refs) == 5
image_binding = next(b for b in job["manifest"] if b["socket"] == "images")
assert any(r["node_id"] == image_binding["node_id"] and r["input_name"] == "images" for r in refs)
decoded = await decoded_inputs(job)
for ref in refs:
tensor = decoded[ref["artifact_id"]]
assert torch.equal(tensor, value["mask"] if "mask" in ref["input_name"] else value["image"])
asyncio.run(check())
@pytest.mark.parametrize("bad", [None, object(), torch.ones(2), torch.ones(2, 3)])
def test_connected_unsupported_generic_values_fail(bad):
value = item()
value["values"]["value_1"] = bad
with pytest.raises((ValueError, TypeError)):
asyncio.run(prepare(value=value))
@pytest.mark.parametrize("bad", [True, -1, "0", 0.0])
def test_start_slot_identity_not_coerced(bad):
prompt = source()
prompt["process"]["inputs"]["image"] = ["ns/start", bad]
with pytest.raises(ValueError, match="link"):
asyncio.run(prepare(prompt))
@pytest.mark.parametrize("bad", ["../bad", "ns//bad", "ns/./bad", "bad ", 42])
def test_node_identity_not_normalized_even_on_pruned_branch(bad):
prompt = source()
prompt[bad] = node("PrimitiveString", value="unused")
with pytest.raises(ValueError):
asyncio.run(prepare(prompt))
def test_placeholder_namespace_collision_and_empty_text():
async def check():
prompt, value = source(), item()
prompt["image-list:input:0"] = node("PrimitiveInt", value=5)
prompt["process"]["inputs"]["fixed"] = ["image-list:input:0", 0]
value["values"]["value_1"] = ""
job = await prepare(prompt, value)
assert job["workflow"]["image-list:input:0"] == prompt["image-list:input:0"]
assert job["workflow"]["process"]["inputs"]["image"] == ["image-list:input:0:1", 0]
assert any(n == node("PrimitiveString", value="") for n in job["workflow"].values())
asyncio.run(check())
def test_no_connected_none_and_payload_budget_before_submission():
value = item()
value["mask"] = None
with pytest.raises(ValueError, match="empty"):
asyncio.run(prepare(value=value))
client = importlib.import_module(PACKAGE + ".api.orchestration.runpod_client")
with patch.object(client, "MAX_REQUEST_BYTES", 10):
with pytest.raises(ValueError, match="Serialized"):
asyncio.run(prepare())
def test_fixed_file_inputs_are_prepared_on_private_copy_and_merge(tmp_path, monkeypatch):
input_dir = tmp_path / "input"
input_dir.mkdir()
(tmp_path / "output").mkdir()
(tmp_path / "temp").mkdir()
payload = b"bounded original file bytes"
(input_dir / "fixed.png").write_bytes(payload)
folders = types.SimpleNamespace(get_input_directory=lambda: str(input_dir),
get_output_directory=lambda: str(tmp_path / "output"), get_temp_directory=lambda: str(tmp_path / "temp"),
get_annotated_filepath=lambda name: str(input_dir / name))
monkeypatch.setitem(sys.modules, "folder_paths", folders)
prompt = source()
prompt["fixed"] = node("LoadImage", image="fixed.png")
prompt["process"]["inputs"]["fixed"] = ["fixed", 0]
original = copy.deepcopy(prompt)
job = asyncio.run(prepare(prompt))
assert prompt == original
assert len(job["images"]) == 1
assert base64.b64decode(job["images"][0]["image"]) == payload
assert job["workflow"]["fixed"]["inputs"]["image"] == job["images"][0]["name"]
assert len(job["media"]["artifacts"]) == 2
def test_merge_rejects_conflicting_artifact_ids_and_combined_caps():
async def check():
job = await prepare()
artifact = job["media"]["artifacts"][0]
assert adapter._merge_artifacts([artifact], [copy.deepcopy(artifact)]) == [artifact]
bad = copy.deepcopy(artifact)
bad["sha256"] = "0" * 64
with pytest.raises(ValueError, match="identity"):
adapter._merge_artifacts([artifact], [bad])
with patch.object(contract, "MAX_TOTAL_BYTES", 1):
with pytest.raises(ValueError, match="limits"):
adapter._merge_artifacts([artifact])
asyncio.run(check())
def test_handler_injects_exact_native_values_and_prunes_placeholders():
async def check():
value = item(dtype=torch.float64)
prompt = source()
prompt["ns/end"]["inputs"].update(images=["ns/start", 0], masks=["ns/start", 1])
job = await prepare(prompt, value)
workflow, media, legacy, targets = handler._validate_request(
{key: job[key] for key in ("workflow", "images", "media")})
buffers = {}
def write(payload):
name = f"owned-{len(buffers)}.bin"
buffers[name] = payload
return name
class Submitted(Exception):
pass
async def submit(native_graph):
assert all(n["class_type"] in {"MediaExportV1", "MediaImportV1", "PrimitiveString"}
for n in native_graph.values())
for binding in job["manifest"]:
link = native_graph[binding["node_id"]]["inputs"][binding["socket"]]
native = native_graph[link[0]]
if binding["kind"] == "STRING":
assert native == node("PrimitiveString", value=value["values"]["value_1"])
continue
assert native["class_type"] == "MediaImportV1"
metadata = json.loads(native["inputs"]["artifact_json"])
decoded = codec.decode_payload(metadata["kind"], metadata["descriptor"],
buffers[native["inputs"]["filename"]])
assert link[1] == {"IMAGE": 0, "MASK": 2}[binding["kind"]]
assert torch.equal(decoded, value["image" if binding["kind"] == "IMAGE" else "mask"])
# Stop at the mocked HTTP boundary; no endpoint/process/provider exists.
raise Submitted()
execution = types.SimpleNamespace(media=media, targets=targets, remaining=lambda: 30,
stage=types.SimpleNamespace(write=write), submit_and_wait=submit)
with pytest.raises(Submitted):
await handler._run(execution, workflow, legacy, None, None)
asyncio.run(check())
def test_fixed_typed_inputs_merge_with_start_refs_without_losing_consumers():
async def check():
prompt = source()
prompt["process"]["inputs"]["fixed_audio"] = 0
audio = {"waveform": torch.ones(1, 2, 3), "sample_rate": 48000}
descriptor, payload = codec.encode_payload("AUDIO", audio)
artifact = contract.artifact_from_payload("fixed-audio", "AUDIO", descriptor, payload)
fixed = AsyncMock(return_value=([], [artifact], [
{"node_id": "process", "input_name": "fixed_audio", "artifact_id": "fixed-audio"}]))
with patch.object(adapter, "prepare_media_inputs", fixed):
job = await prepare(prompt)
assert len(job["media"]["artifacts"]) == 3
assert len(job["media"]["inputs"]) == 3
assert any(ref["input_name"] == "fixed_audio" for ref in job["media"]["inputs"])
decoded = await decoded_inputs(job)
assert decoded["fixed-audio"]["sample_rate"] == 48000
assert torch.equal(decoded["fixed-audio"]["waveform"], audio["waveform"])
asyncio.run(check())
class LifecycleTests(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
self.temp = tempfile.TemporaryDirectory()
self.server = types.SimpleNamespace(distributed_pending_jobs={}, distributed_jobs_lock=asyncio.Lock())
self.manager = manager_module.ServerlessManager(self.server,
types.SimpleNamespace(get=lambda _wid: "fake-key"), Path(self.temp.name) / "jobs.json", AsyncMock())
self.manager.poll_seconds = 0
self.state = runtime.ImageListJob("context", "ns/start", "ns/end", source(),
[item(i) for i in range(40)], ["pool"], "", prompt_id="master-prompt")
self.gates, self.jobs, self.mutations = {}, {}, {}
self.started = asyncio.Event()
async def submit(workflow, images, timeout, *, media):
jid = "provider-" + str(len(self.jobs))
self.jobs[jid] = dict(workflow=workflow, images=images, media=media)
self.gates[jid] = asyncio.Event()
self.started.set()
return jid
async def status(jid):
await self.gates[jid].wait()
output = self.output(self.jobs[jid])
if jid in self.mutations:
self.mutations[jid](output)
return {"status": "COMPLETED", "output": output}
self.api = types.SimpleNamespace(submit=AsyncMock(side_effect=submit), status=AsyncMock(side_effect=status),
cancel=AsyncMock(return_value={"status": "CANCELLED"}))
self.patches = [patch.object(manager_module, "RunpodClient", return_value=self.api),
patch.object(adapter, "get_manager", return_value=self.manager)]
for p in self.patches:
p.start()
self.event = asyncio.Event()
self.controllers = []
self.controller = await self.controller_for()
async def controller_for(self, workers=None, state=None):
ctl = await adapter.create_serverless_slots(state or self.state, region(),
{"workers": workers or [pool()]}, self.event)
self.controllers.append(ctl)
return ctl
async def asyncTearDown(self):
for ctl in self.controllers:
await ctl.close()
await self.manager.cancel()
for p in reversed(self.patches):
p.stop()
self.temp.cleanup()
def output(self, job):
media = job["media"]
output = dict(version=1, profile=contract.PROFILE, request_id=media["request_id"],
bindings=[], artifacts=[], items=[])
index = int(media["request_id"].rsplit(":", 1)[1])
data = item(index)
values = {"images": data["image"], "masks": data["mask"], "texts": str(index)}
for n, binding in enumerate(media["outputs"]):
descriptor, payload = codec.encode_payload(binding["kind"], values[binding["socket"]])
aid = f"result:{n}"
output["bindings"].append(dict(binding, count=1))
output["artifacts"].append(contract.artifact_from_payload(aid, binding["kind"], descriptor, payload))
output["items"].insert(0, dict(binding_id=binding["binding_id"], item_index=0, artifact_id=aid))
return {"media": output}
async def dispatch(self, index=0, ctl=None, slot=None):
ctl = ctl or self.controller
slot = slot or ctl.slots[index]
handle = await ctl.dispatch(slot, index)
return slot, handle
async def finish(self, handle):
# Submission has run by the time dispatch's shield completes, but yield
# explicitly rather than assuming provider status has already been entered.
while len(self.jobs) <= handle["index"]:
await asyncio.sleep(0)
jid = next(j for j, job in self.jobs.items()
if job["media"]["request_id"] == handle["execution_id"])
self.gates[jid].set()
await handle["task"]
async def test_no_pool_does_not_initialize_manager_or_credentials(self):
state = copy.copy(self.state)
state.worker_ids = []
with patch.object(adapter, "get_manager", side_effect=AssertionError("must stay lazy")):
ctl = await adapter.create_serverless_slots(state, region(), {"workers": [pool()]}, self.event)
assert ctl.slots == []
await ctl.close()
async def test_slots_are_bounded_not_jobs_per_run_and_cannot_collide(self):
assert len(self.controller.slots) == manager_module.PER_WORKER_JOB_LIMIT == 16
ctl = await self.controller_for([pool(jobs=16)])
assert ctl.slots == self.controller.slots
assert all(isinstance(slot, tuple) and len(slot) == 3 for slot in ctl.slots)
assert len(set(ctl.slots)) == 16 and "pool" not in ctl.slots
many = [pool(f"p{i}") for i in range(8)]
state = copy.copy(self.state)
state.worker_ids = [w["id"] for w in many]
ctl = await self.controller_for(many, state)
assert len(ctl.slots) == 64
assert all(sum(s[1] == w["id"] for s in ctl.slots) <= 16 for w in many)
async def test_reverse_completion_order_and_slot_reuse(self):
first, second = await self.dispatch(0), await self.dispatch(1)
inflight = dict([first, second])
assert self.controller.poll(inflight) is None
await self.finish(second[1])
await asyncio.sleep(0)
assert self.event.is_set()
slot, index, result = self.controller.poll(inflight)
assert (slot, index) == (second[0], 1) and result["text"] == "1"
assert torch.equal(result["image"], item(1)["image"])
assert second[1]["job_id"] not in self.server.distributed_pending_jobs
del inflight[slot]
third = await self.dispatch(2, slot=slot)
assert third[1]["execution_id"] != second[1]["execution_id"]
await self.finish(first[1])
assert self.controller.poll(inflight)[1] == 0
await self.finish(third[1])
assert self.controller.poll(dict([third]))[1] == 2
async def test_many_items_submit_once_each_through_bounded_reusable_slots(self):
ctl = await self.controller_for([pool(jobs=16)])
first_wave = asyncio.Event()
active = 0
peak = 0
original_submit = self.api.submit.side_effect
async def submit(*args, **kwargs):
jid = await original_submit(*args, **kwargs)
if len(self.jobs) == 16:
first_wave.set()
return jid
async def status(jid):
nonlocal active, peak
active += 1
peak = max(peak, active)
try:
await first_wave.wait()
await asyncio.sleep(0.001)
return {"status": "COMPLETED", "output": self.output(self.jobs[jid])}
finally:
active -= 1
self.api.submit.side_effect = submit
self.api.status.side_effect = status
async def next_result(inflight):
while True:
self.event.clear()
completed = ctl.poll(inflight)
if completed is not None:
return completed
await self.event.wait()
async def cleanup(*_):
pass
results = await asyncio.wait_for(runtime.dynamic_schedule(
len(self.state.items), ctl.slots, ctl.dispatch, next_result, cleanup), 10)
assert self.api.submit.await_count == len(self.state.items)
assert [row["text"] for row in results] == [str(i) for i in range(len(self.state.items))]
assert peak == 16
assert not self.server.distributed_pending_jobs
assert all(task.done() for task in self.manager.tasks.values())
async def test_waits_for_task_drain_not_provider_terminal_or_queue_message(self):
entered, release = asyncio.Event(), asyncio.Event()
original = self.manager._notify_capacity
async def delayed():
entered.set()
await release.wait()
await original()
with patch.object(self.manager, "_notify_capacity", delayed):
slot, handle = await self.dispatch()
self.gates["provider-0"].set()
await entered.wait()
assert self.server.distributed_pending_jobs[handle["job_id"]].qsize() == 1
assert self.controller.poll({slot: handle}) is None
with pytest.raises(RuntimeError, match="occupied"):
await self.controller.dispatch(slot, 1)
release.set()
await handle["task"]
assert self.controller.poll({slot: handle})[1] == 0
async def test_unknown_reservations_survive_and_prevent_provider_admission(self):
for i in range(16):
self.manager.ledger.update(f"unknown-{i}", worker_id="pool", status="UNKNOWN", job_id=None)
slot, handle = await self.dispatch()
await asyncio.sleep(0)
self.api.submit.assert_not_awaited()
assert self.controller.poll({slot: handle}) is None
await self.controller.close()
assert sum(r["status"] == "UNKNOWN" for r in self.manager.ledger.all()) == 16
assert not self.server.distributed_pending_jobs
assert self.manager.pool_is_active("pool")
async def test_local_pending_cap_checked_before_journal(self):
waiting = [asyncio.create_task(asyncio.Event().wait()) for _ in range(64)]
self.manager.tasks.update({f"unrelated-{i}": t for i, t in enumerate(waiting)})
self.manager.runs.update({f"unrelated-{i}": {"execution_id": "unrelated"} for i in range(64)})
try:
with pytest.raises(ValueError, match="limit 64"):
await self.dispatch()
assert not self.manager.ledger.all()
self.api.submit.assert_not_awaited()
assert not self.server.distributed_pending_jobs
finally:
for i, task in enumerate(waiting):
self.manager.tasks.pop(f"unrelated-{i}")
self.manager.runs.pop(f"unrelated-{i}")
task.cancel()
await asyncio.gather(*waiting, return_exceptions=True)
async def test_missing_corrupt_or_mismatched_results_are_atomic_errors(self):
mutations = [lambda o: o["media"]["items"].pop(),
lambda o: o["media"]["artifacts"][-1].update(sha256="0" * 64),
lambda o: o["media"].update(request_id="wrong-request"),
lambda o: o["media"]["bindings"][-1].update(participant_id="wrong-worker")]
for index, mutation in enumerate(mutations):
slot, handle = await self.dispatch(index)
self.mutations[f"provider-{index}"] = mutation
await self.finish(handle)
queue = self.server.distributed_pending_jobs[handle["job_id"]]
assert queue.qsize() == 1
with pytest.raises(RuntimeError, match="failed"):
self.controller.poll({slot: handle})
async def test_terminal_queue_identity_completeness_and_multiplicity(self):
for index, kind in enumerate(("missing", "duplicate", "worker", "mask", "text", "multiple", "empty")):
slot, handle = await self.dispatch(index)
await self.finish(handle)
queue = self.server.distributed_pending_jobs[handle["job_id"]]
message = queue.get_nowait()
if kind == "duplicate":
queue.put_nowait(message)
if kind == "worker":
message["worker_id"] = "unrelated"
if kind in ("mask", "text"):
message["media"].pop("masks" if kind == "mask" else "texts")
if kind == "multiple":
message["media"]["images"].append(item()["image"])
if kind == "empty":
message["media"]["texts"] = [None]
if kind != "missing":
queue.put_nowait(message)
with pytest.raises(RuntimeError):
self.controller.poll({slot: handle})
async def test_wrong_frame_count_channels_and_unpaired_mask_fail(self):
for index, kind in enumerate(("batch", "channels", "grid")):
slot, handle = await self.dispatch(index)
await self.finish(handle)
queue = self.server.distributed_pending_jobs[handle["job_id"]]
message = queue.get_nowait()
if kind == "batch":
message["media"]["images"] = [torch.ones(2, 2, 3, 4)]
elif kind == "channels":
message["media"]["images"] = [torch.ones(1, 2, 3, 1)]
else:
message["media"]["masks"] = [torch.ones(1, 5, 5)]
queue.put_nowait(message)
with pytest.raises(ValueError):
self.controller.poll({slot: handle})
async def test_close_cancels_only_owned_execution_and_exact_queues(self):
state = copy.copy(self.state)
state.context_id = "unrelated"
unrelated = await self.controller_for(state=state)
other_slot, other = await self.dispatch(0, unrelated)
slot, handle = await self.dispatch(0)
queue = self.server.distributed_pending_jobs[handle["job_id"]]
replacement = asyncio.Queue()
self.server.distributed_pending_jobs[handle["job_id"]] = replacement
await self.controller.close()
assert other["task"].done() is False
assert self.server.distributed_pending_jobs[handle["job_id"]] is replacement
assert other["job_id"] in self.server.distributed_pending_jobs
assert handle["task"].done()
assert len(self.api.cancel.await_args_list) == 1
assert queue.empty()
self.server.distributed_pending_jobs.pop(handle["job_id"])
# A late manager callback skips a retired destination instead of recreating it.
run = next(r for r in self.manager.runs.values() if r["execution_id"] == handle["execution_id"])
await self.manager._deliver(run, error="late")
assert handle["job_id"] not in self.server.distributed_pending_jobs
async def test_cancel_dispatch_after_start_loses_handle_but_not_ownership(self):
entered = asyncio.Event()
original = self.manager.start
async def delayed(*args):
ids = await original(*args)
entered.set()
await asyncio.Event().wait()
return ids
with patch.object(self.manager, "start", delayed):
task = asyncio.create_task(self.controller.dispatch(self.controller.slots[0], 0))
await entered.wait()
await self.started.wait()
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
await self.controller.close()
assert all(t.done() for t in self.manager.tasks.values())
assert not self.server.distributed_pending_jobs
self.api.cancel.assert_awaited_once_with("provider-0")
async def test_close_during_preparation_prevents_late_start(self):
entered = asyncio.Event()
prepared = await prepare()
async def resistant(*args, **kwargs):
entered.set()
try:
await asyncio.Event().wait()
except asyncio.CancelledError:
return prepared
with patch.object(adapter, "prepare_serverless_item", resistant):
task = asyncio.create_task(self.controller.dispatch(self.controller.slots[0], 0))
await entered.wait()
await self.controller.close()
with pytest.raises(RuntimeError, match="closed"):
await task
assert not self.manager.ledger.all()
assert not self.server.distributed_pending_jobs
self.api.submit.assert_not_awaited()
async def test_cancel_during_provider_submission_preserves_unknown(self):
entered = asyncio.Event()
async def ambiguous(*args, **kwargs):
entered.set()
await asyncio.Event().wait()
self.api.submit.side_effect = ambiguous
slot, handle = await self.dispatch()
await entered.wait()
await self.controller.close()
assert next(iter(self.manager.ledger.all()))["status"] == "UNKNOWN"
assert self.manager.pool_is_active("pool")
self.api.cancel.assert_not_awaited()
assert not self.server.distributed_pending_jobs
async def test_cancelled_wait_closes_owned_work(self):
entered = asyncio.Event()
async def job():
try:
await self.dispatch()
entered.set()
await asyncio.Event().wait()
finally:
await self.controller.close()
task = asyncio.create_task(job())
await entered.wait()
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
assert all(t.done() for t in self.manager.tasks.values())
assert not self.server.distributed_pending_jobs
async def test_repeated_cancellation_does_not_abandon_close(self):
slot, handle = await self.dispatch()
entered, release = asyncio.Event(), asyncio.Event()
original = self.manager.cancel
async def delayed(**kwargs):
entered.set()
await release.wait()
return await original(**kwargs)
with patch.object(self.manager, "cancel", delayed):
closing = asyncio.create_task(self.controller.close())
await entered.wait()
closing.cancel()
await asyncio.sleep(0)
closing.cancel()
await asyncio.sleep(0)
assert not closing.done()
assert not self.server.distributed_pending_jobs
release.set()
with pytest.raises(asyncio.CancelledError):
await closing
assert handle["task"].done()
assert self.controller._close_task.done()
async def test_serialization_failure_never_journals_or_submits(self):
with patch.object(adapter, "serialize_request", side_effect=ValueError("budget")):
with pytest.raises(ValueError, match="budget"):
await self.dispatch()
assert not self.manager.ledger.all()
assert not self.server.distributed_pending_jobs
self.api.submit.assert_not_awaited()
async def test_duplicate_index_and_mismatched_handle_fail(self):
slot, handle = await self.dispatch()
with pytest.raises(ValueError, match="duplicate"):
await self.controller.dispatch(self.controller.slots[1], 0)
with pytest.raises(RuntimeError, match="Mismatched"):
self.controller.poll({slot: dict(handle)})
await self.finish(handle)
self.controller.poll({slot: handle})
with pytest.raises(RuntimeError, match="duplicate"):
self.controller.poll({slot: handle})
@@ -0,0 +1,359 @@
"""Offline image-list queue/scheduler integration; no provider or GPU calls."""
import asyncio
import copy
import json
import os
from pathlib import Path
import subprocess
import sys
import types
import unittest
from unittest.mock import AsyncMock, patch
import torch
import test_image_list_master_runtime as direct_fixture
from test_serverless_integration import PKG, load_modules
def pool(**updates):
return dict({"id": "pool", "name": "Cloud", "type": "serverless", "enabled": True,
"provider": "runpod", "endpoint_id": "endpoint", "jobs_per_run": 16,
"timeout_seconds": 30, "media_profile": "comfy-media-v1"}, **updates)
class MixedRuntimeTests(unittest.IsolatedAsyncioTestCase):
def setUp(self):
# Reuse only fixture setup, not inherited tests. The transport/slot doubles
# execute real runtime staging, assignment and result ordering code.
self.fixture = direct_fixture.MasterRuntimeTests()
self.fixture.setUp()
# This reused TestCase has no asyncio runner: invoke its patch cleanup
# directly, not doCleanups(), which would silently fail and leak aiohttp.
self.addCleanup(self.fixture.modules.stop)
self.f = f = self.fixture
self.rt = f.rt
self.configured_pool = pool()
f.config["workers"] = [self.configured_pool]
self.cloud_calls = []
self.completed = []
self.closed = 0
self.hold = False
self.missing = False
self.dispatch_error = False
self.poll_entered = asyncio.Event()
self.dispatch_entered = asyncio.Event()
self.hold_dispatch = False
self.slot_count = 2
fixture = self
class Controller:
def __init__(self, state, event):
self.state, self.event = state, event
self.slots = [("serverless", "pool", index) for index in range(fixture.slot_count)]
self.tasks = []
self.closed = False
async def dispatch(self, slot, index):
assert not self.closed
fixture.cloud_calls.append((slot, index))
fixture.dispatch_entered.set()
if fixture.dispatch_error:
raise RuntimeError("serverless dispatch failed")
async def execute():
if fixture.hold:
await asyncio.Event().wait()
# Make a later source item complete before the first local one.
await asyncio.sleep(0.001)
fixture.completed.append(index)
if fixture.missing:
raise RuntimeError("serverless completed without an image result")
item = state.items[index]
return {"image": item["image"], "mask": item["mask"],
"text": item["values"]["value_1"]}
state = self.state
task = asyncio.create_task(execute())
self.tasks.append(task)
task.add_done_callback(lambda _: self.event.set())
# Own the task before any await that might be cancelled.
if fixture.hold_dispatch:
await asyncio.Event().wait()
return {"index": index, "task": task}
def poll(self, inflight):
fixture.poll_entered.set()
for slot, handle in inflight.items():
if slot in self.slots and handle["task"].done():
return slot, handle["index"], handle["task"].result()
return None
async def close(self):
self.closed = True
for task in self.tasks:
if not task.done():
task.cancel()
await asyncio.gather(*self.tasks, return_exceptions=True)
fixture.closed += 1
async def create(state, region, config, event):
self.assertEqual(region["end_id"], "end")
self.assertEqual(config["workers"][-1]["id"], "pool")
self.controller = Controller(state, event)
return self.controller
self.create_controller = AsyncMock(side_effect=create)
sys.modules['_master_slot_tests.image_list.serverless'] = types.SimpleNamespace(
create_serverless_slots=self.create_controller)
self.direct_dispatch = sys.modules['_master_slot_tests.api.orchestration.dispatch'].dispatch_worker_prompt
def create(self, *, master=True, direct=True, count=9):
f = self.f
if direct:
f.workers.append({"id": "peer", "type": "local"})
f.config["workers"] = f.workers + [self.configured_pool]
f.local_delay = 0.04
context = f.create(participates=master, count=count) if (master or direct) else None
if context is None:
# Fixture.create assumes only direct peers; cloud-only uses a pool ID.
f.items = self.rt.normalize_image_list_inputs(torch.zeros((count, 2, 2, 3)),
mask=torch.zeros((count, 2, 2)), values={"value_1": [str(i) for i in range(count)]})
context = self.rt.create_master_job('start', 'end', direct_fixture.graph(), f.items, ['pool'], '')
f.context = context
f.state = self.rt.get_master_job(context)
else:
f.state.worker_ids.append('pool')
return context
async def test_mixed_roles_share_one_queue_and_preserve_pairing(self):
context = self.create()
original = copy.deepcopy(self.f.state.original_prompt)
result = await self.rt.run_image_list_job(context)
indices = self.f.local_calls + self.f.dispatched + [i for _, i in self.cloud_calls]
self.assertEqual(sorted(indices), list(range(9)))
self.assertTrue(self.f.local_calls and self.f.dispatched and self.cloud_calls)
self.assertNotEqual(self.completed[0], 0)
self.assertEqual(result[2], [str(i) for i in range(9)])
for index, (image, mask) in enumerate(zip(*result[:2])):
self.assertTrue(torch.equal(image, self.f.items[index]['image']))
self.assertTrue(torch.equal(mask, self.f.items[index]['mask']))
self.assertEqual(self.f.state.original_prompt, original)
self.f.preflight.assert_awaited_once_with(self.f.workers, require_idle=False)
for call in self.direct_dispatch.await_args_list:
self.assertEqual(call.kwargs['partial_execution_targets'], ['end'])
self.assertEqual(self.closed, 1)
self.assertFalse(self.rt._MASTER_JOBS)
async def test_cloud_only_one_job_per_item_ignores_images_per_run(self):
for jobs_per_run in (1, 16):
with self.subTest(jobs_per_run=jobs_per_run):
self.configured_pool['jobs_per_run'] = jobs_per_run
self.cloud_calls.clear()
result = await self.rt.run_image_list_job(self.create(master=False, direct=False, count=7))
self.assertEqual([i for _, i in self.cloud_calls], list(range(7)))
self.assertEqual(result[2], [str(i) for i in range(7)])
self.assertEqual(len({slot for slot, _ in self.cloud_calls}), self.slot_count)
self.f.preflight.assert_not_awaited()
self.f.network.get_client_session.assert_not_awaited()
self.assertFalse(self.f.slot_instances)
async def test_missing_cloud_result_fails_without_refill(self):
self.missing = True
with self.assertRaisesRegex(RuntimeError, 'without an image result'):
await self.rt.run_image_list_job(self.create(master=False, direct=False))
self.assertEqual(len(self.cloud_calls), self.slot_count)
self.assertEqual(self.closed, 1)
self.assertFalse(self.rt._MASTER_JOBS)
async def test_controller_closed_when_direct_preflight_fails(self):
self.f.preflight.side_effect = RuntimeError('direct preflight failed')
with self.assertRaisesRegex(RuntimeError, 'direct preflight failed'):
await self.rt.run_image_list_job(self.create())
self.assertEqual(self.closed, 1)
self.assertFalse(self.cloud_calls)
async def test_controller_closed_when_local_setup_fails(self):
slot_module = sys.modules['_master_slot_tests.image_list.local_executor']
with patch.object(slot_module, 'LocalExecutionSlot', side_effect=RuntimeError('local setup failed')):
with self.assertRaisesRegex(RuntimeError, 'local setup failed'):
await self.rt.run_image_list_job(self.create())
self.assertEqual(self.closed, 1)
self.assertFalse(self.cloud_calls)
async def test_controller_closed_on_dispatch_failure(self):
self.dispatch_error = True
with self.assertRaisesRegex(RuntimeError, 'serverless dispatch failed'):
await self.rt.run_image_list_job(self.create(master=False, direct=False))
self.assertEqual(len(self.cloud_calls), 1)
self.assertEqual(self.closed, 1)
async def test_cancelled_dispatch_without_returned_handle_is_owned(self):
self.hold = self.hold_dispatch = True
with patch.object(self.rt, 'SUBMISSION_CANCEL_GRACE_SECONDS', 0.01):
task = asyncio.create_task(self.rt.run_image_list_job(self.create(master=False, direct=False)))
await asyncio.wait_for(self.dispatch_entered.wait(), 1)
task.cancel()
with self.assertRaises(self.rt.ImageListCancelledError):
await asyncio.wait_for(task, 1)
self.assertEqual(len(self.cloud_calls), 1)
self.assertEqual(self.closed, 1)
self.assertTrue(all(t.done() for t in self.controller.tasks))
async def interrupt_probe(self, models):
self.hold = True
task = asyncio.create_task(self.rt.run_image_list_job(self.create(master=False, direct=False)))
try:
await asyncio.wait_for(self.poll_entered.wait(), 1)
assigned = list(self.cloud_calls)
models.interrupt_current_processing(True)
with self.assertRaises(self.rt.ImageListCancelledError):
await asyncio.wait_for(task, 1)
self.assertEqual(self.cloud_calls, assigned)
self.assertEqual(self.closed, 1)
self.assertTrue(all(t.done() for t in self.controller.tasks))
self.assertFalse(self.rt._MASTER_JOBS)
finally:
models.interrupt_current_processing(False)
if not task.done():
task.cancel()
await asyncio.gather(task, return_exceptions=True)
class QueueSelectionTests(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
self.q, modules, self.ps = load_modules()
self.modules_patch = patch.dict(sys.modules, modules)
self.modules_patch.start()
self.addCleanup(self.modules_patch.stop)
self.pool = pool()
self.peer = {'id': 'peer', 'name': 'Peer', 'type': 'local', 'enabled': True}
self.config = {'workers': [self.pool], 'settings': {'master_delegate_only': True}}
self.q.load_config = lambda: self.config
self.q.select_active_workers = AsyncMock(side_effect=lambda workers, ws, delegate, **kw: (workers, delegate))
self.preflight = AsyncMock(side_effect=lambda workers, **kw: {w['id']: True for w in workers})
sys.modules[PKG + '.api.orchestration.dispatch'].preflight_image_list_workers = self.preflight
self.q.queue_prompt_payload = AsyncMock(return_value={'prompt_id': 'outer', 'number': 1})
self.prompt = direct_fixture.graph()
async def queue(self, **kwargs):
return await self.q.orchestrate_distributed_execution(self.prompt, None, 'client', **kwargs)
async def test_delegate_pool_selected_once_no_direct_probe_or_source_mutation(self):
original = copy.deepcopy(self.prompt)
result = await self.queue()
selected = self.q.select_active_workers.await_args.args[0]
self.assertEqual([w['id'] for w in selected], ['pool'])
prepared = self.q.queue_prompt_payload.await_args.args[0]
inputs = prepared['start']['inputs']
self.assertEqual(json.loads(inputs['image_list_enabled_worker_ids']), ['pool'])
self.assertIs(inputs['image_list_master_participates'], False)
self.assertEqual(self.q.queue_prompt_payload.await_args.kwargs['partial_execution_targets'], ['end'])
self.assertEqual(result[2], 1)
self.assertEqual(self.prompt, original)
self.preflight.assert_not_awaited()
self.q.dispatch_worker_prompt.assert_not_awaited()
self.assertEqual(self.ps.distributed_pending_jobs, {})
async def test_mixed_selection_preflights_only_direct_peers(self):
self.config['workers'].insert(0, self.peer)
result = await self.queue(delegate_master=False)
self.assertEqual([w['id'] for w in self.preflight.await_args.args[0]], ['peer'])
self.assertFalse(self.preflight.await_args.kwargs['require_idle'])
inputs = self.q.queue_prompt_payload.await_args.args[0]['start']['inputs']
self.assertEqual(json.loads(inputs['image_list_enabled_worker_ids']), ['peer', 'pool'])
self.assertEqual(result[2], 2)
async def test_legacy_pool_rejected_before_probe_or_queue(self):
self.pool['media_profile'] = 'legacy-image-v1'
with self.assertRaisesRegex((ValueError, RuntimeError), 'comfy-media-v1'):
await self.queue()
self.q.select_active_workers.assert_not_awaited()
self.q.queue_prompt_payload.assert_not_awaited()
async def test_unknown_selection_rejected_before_queue(self):
with self.assertRaisesRegex((ValueError, RuntimeError), 'Unknown|unknown'):
await self.queue(enabled_worker_ids=['missing'])
self.q.select_active_workers.assert_not_awaited()
self.q.queue_prompt_payload.assert_not_awaited()
async def test_disabled_pool_can_be_explicitly_selected(self):
self.pool['enabled'] = False
await self.queue(enabled_worker_ids=['pool'])
self.assertEqual([w['id'] for w in self.q.select_active_workers.await_args.args[0]], ['pool'])
async def test_explicit_empty_selection_does_not_import_cloud_adapter(self):
sys.modules[PKG + '.image_list.serverless'] = None
result = await self.queue(enabled_worker_ids=[], delegate_master=False)
self.assertEqual(result[2], 0)
self.preflight.assert_not_awaited()
async def test_cloud_auth_or_capacity_failure_never_queues_master(self):
for error in ('authentication failed', 'capacity exhausted'):
with self.subTest(error=error):
self.q.select_active_workers.side_effect = ValueError(error)
with self.assertRaisesRegex(ValueError, error):
await self.queue()
self.q.queue_prompt_payload.assert_not_awaited()
async def test_real_selection_uses_manager_health_not_direct_http(self):
from test_dispatch_selection import _load_dispatch_module
dispatch = _load_dispatch_module()
health = AsyncMock(return_value={'ok': True, 'queueRemaining': 3})
sys.modules['dist_dispatch_testpkg.api.orchestration.serverless_runtime'] = types.SimpleNamespace(
get_manager=lambda: types.SimpleNamespace(health=health))
self.q.select_active_workers = dispatch.select_active_workers
with patch.object(dispatch, 'get_client_session', AsyncMock(side_effect=AssertionError('no HTTP'))), \
patch.object(dispatch, 'probe_worker', AsyncMock(side_effect=AssertionError('no direct probe'))):
await self.queue()
health.assert_awaited_once()
self.assertEqual(health.await_args.args[0]['id'], 'pool')
self.preflight.assert_not_awaited()
self.q.queue_prompt_payload.reset_mock()
health.side_effect = ValueError('provider authentication failed')
with self.assertRaisesRegex(ValueError, 'authentication failed'):
await self.queue()
self.q.queue_prompt_payload.assert_not_awaited()
async def test_unreachable_pool_never_enables_master_fallback(self):
self.q.select_active_workers.side_effect = None
self.q.select_active_workers.return_value = ([], False)
with self.assertRaisesRegex(RuntimeError, 'orchestrator|Orchestrator'):
await self.queue()
self.q.queue_prompt_payload.assert_not_awaited()
class RealInterruptTests(unittest.TestCase):
@unittest.skipUnless(os.environ.get('COMFYUI_SOURCE_ROOT'), 'set COMFYUI_SOURCE_ROOT for CPU interrupt probe')
def test_processing_interrupted_signal_during_cloud_result_wait(self):
result = subprocess.run([sys.executable, str(Path(__file__).resolve()), '--interrupt-probe',
os.environ['COMFYUI_SOURCE_ROOT']], text=True, capture_output=True, timeout=45)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertIn('SERVERLESS_INTERRUPT_OK', result.stdout)
def real_interrupt_probe(comfy_root):
sys.path.insert(0, str(Path(comfy_root).resolve()))
import comfy.cli_args
comfy.cli_args.args.cpu = True
comfy.cli_args.args.disable_assets = True
import comfy.model_management as models
real_comfy = sys.modules['comfy']
case = MixedRuntimeTests()
case.setUp()
try:
# Keep actual thread-safe ComfyUI interruption state, not a task.cancel
# surrogate or a fake processing_interrupted callback.
sys.modules['comfy'] = real_comfy
sys.modules['comfy.model_management'] = models
asyncio.run(case.interrupt_probe(models))
finally:
case.f.modules.stop()
print('SERVERLESS_INTERRUPT_OK no refill, owned close, actual ComfyUI flag')
if __name__ == '__main__':
if len(sys.argv) > 1 and sys.argv[1] == '--interrupt-probe':
real_interrupt_probe(sys.argv[2])
else:
unittest.main()