Thoroughly sense-check docs/worker-matrix-runner.md against the actual implementation. Read the doc and then verify every claim against the real code. Check:
CLI flags: Does the script actually support every flag mentioned in the doc? (--list-cases, --case-id, --tag, --task-type, --failed-from). Read scripts/run_worker_matrix.py parse_args() and confirm each one.
Artifact structure: Does the doc accurately list all artifacts produced? Check what files are actually written in main() and run_case(). Are any artifacts missing from the doc? Are any doc'd artifacts not actually produced?
Per-case files listed: case_definition.json, prepared_input.json, captured_generation_task.json, worker.log, result.json, traceback.txt — verify each is actually written in the code.
"Current Locked Cases" section: Compare exactly against scripts/worker_matrix_cases.json. Any mismatches in case IDs?
Descriptions accuracy: "Real worker.py -> process_single_task() execution" — is this actually true or are things mocked? What exactly is real vs fake? Is the doc misleading about what's actually being tested?
The "serial" note — verify the runner doesn't use threading/multiprocessing.
The marker strings — verify [WORKER_MATRIX][CASE_START], [CASE_END], [CASE_EXCEPTION] match what's in the code exactly.
Any missing documentation — are there features in the script not mentioned in the doc? (e.g., --family, --all-cases, --stop-on-failure, --manifest, --output-dir flags)
Report every discrepancy, inaccuracy, or gap you find.
Assistant
I'll start by reading the doc and the main script in parallel, then verify each claim systematically.
Assistant
Now let me read the cases manifest file.
User
Do a thorough code review / sense-check of scripts/run_worker_matrix.py. Read the entire file carefully and check for bugs, logic errors, edge cases, and correctness issues. Specifically check:
filter_case_definitions(): The set(args.case_id) | failed_case_ids or None expression on line 322 — is this correct? What does Python's operator precedence do here? Does set() | set() or None evaluate to None when both sets are empty?
_normalize_worker_result(): Does it handle all possible return shapes from worker.process_single_task()? Read worker.py to see what it actually returns.
FakeImmediateTaskQueue: Does the interface match what worker.py actually expects from a task_queue? Read worker.py and check what methods it calls on task_queue.
TeeWriter: Any issues with the stream handling? Does it properly handle encoding, newlines, flush behavior?
Status logic in run_case(): Lines 471-477 — the expectation_matched / status logic. Is it correct? Are there cases where it could be wrong? What about "skipped" outcomes?
shlex_quote: Why roll their own instead of using shlex.quote from stdlib? Is the custom implementation correct?
_json_safe(): Does it handle all types that could appear in params? What about numpy arrays, torch tensors, Path objects nested in lists?
Global _DB_SNAPSHOTS_CACHE: Thread safety issues? (Probably fine since serial, but worth noting.)
ensure_repo_on_path(): Called in both main() and run_case() — is the double-call intentional/needed?
The manifest cases reference builders: Read scripts/worker_matrix_cases.json and verify every "builder" value maps to an entry in CASE_BUILDERS. Also check: do the 6 manifest cases use any of these builders: t2v_basic, i2v_basic, wan_22_t2i_basic, qwen_image_style_db_like, extract_frame_basic, create_visualization_basic? (These are the ones we plan to delete.)
DB snapshot loading: Check scripts/worker_matrix_db_snapshots.json — are the fixture token replacements (FIXTURE_PATH, FIXTURE_URL) used correctly? Do the builders that load snapshots pass the right fixture keys?
Any other bugs, dead code, or issues you notice.
Report every issue found with line numbers and severity (bug, nit, potential issue).
Assistant
I'll start by reading the main file and its dependencies in parallel.
Assistant
Now let me read the JSON files and check the TaskResult class.
Assistant
Now let me check what methods worker.py actually calls on task_queue, and look at HeadlessTaskQueue for the interface.
Assistant
Good. The task_queue interface used is submit_task() and get_task_status() -- both of which FakeImmediateTaskQueue implements. Let me also check if there are other methods called.
Assistant
That confirms the bug on line 322. Let me also check a non-empty case:
Assistant
Now let me verify the shlex.quote from stdlib to compare with the custom implementation:
Assistant
Now let me check _normalize_worker_result more carefully against the TaskResult __iter__ and the tuple return from process_single_task:
Assistant
I now have all the information needed. Let me compile the full report.
Sense-Check Report: docs/worker-matrix-runner.md vs Actual Implementation
1. CLI Flags
The doc mentions these flags: --list-cases, --case-id, --tag, --task-type, --failed-from.
parse_args() (lines 291-303) actually defines:
Flag
In Doc?
In Code?
Status
--list-cases
Yes
Yes
OK
--case-id
Yes
Yes
OK
--tag
Yes
Yes
OK
--task-type
Yes
Yes
OK
--failed-from
Yes
Yes
OK
--manifest
No
Yes
MISSING from doc
--output-dir
No
Yes
MISSING from doc
--family
No
Yes
MISSING from doc
--all-cases
No
Yes
MISSING from doc
--stop-on-failure
No
Yes
MISSING from doc
5 undocumented flags. The --manifest, --output-dir, --family, --all-cases, and --stop-on-failure flags all exist in the code but are not mentioned anywhere in the doc. The --family flag is particularly notable because it enables filtering by family (e.g., direct_queue, travel_segment), a first-class concept in the case definitions.
2. Artifact Structure (Top-Level Files)
The doc lists these top-level artifacts:
Assistant
Good, the "failed" in outcome_name check works but is fragile. Let me check _utc_timestamp format since line 340 replaces colons:
Assistant
No colons in that format, so line 340's .replace(":", "") is a no-op. Not a bug, just dead code.
Now let me check the _json_safe function for numpy/torch/bytes handling:
Assistant
Now let me check the _normalize_worker_result function against process_single_task's return more carefully. At line 502, for a failed TaskResult, the error_message fallback:
Assistant
Now I have enough to write a comprehensive report. Let me also check the _utc_timestamp line 340 more carefully and look at the TeeWriter type hint:
Assistant
Now let me check if TeeWriter needs to implement writable() or encoding for contextlib.redirect_stdout to work properly:
Assistant
Good, it works in basic cases. Now let me check one more thing -- the logging module often checks for encoding attribute:
Assistant
Let me check one more thing -- TeeWriter.encoding being None while logging or third-party code might expect a string:
Assistant
OK, works fine in practice. Now here is my comprehensive report.
case_ids=set(args.case_id) | failed_case_ids or None,
Python's operator precedence is: | binds tighter than or. So this parses as:
python
(set(args.case_id) | failed_case_ids) or None
When both sets are empty, set() | set() produces set(), which is falsy, so set() or None evaluates to None. This is correct by accident for the empty case.
However, when at least one set is non-empty, the union is truthy so or None never fires, and the result is the union set. This is also correct.
So the logic happens to work, but only by coincidence. The intent is clearly (set(args.case_id) | failed_case_ids) or None, and the fact it works depends on Python's truthiness rules for empty sets. The expression should be parenthesized for clarity, or rewritten:
python
combined = set(args.case_id) | failed_case_ids
case_ids=combined or None,
Verdict: Works correctly but is a readability trap. The or None makes the intent ambiguous -- someone might think this was meant to be set(args.case_id) | (failed_case_ids or None) which would crash. Nit-level since it works.
Lines 323-325 (set(args.task_type) or None, etc.) use the same pattern but are simpler and clearly correct.
outcome_name = str(raw_result.outcome).lower()
if "failed" in outcome_name:
str(TaskOutcome.FAILED) produces "TaskOutcome.FAILED", so "failed" in "taskoutcome.failed" works. But this is a substring match that is fragile. If anyone ever adds or similar, it would match incorrectly. A safer approach:
User
I need to understand the full set of task types that worker.py can handle, compared to what the worker matrix runner currently tests.
Read worker.py and find how task types are routed (look for process_single_task, TaskRegistry, or any dispatch mechanism that maps task_type strings to handlers).
Find the complete list of registered task types. Check source/task_handlers/ for any registry, and look for all task_type string values that appear in routing logic.
Read scripts/worker_matrix_cases.json to see which task types are currently covered by the matrix.
Report:
The full list of task types the worker can handle
Which ones are covered by the matrix
Which ones are NOT covered
For uncovered ones, note whether they seem testable with the fake-queue approach (i.e. they go through direct-queue generation) vs requiring special handling (DB lookups, file dependencies, etc.)
Be thorough — check TaskRegistry, any handler mapping dicts, and the task_handlers directory structure.
Assistant
I'll systematically trace the task routing from worker.py through to all registered task types.
Assistant
Now let me read the TaskRegistry and task_types files, plus the matrix cases.
Assistant
Now let me read the full task registry to see all registered handlers.
Assistant
Now let me read the dispatch method and the TASK_HANDLERS definition section more carefully.
Assistant
Now let me also check if there's an inpaint_frames handler file.
Assistant
I now have all the information needed. Let me compile the complete picture.
Full Report: Task Types vs. Worker Matrix Coverage
How Task Routing Works
In worker.py line 150, TaskRegistry.dispatch(task_type, context) is the single entry point. The dispatch method in /Users/user_c042661f/Documents/Headless-Wan2GP/source/task_handlers/tasks/task_registry.py (line 1103) routes in three tiers:
Tier 1 - Direct Queue (line 1118-1120): If task_type in DIRECT_QUEUE_TASK_TYPES, route to _handle_direct_queue_task() which calls db_task_to_generation_task() and submits to HeadlessTaskQueue.
Tier 2 - Specialized Handlers (line 1122-1202): A handlers dict maps specific task types to lambda-wrapped handler functions.
Tier 3 - Fallthrough (line 1204-1206): Any unrecognized task type with a queue also goes to _handle_direct_queue_task().
Complete List of Task Types
DIRECT_QUEUE_TASK_TYPES (from /Users/user_c042661f/Documents/Headless-Wan2GP/source/task_handlers/tasks/task_types.py, line 43-63):
#
Task Type
Category
1
vace
VACE model
2
vace_21
VACE model
3
vace_22
VACE model
4
flux
Flux model
5
t2v
Text-to-video
6
t2v_22
Text-to-video
7
wan_2_2_t2i
Text-to-image
8
i2v
Image-to-video
9
i2v_22
Image-to-video
10
hunyuan
Video model
11
ltxv
Video model
12
ltx2
Video model
User
I need to build a realistic vace test case for the worker matrix runner. There are no vace tasks in the database, so I need to figure out what parameters a vace task needs from the code.
Read source/task_handlers/tasks/task_registry.py and find how vace task type is handled. It's a DIRECT_QUEUE_TASK_TYPE, so trace through _handle_direct_queue_task() and db_task_to_generation_task().
Find the db_task_to_generation_task function (likely in source/task_handlers/) and see what params it expects for vace tasks. What model does it map to? What parameters does it pass through?
Check source/task_handlers/tasks/task_types.py for any vace-specific configuration.
Check the Wan2GP defaults for vace - read files like Wan2GP/defaults/vace_14B_fusionix.json or similar to understand what parameters WGP expects.
Check if there's a model mapping - what model string does vace map to in the generation task?
Report the exact parameter shape needed to construct a PreparedCase for a vace direct-queue test, including:
What params dict keys are needed
What model string the generation task should have
Any special handling (image inputs, masks, etc.)
A realistic example parameter set
Assistant
I'll trace through the vace task handling from the task registry through to the generation parameters.
Assistant
Now let me find the _handle_direct_queue_task method and db_task_to_generation_task.
Assistant
Now let me read the _handle_direct_queue_task method and the vace defaults.
Assistant
Now let me check the GenerationTask class and the worker matrix runner to understand PreparedCase.
Assistant
Now let me check the existing manifest and db snapshots to understand the pattern.
Assistant
Now let me check how vace tasks typically use video_guide and video_prompt_type, and what the WGP handler expects for vace.
Assistant
Now let me check what vace-specific handling happens in the WGP handler side -- specifically how video_prompt_type, video_guide, and video_mask work for vace tasks.
Assistant
Let me check how the WGP handler processes vace parameters. Let me look at the wan_handler and the _convert_to_wgp_task method.
Assistant
Let me look at the _convert_to_wgp_task method to understand how vace params flow through.
Assistant
Now let me check what video_prompt_type values are valid for vace and how a typical vace task from the frontend looks. Let me also look at the WGP wgp.py model definitions for vace models.
Assistant
Now I have all the information needed. Let me also check the vace_14B_cocktail_2_2.json defaults to confirm the default parameters.
The vace_14B_cocktail_2_2.json was already read above. Let me also look at how video_prompt_type is used in vace context -- the "VM" value means "Video + Mask" for VACE control.
Assistant
Now let me check the process_single_task function to see how task_type routes to the task registry for vace.
Assistant
I now have everything needed. Here is the full analysis:
VACE Task Parameter Shape for Worker Matrix Runner
1. Task Type Routing
In task_types.py (line 75), "vace" maps to model "vace_14B_cocktail_2_2" via TASK_TYPE_TO_MODEL. It is a DIRECT_QUEUE_TASK_TYPE, so it goes through _handle_direct_queue_task() -> db_task_to_generation_task().
2. How db_task_to_generation_task Handles VACE
VACE has no special-case handling in task_conversion.py. Unlike z_image_turbo, qwen_image_edit, etc., there is no elif task_type == "vace": block. This means vace is the simplest possible direct-queue path:
prompt is extracted (required, non-empty)
model is taken from params, or defaults to get_default_model("vace") = "vace_14B_cocktail_2_2"
All params in the param_whitelist (lines 38-76 of task_conversion.py) are passed through verbatim
A GenerationTask is created with id, model, prompt, parameters, priority
3. Model String
Task type "vace" -> model "vace_14B_cocktail_2_2"
Task type "vace_21" -> model "vace_14B"
Task type "vace_22" -> model "vace_14B_cocktail_2_2"
The model can also be overridden by passing "model" in the params dict.
4. VACE-Specific Parameters
VACE tasks use video/mask inputs for control. The key VACE-specific params (all in the whitelist):
video_prompt_type: Controls input mode. "VM" = Video + Mask (the standard VACE mode). Found in vace_frame_utils.py line 440 and the lightning baseline defaults.
video_guide: Path to the guide video (the reference/control video)
video_mask: Path to the mask video (defines which areas to regenerate)
/ : Control weights
User
The worker matrix runner (scripts/run_worker_matrix.py) calls worker.process_single_task() which routes through TaskRegistry.dispatch. I need to verify the actual executor code is consistent with what the 7 test cases expect.
Check each of these execution paths end-to-end:
VACE case (task_type="vace", model="vace_14B_cocktail_2_2"):
Read source/task_handlers/tasks/task_types.py and confirm vace is in DIRECT_QUEUE_TASK_TYPES
Read source/task_handlers/tasks/task_conversion.py and trace what happens to vace params. Does db_task_to_generation_task handle it? What model does it resolve to?
The test expects expected_model="vace_14B_cocktail_2_2" — verify this matches TASK_TYPE_TO_MODEL
LTX2 case (task_type="ltx2", model="ltx2_22B"):
Confirm ltx2 is in DIRECT_QUEUE_TASK_TYPES
Trace model resolution — does passing model="ltx2_22B" in params override the default?
The test expects expected_model="ltx2_22B" — verify
Z-Image turbo (task_type="z_image_turbo"):
The test expects expected_model="z_image" and expected_parameters={"video_length": 1, "guidance_scale": 0}
Read the z_image_turbo handling in task_conversion.py — does it actually set video_length=1 and guidance_scale=0?
Now let me check the z_image_turbo_i2i denoising_strength expectation more carefully. The test expects denoising_strength: 0.4. The snapshot has "strength": 0.4. Let me verify the code path.
Looking at task_conversion.py line 235:
python
actual_strength = db_task_params.get("denoising_strength") or db_task_params.get("denoise_strength") or db_task_params.get("strength", 0.7)
The snapshot params have "strength": 0.4 (not "denoising_strength"), so actual_strength will be 0.4. But wait -- the whitelist on line 75 includes "denoising_strength". Let me check if "strength" is in the snapshot params and whether denoising_strength might be passed through from the whitelist first.
The snapshot params for z_image_turbo_i2i do NOT contain a "denoising_strength" key -- they have "strength": 0.4. So the whitelist won't copy it. Then the z_image_turbo_i2i branch hits line 235, and returns None, returns None, returns 0.4. So . This matches the test expectation.
User
Do a comprehensive end-to-end checklist audit of the worker matrix runner system. Check EVERYTHING — not just the test cases vs executor, but the full infrastructure.
Files to check:
scripts/run_worker_matrix.py
scripts/worker_matrix_cases.json
scripts/worker_matrix_db_snapshots.json
docs/worker-matrix-runner.md
worker.py (the entry point being tested)
CHECKLIST:
A. Manifest integrity
Every case in manifest has a valid builder that exists in CASE_BUILDERS dict
Every case has all required fields (case_id, description, task_type, family, builder)
No duplicate case_ids
All tags are consistent/meaningful
B. Snapshot integrity
5. Every builder that calls _load_snapshot_params(name) references a snapshot that exists in db_snapshots.json
6. Every snapshot has required fields (snapshot_name, source_task_id, source_created_at, task_type, params)
7. Every __FIXTURE_PATH__ and __FIXTURE_URL__ token in snapshots has a corresponding fixture_paths/fixture_urls in the builder
8. No orphan snapshots (snapshots not referenced by any builder)
C. Builder correctness
9. Every builder in CASE_BUILDERS is referenced by at least one manifest case (no dead builders)
10. Builders that create fixture images/videos do so before passing paths to snapshot params
11. Patchers target real import paths that exist (check source.models.model_handlers.qwen_handler.hf_hub_download exists)
D. FakeImmediateTaskQueue interface
12. Does it implement all methods that worker code actually calls on task_queue? Check what methods are called on task_queue in task_registry.py and elsewhere
13. Does get_task_status return shape match what callers expect?
E. Script infrastructure
14. Does VIDEO_OUTPUT_TASK_TYPES set correctly determine image vs video output? Is vace missing from it (it should produce video)?
15. Are REQUIREMENT_CHECKERS complete? Any cases that should declare requirements but don't?
16. Does _utc_timestamp format produce filesystem-safe names?
F. Doc accuracy
17. Doc locked cases list matches manifest exactly
18. Doc CLI examples reference valid flags
19. Doc artifact list matches what code produces
20. Doc "What It Covers" section is accurate
G. Edge cases
21. What happens if worker.py returns an unexpected type? Does _normalize_worker_result handle it?
22. What happens if a builder's snapshot is missing? Does it crash with a clear error?
23. The rerun_failed.sh — does it generate valid bash?
Report PASS/FAIL for each item with details on any failures.
Assistant
I'll systematically audit the entire worker matrix runner system. Let me start by reading all the relevant files in parallel.
Assistant
Now let me read the manifest and snapshots files, plus check some key source files.
Assistant
Now let me check the task_queue interface, the qwen_handler import path, and task types.
Assistant
Now let me check what attributes are accessed on status from get_task_status, and check the VIDEO_OUTPUT_TASK_TYPES logic.
Assistant
Now let me check the __FIXTURE_PATH__ tokens in snapshots, the qwen_image_style snapshot for a second fixture token, and verify the VIDEO_OUTPUT_TASK_TYPES logic is correct (inverted or not).
Assistant
Now let me verify the VIDEO_OUTPUT_TASK_TYPES naming. The set lists task types that produce IMAGE outputs (confusingly named). Let me verify the logic.
Looking at line 725-729 of the runner:
python
def _create_synthetic_output(output_dir, task_id, task_type):
if task_type in VIDEO_OUTPUT_TASK_TYPES:
return _create_test_image(...) # creates .png
return _create_test_video(...) # creates .mp4
So VIDEO_OUTPUT_TASK_TYPES is actually "image output task types" -- task types where the output is an image, not video. The name is misleading/inverted. But more importantly: is vace missing? VACE produces video. It is NOT in VIDEO_OUTPUT_TASK_TYPES, which means it gets a .mp4 -- correct. Let me check what the current cases actually use.
Now let me check the qwen_image_style snapshot -- it has __FIXTURE_PATH__:qwen_style_reference used for both style_reference_image AND subject_reference_image, but the builder only passes one fixture path:
Looking at build_qwen_image_basic (line 624-639): it passes fixture_paths={"qwen_style_reference": reference_image}. The snapshot uses __FIXTURE_PATH__:qwen_style_reference for both fields. Since both use the same key, one fixture path covers both. This is fine.
Let me check the individual_travel_segment_wan22_i2v snapshot and its builder for the orchestrator_details.input_image_paths_resolved tokens.
The snapshot has __FIXTURE_PATH__:wan22_start_image and __FIXTURE_PATH__:wan22_end_image scattered through nested structures. The builder build_wan22_individual_segment_db_like passes fixture_paths={"wan22_start_image": start_image, "wan22_end_image": end_image}. The _replace_snapshot_tokens function recursively walks dicts and lists. This should work.
Now let me check if the _utc_timestamp format is filesystem-safe.
Line 798: datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ") -- this produces something like 20260316T143521123456Z. No colons, slashes, or spaces. Filesystem-safe on all platforms. PASS.
Let me verify the doc locked cases list versus the manifest.
Assistant
Now I have enough information to compile the full audit. Let me verify one last thing -- processing_time is accessed on the status but FakeImmediateTaskQueue doesn't set it.
Assistant
The FakeImmediateTaskQueue doesn't set processing_time on its SimpleNamespace status objects, but callers in inpaint_frames.py and join/generation.py access status.processing_time. However, these callers only run inside task handlers that use task_queue for WGP generation tasks -- those specific handlers (inpaint_frames, join_clips) are not exercised by the current matrix cases. The current cases go through the direct-queue path in task_registry.py which accesses status.status, status.result_path, and status.error_message -- all of which ARE present in FakeImmediateTaskQueue.
All 7 cases have: case_id, description, task_type, family, builder. Verified by inspection of the JSON.
3. No duplicate case_ids -- PASS
The 7 case_ids are: vace_cocktail_2_2_basic, individual_travel_segment_wan22_i2v_baseline_2_2_2, ltx2_22b_basic, z_image_turbo_db_task, z_image_turbo_i2i_db_task, qwen_image_style_db_task, qwen_image_edit_db_task. All unique. Additionally, load_case_definitions() (line 213-216) has a runtime duplicate check that raises ValueError.
4. All tags are consistent/meaningful -- PASS
All cases use default and core. Image cases use image, video cases use . Family-specific tags like , , , , are consistent. tag matches the family where applicable. No orphan or meaningless tags.
User
I need to understand how the LTX2 distilled model path works through task_conversion.py to build a realistic test case.
Read source/task_handlers/tasks/task_types.py — is there a separate task_type for ltx2 distilled, or does the same ltx2 task_type handle both dev and distilled based on the model param?
Read source/task_handlers/tasks/task_conversion.py — trace what happens when task_type="ltx2" and model="ltx2_22B_distilled". Does it have any special handling? Does it pass through guidance_scale, audio_guidance_scale, perturbation_layers, perturbation_switch, alt_guidance_scale, alt_scale? Check the param whitelist.
Read Wan2GP/defaults/ltx2_22B_distilled.json to see the default params for the distilled model.
Read Wan2GP/defaults/ltx2_22B.json to see the default params for the dev model.
Check if ltx2_pipeline is a param that gets passed through the whitelist or is handled specially.
Report what model string and parameters a distilled LTX2 test case should use, and what expected_model / expected_parameters to validate.
Assistant
I'll read all these files in parallel.
Assistant
Now let me check whether ltx2_pipeline is in the whitelist or handled anywhere specially, and also look at the ltx2_19B defaults for comparison.
Assistant
Now let me check what params are NOT in the whitelist but appear in the ltx2 dev defaults:
Assistant
Now I have a complete picture. Here is the full analysis:
Task Type: No separate type for distilled — same ltx2 handles both
There is one task type"ltx2" for all LTX2 variants. The distinction between dev and distilled is made entirely by the model parameter, not the task type. TASK_TYPE_TO_MODEL["ltx2"] defaults to "ltx2_19B" — callers must pass "model": "ltx2_22B_distilled" (or "ltx2_distilled") explicitly to get the distilled path.
What ltx2_pipeline is and how it works
ltx2_pipeline is a model definition field (inside the .json"model" block), not a task param. It is read by Wan2GP/models/ltx2/ltx2_handler.py and ltx2.py from the loaded model definition at generation time. It is not passed through the task params whitelist at all — there is no entry for it in param_whitelist in task_conversion.py. Callers cannot and do not need to pass it; it is encoded in the model JSON itself.
The distilled model JSONs (ltx2_distilled.json and ltx2_22B_distilled.json) both set "ltx2_pipeline": "distilled" in their "model" block. The dev models omit this key, so they default to "two_stage" in the handler.
What params pass through the whitelist — and what don't
Present in the whitelist and relevant to LTX2 dev:
guidance_scale — yes (line 40)
audio_guidance_scale — yes (line 41)
cfg_star_switch — yes (line 53)
NOT in the whitelist at all:
perturbation_switch
perturbation_layers
perturbation_start_perc
perturbation_end_perc
alt_guidance_scale
alt_scale
apg_switch
These appear in the dev model defaults (ltx2_22B.json and ltx2_19B.json) but the whitelist has no entries for them. If a caller puts them in db_task_params, they will be silently dropped and never reach generation_params.
Distilled model test case
User
I need to understand how the distill LoRA works in the LTX2 pipeline for both dev and distilled models. Specifically:
Read Wan2GP/defaults/ltx2_22B.json — it has a loras field with the distill LoRA and loras_multipliers with "0;1". What does "0;1" mean? Is it a per-phase multiplier?
Read Wan2GP/defaults/ltx2_22B_distilled.json — does it have any loras defined?
Read source/task_handlers/tasks/task_conversion.py — check the param_whitelist. Is there any entry for lora-related params like loras, lora_multipliers, lora_names, additional_loras? Would these pass through to the generation task?
Read Wan2GP/models/ltx2/ltx2_handler.py or ltx2.py — how does it handle the distill LoRA? Does the model definition's loras field get applied automatically by WGP, or does it need to come from task params?
Check if the ltx2_pipeline: "distilled" setting in the distilled model JSON changes whether/how the distill LoRA is applied.
Most importantly: when a task comes through with model: "ltx2_22B" (dev), does the distill LoRA from the model definition get applied automatically? Or does the caller need to pass LoRA params explicitly?
Report whether our test cases need to include any LoRA-related params, or whether WGP handles it from the model definition.
Assistant
Let me read all the relevant files in parallel.
Assistant
Now let me look for the LTX2 handler files and how WGP loads model definition loras.
Assistant
The ltx2.py is large. Let me search for the critical LoRA-related sections and also look at how WGP's core wgp.py processes model definition loras fields.
Assistant
Let me search more specifically in wgp.py for how model definition loras are applied, and how the loras_multipliers"0;1" format is parsed.
Assistant
Now let me look at the parse_loras_multipliers function to understand "0;1" format, and the get_transformer_loras function more closely (lines 5386-5393 above show it reads loras from model def), and also how WGP headless handles the model-def loras during generation.
Assistant
Now let me check how the headless wgp handles these transformer loras and whether the loras from the model definition flows through to headless generation. Let me also check what get_model_recursive_prop does with loras.
Assistant
Now let me look at how headless_wgp.py triggers generation and what happens to activated_loras and the default settings applied before calling the WGP generate function:
Assistant
Now let me look at how wgp_params.py builds the params dict (since it receives activated_loras and loras_multipliers_str), and also check what resolve_parameters does with loras from task params:
Assistant
Now I have a complete picture. Let me also check what happens in param_resolution to understand whether activated_loras/loras_multipliers from task params actually make it through:
Assistant
Now I have the complete picture. Here is a comprehensive analysis:
Analysis of Distill LoRA in the LTX2 Pipeline
1. What does "0;1" mean in loras_multipliers?
"0;1" is a per-guidance-phase multiplier for the distill LoRA. The ; syntax in parse_loras_multipliers (see /Wan2GP/shared/utils/loras_mutipliers.py lines 69-95) splits the string on ; to produce one value per guidance phase:
For the LTX2 dev model, guidance_phases is locked to 2 (guidance_max_phases: 2, lock_guidance_phases: True per ltx2_handler.py lines 228-230). So the distill LoRA is disabled in phase 1 (the high-noise denoising phase) and enabled at full strength in phase 2 (the refinement phase). This is the standard two-stage dev pipeline behaviour — the distill LoRA is used as a phase-2 refinement prior only.
2. Does ltx2_22B_distilled.json define any loras?
No. The distilled model JSON has no loras field at all. It only sets "ltx2_pipeline": "distilled". The distill LoRA is not needed for the distilled checkpoint because distillation is already baked into the weights. The _ARCH_SPECS in ltx2_handler.py (line 32) does keep a distilled_lora filename reference (ltx-2.3-22b-distilled-lora-384.safetensors), but the handler itself never auto-injects it — it is only listed in the model def JSON's loras field for the dev variant.
So activated_loras, loras_multipliers, additional_loras, and loras all pass through from the task's DB params to the GenerationTask.parameters dict. They would then flow into the WGP call.
4. How WGP applies the model definition's loras — the critical mechanism
This is the heart of the answer. WGP's (in ) calls (lines 5386-5393) , regardless of what the task passes in:
User
The full Wan2GP upstream update has just been committed. I need to verify that worker matrix test cases 1-4 are still correct against the updated codebase. For each case, trace the FULL execution path and verify every expected value.
Case 1: vace_cocktail_2_2_basic (task_type="vace", expected_model="vace_14B_cocktail_2_2")
Check source/task_handlers/tasks/task_types.py — is "vace" still in DIRECT_QUEUE_TASK_TYPES? What does TASK_TYPE_TO_MODEL["vace"] resolve to now?
Check source/task_handlers/tasks/task_conversion.py — any new special handling for vace?
Verify expected_parameters: guidance_phases=2, guidance_scale=1 would pass through whitelist
Case 2: individual_travel_segment_wan22_i2v_baseline_2_2_2 (task_type="individual_travel_segment")
Check source/task_handlers/tasks/task_registry.py — is "individual_travel_segment" still in the specialized handlers dict? What function handles it?
Has the handler been refactored? Check if it's still at the same import path or moved (there are new source/task_handlers/travel/ directories)
expected_model="wan_2_2_i2v_lightning_baseline_2_2_2", expected_parameters={"video_length": 50} — still valid?
Case 3: ltx2_22b_basic (task_type="ltx2", model="ltx2_22B")
Check TASK_TYPE_TO_MODEL["ltx2"] — what's the default now?
Does passing model="ltx2_22B" in params override the default?
expected_parameters: guidance_scale=3.0, audio_guidance_scale=7.0 — are these in the whitelist?
Is "ltx2" still in DIRECT_QUEUE_TASK_TYPES?
Case 4: ltx2_22b_distilled_basic (task_type="ltx2", model="ltx2_22B_distilled")
Same task_type "ltx2" — does model="ltx2_22B_distilled" pass through correctly?
expected_parameters: num_inference_steps=8 — passes through whitelist?
For each case, read the actual files and report PASS/FAIL with specific line numbers if anything changed.
Assistant
I'll trace each test case through the execution path. Let me start by reading all the relevant files in parallel.
Assistant
Now let me read the task_registry.py file fully (it was truncated) and check for the worker matrix test file.
User
The full Wan2GP upstream update has just been committed. I need to verify that worker matrix test cases 5-8 are still correct against the updated codebase. For each case, trace the FULL execution path and verify every expected value.
Case 5: z_image_turbo_db_task (task_type="z_image_turbo")
Check source/task_handlers/tasks/task_types.py — is "z_image_turbo" still in DIRECT_QUEUE_TASK_TYPES?
Check source/task_handlers/tasks/task_conversion.py — trace the z_image_turbo handling. Does it still set model="z_image", video_length=1, guidance_scale=0?
The snapshot params include: model="z-image", steps=12, resolution="1152x864", seed, prompt, hires_, lightning_lora_strength_. Do these all pass through the whitelist?
Case 6: z_image_turbo_i2i_db_task (task_type="z_image_turbo_i2i")
Check task_conversion.py — does it still set model="z_image_img2img"?
The snapshot has "strength": 0.4 (not "denoising_strength") — verify the conversion code still maps strength → denoising_strength via the fallback chain
The builder patches requests.get — verify source code still uses requests.get for image download at the same import path
Case 7: qwen_image_style_db_task (task_type="qwen_image_style")
Check task_conversion.py — trace qwen_image_style handling. Does it still override model to "qwen_image_edit_20B"?
expected_parameters: video_length=1
The builder patches source.models.model_handlers.qwen_handler.hf_hub_download — verify this import path still exists and still imports hf_hub_download
Check if any of the qwen handler paths have been refactored
Case 8: qwen_image_edit_db_task (task_type="qwen_image_edit")
Check task_conversion.py — any special handling for qwen_image_edit?
TASK_TYPE_TO_MODEL["qwen_image_edit"] — still maps to "qwen_image_edit_20B"?
expected_parameters: video_length=1
Same patcher path check as case 7
Also check:
worker.py process_single_task signature — has it changed with the upstream update?
source/core/log enable_debug_mode — still exists?
source/core/params/task_result TaskOutcome — still has FAILED, ORCHESTRATING, ORCHESTRATOR_COMPLETE, SUCCESS?
For each case, read the actual files and report PASS/FAIL with specific line numbers if anything changed.
Assistant
I'll trace through all the files systematically. Let me start by reading all the relevant source files in parallel.
Assistant
Now let me check the TASK_HANDLERS dict and the handle_travel_segment_via_queue function more closely, plus verify the DB snapshot for Case 1.
Assistant
Now let me check the qwen_handler import path and the enable_debug_mode function.
Assistant
Now let me check one more thing -- whether vace_14B_cocktail_2_2 still exists as a valid model default file after the upstream update (some vace_cocktail files were deleted).
Assistant
Now let me check the worker matrix test file to see the exact test cases and expected values.
Assistant
Now let me check one final thing -- the _handle_direct_queue_task method and verify the deleted defaults don't affect anything.
Assistant
Now let me check the DB snapshots to verify the snapshot params for cases 5-8.
Assistant
Now let me verify the whitelist handling for the z_image_turbo snapshot params and check the parse_phase_config import.
Assistant
The parse_phase_config is used in task_conversion.py at line 262 but never imported. Let me check if it's a missing import or defined locally.
Assistant
I now have everything I need. Here is the full analysis:
Case-by-Case Verification Report
Case 1: vace_cocktail_2_2_basic -- PASS
Routing:task_type="vace" is in DIRECT_QUEUE_TASK_TYPES (line 45 of task_types.py). The dispatch method at line 1120 of task_registry.py calls _handle_direct_queue_task, which calls db_task_to_generation_task.
Model resolution: The DB snapshot (vace_basic in worker_matrix_db_snapshots.json, line 10) has "model": "vace_14B_cocktail_2_2" explicitly set, so the get_default_model fallback is not reached. But if it were, TASK_TYPE_TO_MODEL["vace"] = "vace_14B_cocktail_2_2" (task_types.py line 75) -- still correct.
Default file exists:Wan2GP/defaults/vace_14B_cocktail_2_2.json is present on disk. The deleted file vace_14B_fake_cocktail_2_2 has zero references anywhere in the codebase.
Expected parameters:guidance_phases=2 and guidance_scale=1 are both in the DB snapshot (lines 14, 21) and both are in the param_whitelist in task_conversion.py (lines 42-43). They pass through to generation_params and into the GenerationTask.parameters dict. The FakeImmediateTaskQueue validation at run_worker_matrix.py line 167-171 checks these exact values.
Verdict: PASS -- no changes affect this case.
Case 2: individual_travel_segment_wan22_i2v_baseline_2_2_2 -- PASS
Routing:task_type="individual_travel_segment" is NOT in DIRECT_QUEUE_TASK_TYPES. It hits the specialized handlers dict at task_registry.py line 1138, which routes to handle_travel_segment_via_queue(is_standalone=True). This function is defined in task_registry.py (starts around line 126 with _resolve_segment_context).
Import path: The handler lives in the same task_registry.py file, not in a separate module. The new source/task_handlers/travel/ directories contain orchestrator.py, stitch.py, and segment_processor.py (imported at lines 33-34, 42), but handle_travel_segment_via_queue itself remains in task_registry.py.
Expected model: The builder at run_worker_matrix.py line 719 expects . This comes from the DB snapshot's field (db_snapshots.json line 119). The travel segment handler reads from and passes it to the queue as the model for the generation task.
Assistant
That's a missing import -- parse_phase_config is used at line 262 but never imported. However, this code path is only reached when "phase_config" in db_task_params, which is not the case for any of cases 5-8 (none of the z_image or qwen snapshots have phase_config). So it won't affect these cases, but it's a latent bug.
Now I have all the information needed. Let me compile the full verification report.
Worker Matrix Cases 5-8 Verification Report
Case 5: z_image_turbo_db_task (task_type="z_image_turbo")
Is "z_image_turbo" in DIRECT_QUEUE_TASK_TYPES?
PASS -- Line 60 of /Users/user_c042661f/Documents/Headless-Wan2GP/source/task_handlers/tasks/task_types.py: "qwen_image", "qwen_image_2512", "z_image_turbo",
Does task_conversion.py set model="z_image", video_length=1, guidance_scale=0?
PASS -- Lines 135-147 of /Users/user_c042661f/Documents/Headless-Wan2GP/source/task_handlers/tasks/task_conversion.py:
Line 138: generation_params.setdefault("video_length", 1)
Line 139: generation_params.setdefault("guidance_scale", 0)
Line 147: model = "z_image"
Do snapshot params pass through the whitelist?
The z_image_turbo snapshot params are: hires_denoise, hires_scale, hires_steps, lightning_lora_strength_phase_1, lightning_lora_strength_phase_2, model, prompt, resolution, seed, steps, add_in_position.
Checking whitelist (lines 38-76):
hires_denoise -- in whitelist (line 55)
hires_scale -- in whitelist (line 55)
hires_steps -- in whitelist (line 55)
lightning_lora_strength_phase_1 -- NOT in whitelist. The whitelist has lightning_lora_strength (line 55) but NOT lightning_lora_strength_phase_1 or lightning_lora_strength_phase_2.
lightning_lora_strength_phase_2 -- NOT in whitelist (same reason)
model -- not whitelisted, but handled separately at line 31-34
prompt -- not whitelisted, but handled separately at line 19
Assistant
Good. Now let me verify the patcher path for qwen_handler.
handle_qwen_image_style sets video_length=1 -- Line 489: generation_params.setdefault("video_length", 1). PASS
Builder patches source.models.model_handlers.qwen_handler.hf_hub_download (line 673 of run_worker_matrix.py). The actual import in qwen_handler.py is at line 15: from huggingface_hub import hf_hub_download. This means source.models.model_handlers.qwen_handler.hf_hub_download is the module-level attribute, and patching it will intercept any call to hf_hub_download made inside that module. PASS -- the import path is still valid.
Verdict for Case 7: PASS
Case 8: qwen_image_edit_db_task (task_type="qwen_image_edit")
Any special handling for qwen_image_edit in task_conversion.py?
PASS -- Lines 117-118: if task_type == "qwen_image_edit": then qwen_handler.handle_qwen_image_edit(db_task_params, generation_params). Note: unlike qwen_image_style, this does NOT explicitly set model = "qwen_image_edit_20B" after the handler call. Instead the model comes from the fallback at lines 31-34: since the snapshot has no model key in params, it falls through to get_default_model(task_type).
TASK_TYPE_TO_MODEL["qwen_image_edit"] still maps to "qwen_image_edit_20B"?
PASS -- Line 95 of task_types.py: "qwen_image_edit": "qwen_image_edit_20B"
expected_parameters: video_length=1?
PASS -- handle_qwen_image_edit sets generation_params.setdefault("video_length", 1) at line 358.
Same patcher path check: source.models.model_handlers.qwen_handler.hf_hub_download?
PASS -- Same as case 7, line 15 of qwen_handler.py imports hf_hub_download at module level.
But wait: The qwen_image_edit snapshot params include "image": "__FIXTURE_PATH__:qwen_edit_input". The handler at line 335 does db_task_params.get("image") to get the image URL. The fixture path will be a local file path after token replacement. Then download_image_if_url is called (line 341). Let me verify that function handles local paths.
Assistant
Good. If the path is a local file (not http/https), download_image_if_url returns it as-is (line 191 check). The fixture path substitution will produce a local path, so this is fine. PASS
Verdict for Case 8: PASS
Cross-cutting checks
worker.py process_single_task signature -- has it changed?
The runner calls it at lines 477-485 with: task_params_dict, main_output_dir_base, task_type, project_id_for_task, task_queue, colour_match_videos, mask_active_frames (all keyword args).
PASS -- signature unchanged, all keyword arguments match.
source/core/log enable_debug_mode -- still exists?
PASS -- Found at /Users/user_c042661f/Documents/Headless-Wan2GP/source/core/log/core.py:72 and exported via source/core/log/__init__.py (star import from core).
TaskOutcome enum -- still has FAILED, ORCHESTRATING, ORCHESTRATOR_COMPLETE, SUCCESS?
PASS -- Lines 28-32 of /Users/user_c042661f/Documents/Headless-Wan2GP/source/core/params/task_result.py:
SUCCESS = "success"
FAILED = "failed"
ORCHESTRATING = "orchestrating"
ORCHESTRATOR_COMPLETE = "orchestrator_complete"
Summary
Case
Status
Notes
Case 5: z_image_turbo_db_task
PASS
model="z_image", video_length=1, guidance_scale=0 all correct. lightning_lora_strength_phase_1/2 params silently dropped (not in whitelist) but not in expected_parameters so test passes.
Case 6: z_image_turbo_i2i_db_task
PASS
model="z_image_img2img", strength->denoising_strength fallback chain works (0.4), requests.get patch path correct.
User
I need to understand the full end-to-end flow of how a task gets from the database to a completed generation on a worker. Trace the entire pipeline:
Read worker.py — how does it poll for tasks? What's the main loop? Does it call something like claim_next_task from the DB?
How does a task get into the DB in the first place? Is there a tasks table? What columns matter (task_type, status, params, etc.)?
Once a task is claimed, trace through process_single_task → TaskRegistry.dispatch → what happens for a direct-queue task vs specialized handler
For direct-queue tasks: after db_task_to_generation_task creates the GenerationTask, what does HeadlessTaskQueue.submit_task actually do? Does it call WGP? How does WGP get invoked?
Read headless_wgp.py and headless_model_management.py — how do models get loaded? Is there a model loading step before generation?
When generation completes, how does the result get written back to the DB? What's the completion flow?
What environment does this run in? Check for .env usage, SUPABASE_URL, model paths, output directories.
Is there a way to manually insert a task into the DB and have a running worker pick it up? What's the minimum viable task row?
Report the full flow from "task appears in DB" to "generation complete, result written back".
Assistant
I'll trace the full end-to-end pipeline. Let me start by reading the key entry points and following the chain.
Assistant
Now let me read the DB operations, task registry, task queue, and the actual runtime entrypoints.
Assistant
Now let me read the DB polling, task claim, task conversion, task processor, and WGP init modules.
Assistant
Now let me read the task status update functions, the orchestrator, the queue lifecycle, and the DB config.
Assistant
Let me read the task registry dispatch logic and the orchestrator's generate methods, plus the queue lifecycle.
Assistant
Now let me read the task registry's dispatch method and the direct-queue handler logic.
Assistant
Now let me check how models get loaded and the generation strategies.
Assistant
Now let me check the orchestrator's generate method and .env usage.
Assistant
I now have a complete picture of the entire pipeline. Here is the full end-to-end flow.
Full End-to-End Pipeline: Task Appears in DB to Generation Complete
1. Environment and Configuration
Environment variables (loaded from .env via dotenv):
SUPABASE_URL -- Supabase project URL
SUPABASE_SERVICE_ROLE_KEY -- service role JWT for DB access
SUPABASE_ACCESS_TOKEN -- auth token for Edge Functions (often same as service key)
SUPABASE_ANON_KEY -- fallback for local workers
RUNPOD_POD_ID -- auto-derived as worker_id on RunPod
SUPABASE_VIDEO_BUCKET -- defaults to "image_uploads"
Initialize Supabase client -- create_client(url, key) stored in db_config.SUPABASE_CLIENT.
Import and configure WGP -- os.chdir(wan_dir), import wgp, apply CLI overrides to wgp_mod.server_config (attention mode, profile, quantization, etc.), then os.chdir(original_cwd).
Initialize HeadlessTaskQueue -- creates the queue manager (/Users/user_c042661f/Documents/Headless-Wan2GP/source/task_handlers/queue/task_queue.py). At this point, the is NOT created yet (lazy init to avoid CUDA during setup).
User
I need to understand the HeadlessTaskQueue and WanOrchestrator initialization so we can build a real-generation test harness that bypasses the DB but uses the real GPU pipeline.
Read source/task_handlers/queue/task_queue.py — what does HeadlessTaskQueue.init take? What's the interface? What does submit_task do internally?
Read source/task_handlers/queue/wgp_init.py — how does _ensure_orchestrator work? What does it need (paths, config)?
Read source/task_handlers/queue/task_processor.py — trace process_task_impl(). What's the sequence: model switch → generation → result? What does it return?
Read source/task_handlers/queue/queue_lifecycle.py — what does start_queue() do? Does it spawn threads? Can we skip that and call process_task_impl directly?
Read source/models/wgp/orchestrator.py — what does WanOrchestrator.init take? What's generate_t2v/generate_vace signature?
Read worker.py process_single_task — what's the minimum context it needs? Could we call it directly with a real HeadlessTaskQueue instead of FakeImmediateTaskQueue?
Check: does HeadlessTaskQueue need a Supabase connection, or does it work purely locally? Are there any DB calls inside the queue/generation path that would need mocking?
Report what we need to initialize, what we can skip, and where DB calls happen that would need spoofing.
Assistant
I'll read all the relevant files in parallel to trace the initialization and generation paths.
User
I need to find every place in the generation pipeline that touches the database (Supabase), so we can mock/spoof those calls in a real-generation test harness.
Search for all DB interactions in these files and their imports:
source/task_handlers/queue/task_processor.py — any db_ops calls?
source/task_handlers/queue/download_ops.py — does model switching touch DB?
source/task_handlers/tasks/task_registry.py — the _handle_direct_queue_task path and specialized handlers — any DB calls during execution (not just at the end)?
source/task_handlers/tasks/task_conversion.py — any DB lookups during param conversion?
source/models/wgp/orchestrator.py — any DB calls during generation?
worker.py process_single_task — what DB calls happen BEFORE and AFTER the actual generation?
Search for patterns like:
db_ops.
supabase
SUPABASE
update_task_status
reset_generation_started_at
add_task_to_db
get_task_output_location
upload
complete_task
For each DB call found, note: file, line, what it does, and whether it's essential for generation or just bookkeeping (status updates, billing, uploads).
Assistant
I'll search all six files in parallel, plus grep for the key DB patterns across the source directory.
Assistant
Now let me read the orchestrator file fully and check for DB calls in the generation path.
User
Look at how the existing worker matrix runner (scripts/run_worker_matrix.py) initializes things and what it mocks. I want to understand the pattern so we can extend it for real generation.
Read scripts/run_worker_matrix.py — specifically run_case() and how it calls worker.process_single_task. What does it pass for each arg?
What does the FakeImmediateTaskQueue look like vs the real HeadlessTaskQueue? What methods differ?
Look at how the matrix runner imports worker — does it do anything special with sys.path or os.chdir?
Check if there's a way to construct a real HeadlessTaskQueue without starting worker threads — can we just use it as a synchronous wrapper?
Read source/task_handlers/queue/task_queue.py — does HeadlessTaskQueue have a synchronous "run one task and wait" mode, or is it always async with threads?
Check headless_model_management.py — what does it export? Is HeadlessTaskQueue defined there or imported from elsewhere?
Report the minimal changes needed to make the matrix runner use a real queue instead of the fake one.
Assistant
I'll investigate all of these in parallel.
Assistant
Now let me read the task_registry.py fully and search for DB patterns in the orchestrator and related files.
Assistant
Now let me read the generate_t2v/generate_vace/generate_flux signatures and the generation_helpers notify function.
Assistant
I see headless_model_management.py is a shim now. Let me check where the real HeadlessTaskQueue lives and look at the queue lifecycle, worker module, and how process_single_task works.
Assistant
Now let me check the submit_task flow and the WgpInitMixin to understand the init dependencies.
Assistant
Let me also check what _save_queue_state is and look at the task registry dispatch for WGP tasks.
Assistant
Now let me look at the remaining task_registry.py lines (the DB call around line 329) and the db_operations module, plus search for DB calls in the specialized handlers referenced by task_registry.
Assistant
Now let me check the remaining orchestrator.py and the generation_helpers.py notification call, plus the reset_generation_started_at function.
Assistant
_save_queue_state is called on the queue object but never defined -- it must be defined elsewhere or is a no-op. Let me check.
Assistant
Now let me check upload_and_get_final_output_location and the model_ops notify call to understand what happens during model loading.
Assistant
So _save_queue_state is called but never defined -- it would raise AttributeError on shutdown. Not relevant for our purposes. Now let me check the TaskRegistry dispatch for WGP tasks.
Assistant
Now let me check the TaskRegistry dispatch method to see how WGP tasks get routed to the queue.
Assistant
Now I have a thorough picture. Here is the full analysis:
1. How run_case() calls worker.process_single_task
In run_case() (line 477 of scripts/run_worker_matrix.py), the call is:
It does NOT pass image_download_dir (defaults to None in process_single_task). The task_queue is the FakeImmediateTaskQueue from the PreparedCase.
2. FakeImmediateTaskQueue vs real HeadlessTaskQueue
The FakeImmediateTaskQueue implements exactly two methods:
submit_task(generation_task) -- Synchronously captures the task, validates expected model/parameters, creates a synthetic output (fake image/video), records status as completed/failed immediately in self.status_map. Returns the task id.
get_task_status(task_id) -- Returns a SimpleNamespace with .status, .result_path, .error_message, .processing_time.
The real HeadlessTaskQueue has the same two methods but they behave completely differently:
submit_task(task) -- Puts the task on a queue.PriorityQueue via submit_task_impl(). The task is then picked up asynchronously by a worker_loop running in a daemon thread. This worker loop calls process_task_impl() which calls _switch_model() then _execute_generation() via the orchestrator.
Assistant
I now have a complete picture. Here is the full analysis.
DB Interaction Map for the Generation Pipeline
1. source/task_handlers/queue/task_processor.py
Line
Call
Purpose
Essential for Generation?
77-78
from source.db_operations import reset_generation_started_at; reset_generation_started_at(task.id)
Resets billing clock after model load (so users are not charged for model switch time)
Bookkeeping -- billing only. Generation proceeds even if this fails (line 81 catches and logs).
That is the only DB call in this file. The rest is purely local queue state (queue.current_task, queue.stats).
2. source/task_handlers/queue/download_ops.py
Zero DB calls. The only Supabase-related line (145) is strippingsupabase_url, supabase_anon_key, supabase_access_token keys from task params so they are not passed to WGP. No DB reads or writes.
3. source/task_handlers/tasks/task_registry.py
Line
Call
Purpose
Essential for Generation?
158
db_ops.get_task_params(orchestrator_task_id_ref)
In _resolve_segment_context: fetches parent orchestrator's params from DB when orchestrator_details is not inline in the segment task. Only for travel_segment tasks dispatched by an orchestrator.
Essential for orchestrated travel segments -- without this, the segment does not know its generation parameters. NOT needed for direct/simple generation tasks.
In _resolve_image_references: SVI chaining -- fetches predecessor segment's output URL so we can download and extract tail frames for temporal continuity. Only for SVI-mode travel segments where segment_idx > 0.
Essential for SVI continuation segments -- needed to chain video segments. Not needed for standalone generation or first segments.
Both calls are in the travel-segment handler path (handle_travel_segment_via_queue), not in the simple WGP generation path ().
Assistant
Now I have a complete picture. Here is the full analysis.
Complete Analysis: HeadlessTaskQueue and WanOrchestrator Initialization
self.wan_dir -- an absolute path to the Wan2GP/ directory
self.main_output_dir -- optional output dir
CUDA must be available (it does a warmup: creates a test tensor on GPU)
Working directory must be self.wan_dir at creation time (it uses temporary_process_globals to chdir)
What it does:
Warms up CUDA (creates test tensor on GPU)
Gets a via , calls to chdir + fix sys.path/argv
User
Design a plan to add a --real mode to the worker matrix runner that performs actual GPU generation instead of using FakeImmediateTaskQueue.
Context from exploration
Architecture:
The matrix runner (scripts/run_worker_matrix.py) calls worker.process_single_task() which dispatches through TaskRegistry → _handle_direct_queue_task() → db_task_to_generation_task() → task_queue.submit_task(generation_task) → polls task_queue.get_task_status().
Currently, FakeImmediateTaskQueue intercepts submit_task, creates synthetic output, and returns immediately.
The real HeadlessTaskQueue (from source/task_handlers/queue/task_queue.py) uses background threads to process tasks through process_task_impl → model switch → execute_generation_impl → orchestrator.generate_*() → real GPU generation.
DB calls in the generation path (only 2, both non-fatal):
reset_generation_started_at(task.id) in task_processor.py:78 — billing clock reset. Already wrapped in try/except, logs warning on failure.
notify_worker_model_switch() in generation_helpers.py:21 — only fires if WORKER_ID env var is set. Silently skips otherwise.
No other DB calls in the core generation path. All DB interaction is in worker.py's main loop (task claiming, status updates, uploads) which the matrix runner already bypasses.
HeadlessTaskQueue initialization needs:
wan_dir path to Wan2GP directory
main_output_dir for outputs
.start() call to spawn worker threads (1 thread is fine)
CUDA available
Model weights on disk (or downloadable)
Key design decisions:
A single shared HeadlessTaskQueue across all cases (models stay loaded between cases)
worker.process_single_task is still the entry point (preserves full routing/conversion coverage)
The task handlers inside will call task_queue.submit_task() which goes to the real queue's PriorityQueue, gets picked up by the worker thread, and actually generates
The polling in _handle_direct_queue_task (which calls every 2s) naturally waits for completion
Assistant
I'll explore the codebase to understand the current structure and fill in any gaps before designing the plan.
Assistant
Now let me look at a few more key files to understand the initialization flow and the polling mechanism.
Assistant
Now let me check how _handle_direct_queue_task polls the queue and what the timeout behavior looks like.
Assistant
Now let me check the _save_queue_state method referenced in stop_queue:
Assistant
It seems _save_queue_state doesn't exist as a method - it'll likely crash on stop. Let me check if it exists somewhere on HeadlessTaskQueue or as a mixin method.
Assistant
OK so it's defined on wgp.py's side, likely inherited through the orchestrator. Let me check the _handle_direct_queue_task more fully and also the db_task_to_generation_task conversion.
Assistant
Now let me check the DB snapshots to understand the fixture URL/path tokens used:
Assistant
Now let me check the process_single_task signature more carefully and how wan2gp_path gets into the context:
Assistant
I see there are two process_single_task definitions. Let me check which one the matrix runner uses (it imports worker).
Assistant
Now I have a complete picture. Let me also check the REQUIREMENT_CHECKERS to understand how to add a cuda requirement:
Assistant
Good. Now I have a thorough understanding of the entire flow. Let me design the plan.
Implementation Plan: --real Mode for Worker Matrix Runner
1. Overview
The --real flag transforms the worker matrix runner from a fast, synthetic-output smoke test into an actual GPU generation test. The key insight is that the existing architecture already supports this cleanly: worker.process_single_task() accepts any object with submit_task() and get_task_status() methods as task_queue. In fake mode it gets a FakeImmediateTaskQueue; in real mode it gets a shared HeadlessTaskQueue that actually generates.
2. Changes to scripts/run_worker_matrix.py
2a. CLI Arguments (in parse_args)
Add three new flags:
--real (store_true, default False) -- enables real GPU generation
--preload-model MODEL (str, optional) -- model to preload during queue startup
--real-timeout SECONDS (int, default 600) -- per-case timeout in real mode (overrides the 3600s default in _handle_direct_queue_task)
2b. Shared Queue Lifecycle (in main)
When --real is set:
After ensure_repo_on_path(), initialize a single shared HeadlessTaskQueue:
Note: Unused builders (t2v_basic, i2v_basic, wan_22_t2i_basic, qwen_image_style_db_like, extract_frame_basic, create_visualization_basic) can be added to the manifest as needed.
CASE_BUILDERS dict - All 12 builders complete and functional
Manifest file - Valid JSON with 6 properly configured test cases
DB snapshots - All referenced snapshots populated with realistic task params
worker.py - Has process_single_task() with correct signature
Imports - All critical dependencies resolve without errors
Logging - source.core.log.enable_debug_mode available
Test infrastructure - FakeImmediateTaskQueue, TeeWriter, result validation all present
What Would NOT Break
All manifest cases - Each references an existing builder
All builder calls - Properly construct PreparedCase with patchers, params, notes
Import chain - No circular dependencies or missing modules
Mock patching - Qwen handler HF download mocked; extract_frame DB calls mocked; requests.get patched for I2I
Result normalization - Handles both TaskResult and (bool, str) tuple returns
What Could Be Enhanced (Optional)
Expand manifest - Add cases for the 6 unused builders (t2v_basic, i2v_basic, etc.)
Add more snapshots - Create snapshot entries for other task types if needed
Add integration tests - Test actual WGP model invocations (currently using FakeImmediateTaskQueue)
Conclusion
Status: FULLY OPERATIONAL AND PRODUCTION-READY
The worker matrix runner is completely wired up with:
Fully defined case builders matching manifest references
Valid JSON manifests and snapshots
All required Python dependencies and modules present
Recent successful execution history (6/6 cases passing)
No TODO comments or incomplete sections
You can run it today without issues:
bash
cd /Users/user_c042661f/Documents/Headless-Wan2GP
python scripts/run_worker_matrix.py --manifest scripts/worker_matrix_cases.json
selected_cases.json -- written at line 344. OK.
summary.json -- written at line 361. OK.
summary.md -- written at lines 362-365. OK.
failures.txt -- written at line 368. OK.
rerun_failed.sh -- written at lines 369-383. OK.
No top-level artifacts are missing from the doc and no doc'd artifacts are absent from the code. This section is accurate.
3. Per-Case Files
case_definition.json -- written at line 393 in run_case(). OK.
prepared_input.json -- written at lines 413-418 in run_case(). OK.
captured_generation_task.json -- written at line 151 in FakeImmediateTaskQueue.submit_task(), only for cases that use the fake queue. The doc says "for fake-queue direct cases." OK, accurately qualified.
worker.log -- written via the TeeWriter at line 426. OK.
result.json -- written at line 494 (and also at line 409 for skipped cases). OK.
traceback.txt -- written at line 464, only when an exception occurs. The doc says "when a case crashes." OK.
"generated local outputs" -- the doc mentions this. The code creates an outputs/ subdirectory (e.g., line 522-523 in _build_direct_queue_case). OK, vague but not wrong.
Manifest (worker_matrix_cases.json) contains exactly these 6 case IDs with default_enabled: true. Perfect match. No mismatches in case IDs.
However, there are also builders registered in CASE_BUILDERS (lines 794-807) that have no corresponding manifest entries:
t2v_basic
i2v_basic
wan_22_t2i_basic
qwen_image_style_db_like
extract_frame_basic
create_visualization_basic
These are available builders but not in the manifest, so they are not "locked cases." The doc does not mention these latent builders exist. This is a minor gap -- users looking at the doc would not know additional builders are ready to be wired up in the manifest.
Real direct-queue task conversion for representative task types
Real specialized handler execution for low-cost local cases
What is actually real vs. mocked:
Real:
worker.process_single_task() is called for real (line 444).
Task routing through whatever registry process_single_task uses is real.
Parameter preparation/conversion is real.
Mocked/Faked:
The task queue is a FakeImmediateTaskQueue that captures the generation task and immediately returns a synthetic result. It never actually runs any ML model. The doc does mention this on line 13: "the runner uses a fake immediate queue after real payload conversion."
requests.get is mocked for the Z-Image i2i case (line 634-638).
hf_hub_download is mocked for Qwen cases (lines 657, 675, 689).
DB operations are mocked for the extract_frame case (lines 747-748).
Synthetic outputs (solid-color images/videos) are created instead of real generation (lines 835-839).
Assessment: The doc's claim of "Real specialized handler execution for low-cost local cases" is accurate but could be misleading. For direct-queue generation cases, the handler runs up to the point of queue submission, then the fake queue short-circuits everything. The doc's qualifying paragraph on line 13 does explain this, but the bullet points at the top could give a false impression of end-to-end execution. The phrase "Real specialized handler execution" specifically applies to non-generation tasks like extract_frame and create_visualization which can actually complete locally.
6. The "Serial" Note
Doc says: "The runner is intentionally serial."
The code confirms this. The main loop at lines 349-354 is a simple for case in selected: loop with no threading, multiprocessing, or async. Accurate.
7. Marker Strings
Doc says: [WORKER_MATRIX][CASE_START], [CASE_END], and [CASE_EXCEPTION]
Code has:
Line 432: [WORKER_MATRIX][CASE_START] -- OK.
Line 456: [WORKER_MATRIX][CASE_END] -- OK.
Line 466: [WORKER_MATRIX][CASE_EXCEPTION] -- OK.
All three markers match exactly.
8. Missing Documentation Summary
Features in the code not mentioned in the doc:
--manifest flag -- lets you point to a custom manifest file instead of the default scripts/worker_matrix_cases.json.
--output-dir flag -- lets you change the output root from the default artifacts/worker-matrix/.
--family flag -- filter cases by family (e.g., direct_queue, travel_segment).
--all-cases flag -- include non-default-enabled cases in the run.
--stop-on-failure flag -- halt the suite on the first failed case.
CaseDefinition.requires mechanism -- cases can declare requirements (e.g., ffmpeg, moviepy) and get auto-skipped if not met. The REQUIREMENT_CHECKERS dict (lines 907-910) and requirements_status() (lines 244-253) implement this. Not mentioned in the doc at all.
CaseDefinition.default_enabled field -- cases can be marked non-default. Not mentioned.
CaseDefinition.expected_outcome field -- cases can expect failure (the runner compares actual vs expected to determine pass/fail status). Not mentioned.
DB snapshots system -- worker_matrix_db_snapshots.json provides frozen DB task payloads with placeholder tokens that get substituted with local fixture paths. This is a significant architectural detail not documented.
6 additional builder functions (t2v_basic, i2v_basic, wan_22_t2i_basic, qwen_image_style_db_like, extract_frame_basic, create_visualization_basic) that are wired up in CASE_BUILDERS but have no manifest entries. These are ready to be activated.
The skipped status -- when requirements are not met, a case gets status skipped (line 403). The doc only implies pass/fail.
Additional Minor Note
The doc says the locked suite includes "an LTX 2.3 representative ltx2_22B case." The manifest description for ltx2_22b_basic says "Direct queue LTX 2.3 representative smoke path." The builder at line 582 sets expected_model="ltx2_22B" and the model param is "ltx2_22B". However, the doc text says "LTX 2.3" -- this appears to be a version identifier for the LTX Video model family, not necessarily verifiable from this code alone. Not flagging as a discrepancy but worth noting.
TaskOutcome.NOT_FAILED
python
if raw_result.outcome == TaskOutcome.FAILED:
or at minimum:
python
if raw_result.outcome.value == "failed":
3. CORRECT: _normalize_worker_result() handles all return shapes
A TaskResult (which has .outcome) -- handled by the hasattr(raw_result, "outcome") branch
A (bool, str) tuple -- handled by the isinstance(raw_result, tuple) branch
This is correct and complete.
4. CORRECT: FakeImmediateTaskQueue interface
The real HeadlessTaskQueue is used via two methods:
submit_task(generation_task) -- called at task_registry.py:1045, generation.py:870, inpaint_frames.py:247
get_task_status(task_id) -- called at task_registry.py:1052, generation.py:881, inpaint_frames.py:256
FakeImmediateTaskQueue implements both. The real get_task_status returns a GenerationTask (or None), while the fake returns a SimpleNamespace. The callers access .status, .result_path, .error_message on the returned object, and SimpleNamespace provides all three. This is correct.
5. NIT: TeeWriter type hint (line 106)
Severity: Nit
python
def __init__(self, *streams: io.TextIOBase):
sys.__stdout__ is a TextIOWrapper, which is a subclass of TextIOBase, and file objects from path.open("w") are also TextIOWrapper. The type hint is fine. However, TeeWriter.encoding is None (inherited from TextIOBase). Some third-party code checks sys.stdout.encoding and may get None instead of "utf-8". In practice, this is unlikely to cause issues for this test runner, but it is worth noting.
6. NIT: Status logic in run_case() (lines 471-477)
Severity: Nit (dead code)
python
expectation_matched = (
(case.expected_outcome == "success" and actual_outcome == "success") or
(case.expected_outcome == "failure" and actual_outcome == "failure")
)
status = "passed" if expectation_matched else "failed"
if actual_outcome == "failure" and case.expected_outcome == "success":
status = "failed"
Line 476-477 is redundant. If actual_outcome == "failure" and case.expected_outcome == "success", then expectation_matched is already False, so status is already "failed". The if block does nothing.
Missing case: If actual_outcome == "skipped", this code path is never reached (skipped cases return early at line 410), so that is fine.
Another missing case: actual_outcome can only ever be "success" or "failure" (set at lines 421, 454, 462). There is no "skipped" path here. If expected_outcome were something other than "success" or "failure" (e.g., a typo in the manifest), expectation_matched would be False and the case would be marked "failed". This is reasonable behavior.
7. NIT: shlex_quote (lines 913-914)
Severity: Nit
The custom implementation is functionally equivalent to shlex.quote from the standard library. The stdlib version has been available since Python 3.3. The only difference is that shlex.quote handles the empty-string case the same way (wraps in single quotes) and avoids quoting safe strings (e.g., shlex.quote("simple") returns "simple" without quotes, while the custom one returns "'simple'"). The custom version is more conservative (always quotes), which is safe for shell scripts. However, there is no reason not to use the stdlib version. shlex is already in the standard library.
8. POTENTIAL ISSUE: _json_safe() incomplete type coverage (lines 884-891)
Severity: Potential issue
_json_safe handles Path, dict, list, tuple, and passes through everything else. It does NOT handle:
numpy scalar types (np.float32, np.int64, etc.) -- these will cause json.dumps to raise TypeError
bytes objects
set objects
Custom objects with no __str__
The params from DB snapshots are plain JSON types, so this is unlikely to be triggered by the current cases. But if a builder constructs params with numpy values (possible since numpy is imported), _write_json will crash. The function is called on generation_task.parameters (line 147), prepared.params (line 416), and prepared.notes (line 417).
9. NIT: Global _DB_SNAPSHOTS_CACHE thread safety (line 43)
Severity: Nit
Cases run serially in the main() loop, so there is no thread safety issue. Fine as-is.
Called in main() (line 307) and again in run_case() (line 389). The function is idempotent (checks before inserting), so the double call is harmless. The call in run_case exists so that run_case can be called standalone (e.g., from tests) without requiring main() to have run first. This is intentional and correct.
11. Manifest cases vs. CASE_BUILDERS (line 794-807)
The 6 manifest cases use these builders:
wan22_individual_segment_db_like -- in CASE_BUILDERS (line 804)
ltx2_basic -- in CASE_BUILDERS (line 797)
z_image_turbo_basic -- in CASE_BUILDERS (line 799)
z_image_turbo_i2i_basic -- in CASE_BUILDERS (line 800)
qwen_image_basic -- in CASE_BUILDERS (line 801)
qwen_image_edit_basic -- in CASE_BUILDERS (line 802)
All 6 manifest builders exist in CASE_BUILDERS. Good.
The builders that are in CASE_BUILDERS but NOT referenced by any manifest case:
t2v_basic (line 795)
i2v_basic (line 796)
wan_22_t2i_basic (line 798)
qwen_image_style_db_like (line 803)
extract_frame_basic (line 805)
create_visualization_basic (line 806)
These 6 are exactly the ones you plan to delete. They are dead code with respect to the current manifest.
12. DB snapshot fixture token replacements
The snapshots use these tokens:
individual_travel_segment_wan22_i2v: uses __FIXTURE_PATH__:wan22_start_image and __FIXTURE_PATH__:wan22_end_image
_utc_timestamp() at line 900 uses strftime("%Y%m%dT%H%M%S%fZ") which produces a string like 20260316T142905936162Z -- no colons or + signs. The .replace(":", "").replace("+", "_") calls are no-ops. Looks like _utc_timestamp was changed at some point from isoformat() (which does contain colons and +) but the caller was not updated to remove the now-unnecessary replacements.
14. POTENTIAL ISSUE: _normalize_worker_result does not handle ORCHESTRATING outcome (line 498-509)
Severity: Potential issue
For a TaskResult with outcome=TaskOutcome.ORCHESTRATING, _normalize_worker_result returns (True, output_path, None). This means actual_outcome is set to "success". Then line 471-474 compares case.expected_outcome == "success" which would pass. However, ORCHESTRATING means the task is not done yet -- it would be a misleading "success". Currently no manifest case expects orchestrator behavior, so this is not a live issue, but it is a latent correctness problem if orchestrator test cases are ever added.
15. NIT: Missing encoding property on TeeWriter for third-party compatibility
Severity: Nit
Some libraries (e.g., click, some logging formatters) check sys.stdout.encoding. TeeWriter inherits encoding = None from io.TextIOBase. If any code inside the worker path does sys.stdout.encoding, it will get None instead of "utf-8". Adding an encoding property that delegates to the first stream would make this more robust.
Summary
#
Line(s)
Severity
Description
1
322
Nit (works by accident)
set() | set() or None relies on operator precedence and truthiness coincidence
2
500-501
Potential issue
Fragile substring match on str(TaskOutcome) instead of direct comparison
3
476-477
Nit (dead code)
Redundant if block, status is already "failed" from line 475
4
913-914
Nit
Custom shlex_quote when shlex.quote from stdlib would suffice
5
884-891
Potential issue
_json_safe() does not handle numpy scalars, bytes, sets
6
340
Nit (dead code)
.replace(":", "").replace("+", "_") are no-ops given the timestamp format
7
498-509
Potential issue
ORCHESTRATING outcome mapped to "success" could mislead future orchestrator test cases
8
106
Nit
TeeWriter lacks encoding property; could break code that reads sys.stdout.encoding
9
795-806
Info
6 builders (t2v_basic, i2v_basic, wan_22_t2i_basic, qwen_image_style_db_like, extract_frame_basic, create_visualization_basic) are unreferenced by the manifest -- safe to delete
No show-stopping bugs found. The most actionable item is issue #2 (fragile outcome detection), which could silently break if the TaskOutcome enum changes.
13
generate_video
Generic generation
14
qwen_image_edit
Qwen image
15
qwen_image_hires
Qwen image
16
qwen_image_style
Qwen image
17
image_inpaint
Qwen image
18
annotated_image_edit
Qwen image
19
qwen_image
Text-to-image
20
qwen_image_2512
Text-to-image
21
z_image_turbo
Z-Image
22
z_image_turbo_i2i
Z-Image i2i
Specialized Handler Task Types (from the handlers dict, lines 1123-1193):
Note: inpaint_frames appears in bothDIRECT_QUEUE_TASK_TYPES (line 63 of task_types.py -- wait, actually it does NOT appear there). Let me re-check. Looking at task_types.py again: inpaint_frames is in WGP_TASK_TYPES (line 31) but NOT in DIRECT_QUEUE_TASK_TYPES. So it hits the specialized handler in tier 2.
Total: 36 distinct task types.
Matrix Coverage
The worker matrix (/Users/user_c042661f/Documents/Headless-Wan2GP/scripts/worker_matrix_cases.json) currently covers 6 cases:
Direct Queue types NOT in matrix (16 uncovered out of 22):
Task Type
Testable with fake-queue?
Notes
vace
Yes
Standard direct queue, no special inputs beyond prompt
vace_21
Yes
Same as vace
vace_22
Yes
Same as vace
flux
Yes
Direct queue, text-to-image
t2v
Yes
Core text-to-video, straightforward
t2v_22
Yes
Same pattern as t2v
wan_2_2_t2i
Yes
Direct queue, sets video_length=1 (line 1221-1222)
i2v
Mostly yes
Needs input image URL/path, but fixture substitution works (like z_image_turbo_i2i)
i2v_22
Mostly yes
Same as i2v
hunyuan
Yes
Direct queue
ltxv
Yes
Direct queue (ltx2 already tested, ltxv is similar)
generate_video
Yes
Generic, maps to t2v model
qwen_image_hires
Mostly yes
Needs input image, similar to qwen_image_edit
image_inpaint
Mostly yes
Needs input image + mask
annotated_image_edit
Mostly yes
Needs input image + annotations
qwen_image
Yes
Text-to-image, no input image needed
qwen_image_2512
Yes
Text-to-image, no input image needed
Specialized handler types NOT in matrix (13 uncovered out of 14):
Task Type
Testable with fake-queue?
Notes
travel_orchestrator
No
Requires DB project_id, creates child tasks in DB, polls DB for completion. Heavy DB dependency.
travel_segment
Partially
Similar to individual_travel_segment (which IS tested) but runs in orchestrated mode (is_standalone=False). Needs orchestrator context.
travel_stitch
No
Reads segment video files from disk that were produced by prior travel_segment tasks. File dependency.
magic_edit
Partially
Needs input video URL. Handler does its own downloading/processing. Could work with fixture substitution.
join_clips_orchestrator
No
Like travel_orchestrator: DB-heavy, creates child tasks, requires project_id.
edit_video_orchestrator
No
Same as join_clips_orchestrator.
join_clips_segment
Partially
Needs prior segment data and input video. Submits to task queue internally.
join_final_stitch
No
Reads completed segment outputs from disk. File dependency chain.
inpaint_frames
Partially
Needs input video + mask. Submits WGP tasks internally via task_queue.
create_visualization
No
Reads from DB (task results, segment data) to create visualizations. DB dependency.
extract_frame
Partially
Needs input video path. Relatively simple -- could work if video fixture exists.
rife_interpolate_images
Partially
Needs input images. Submits to task_queue for RIFE processing.
comfy
No
Requires ComfyUI server running. External service dependency.
Summary
36 total task types the worker can handle
6 covered by the matrix (17%)
30 uncovered
Easiest wins for expanding matrix coverage (pure direct-queue, no special inputs):
t2v, t2v_22, flux, vace, vace_22, hunyuan, ltxv, generate_video, qwen_image, qwen_image_2512, wan_2_2_t2i -- these 11 are text-only direct queue tasks, need only a prompt and model name. Very straightforward to add.
Medium effort (direct-queue but need fixture images):
i2v, i2v_22, qwen_image_hires, image_inpaint, annotated_image_edit -- need input image fixtures with URL substitution, same pattern as the existing z_image_turbo_i2i and qwen_image_edit cases.
Medium effort (specialized handlers, partially testable):
extract_frame, magic_edit, rife_interpolate_images, inpaint_frames, join_clips_segment -- need fixture files but the handlers themselves can run through the fake queue with appropriate mocking.
Hard / not fake-queue testable (DB or multi-task orchestrators):
travel_orchestrator, join_clips_orchestrator, edit_video_orchestrator -- create child tasks in DB, poll for their completion
travel_stitch, join_final_stitch, create_visualization -- depend on outputs from prior tasks existing on disk
travel_segment (orchestrated mode) -- needs orchestrator context from DB
comfy -- needs external ComfyUI server
control_net_weight
control_net_weight2
keep_frames_video_guide: Whether to preserve guide frames
For a basic text-to-video vace task (no control inputs), these can be omitted entirely -- VACE models also work as pure t2v generators.
5. Default Parameters from vace_14B_cocktail_2_2.json
This would require creating fixture videos (similar to how z_image_turbo_i2i creates fixture images) using _create_test_video() which already exists in the runner.
Key Files Referenced
/Users/user_c042661f/Documents/Headless-Wan2GP/source/task_handlers/tasks/task_types.py -- model mapping (line 75)
/Users/user_c042661f/Documents/Headless-Wan2GP/source/task_handlers/tasks/task_conversion.py -- db_task_to_generation_task() and param whitelist (lines 38-76)
This is a SPECIALIZED HANDLER, not direct queue. Read how it's dispatched in task_registry.py
The test expects expected_model="wan_2_2_i2v_lightning_baseline_2_2_2" and expected_parameters={"video_length": 50}
Trace: does the handler call task_queue.submit_task with these values?
worker.py process_single_task signature: Read it and confirm the runner's call at line 454 matches (task_params_dict, main_output_dir_base, task_type, project_id_for_task, task_queue, colour_match_videos, mask_active_frames)
Check for any recent changes to task_conversion.py, task_types.py, or task_registry.py that might have changed model mappings or parameter handling since the test cases were written. Look at git status for these files.
Report any mismatches between what the runner expects and what the code actually does.
db_task_params.get("denoising_strength")
db_task_params.get("denoise_strength")
db_task_params.get("strength", 0.7)
generation_params["denoising_strength"] = 0.4
Now let me verify the qwen_image_edit case more carefully. The test expects expected_model="qwen_image_edit_20B" and expected_parameters={"video_length": 1}.
In task_conversion.py, for qwen_image_edit (line 117-118):
python
if task_type == "qwen_image_edit":
qwen_handler.handle_qwen_image_edit(db_task_params, generation_params)
The model is NOT explicitly overridden for qwen_image_edit in the conversion code (unlike qwen_image_style at line 128). But the snapshot's params don't have a "model" key -- let me re-check.
Looking at the qwen_image_edit snapshot (line 237): no "model" key in params. So db_task_params.get("model") returns None, which triggers line 33-34:
python
from source.task_handlers.tasks.task_types import get_default_model
model = get_default_model(task_type)
And TASK_TYPE_TO_MODEL["qwen_image_edit"] = "qwen_image_edit_20B". Good, that matches.
The handle_qwen_image_edit sets video_length=1 via setdefault (line 358). Match.
Now let me verify the qwen_image_style case. The snapshot has "model": "qwen-image" (line 261). So db_task_params.get("model") returns "qwen-image". This means model = "qwen-image" initially. But then the qwen_image_style branch at line 128 does model = "qwen_image_edit_20B", overriding it. Good, matches.
The handle_qwen_image_style sets video_length=1 via setdefault (line 489). Match.
Now for the qwen_image_style snapshot, note "steps": 12 but no "num_inference_steps". Line 106-107 handles this:
python
if "steps" in db_task_params and "num_inference_steps" not in generation_params:
generation_params["num_inference_steps"] = db_task_params["steps"]
And handle_qwen_image_style sets num_inference_steps via setdefault at line 488, which would have already set it to 12. So the steps fallback wouldn't apply since num_inference_steps is already in generation_params. Fine.
Let me now verify the vace case. The snapshot has "model": "vace_14B_cocktail_2_2" and the test expects expected_model="vace_14B_cocktail_2_2" and expected_parameters={"guidance_phases": 2, "guidance_scale": 1}. The snapshot params include "guidance_phases": 2 and "guidance_scale": 1, which are in the whitelist and will be copied. Match.
For ltx2, the builder passes params={"model": "ltx2_22B", ...} and expects expected_model="ltx2_22B". In db_task_to_generation_task, db_task_params.get("model") returns "ltx2_22B", so model stays "ltx2_22B". The default from TASK_TYPE_TO_MODEL["ltx2"] is "ltx2_19B", but since model is explicitly provided, the default isn't used. Match.
For the individual_travel_segment: The snapshot has "model_name": "wan_2_2_i2v_lightning_baseline_2_2_2" and "num_frames": 50. The handler handle_travel_segment_via_queue resolves model_name from segment_params.get("model_name") (line 192) which is "wan_2_2_i2v_lightning_baseline_2_2_2". The total_frames_for_segment resolves from individual_params.get("num_frames") which is 50. Then it's set as "video_length": gen.total_frames_for_segment (line 605) = 50. The GenerationTask is created with model=gen.model_name = "wan_2_2_i2v_lightning_baseline_2_2_2". Match.
Now let me verify the runner's call signature matches process_single_task.
The runner skips image_download_dir (it's an optional kwarg with default None). All other kwargs match. The runner passes main_output_dir as a Path (from PreparedCase.main_output_dir), which matches the type annotation. Match.
Here is the full report:
Verification Results
1. VACE case (task_type="vace", model="vace_14B_cocktail_2_2")
vace in DIRECT_QUEUE_TASK_TYPES: Confirmed (line 45 of task_types.py).
Model resolution: The snapshot provides "model": "vace_14B_cocktail_2_2" explicitly, so db_task_to_generation_task uses it directly (line 31-32). If it were missing, TASK_TYPE_TO_MODEL["vace"] = "vace_14B_cocktail_2_2" (line 75) would be the fallback. Match.
Expected parameters {"guidance_phases": 2, "guidance_scale": 1}: Both are in the snapshot params and in the whitelist. They pass through to generation_params. Match.
2. LTX2 case (task_type="ltx2", model="ltx2_22B")
ltx2 in DIRECT_QUEUE_TASK_TYPES: Confirmed (line 53).
Model resolution: The builder passes "model": "ltx2_22B" in params, so db_task_params.get("model") = "ltx2_22B", overriding the default of "ltx2_19B". Match.
3. Z-Image turbo (task_type="z_image_turbo")
z_image_turbo in DIRECT_QUEUE_TASK_TYPES: Confirmed (line 60).
Model: The z_image_turbo branch (line 147) sets model = "z_image". Match.
Parameters: Line 138-139 sets video_length=1 and guidance_scale=0 via setdefault. The snapshot params do not contain these keys, so the defaults take effect. Match.
z_image_turbo_i2i in DIRECT_QUEUE_TASK_TYPES: Confirmed (line 62).
Model: Line 245 sets model = "z_image_img2img". Match.
video_length=1, guidance_scale=0: Set via setdefault at lines 230-231. Match.
denoising_strength=0.4: The snapshot has "strength": 0.4. Line 235 falls through get("denoising_strength") (None) and get("denoise_strength") (None) to get("strength", 0.7) = 0.4. Match.
qwen_image_style in DIRECT_QUEUE_TASK_TYPES: Confirmed (line 57).
Model: Initially set to "qwen-image" from snapshot, then overridden at line 128 to "qwen_image_edit_20B". Match.
video_length=1: Set by handle_qwen_image_style at qwen_handler.py line 489 via setdefault. Match.
6. Qwen image edit (task_type="qwen_image_edit")
qwen_image_edit in DIRECT_QUEUE_TASK_TYPES: Confirmed (line 57).
Model: Snapshot has no "model" key, so get_default_model("qwen_image_edit") returns "qwen_image_edit_20B" (task_types.py line 95). Note: unlike qwen_image_style, there is no explicit model = "qwen_image_edit_20B" override in the conversion code for this task type -- it relies entirely on the default mapping. Match.
video_length=1: Set by handle_qwen_image_edit at qwen_handler.py line 358 via setdefault. Match.
Dispatch routing: individual_travel_segment is NOT in DIRECT_QUEUE_TASK_TYPES, so it falls through to the specialized handlers dict at task_registry.py line 1138. It calls handle_travel_segment_via_queue with is_standalone=True. Correct.
Model: _resolve_generation_inputs reads segment_params.get("model_name") = "wan_2_2_i2v_lightning_baseline_2_2_2" (from the snapshot). Match.
video_length=50: individual_params.get("num_frames") = 50 (from the snapshot's individual_segment_params). This becomes gen.total_frames_for_segment = 50, then set as "video_length": gen.total_frames_for_segment in _build_generation_params (line 605). The GenerationTask is created at line 1038-1043 and submitted to task_queue.submit_task. Match.
The process_single_task call signature also matches. All model mappings, parameter defaults, and routing logic are consistent between what the test cases expect and what the code actually does.
video
vace
qwen
wan22
ltx
travel
direct_queue
direct_queue
B. Snapshot Integrity
5. Every builder that calls _load_snapshot_params(name) references a snapshot that exists -- PASS
Builders calling _load_snapshot_params:
build_vace_basic -> "vace_basic" -- exists in snapshots
qwen_image_style snapshot: uses __FIXTURE_PATH__:qwen_style_reference (twice, for both style and subject). Builder passes fixture_paths={"qwen_style_reference": ...}. Match.
z_image_turbo snapshot: no fixture tokens. No fixtures passed. Match.
All 6 snapshots in worker_matrix_db_snapshots.json are referenced by exactly one builder. No orphans.
C. Builder Correctness
9. Every builder in CASE_BUILDERS is referenced by at least one manifest case -- PASS
All 7 builder names in CASE_BUILDERS appear as builder values in manifest cases. No dead builders.
10. Builders that create fixture images/videos do so before passing paths to snapshot params -- PASS
build_z_image_turbo_i2i_basic: calls _create_test_image() at line 594, then passes image_path to the patcher lambda at line 611. Correct order.
build_qwen_image_basic: calls _create_test_image() at line 625, then passes reference_image to fixture_paths at line 628. Correct order.
build_qwen_image_edit_basic: calls _create_test_image() at line 643, then passes image_path to fixture_paths at line 646. Correct order.
build_wan22_individual_segment_db_like: creates both images at lines 661-662 before loading snapshot at line 663. Correct order.
11. Patchers target real import paths that exist -- FAIL (minor)
Two patchers are used:
patch("requests.get", ...) in build_z_image_turbo_i2i_basic (line 608) -- patches requests.get globally. This is valid.
patch("source.models.model_handlers.qwen_handler.hf_hub_download", ...) in build_qwen_image_basic and build_qwen_image_edit_basic (lines 630, 648).
The actual import at /Users/user_c042661f/Documents/Headless-Wan2GP/source/models/model_handlers/qwen_handler.py:15 is from huggingface_hub import hf_hub_download. The patch path source.models.model_handlers.qwen_handler.hf_hub_download patches the name as imported in the target module, which is the correct unittest.mock.patch pattern. PASS (correcting myself -- this is actually correct).
D. FakeImmediateTaskQueue Interface
12. Does it implement all methods that worker code actually calls on task_queue? -- PASS (for current cases), WARNING (for potential future cases)
Methods called on task_queue across the codebase:
submit_task(generation_task) -- implemented in FakeImmediateTaskQueue
get_task_status(task_id) -- implemented in FakeImmediateTaskQueue
The current matrix cases route through task_registry.py lines 1038-1089 which only use submit_task and get_task_status. Those same methods are also used in inpaint_frames.py and join/generation.py.
However, callers in inpaint_frames.py:265 and join/generation.py:890 also access status.processing_time, which is NOT set on the SimpleNamespace returned by FakeImmediateTaskQueue.get_task_status(). If an inpaint_frames or join_clips_segment case is added in the future, it will crash with AttributeError. For the current 7 cases, this is not triggered.
13. Does get_task_status return shape match what callers expect? -- PASS (for current cases)
Callers expect status.status, status.result_path, and status.error_message. FakeImmediateTaskQueue returns a SimpleNamespace with exactly these three attributes. Match.
The missing attribute is processing_time as noted above, but no current case exercises code paths that access it.
E. Script Infrastructure
14. Does VIDEO_OUTPUT_TASK_TYPES correctly determine image vs video output? -- FAIL (naming is inverted; vace correctness is fine)
The set is misleadingly namedVIDEO_OUTPUT_TASK_TYPES but it contains task types that produce image output. The logic at line 727:
python
if task_type in VIDEO_OUTPUT_TASK_TYPES:
return _create_test_image(...) # .png
return _create_test_video(...) # .mp4
So task types in the set get images, and everything else gets video. The name should be IMAGE_OUTPUT_TASK_TYPES. Functionally:
vace is NOT in the set, so it produces .mp4 -- correct, VACE produces video.
z_image_turbo and z_image_turbo_i2i are NOT in the set either, so they produce .mp4 -- BUG. These are image-generation task types (they produce single images). They should be in the set.
ltx2 is NOT in the set, so it produces .mp4 -- correct, LTX2 produces video.
individual_travel_segment is NOT in the set, so it produces .mp4 -- correct, travel segments produce video.
qwen_image_style and qwen_image_edit ARE in the set (qwen_image_style and qwen_image_edit appear as entries) -- correct, these produce images.
Actually z_image_turbo and z_image_turbo_i2i ARE in the set. I misread. Let me recount: the set includes z_image_turbo and z_image_turbo_i2i. So both z_image types get .png output -- correct.
Revised verdict: The set membership is functionally correct for all current cases. The naming is confusing (should be IMAGE_OUTPUT_TASK_TYPES) but the logic works correctly. PASS (with naming caveat).
15. Are REQUIREMENT_CHECKERS complete? -- PASS
Only two requirement checkers exist: ffmpeg and moviepy (line 805-808). No current manifest cases declare any requires (all have "requires": []). If a future case needs extract_frame (which needs ffmpeg), it should declare requires: ["ffmpeg"]. For the current 7 cases, this is complete.
16. Does _utc_timestamp format produce filesystem-safe names? -- PASS
Format: %Y%m%dT%H%M%S%fZ produces strings like 20260316T143521123456Z. No colons, slashes, spaces, or special characters. Safe on Linux, macOS, and Windows.
F. Doc Accuracy
17. Doc locked cases list matches manifest exactly -- PASS
All match. The doc correctly notes captured_generation_task.json is only for "fake-queue direct cases" and traceback.txt is only "when a case crashes".
20. Doc "What It Covers" section is accurate -- PASS
The doc claims:
"Real worker.py -> process_single_task() execution" -- confirmed, line 454
"fake immediate queue captures the submitted generation task" -- confirmed via FakeImmediateTaskQueue
"For local-only cases (e.g. extract_frame, create_visualization), the handler runs end-to-end" -- this is slightly aspirational since no such cases exist in the manifest yet, but the infrastructure supports it. Minor inaccuracy but the doc uses "e.g." framing. Borderline PASS.
"Per-case logs, inputs, outputs, and summaries" -- confirmed.
G. Edge Cases
21. What happens if worker.py returns an unexpected type? -- PASS
_normalize_worker_result (line 503-518) handles:
Objects with .outcome attribute (TaskResult) -- handled
2-tuple (bool, str) -- handled
Anything else -- raises TypeError with a clear message including the type name
The TypeError is caught by the outer except Exception at line 470, which writes it to traceback.txt and marks the case as actual_outcome="failure". Clean behavior.
22. What happens if a builder's snapshot is missing? -- PASS (clear error)
_load_snapshot_params at line 745 does load_db_snapshots()[snapshot_name]. If the key is missing, Python raises KeyError. This propagates up through run_case -> CASE_BUILDERS[case.builder](case, case_dir) (line 422). There is no try/except around this call before the main try block at line 445. Wait -- actually the builder call is at line 422, which is OUTSIDE the try/except that starts at line 445. Let me re-read.
Looking again at run_case():
Line 422: prepared = CASE_BUILDERS[case.builder](case, case_dir) -- this is OUTSIDE the try/except block (which starts at line 445)
If this raises KeyError, it propagates to the caller main() at line 360: result = run_case(case, run_dir), which also has no try/except around it.
FAIL -- If a builder's snapshot name is wrong, the KeyError will crash the entire runner, not just fail that case. The builder call and prepared_input write should be inside the try/except, or there should be a separate guard. The run_case function catches exceptions only around the worker_mod.process_single_task call, not around builder preparation.
23. The rerun_failed.sh -- does it generate valid bash? -- PASS
Lines 379-393:
Starts with #!/usr/bin/env bash and set -euo pipefail
Uses shlex.quote() for the REPO_ROOT path and all case_ids
Uses proper backslash line continuation
The last --case-id argument omits the trailing backslash
If no failures, emits --list-cases (a no-op that won't accidentally run cases)
File is chmod 755
The generated bash is syntactically valid. One edge case: if there are zero failed cases, the script runs --list-cases which prints and exits 0. This is reasonable.
Summary Table
#
Check
Result
A1
Builders exist in CASE_BUILDERS
PASS
A2
Required fields present
PASS
A3
No duplicate case_ids
PASS
A4
Tags consistent
PASS
B5
Snapshot names resolve
PASS
B6
Snapshot required fields
PASS
B7
Fixture tokens have matching fixtures
PASS
B8
No orphan snapshots
PASS
C9
No dead builders
PASS
C10
Fixture creation order correct
PASS
C11
Patcher import paths valid
PASS
D12
FakeImmediateTaskQueue interface complete
PASS (current cases); WARNING for future inpaint_frames/join_clips cases -- processing_time attribute missing from status SimpleNamespace
D13
get_task_status return shape
PASS
E14
VIDEO_OUTPUT_TASK_TYPES correctness
PASS (logic correct; name is misleading -- should be IMAGE_OUTPUT_TASK_TYPES)
E15
REQUIREMENT_CHECKERS complete
PASS
E16
_utc_timestamp filesystem-safe
PASS
F17
Doc locked cases match manifest
PASS
F18
Doc CLI examples valid
PASS
F19
Doc artifact list accurate
PASS
F20
Doc "What It Covers" accurate
PASS (minor: mentions extract_frame/create_visualization cases that don't exist yet)
G21
Unexpected return type handling
PASS
G22
Missing snapshot crash behavior
FAIL -- KeyError from missing snapshot crashes entire runner instead of failing single case. Builder call at line 422 is outside the try/except block.
G23
rerun_failed.sh validity
PASS
Issues Found
FAIL: G22 -- Builder exceptions crash the entire runner
In run_case(), the builder invocation at line 422 (prepared = CASE_BUILDERS[case.builder](case, case_dir)) is outside the try/except block that starts at line 445. Any exception during case preparation (missing snapshot key, fixture creation failure, etc.) will propagate unhandled to main() and crash the entire runner, aborting all remaining cases.
File: /Users/user_c042661f/Documents/Headless-Wan2GP/scripts/run_worker_matrix.py, line 422
The SimpleNamespace status objects returned by FakeImmediateTaskQueue.get_task_status() (lines 184-201) include status, result_path, and error_message but NOT processing_time. Code in source/task_handlers/inpaint_frames.py:265 and source/task_handlers/join/generation.py:890 accesses status.processing_time. If inpaint_frames or join_clips_segment cases are added to the matrix, they will hit AttributeError.
NAMING: E14 -- VIDEO_OUTPUT_TASK_TYPES is misnamed
The set at line 32 is named VIDEO_OUTPUT_TASK_TYPES but contains task types that produce image output (the conditional creates a .png for members and a .mp4 for non-members). Should be IMAGE_OUTPUT_TASK_TYPES for clarity.
File: /Users/user_c042661f/Documents/Headless-Wan2GP/scripts/run_worker_matrix.py, line 32
Model string to use:"ltx2_22B_distilled" (or "ltx2_distilled" for 19B variant)
Default params from ltx2_22B_distilled.json:
num_inference_steps: 8
video_length: 241
resolution: "1280x720"
No guidance_scale set (the distilled model doesn't use it)
No perturbation_*, alt_*, or apg_switch — those are dev-only
What db_task_to_generation_task will produce for a distilled task:
task.parameters does NOT contain perturbation_switch, alt_guidance_scale, alt_scale, apg_switch, or ltx2_pipeline
Key assertion to make in the test: If you pass perturbation_switch, alt_guidance_scale, or alt_scale in the input, they should be absent from task.parameters — confirming the whitelist drops them silently. This is also a bug worth flagging: callers of the dev model who expect those params to reach WGP will be disappointed.
task_type to pass to db_task_to_generation_task:"ltx2" — this is the only task type; there is no "ltx2_distilled" entry anywhere in WGP_TASK_TYPES or TASK_TYPE_TO_MODEL.
The transformer (model-def) LoRAs are prepended to the LoRA stack, and then user activated_loras (if any) are merged on top (lines 6025-6031). The transformer LoRAs are also stored in metadata (lines 7020-7024).
Crucially, get_model_recursive_prop reads from models_def which is populated by loading the model's JSON file (the defaults/ltx2_22B.json). This is per-model-type, not per-task.
5. Does ltx2_pipeline: "distilled" change how the distill LoRA is applied?
Yes, but indirectly. The distilled model JSON has no loras field, so get_transformer_loras returns an empty list for ltx2_22B_distilled. There is nothing to apply. The ltx2_pipeline: "distilled" flag also changes the load_model return value (line 382-383): for the distilled pipeline it does not include the "loras": ["text_embedding_projection", "text_embeddings_connector"] exclusion directive — meaning the distilled model loads slightly differently at the pipe level, but that's internal to model loading.
Also from ltx2_handler.py lines 204-210: the distilled pipeline sets lock_inference_steps: True, no_negative_prompt: True, and locks guidance_phases to 1 (line 450), removing the two-phase structure entirely.
6. The bottom line: does the caller need to pass LoRA params?
No. For model: "ltx2_22B" (dev model), the distill LoRA is applied automatically by WGP from the model definition. The flow is:
WGP loads defaults/ltx2_22B.json into models_def["ltx2_22B"]
At generation time, get_transformer_loras("ltx2_22B") reads loras from that def → finds ltx-2.3-22b-distilled-lora-384.safetensors
It reads loras_multipliers → finds ["0;1"]
These become the "transformer LoRAs" (always-on baseline stack) — applied before any user LoRAs
With guidance_phases=2 (locked), the "0;1" is parsed as phase1=0.0, phase2=1.0
For model: "ltx2_22B_distilled", there are no model-def LoRAs — the distilled weights have it baked in.
What this means for test cases
Test cases do NOT need to include any LoRA-related params for the distill LoRA. WGP handles it entirely from the model definition for ltx2_22B. The only time you'd need to pass LoRA params is if a test is explicitly testing user-specified LoRAs (via activated_loras + loras_multipliers) on top of the model baseline. The param_resolution.py does set "activated_loras": [] and "loras_multipliers": "" as system defaults, which is correct — they'll be empty unless the task or model defaults supply them, and the model-def LoRAs go through a completely separate get_transformer_loras() code path in WGP that bypasses the activated_loras parameter entirely.
"wan_2_2_i2v_lightning_baseline_2_2_2"
"model_name"
model_name
orchestrator_details
Expected parameters:{"video_length": 50} -- the snapshot has "num_frames": 50 at line 62 (individual_segment_params) and line 123 (top-level). The travel segment handler maps num_frames to video_length in the generation task parameters.
Verdict: PASS -- the handler location has not changed; DB snapshot values are consistent with the expected model and parameters.
Case 3: ltx2_22b_basic -- PASS
Routing:task_type="ltx2" is in DIRECT_QUEUE_TASK_TYPES (line 53 of task_types.py). Routes through _handle_direct_queue_task -> db_task_to_generation_task.
Model resolution: The builder at run_worker_matrix.py line 593 passes "model": "ltx2_22B" in params. In db_task_to_generation_task (task_conversion.py line 31-32), model = db_task_params.get("model") picks up "ltx2_22B" directly, overriding the default. The default TASK_TYPE_TO_MODEL["ltx2"] = "ltx2_19B" (line 90) is not used.
Default file exists:Wan2GP/defaults/ltx2_22B.json is present on disk.
Expected parameters:{"guidance_scale": 3.0, "audio_guidance_scale": 7.0} -- both are in the param_whitelist in task_conversion.py (lines 40 and 48). Both are explicitly set in the builder params (lines 598-599) and will pass through to generation_params.
Verdict: PASS -- no changes affect this case.
Case 4: ltx2_22b_distilled_basic -- PASS
Routing: Same as Case 3 -- "ltx2" is in DIRECT_QUEUE_TASK_TYPES.
Model resolution: The builder at run_worker_matrix.py line 611 passes "model": "ltx2_22B_distilled" in params. This overrides the default "ltx2_19B".
Default file exists:Wan2GP/defaults/ltx2_22B_distilled.json is present on disk.
Expected parameters:{"num_inference_steps": 8} -- num_inference_steps is in the param_whitelist (task_conversion.py line 39). The builder passes "num_inference_steps": 8 directly in params (line 617), which flows through to generation_params.
All four cases remain valid. The upstream update deleted some default files (vace_14B_fake_cocktail_2_2.json, several vace_fun_14B_cocktail_lightning* files), but none of these are referenced by any of the four test cases or by TASK_TYPE_TO_MODEL. The key files (vace_14B_cocktail_2_2.json, ltx2_22B.json, ltx2_22B_distilled.json) all still exist on disk. The routing logic in task_types.py, task_conversion.py, and task_registry.py is unchanged for all four task types.
resolution -- in whitelist (line 39), and also explicitly set at lines 143-144 for z_image_turbo
seed -- in whitelist (line 40)
steps -- not in whitelist, but handled by fallback at line 106-107: maps steps to num_inference_steps
add_in_position -- NOT in whitelist (this is fine, it's a UI-only param)
FINDING: lightning_lora_strength_phase_1 and lightning_lora_strength_phase_2 are NOT in the param_whitelist. They will be silently dropped. However, these are NOT in the expected_parameters dict of the builder (line 631: expected_parameters={"video_length": 1, "guidance_scale": 0}), so the test case itself will still PASS. Whether the actual generation behavior is correct is a separate question -- those lightning lora strength params are being silently lost.
Verdict: PASS (test will pass; silent param loss is a functional concern but not a test correctness issue)
Case 6: z_image_turbo_i2i_db_task (task_type="z_image_turbo_i2i")
Does task_conversion.py set model="z_image_img2img"?
PASS -- Line 230: generation_params.setdefault("video_length", 1), Line 231: generation_params.setdefault("guidance_scale", 0)
For denoising_strength: Line 235: actual_strength = db_task_params.get("denoising_strength") or db_task_params.get("denoise_strength") or db_task_params.get("strength", 0.7)
The snapshot has "strength": 0.4 (not "denoising_strength")
The first two .get() calls return None, so it falls through to db_task_params.get("strength", 0.7) which returns 0.4
Line 236: generation_params["denoising_strength"] = actual_strength sets it to 0.4
PASS
Builder patches requests.get -- does the source code still use requests.get?
PASS -- Line 165 of task_conversion.py: response = requests.get(image_url, timeout=30) with import requests at line 162.
The builder patches at the global requests.get level (line 652 of run_worker_matrix.py: patch("requests.get", ...)), which matches the import requests + requests.get(...) pattern in task_conversion.py.
Verdict: PASS
Case 7: qwen_image_style_db_task (task_type="qwen_image_style")
Does task_conversion.py override model to "qwen_image_edit_20B"?
The QwenHandler's handle_qwen_image_style is called (line 126). Let me verify it sets video_length=1.
Actually, the expected_parameters only checks {"video_length": 1}. The question is: does the qwen handler set video_length=1? Let me check.
Case 7: qwen_image_style_db_task
PASS
model overridden to "qwen_image_edit_20B" at line 128, video_length=1 set at line 489, hf_hub_download patch path valid.
Case 8: qwen_image_edit_db_task
PASS
Model resolved via TASK_TYPE_TO_MODEL -> "qwen_image_edit_20B", video_length=1 set at line 358, hf_hub_download patch path valid, local fixture path handled correctly by download_image_if_url.
process_single_task signature
PASS
Unchanged
enable_debug_mode
PASS
Still at source/core/log/core.py:72
TaskOutcome enum
PASS
All 4 members present
Latent issue found (not blocking tests):
parse_phase_config is used at line 262 of task_conversion.py but never imported. This would crash if any task had a phase_config in db_task_params, but none of cases 5-8 hit that path. Cases 1-2 (vace_basic, wan22 individual segment) do have phase_config in their snapshots and WOULD hit this -- that's a separate concern.
WanOrchestrator
Start queue (queue_lifecycle.py:start_queue) -- spawns GenerationWorker-N daemon threads running worker_loop(), plus a QueueMonitor thread. Optionally calls orchestrator.load_model(preload_model).
Start heartbeat guardian -- separate process that sends heartbeats to Supabase.
while True:
task_info = db_ops.get_oldest_queued_task_supabase(worker_id=cli_args.worker)
if not task_info:
time.sleep(cli_args.poll_interval) # default 10s
continue
get_oldest_queued_task_supabase() does:
Recovery check -- queries tasks table for rows where worker_id = this_worker AND status = 'In Progress'. If found (non-orchestrator), returns it immediately (handles lost HTTP responses).
Task counts check -- calls Edge Function task-counts to see if any queued tasks exist, avoiding unnecessary claim attempts.
Atomic claim -- calls Edge Function claim-next-task at {SUPABASE_URL}/functions/v1/claim-next-task with POST {"worker_id": ..., "run_type": "gpu"}. The Edge Function atomically sets status='In Progress', worker_id=this_worker, and returns the task data.
Frontend/API -- external callers insert rows via Edge Functions
Orchestrators -- travel_orchestrator, join_clips_orchestrator, and edit_video_orchestrator create child tasks (segments, stitches) via add_task_to_db()
Key DB columns (from the code's usage):
id (UUID primary key)
status ("Queued", "In Progress", "Complete", "Failed")
task_type (string)
params (JSONB)
project_id (UUID)
worker_id (string, set on claim)
output_location (string -- file URL or storage path)
created_at, generation_started_at (timestamps)
attempts (int, for retry counting)
dependant_on (array of UUIDs)
error_details (string)
thumbnail_url (string)
5. Task Dispatch: process_single_task to TaskRegistry.dispatch
File: /Users/user_c042661f/Documents/Headless-Wan2GP/worker.py line 132, then /Users/user_c042661f/Documents/Headless-Wan2GP/source/task_handlers/tasks/task_registry.py line 1104.
process_single_task() builds a context dict and calls TaskRegistry.dispatch(task_type, context).
dispatch() routes via two paths:
Path A: Direct Queue Tasks (line 1119)
If task_type in DIRECT_QUEUE_TASK_TYPES (defined in /Users/user_c042661f/Documents/Headless-Wan2GP/source/task_handlers/tasks/task_types.py), calls _handle_direct_queue_task(). This covers: vace, t2v, flux, i2v, hunyuan, ltxv, ltx2, qwen_image_*, z_image_turbo, etc.
Path B: Specialized Handlers (line 1123)
Orchestrators and specialized types get routed to dedicated handler functions:
extract_frame, rife_interpolate_images, comfy, etc.
6. Direct Queue Path: DB Task to WGP Generation
File: /Users/user_c042661f/Documents/Headless-Wan2GP/source/task_handlers/tasks/task_registry.py line 1211.
_handle_direct_queue_task():
Convert DB params to GenerationTask -- db_task_to_generation_task() (file: /Users/user_c042661f/Documents/Headless-Wan2GP/source/task_handlers/tasks/task_conversion.py):
Extracts prompt, model (or gets default from TASK_TYPE_TO_MODEL)
Whitelists ~80 parameter names from DB params into generation_params
Handles special task types (qwen_image_edit, z_image_turbo_i2i downloads image, etc.)
Lazy-initializes the WanOrchestrator if not already done (_ensure_orchestrator() in /Users/user_c042661f/Documents/Headless-Wan2GP/source/task_handlers/queue/wgp_init.py)
Converts task params to WGP format via _convert_to_wgp_task() (uses TaskConfig typed parsing)
Acquires _wgp_patch_lock (thread safety for WGP global monkey-patching)
Applies any phase_config or svi2pro patches to WGP globals
Routes to the appropriate generation method:
VACE model -> orchestrator.generate_vace(prompt, video_guide=..., ...)
Flux model -> orchestrator.generate_flux(prompt, ...)
All three are thin wrappers around orchestrator.generate() (file: /Users/user_c042661f/Documents/Headless-Wan2GP/source/models/wgp/orchestrator.py line 497)
Sets a 20-minute SIGALRM timeout
Restores any WGP patches in finally block
orchestrator.generate() (line 497):
Resolves final parameters with model defaults (_resolve_parameters)
Sets up LoRAs
Builds WGP-compatible parameter dict
Calls wgp.generate_video(...) (the vendored WGP engine)
Captures stdout to extract the output file path
Returns the path to the generated file
Post-generation:
Single-frame videos are converted to PNG if video_length == 1
Output path existence is verified (with 2s retry for network volumes)
Task status updated in task_history
Memory cleanup (PyTorch cache clear, GC)
8. Completion: Result Written Back to DB
Back in worker.py (line 421):
On success:
For non-orchestrator tasks: calls db_ops.update_task_status_supabase(task_id, "Complete", output_location) (file: /Users/user_c042661f/Documents/Headless-Wan2GP/source/core/db/task_status.py line 234)
This function handles file upload:
Files < 2MB: base64-encodes the file and sends to complete_task Edge Function
Files >= 2MB: Gets a presigned upload URL from generate-upload-url Edge Function, uploads via PUT, then calls complete_task with the storage_path
For videos: extracts a thumbnail frame and uploads it alongside
After upload, calls cleanup_generated_files() to delete the local file
For orchestrator tasks: uses TaskResult.outcome to distinguish between ORCHESTRATING (still running) and ORCHESTRATOR_COMPLETE (all done)
On failure:
Checks if the error is retryable via is_retryable_error() (OOM, edge function failures)
If retryable and attempts < max: calls requeue_task_for_retry() which resets status to "Queued" and increments attempts
The WanOrchestrator is created lazily on first task (WgpInitMixin._ensure_orchestrator() in /Users/user_c042661f/Documents/Headless-Wan2GP/source/task_handlers/queue/wgp_init.py):
CUDA warmup (creates test tensor)
os.chdir(wan_dir) via temporary_process_globals context manager
from headless_wgp import WanOrchestrator (which resolves through the compat shim to source.runtime.entrypoints.headless_wgp)
Checks wgp.get_model_def(model_key) to verify model exists
Calls wgp.apply_changes(model_key, ...) which is the vendored WGP's model loading code
Model definitions come from JSON files in Wan2GP/defaults/*.json
10. Minimum Viable Task Row for Manual Insertion
To have a running worker pick up a task, you need to create a row in the tasks table with at minimum:
json
{
"id": "uuid",
"status": "Queued",
"task_type": "t2v",
"project_id": "any-uuid",
"params": {
"prompt": "a cat walking on the moon",
"model": "t2v"
}
}
The recommended way is via the create-task Edge Function (which add_task_to_db calls), but you could also insert directly into the tasks table in Supabase. The worker's claim-next-task Edge Function will find the oldest "Queued" row and atomically claim it.
get_task_status(task_id) -- Returns the GenerationTask dataclass from self.task_history.
Key differences:
FakeImmediateTaskQueue is synchronous -- submit_task immediately returns with the result baked in. No threads, no models, no GPU.
HeadlessTaskQueue is asynchronous -- submit_task enqueues the work and returns immediately. A background thread does the actual generation. You must poll get_task_status or use wait_for_completion.
The status objects also differ: Fake returns SimpleNamespace(status=..., result_path=..., error_message=..., processing_time=...), while Real returns a GenerationTask dataclass with the same fields as attributes (.status, .result_path, .error_message, .processing_time). They happen to have compatible attribute names.
3. How the matrix runner imports worker
At /Users/user_c042661f/Documents/Headless-Wan2GP/scripts/run_worker_matrix.py:
ensure_repo_on_path() (line 855-858) adds REPO_ROOT (one directory above scripts/) to sys.path[0]. That is all -- no os.chdir(), no special env vars.
The import itself uses __import__("worker") (line 473), which finds worker.py at the repo root thanks to the path manipulation. Worker.py in turn does its own path setup at module level (lines 39-42):
4. Can HeadlessTaskQueue work without starting worker threads?
Not directly. Looking at the architecture:
HeadlessTaskQueue.__init__() does a lot of setup: path manipulation, sys.argv protection, tkinter stubs, PriorityQueue creation, logging setup, and _init_wgp_integration() (which is a no-op when orchestrator is None).
start() spawns worker threads and optionally pre-loads a model. This is the async machinery.
submit_task() puts work on the internal PriorityQueue. Without started worker threads, tasks just sit there forever.
However, there is wait_for_completion(task_id, timeout) (lines 212-252) which polls get_task_status in a sleep loop. So the pattern for "synchronous single task" with the real queue would be:
There is no run_one_task_synchronously() method. The closest is the wait_for_completion polling approach described above.
6. What headless_model_management.py exports
/Users/user_c042661f/Documents/Headless-Wan2GP/headless_model_management.py is a thin compatibility shim. It:
Warns about deprecation
Delegates main() to source.runtime.entrypoints.headless_model_management
Delegates attribute access (like HeadlessTaskQueue) to source.task_handlers.queue.task_queue via __getattr__
So from headless_model_management import HeadlessTaskQueue ultimately resolves to the class defined in /Users/user_c042661f/Documents/Headless-Wan2GP/source/task_handlers/queue/task_queue.py.
Minimal Changes to Use a Real Queue Instead of FakeImmediateTaskQueue
The matrix runner currently bypasses the queue entirely. process_single_task in worker.py is the function that routes to TaskRegistry.dispatch(). The task_queue argument is only used by the task handlers that need to submit sub-tasks (generation tasks) to WGP -- it is not what drives the top-level dispatch. So there are two distinct layers:
Layer 1: worker.process_single_task (the matrix runner's current entry point)
This function takes a task_queue that task handlers use to submit generation sub-tasks to WGP. The FakeImmediateTaskQueue intercepts these sub-tasks and creates synthetic outputs. To make this real, you need a real HeadlessTaskQueue that can actually run generation.
Layer 2: The HeadlessTaskQueue's internal worker loop
This is the thread-based system that processes GenerationTask objects through the orchestrator.
Here are the minimal changes:
Option A: Replace FakeImmediateTaskQueue with a real HeadlessTaskQueue (keep process_single_task as entry point)
Initialize a single shared HeadlessTaskQueue at the start of the matrix run:
In _build_direct_queue_case, pass this real queue instead of FakeImmediateTaskQueue:
Replace the construction of FakeImmediateTaskQueue with the shared real queue instance.
The status return shapes are compatible. Both FakeImmediateTaskQueue.get_task_status() and HeadlessTaskQueue.get_task_status() return objects with .status, .result_path, .error_message attributes. The real one returns a GenerationTask dataclass; the fake returns a SimpleNamespace. The attribute names match.
Handle the async nature. The real queue's submit_task is async. The task handlers that call task_queue.submit_task() then poll task_queue.get_task_status() in a loop. The fake queue returns immediately. With the real queue, the generation runs in the background thread and the polling loop in the task handler naturally waits for it.
Shutdown: Call task_queue.stop() after all cases complete.
Key complications to handle:
CUDA/wgp initialization:HeadlessTaskQueue.__init__ does sys.argv protection and tkinter stubs. The matrix runner would need the same os.chdir to Wan2GP that worker.py does (lines 326-356).
wgp module-level globals: Worker.py sets wgp config (attention_mode, compile, profile, etc.) after importing it. The matrix runner would need equivalent setup.
Model preloading: You probably want task_queue.start(preload_model=...) to avoid loading models per-case.
Model switching between cases: If cases use different models, the queue handles this via _switch_model() inside the worker thread.
One queue for all cases, not one per case: The current pattern creates a new FakeImmediateTaskQueue per case. With a real queue, you want a single shared instance (models stay loaded).
Option B: Call the queue's internal methods directly (synchronous, single-threaded)
Instead of using the thread-based start/submit/wait pattern, you could bypass it and call the internals directly:
Create HeadlessTaskQueue without calling .start().
Manually call queue._ensure_orchestrator() once.
For each case, instead of submit_task + poll, directly call:
This avoids threads entirely but requires that the task handlers inside process_single_task (which call task_queue.submit_task() to create sub-generation-tasks) also work synchronously. That means process_task_impl needs to run in the same thread -- which it would, since you are calling it directly.
However, this only works for the inner generation queue. The outer worker.process_single_task call in the matrix runner would still need prepared.task_queue to be something that processes the GenerationTask it submits. For Option B, you would need a hybrid: the task_queue passed to process_single_task needs to synchronously call process_task_impl when submit_task is called -- essentially what FakeImmediateTaskQueue does, but calling the real generation code instead of creating synthetic outputs.
Recommendation
Option A is cleaner. The minimal diff is:
Add a module-level setup function that initializes wgp (mirroring worker.py lines 326-356).
Create one HeadlessTaskQueue at matrix start, call .start().
Replace FakeImmediateTaskQueue construction in _build_direct_queue_case with the shared real queue.
Call .stop() at end.
Remove expected_model/expected_parameters validation (that was test-specific).
The files that need changes:
/Users/user_c042661f/Documents/Headless-Wan2GP/scripts/run_worker_matrix.py -- the only file that needs modification.
_handle_direct_queue_task
4. source/task_handlers/tasks/task_conversion.py
Zero DB calls. Line 145 only strips Supabase credential keys from params. The function db_task_to_generation_task is a pure data transformation from a dict to a GenerationTask object. No DB lookups.
5. source/models/wgp/orchestrator.py
Zero DB calls in the orchestrator itself. The WanOrchestrator class is purely a wgp adapter. However, its delegate source/models/wgp/model_ops.py makes one HTTP call during model loading:
File
Line
Call
Purpose
Essential?
source/models/wgp/model_ops.py
118
notify_worker_model_switch(old_model, new_model)
Calls Supabase edge function update-worker-model via HTTP to update the worker's status display.
Bookkeeping -- purely cosmetic status update. Fails silently if no WORKER_ID or no SUPABASE_SERVICE_ROLE_KEY. Generation is unaffected.
Defined in /Users/user_c042661f/Documents/Headless-Wan2GP/source/models/wgp/generation_helpers.py lines 21-69.
6. worker.pyprocess_single_task and main loop
BEFORE generation (in the main polling loop, lines 378-410):
Line
Call
Purpose
Essential?
379
db_ops.get_oldest_queued_task_supabase(worker_id)
Task claim -- polls for queued tasks and atomically claims one.
Essential -- this is how the worker gets tasks. Must be mocked to inject test tasks.
db_ops.get_oldest_queued_task_supabase() -- worker.py:379 -- Provides task data. Must mock to inject tasks.
db_ops.get_task_params() -- task_registry.py:158 -- Only for orchestrated travel segments that lack inline orchestrator_details. Must mock if testing travel segments.
db_ops.get_predecessor_output_via_edge_function() -- task_registry.py:329 -- Only for SVI continuation segments (segment_idx > 0). Must mock if testing SVI chaining.
Calls that are pure BOOKKEEPING (can return no-ops for test harness):
db_ops.get_completed_segment_outputs_for_stitch() -- travel/stitch.py:149 -- Fetches completed segment paths for stitching.
db_ops.get_task_output_location_from_db() -- join/final_stitch.py:68,121 and join/orchestrator.py:106 and extract_frame.py:26 -- Fetches output paths of dependency tasks.
db_ops.poll_task_status() -- travel/stitch.py:752 -- Waits for upscale task completion.
The cleanest approach: mock the entire source.db_operations module (which is a facade re-exporting from source.core.db.*), since all DB access flows through it.
RuntimeContext
get_runtime_context()
.prepare()
Uses temporary_process_globals(cwd=wan_dir, argv=["headless_model_management.py"], prepend_sys_path=wan_dir) as context manager
Inside that context: from headless_wgp import WanOrchestrator, then self.orchestrator = WanOrchestrator(self.wan_dir, main_output_dir=self.main_output_dir)
Calls _init_wgp_integration() which sets self.wgp_state = self.orchestrator.state
Sets task logging context via set_current_task_context(task.id)
Sets task.status = "processing"
Phase 1: Model switch -- calls queue._switch_model(task.model, worker_name) which delegates to switch_model_impl() -> queue.orchestrator.load_model(model_key)
Phase 2: Billing reset -- DB CALL: from source.db_operations import reset_generation_started_at; reset_generation_started_at(task.id). This is wrapped in try/except and logged as warning on failure. Non-fatal.
Optionally pre-loads a model via queue._ensure_orchestrator() + queue.orchestrator.load_model(preload_model)
Can you skip it and call process_task_impl directly? Yes. process_task_impl is a standalone function that takes (queue, task, worker_name). You don't need the worker threads. You can call it directly on the main thread. The worker loop just pulls tasks from the PriorityQueue and calls process_task_impl.
Even simpler: You could skip process_task_impl entirely and call execute_generation_impl(queue, task, worker_name) directly if you handle model switching yourself.
Converts DB params to a GenerationTask via db_task_to_generation_task()
Calls task_queue.submit_task(generation_task)
Pollstask_queue.get_task_status(task_id) every 2 seconds until completed/failed (up to 1 hour)
After generation: handles travel chaining, moves output to task-type subdirectory
Returns (success: bool, output_path: str) or TaskResult
Could you call it directly? Yes, but it is heavier than needed. It adds: travel chaining, file moving, TaskRegistry dispatch overhead. For a test harness, you're better off going one level deeper.
7. DB Calls in the Queue/Generation Path
Here is the complete inventory of DB/Supabase touchpoints in the queue+generation pipeline:
Location
Call
Fatal?
Notes
task_processor.py:77-78
reset_generation_started_at(task.id)
No
Wrapped in try/except, logs warning on failure
generation_helpers.py:21-68
notify_worker_model_switch()
No
Only fires if WORKER_ID env is set; HTTP call to Supabase edge function; silently fails
download_ops.py:145
Filters out supabase_url, supabase_anon_key, supabase_access_token from params
No
Just removes keys, no actual call
task_registry.py:51
import db_operations as db_ops
No
Import only; DB calls happen in travel/orchestrator handlers, not in direct WGP generation
worker.py:379
db_ops.get_oldest_queued_task_supabase()
N/A
Main polling loop -- bypassed entirely
worker.py:428-478
Various db_ops.update_task_status_*
N/A
Post-generation -- bypassed entirely
source/models/wgp/generators/
None
--
Zero DB calls in the actual generation code
source/models/wgp/model_ops.py
None
--
Zero DB calls in model loading
source/models/wgp/orchestrator.py
None
--
Zero DB calls
Summary: What You Need, What You Can Skip
Minimum initialization for a real-generation test harness:
process_task_impl(task_queue, task, "TestWorker")
# Then check: task.status, task.result_path, task.error_message
Or go even lower -- call execute_generation_impl(task_queue, task, "TestWorker") directly after ensuring the model is loaded via task_queue.orchestrator.load_model("model_key").
DB calls that need spoofing (2 total, both non-fatal):
reset_generation_started_at in task_processor.py:77 -- just let the try/except swallow it. It already handles failure gracefully.
notify_worker_model_switch in generation_helpers.py -- don't set WORKER_ID env var and it silently skips.
No Supabase connection is needed. The HeadlessTaskQueue works purely locally. All DB interaction happens in worker.py's main loop (before/after calling process_single_task) and in the TaskRegistry's orchestrator/travel handlers. The core generation path through process_task_impl -> execute_generation_impl -> orchestrator.generate_* is DB-free except for the two non-fatal calls above.
get_task_status()
FakeImmediateTaskQueue validation (expected_model, expected_parameters) is not applicable in real mode — the real queue doesn't validate, it generates
What needs to happen in worker.py-style setup before the queue works:
Real queue returns GenerationTask dataclass with same attribute names
The task handlers access .status, .result_path, .error_message — compatible
Cases that work in real mode:
All 6 direct-queue cases (vace, ltx2 dev, ltx2 distilled, z_image_turbo, z_image_turbo_i2i, qwen_image_style, qwen_image_edit) can run through the real queue
The individual_travel_segment case uses a custom FakeImmediateTaskQueue with different expected_model/params — it ALSO submits to the queue internally, so it could work too
CLI design:
--real flag enables real generation mode
--preload-model MODEL optionally pre-loads a model during queue startup
Without --real, behavior is exactly as today (fake queue, synthetic outputs)
Output handling:
Real generation writes to case_dir/outputs/ (same as fake mode)
The orchestrator writes to main_output_dir which we set to case_dir/outputs/
After generation, the output file path is in task.result_path
What about the cases that currently use patchers (requests.get mock, hf_hub_download mock)?
In real mode, these patchers should be skipped — the real pipeline handles downloads
But: the fixture URLs in snapshots are fake (e.g., https://worker-matrix.invalid/...). In real mode, we need real URLs or real local files.
For z_image_turbo_i2i: the snapshot has a fake URL. In real mode, we'd need a real test image URL or to provide the image differently.
For qwen cases: the hf_hub_download mock provides a fake LoRA file. In real mode, the real LoRA download needs to work.
Approach for handling this:
In real mode, skip patchers entirely
For cases that need real input images/videos, either: (a) use the fixture images already created by the builder (they're real PNG files on disk, just simple test images), or (b) override the snapshot URLs with local file paths
The builders already create real test images via _create_test_image() — the fixture paths are real local files. The snapshot token replacement (__FIXTURE_PATH__:key) already substitutes them. So for fixture-path-based cases, this works as-is.
For fixture-URL-based cases (z_image_turbo_i2i), the URL is fake. In real mode, we could substitute a local file path instead of the fake URL.
Propose a clean plan that:
Adds --real mode to the existing runner with minimal changes
Handles the shared queue lifecycle (init, start, stop)
Handles cases that need patchers differently in real vs fake mode
Keeps the fake mode as the default (fast, no GPU needed)
Considers model preloading strategy (avoid reloading between same-model cases)
Considers timeouts (real generation can take minutes)
Considers which cases should be enabled/disabled in real mode
Use the shared HeadlessTaskQueue instead of FakeImmediateTaskQueue
Skip patchers (no mocked requests.get, no mocked hf_hub_download)
For fixture-URL cases (z_image_turbo_i2i), substitute a local file:// path or use the fixture file directly
The cleanest approach: add a real_queue parameter to _build_direct_queue_case and each builder. When real_queue is not None, use it instead of creating a FakeImmediateTaskQueue, and skip patchers.
Concretely, modify _build_direct_queue_case:
python
def _build_direct_queue_case(
case, case_dir, *, params, expected_model=None, expected_parameters=None,
patchers=None, notes=None, real_queue=None,
) -> PreparedCase:
output_dir = case_dir / "outputs"
output_dir.mkdir(parents=True, exist_ok=True)
case_params = copy.deepcopy(params)
case_params.setdefault("task_id", f"{case.case_id}-task")
if real_queue is not None:
queue = real_queue
# In real mode, set the output dir on the queue for this case
# (but see note about main_output_dir below)
effective_patchers = [] # Skip all patchers in real mode
else:
queue = FakeImmediateTaskQueue(...)
effective_patchers = patchers or []
return PreparedCase(
definition=case,
params=case_params,
project_id=None,
main_output_dir=output_dir,
task_queue=queue,
patchers=effective_patchers,
notes=notes or {},
)
Each builder signature gains real_queue=None and passes it through. The CASE_BUILDERS dict value type becomes Callable[[CaseDefinition, Path, Any | None], PreparedCase] (or the runner wraps the call with functools.partial).
Alternative (simpler): Store real_queue on a module-level variable (set by main) that builders check. This avoids changing every builder's signature. Less clean but far less churn.
Recommended approach: Use a module-level _REAL_QUEUE: HeadlessTaskQueue | None = None set by main(). Builders check it and pass it into _build_direct_queue_case. This keeps the diff small.
2d. Fixture Handling in Real Mode
Three categories of cases:
No fixtures needed (vace_basic, ltx2_basic, ltx2_distilled): Work as-is. No patchers, no fixture URLs. Just use the real queue.
Fixture paths (qwen_image_basic, qwen_image_edit_basic, wan22_individual_segment): These use __FIXTURE_PATH__ tokens that resolve to real local PNG files created by _create_test_image(). The real pipeline reads these files directly (they are real images on disk). In real mode, skip the hf_hub_download patcher -- the real LoRA download will run. This means the Qwen LoRA must be downloadable from HuggingFace. If it is not available, these cases should be skipped (add a requires: ["qwen_lora"] or similar).
Fixture URLs (z_image_turbo_i2i): The snapshot has __FIXTURE_URL__:z_image_i2i_input which becomes https://worker-matrix.invalid/.... In real mode, instead of patching requests.get, substitute the local file path directly into the params where the URL goes. The z_image handler downloads the URL to get the image; in real mode we should put a file:///... URL or modify the snapshot replacement to use a local path instead. Simplest fix: In real mode, substitute __FIXTURE_URL__ tokens with file:// URLs pointing at the created fixture file, so the same requests.get call in the real pipeline either works with file URLs (if the handler supports it) or we keep a minimal patcher that serves local files for worker-matrix.invalid URLs only.
Pragmatic decision: For z_image_turbo_i2i in real mode, replace the __FIXTURE_URL__ with the actual local file path (not a URL). The real z_image handler's image_url parameter likely gets passed to requests.get() -- so keep a lightweight patcher that intercepts only worker-matrix.invalid URLs and serves the local file. This is one line of existing code, not a full mock.
2e. Output Directory Strategy
The HeadlessTaskQueue has a main_output_dir set at init time. But the matrix runner needs outputs per-case. Two options:
Option A: Set main_output_dir to a shared location, then after generation, the output file path from task.result_path tells us where it went. The run_case function already captures output_path from the result.
Option B: Update queue.main_output_dir before each case (not thread-safe in general, but we only have 1 worker and process cases sequentially).
Recommended: Option A. Set main_output_dir to run_dir / "real_outputs" at init. Each case's CaseResult.output_path will point to wherever the real pipeline wrote its file. The case_dir already gets a result.json with the path.
However, looking more carefully at how _handle_direct_queue_task works: the main_output_dir passed to process_single_task is prepared.main_output_dir (the case's output dir). But the HeadlessTaskQueue's internal main_output_dir (set at construction) is what the orchestrator uses to determine where to write files. These are different paths.
The real generation path: _process_task -> _execute_generation -> orchestrator.generate() which writes to self.main_output_dir. So the output ends up in the queue's main_output_dir, not the per-case output dir.
Resolution: Before each case in real mode, update shared_queue.main_output_dir to the case's output directory. Since we run cases sequentially and the queue has only 1 worker, this is safe. Add a helper:
python
if real_mode:
shared_queue.main_output_dir = str(prepared.main_output_dir)
if shared_queue.orchestrator:
shared_queue.orchestrator.main_output_dir = str(prepared.main_output_dir)
2f. Timeout Handling
The existing _handle_direct_queue_task has max_wait_time = 3600 (1 hour). This is fine for real mode. The --real-timeout flag could be implemented by:
Setting it on the context dict
Having _handle_direct_queue_task read it from context
But this requires modifying task_registry.py. Simpler alternative: just let the existing 1-hour timeout work. Real generation of a short video is 1-5 minutes typically. The per-case wall-clock is captured in CaseResult.duration_seconds regardless.
Decision: Don't add per-case timeout to start. The existing 3600s timeout in _handle_direct_queue_task is sufficient. If needed later, it is a small change.
2g. Case Enabling/Disabling in Real Mode
All 8 cases can theoretically run in real mode, but:
Qwen cases need the LoRA to be downloadable (may fail on first run)
VACE/LTX/z_image cases need their respective model weights on disk
In the manifest, add "requires": ["cuda"] to all cases (or handle this in the runner: if --real is set and CUDA is not available, skip all cases).
Better approach: Don't change the manifest. Instead, in main(), when --real is set, check CUDA availability upfront. If not available, print error and exit. This is a hard requirement for real mode.
2h. Model Sorting for Efficiency
Cases using the same model should run consecutively to avoid model reloads. Sort selected cases by their expected model before running:
python
if args.real:
# Group cases by model to minimize reloads
model_order = {}
for case in selected:
builder = CASE_BUILDERS[case.builder]
# ... extract expected model somehow
selected.sort(key=lambda c: _get_case_model(c))
This is tricky because the model isn't directly on the CaseDefinition -- it's in the builder or params. Options:
Add a model field to CaseDefinition / manifest
Sort by family as a proxy
Don't bother initially -- the real queue handles model switches gracefully
Decision: Don't sort initially. Model switching works fine, just adds time. Can add sorting as a follow-up.
In main(): if --real, check CUDA, create + start HeadlessTaskQueue, store in _REAL_QUEUE, stop in finally
In run_case(): before calling process_single_task, if _REAL_QUEUE, update its main_output_dir to the case's output dir
In _build_direct_queue_case(): if _REAL_QUEUE is not None, use it instead of FakeImmediateTaskQueue, clear patchers
In each builder that has patchers (z_image_turbo_i2i, qwen_image_basic, qwen_image_edit_basic): when _REAL_QUEUE, skip patchers. For z_image_turbo_i2i, use fixture_paths instead of fixture_urls to provide the image directly
Add "cuda" to REQUIREMENT_CHECKERS
scripts/worker_matrix_db_snapshots.json (possible minor change)
For the z_image_turbo_i2i snapshot: currently uses __FIXTURE_URL__:z_image_i2i_input. In real mode, we need to handle this differently. Two options:
Change the snapshot to use __FIXTURE_PATH__ and have the z_image handler accept local paths (requires checking if it does)
Keep the snapshot as-is, and in the builder, when real mode, replace the URL with the local path after snapshot loading
Decision: Handle in the builder, not the snapshot. The builder already has access to the created image path.
No changes needed to:
source/task_handlers/tasks/task_registry.py -- the existing _handle_direct_queue_task polling loop works with the real queue
headless_model_management.py -- HeadlessTaskQueue API is compatible
worker.py -- process_single_task works the same way
Manifest JSON -- no changes needed
4. Step-by-Step Implementation Sequence
Add CLI args --real and --preload-model to parse_args()
Add "cuda" requirement checker
Add module-level _REAL_QUEUE variable
Modify main() to initialize/start/stop HeadlessTaskQueue when --real
Modify _build_direct_queue_case() to accept and use _REAL_QUEUE
Modify each builder to skip patchers when _REAL_QUEUE
Handle z_image_turbo_i2i fixture specially in real mode (local path instead of URL)
Modify run_case() to update queue's output dir before each case
Add summary.md metadata indicating real vs fake mode
Test with --real --case-id z_image_turbo_db_task (simplest case, smallest model)
5. Potential Issues and Mitigations
Issue 1: _save_queue_state doesn't exist on HeadlessTaskQueue.
The stop_queue function calls queue._save_queue_state(). This may crash. Need to check if it's defined somewhere not found (possibly via __getattr__ on orchestrator). If not, add a no-op _save_queue_state method or wrap the call in try/except.
Issue 2: main_output_dir threading.
Updating main_output_dir between cases is safe because: (a) only 1 worker thread, (b) we wait for each case to complete before starting the next, (c) the poll loop in _handle_direct_queue_task blocks until done.
Issue 3: The wan2gp_path module-level variable in worker.py.worker.py sets wan2gp_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "Wan2GP") at module scope. When the matrix runner imports worker, this is set correctly since the runner is in the same repo. The HeadlessTaskQueue also does setup_wgp_path(wan_dir) which adds Wan2GP to sys.path. These should be compatible.
Issue 4: debug_mode global in worker.py.worker.py has a module-level debug_mode = False that process_single_task reads from the module scope. The matrix runner already calls enable_debug_mode() before each case. In real mode, this should work the same way.
Issue 5: Model weights not present.
Real mode requires model weights on disk. If weights are missing, the generation will fail with a clear error. The matrix runner already captures failures gracefully with tracebacks. This is acceptable -- the user should pre-download weights before running --real.
/Users/user_c042661f/Documents/Headless-Wan2GP/headless_model_management.py - HeadlessTaskQueue class: need to verify _save_queue_state exists, understand init requirements
/Users/user_c042661f/Documents/Headless-Wan2GP/source/task_handlers/tasks/task_registry.py - Contains _handle_direct_queue_task polling loop that drives both fake and real queue consumption
/Users/user_c042661f/Documents/Headless-Wan2GP/source/task_handlers/queue/queue_lifecycle.py - Queue start/stop logic, potential _save_queue_state crash to fix
/Users/user_c042661f/Documents/Headless-Wan2GP/scripts/worker_matrix_db_snapshots.json - Snapshot fixtures with __FIXTURE_URL__ tokens that need real-mode handling