Find and understand the debug utility in this project. Look at:
The debug/ package structure and main.py
What commands/capabilities it offers
How to use it to investigate task failures
Search in /Users/user_c042661f/Documents/Headless-Wan2GP for debug-related files, especially under source/ or a top-level debug/ directory. Read the key files to understand how to invoke the debug tool and what it can do.
Assistant
I'll help you find and understand the debug utility in this project. Let me start by exploring the debug-related files.
User
Find and understand the clip joining code in /Users/user_c042661f/Documents/Headless-Wan2GP. Look at:
Files under source/task_handlers/join/
How clip joining works - the main flow
Common failure modes
Read the key files to understand the join task architecture.
Assistant
Great! I found a comprehensive debug package at /Users/user_c042661f/Documents/Headless-Wan2GP/debug/. Let me read the key files to understand its structure and capabilities.
Assistant
I'll explore the clip joining code in the Headless-Wan2GP project. Let me start by examining the structure and key files.
Assistant
Now let me read the key supporting files to understand the architecture and available commands:
Assistant
Now let me read the key files to understand the architecture:
Assistant
Now let me examine a few of the command implementations to understand what they do:
Assistant
Now let me read the other key files to understand the complete architecture:
Assistant
Let me check a couple more command files and the formatters to complete my understanding:
Assistant
Now let me read the remaining join handler files:
Assistant
Let me also check the other commands to see the complete set of capabilities:
Assistant
Perfect! Now let me read a couple more commands to give you a complete picture:
Assistant
Now let me check how the join handlers are invoked from the main dispatcher:
Assistant
Let me check the task registry to understand the complete flow:
Assistant
Let me continue reading the task registry to see the join task dispatch:
Assistant
Perfect! Now let me look for any test files related to joins to understand the failure modes:
Assistant
Let me search for any error handling or exception patterns in the join code:
Assistant
Excellent! Now let me create a comprehensive summary document. Let me also check for any known issues or documentation:
Assistant
Now let me look at the complete generation.py file to understand the full join flow:
Assistant
Excellent! Now let me create a comprehensive summary of the debug utility. Let me compile all the information I've gathered:
Debug Utility Summary
I've thoroughly explored the debug package in your project. Here's a complete breakdown:
Package Location and Structure
The debug utility is located at /Users/user_c042661f/Documents/Headless-Wan2GP/debug/
Directory structure:
code
debug/
├── __main__.py # Entry point for `python -m debug`
├── __init__.py # Package initialization
├── cli.py # Argument parsing and command routing
├── client.py # DebugClient - unified data access layer
├── models.py # Data models (TaskInfo, WorkerInfo, etc.)
├── formatters.py # Output formatting (text/JSON)
├── README.md # Documentation
└── commands/
├── __init__.py
├── task.py # Investigate specific task
├── worker.py # Investigate specific worker
├── tasks.py # Analyze multiple recent tasks
├── workers.py # List recent workers
├── health.py # System health check
├── orchestrator.py # Orchestrator status
├── config.py # Configuration display
├── runpod.py # RunPod sync/orphan detection
└── storage.py # Storage volume health
How to Use It
Invocation:
bash
python -m debug <command> [options]
Available Commands
1. Task Investigation - Diagnose why a task failed
bash
debug.py task <task_id> # Complete task analysis with logs
debug.py task <task_id> --logs-only # Just the log timeline
debug.py task <task_id> --json # JSON output for scripting
Assistant
Perfect! Now I have a thorough understanding. Let me create a comprehensive summary document for the user.
Summary: Clip Joining Code Architecture in Headless-Wan2GP
I've thoroughly explored the clip joining system in /Users/user_c042661f/Documents/Headless-Wan2GP/source/task_handlers/join/. Here's my comprehensive analysis:
1. Directory Structure & Key Files
The join system is organized in /Users/user_c042661f/Documents/Headless-Wan2GP/source/task_handlers/join/:
File
Purpose
orchestrator.py
Main entry point (_handle_join_clips_orchestrator_task): Parses orchestrator payload, validates clips, optionally runs VLM enhancement, creates child join tasks
generation.py
Core join generation (handle_join_clips_task): Bridges two video clips using VACE generation; handles frame extraction, context preservation, gap generation
final_stitch.py
Final stitching phase (handle_join_final_stitch): Assembles all trimmed clips + transitions into single video with crossfades
task_builder.py
Task creation utilities: _create_join_chain_tasks (legacy sequential) and _create_parallel_join_tasks (new parallel pattern)
Pre-join validation: Ensures clips have sufficient frames for safe joining
vlm_enhancement.py
Optional VLM prompts: Extracts boundary frames and generates context-aware transition prompts using Qwen VLM
vace_quantization.py
VACE frame count handling: Adjusts frame counts to match VACE's 4n+1 constraint
2. Main Flow: How Clip Joining Works
A. ORCHESTRATOR PHASE (orchestrator.py:_handle_join_clips_orchestrator_task)
The orchestrator is the entry point that orchestrates the entire join workflow:
code
User
I need to understand how the join clips orchestrator currently works, specifically around clip validation and preprocessing, and what utilities exist for FPS normalization and aspect ratio standardization.
Explore these files thoroughly in /Users/user_c042661f/Documents/Headless-Wan2GP:
source/task_handlers/join/orchestrator.py — Read the full file. I need to understand:
Where clips are downloaded for validation
What happens between validation and task dispatch
How clip_list URLs are passed to child tasks
The full flow of _handle_join_clips_orchestrator_task
source/task_handlers/join/task_builder.py — Read the full file. I need to understand:
How _create_parallel_join_tasks builds segment and final_stitch tasks
What parameters are passed to each child task
Where clip_list URLs come from in the payload
source/task_handlers/join/clip_validator.py — Read the full file. I need to understand:
How clips are downloaded for validation
What frame count info is available after validation
Whether preprocessed clips are available after validation
source/media/video/ — Find and read the ensure_video_fps and standardize_video_aspect_ratio functions. What are their signatures, where do they live, what do they return?
Look at how the upload utility works — find upload_and_get_final_output_location or similar upload functions used in the project. How do you upload a local file and get a URL back?
Check source/task_handlers/join/generation.py around lines 264-310 for the aspect ratio auto-detection logic — how does the segment decide what aspect ratio to standardize to?
Be very thorough — read complete files, not just snippets. I need exact function signatures, parameter names, and return types.
Assistant
I'll help you explore this thoroughly. Let me start by reading the key files you've specified.
Assistant
Now let me read the generation.py file more carefully and search for the video utilities:
Assistant
Let me search for the video utility files:
User
In /Users/user_c042661f/Documents/Headless-Wan2GP, I need to understand the utilities available for:
Uploading files and getting URLs back: Search for upload functions used across the project. Look at:
source/utils/ for upload-related modules
How generation.py and final_stitch.py upload files
The function signatures for upload utilities
Specifically upload_and_get_final_output_location, prepare_output_path_with_upload, and any other upload functions
Also look for any Supabase storage upload utilities (supabase upload, storage upload, etc.)
Video preprocessing utilities: Find the exact location and signature of:
ensure_video_fps — where is it defined, what does it return?
standardize_video_aspect_ratio — where is it defined, what does it return?
Any aspect ratio detection utilities (how does generation.py detect aspect ratio from a video?)
How does generation.py handle the case where no aspect_ratio param is specified? Read generation.py around lines 264-340 to see the auto-detection fallback where it compares starting and ending video aspect ratios.
Download utilities: How does download_video_if_url work? What does it return? Where is it defined?
Read the full source of the relevant utility files to understand their complete interfaces.
Assistant
I'll help you understand these utility functions across the project. Let me search systematically for each category.
Assistant
Now let me read the relevant utility files:
Assistant
Now let me read the specific files that contain these utilities:
Assistant
Now let me search for the generation.py file content around lines 264-310 for aspect ratio auto-detection:
Assistant
Now let me check for ensure_video_fps and look at generation.py to understand aspect ratio detection:
Assistant
Perfect! Now let me check the init.py to see all exports:
Assistant
Let me read the ffmpeg_ops file to find ensure_video_fps:
Assistant
Now let me read those utility files:
Assistant
Now let me find generation.py in the models directory:
Assistant
Let me continue searching:
Assistant
Let me search for "generation" files more broadly:
Assistant
Let me find the DB function:
Assistant
Let me check generation_strategies.py and search for aspect ratio logic:
Assistant
Let me search more carefully:
Assistant
Let me search for where aspect ratio detection happens:
Assistant
Let me try using Read to find this function:
Assistant
Let me search differently:
Assistant
Let me check the join generation.py file:
Assistant
Perfect! Now let me check for any other resolution utilities and read more of that file to understand the full aspect ratio handling:
Assistant
Good! Now let me check the db module:
Assistant
Perfect! Now let me read those function signatures more completely:
Assistant
Perfect! Now I have all the information I need. Let me compile a comprehensive report:
Comprehensive Utility Functions Report
Based on my analysis of the Headless-Wan2GP codebase, here's the complete documentation of the utilities you requested:
Returns proportional reduction recommendations if clips are too short
Resolution Detection (lines 235-259):
If use_input_video_resolution=True:
Downloads first clip with download_video_if_url()
Calls internal _get_video_resolution() which uses ffprobe
Sets join_settings["resolution"] to detected [width, height]
User
I need to design an implementation plan for lifting clip preprocessing (FPS normalization + aspect ratio standardization) into the join clips orchestrator. Here's the full context:
Problem
The parallel join architecture has a bug: the join_clips_segment task preprocesses clips (FPS normalization, aspect ratio cropping) before generating transitions, then records frame counts/indices against preprocessed clips. But join_final_stitch downloads the raw original clips and tries to use those frame indices — causing crashes when clips have different FPS or aspect ratios.
Example: A clip at 24fps/768x512 (122 frames) gets preprocessed by the segment to 16fps/512x512 (81 frames). The transition records clip2_total_frames: 81. Final stitch downloads the original (122 frames) and fails: Frame count mismatch too large: expected 104, got 71.
Solution
Move preprocessing to the orchestrator so both segments and final stitch receive already-preprocessed clip URLs. The orchestrator already downloads clips for validation — we'll extend this to preprocess, validate preprocessed clips, and upload preprocessed versions to Supabase for cross-worker access.
Key existing utilities (all in /Users/user_c042661f/Documents/Headless-Wan2GP):
ensure_video_fps(input_video_path, target_fps, output_dir, fps_tolerance=0.5) -> Path in source/media/video/ffmpeg_ops.py
Returns original path if already at target FPS, resampled path otherwise
Raises OSError, RuntimeError, ValueError
standardize_video_aspect_ratio(input_video_path, output_video_path, target_aspect_ratio, task_id_for_logging) -> Path | None in source/media/video/video_transforms.py
Center-crops to target aspect ratio. Returns Path or None on failure.
target_aspect_ratio is a string like "16:9", "1:1", etc.
upload_intermediate_file_to_storage(local_file_path, task_id, filename) -> str | None in source/utils/output_path_utils.py
Uploads to Supabase and returns public URL. Returns None on failure.
Already imported in orchestrator.py
download_video_if_url(url, download_target_dir, task_id_for_logging, descriptive_name) -> str in source/utils/download_utils.py
Already imported in orchestrator.py
in orchestrator.py
Assistant
I'll start by thoroughly exploring the relevant codebase to understand the current architecture, data flow, and patterns before designing the plan.
Assistant
Now let me read the remaining key files to understand the full picture.
Assistant
Now let me look at the generation.py aspect ratio detection code and the shared.py helper, plus the final_stitch handler to understand how clip_list flows through.
Assistant
Let me also check the FPS normalization logic in generation.py to see the full preprocessing pipeline that currently exists in segment tasks.
Assistant
Now let me check the beginning of the generation.py handle_join_clips_task to see how it downloads and preprocesses clips to understand the full current flow.
Assistant
Now let me check the utils and media init to understand exports, and also verify if get_video_frame_count_and_fps is already available through the existing imports in the join package.
Assistant
Let me look at the download_utils to understand what download_video_if_url returns and how it works.
Assistant
Now let me check how the aspect ratio auto-detection logic in generation.py determines the common ratios -- I need to understand the full pattern to replicate it in the preprocessor.
Assistant
Now I have a thorough understanding of the entire codebase. Let me compile the full implementation plan.
Implementation Plan: Lift Clip Preprocessing to Join Clips Orchestrator
1. Problem Summary
In the parallel join architecture, join_clips_segment tasks preprocess clips (FPS normalization + aspect ratio cropping) before generating transitions. The transition metadata records frame counts and indices against the preprocessed clips. However, join_final_stitch downloads the raw original clips from clip_list and tries to use those frame indices -- causing crashes when the original clips have different FPS or aspect ratios than what the segments preprocessed to.
2. Solution Overview
Create a new clip_preprocessor.py module that runs in the orchestrator after clip_list is resolved but before validation, VLM enhancement, and child task creation. This module:
Downloads each clip
Normalizes FPS (unless use_input_video_fps=True)
Standardizes aspect ratio (explicit or auto-detected from first clip)
Detects resolution from first clip (if use_input_video_resolution=True)
Validates frame counts (folding in clip_validator.py functionality)
Uploads preprocessed clips to Supabase
Returns a new clip_list with preprocessed URLs, detected resolution, and frame counts
The updated clip_list then flows through task_builder.py to both segments and final stitch, so both sides see identical preprocessed clips.
3. New File: source/task_handlers/join/clip_preprocessor.py
Pattern follows:clip_validator.py (same directory, similar purpose, same logging style)
3.1 Function Signature
python
Assistant
Good -- _get_video_resolution is only used internally in orchestrator.py itself. Safe to move.
Let me also verify nothing else imports from clip_validator.py to understand if removing that import is safe.
User
[Request interrupted by user]
What it shows:
Complete task state from database (status, error messages, timing)
Full log timeline from system_logs table
If task failed due to child task, shows cascaded failure details
For orchestrator tasks, lists all child tasks (travel segments, stitches, etc.)
Intelligent error diagnosis with remediation hints
2. Worker Investigation - Debug worker issues
bash
debug.py worker <worker_id> # Full worker analysis
debug.py worker <worker_id> --check-logging # Is worker.py running?
debug.py worker <worker_id> --startup # View initialization logs
debug.py worker <worker_id> --logs-only # Just the log timeline
debug.py worker <worker_id> --hours N # Change time window (default: 24h)
What it shows:
Worker state and metadata
All logs for the worker (initialization, heartbeats, task processing)
Tasks currently assigned to worker
Pre-termination VRAM info
Pod status
Specific use cases:
--check-logging: Verifies if worker.py actually started (checks if any logs exist). If no logs, worker crashed during initialization or hasn't started yet
--startup: Shows first 100 startup-related logs, detects common issues (ModuleNotFoundError, process death, etc.)
3. Multi-Task Analysis - Get task statistics
bash
debug.py tasks # Recent 50 tasks (default)
debug.py tasks --limit 100 # Get different number of tasks
debug.py tasks --status Completed # Filter by status
debug.py tasks --type travel_segment # Filter by task type
debug.py tasks --worker <worker_id> # Filter by worker
debug.py tasks --hours 12 # Filter by time window
What it shows:
Task distribution by status and type
Timing statistics (avg processing time, avg queue time)
Recent failures with error messages
4. Multi-Worker Analysis - Monitor worker fleet
bash
debug.py workers # List recent workers (default: 2 hours)
debug.py workers --hours 24 # Change time window
debug.py workers --detailed # Show detailed failure analysis
What it shows:
Worker status counts (active, spawning, error, terminated)
Healthy vs stale workers (checks heartbeat freshness)
Recent failures and failure rates
Metadata about each worker
5. System Health Check - Quick overview
bash
debug.py health
debug.py health --json
What it shows:
Active workers vs spawning
Healthy workers count
Queued and in-progress task counts
Top 10 recent error logs
6. Orchestrator Status - Is orchestrator running?
bash
debug.py orchestrator # Status of orchestrator GPU
debug.py orchestrator --hours 2 # Check last 2 hours (default: 1h)
What it shows:
Last activity time and cycle number
Status: HEALTHY (< 5 min), WARNING (5-15 min), STALE (> 15 min), or NO_LOGS
This is a comprehensive debugging toolkit designed to help you quickly diagnose issues with task failures, worker health, and system performance!
Input: clip_list = [clip_A, clip_B, clip_C, clip_D]
+ orchestrator_details (settings for all joins)
1. PARSE PAYLOAD
- Extract clip_list, run_id, join_settings, per_join_settings
- Support dynamic clip_list from segment_task_ids (for travel → join pipelines)
- Handle loop_first_clip: reverse first clip to create looping effect
2. EARLY IDEMPOTENCY CHECK
- Look for existing child tasks (both chain and parallel patterns)
- Return early if tasks already exist and are complete/in-progress
3. VALIDATE CLIP FRAMES
- Download each clip, count frames
- Ensure clips have minimum required frames for safe joining
- REPLACE mode: needs gap_frame_count + 2×context_frame_count per clip
- INSERT mode: needs 2×context_frame_count per clip
- Return proportional reduction suggestions if validation fails
4. DETECT RESOLUTION (optional)
- If use_input_video_resolution=True: detect from first clip
- Override resolution parameter
5. VLM ENHANCEMENT (optional)
- If enhance_prompt=True: Extract 4 boundary frames per join
- Run Qwen VLM to generate context-aware transition prompts
- Graceful fallback if VLM fails
6. CREATE CHILD TASKS
- Choose pattern: PARALLEL (default) or CHAIN (legacy)
B. PARALLEL PATTERN (New, Recommended)
code
Creates:
- N-1 join_clips_segment tasks (transitions) in PARALLEL (no dependencies)
Each with transition_only=True (only generates transition, no stitching)
- 1 final_stitch task that depends on ALL transitions
Benefits:
- No re-encoding: original clips never reprocessed
- Parallel execution: all transitions run simultaneously
- Better quality: each transition is fresh generation
- Proper handling of per-transition parameters
C. CHAIN PATTERN (Legacy)
code
Creates:
- N-1 join_clips_segment tasks in DEPENDENCY CHAIN
join_0: clip_A + clip_B → AB.mp4
join_1: AB.mp4 + clip_C → ABC.mp4 (depends on join_0)
join_2: ABC.mp4 + clip_D → ABCD.mp4 (depends on join_1)
- 1 final_stitch task (chain_mode=True, passthrough)
Drawback:
- Each join re-encodes the accumulated video (quality degradation)
- Slower: sequential execution
- DEPRECATED in favor of parallel
D. JOIN CLIPS SEGMENT PHASE (generation.py:handle_join_clips_task)
Bridges two consecutive video clips using VACE generation:
code
Input: starting_video_path, ending_video_path, context_frame_count, gap_frame_count, ...
STEPS:
1. PARAMETER VALIDATION
- Check for required paths
- Handle orchestrator context (fetch predecessor output if needed)
- Validate task_queue availability
2. VIDEO PREPROCESSING
a) FPS STANDARDIZATION
- use_input_video_fps: keep original (True) or downsample to fps param (False)
- Default: downsample to 16 fps
- May trigger re-sampling if source is different fps
b) ASPECT RATIO STANDARDIZATION
- If aspect_ratio specified: center-crop both videos to match
- If not specified: auto-detect and standardize ending video to match starting
- Example: 16:9 vs 9:16 → one will be cropped to match the other
3. FRAME COUNT DETECTION
- Use OpenCV + ffprobe to count frames in each video
- Auto-adjust context_frame_count if exceeds available frames
- Fail if video format unsupported (some WebM codecs fail)
4. VACE QUANTIZATION CALCULATION
- VACE requires frame counts = 4n+1 (e.g., 45, 49, 53)
- Adjust gap_frame_count to match quantization
- Calculate gap split for REPLACE mode (how much to take from each clip)
5. CONTEXT FRAME EXTRACTION
- Extract last N frames from starting_video
- Extract first N frames from ending_video
- In REPLACE mode: context comes from OUTSIDE gap region
- In INSERT mode: context frames preserved, gap inserted between
6. GUIDE & MASK VIDEO CREATION
- Create guide video: context1 + gap + context2
- Create mask video: marks which frames are "generated" vs "preserved"
- Mask preserves context frames, allows VACE to generate only gap
7. VACE GENERATION
- Queue generation task with prompt + guide + mask
- Generate transition frames
- Handle VLM-enhanced prompts if available
8. OUTPUT MODES:
- transition_only=True (parallel mode):
Return JSON: {transition_url, gap_from_clip1, gap_from_clip2, ...}
- transition_only=False (chain mode):
Stitch: clip1_trimmed + transition + clip2_trimmed → output video
E. FINAL STITCH PHASE (final_stitch.py:handle_join_final_stitch)
Assembles all clips and transitions into final seamless video:
code
Input: clip_list, transition_task_ids (from completed join tasks)
STEPS:
1. CHAIN MODE HANDLING (chain_only)
- Passthrough: return output from last join in chain
- No re-stitching needed (already done sequentially)
- Audio already muxed by last join
2. PARALLEL MODE (NEW):
a) FETCH TRANSITION OUTPUTS
- Get JSON from each transition_task_id
- Extract: transition_url, gap_frames, context_from_clip1/2, gap_from_clip1/2
- Verify structure consistency: frames = ctx1 + gap + ctx2
b) ALIGNMENT VERIFICATION TABLE
- Diagnostic output showing exact frame indices for each transition
- Detects mismatches in clip frame counts vs transition expectations
- Shows context ranges: [start_idx:end_idx]
c) PIXEL VERIFICATION (optional but valuable)
- Extract context frames from original clips
- Compare pixel-identically with transition context frames
- Runs offset detection (-2, -1, 0, +1, +2 frames) to detect alignment bugs
- Logs detailed pixel differences for debugging
d) DOWNLOAD ALL FILES
- Download original clips
- Download all transition videos
- All done locally for final stitching pass
e) TRIM CLIPS BASED ON GAP VALUES
- For each clip:
trim_start = gap_from_clip2 from PREVIOUS transition
trim_end = gap_from_clip1 from CURRENT transition
- First/last clips: 0 trim on outer edges
- Extract trimmed ranges to temporary videos
f) BUILD STITCH LIST WITH CROSSFADES
- Pattern: [clip0] → [trans0] → [clip1] → [trans1] → [clip2]
- Blend frames: context_from_clip1 (clip→trans), context_from_clip2 (trans→clip)
- Each crossfade overlaps N frames (per-transition values)
g) FRAME ACCOUNTING TABLE
- Log exact frame ranges in final output
- Shows which clips/transitions contribute which frames
- Diagnostic for post-stitch validation
h) STITCH VIDEOS WITH CROSSFADE
- Concatenate all videos (clips + transitions)
- Apply linear_sharp crossfades at boundaries
- Output: seamless joined video
i) ADD AUDIO (optional)
- If audio_url provided: mux into final video
- Graceful fallback if audio fails
j) VERIFY & UPLOAD
- Check output exists and is non-empty
- Count final frames and fps
- Upload to storage
- Return final URL
3. Common Failure Modes
A. Input Validation Failures
Failure
Cause
Solution
orchestrator_details missing
Malformed payload
Check orchestrator request structure
clip_list must contain at least 2 clips
Single clip provided
Provide ≥2 clips
run_id is required
Missing orchestrator ID
Ensure run_id in payload
Segment task {id} has no output_location
Segment didn't complete
Wait for segment completion
B. Clip Validation Failures
Failure
Cause
Solution
Clip {idx} missing 'url' field
Malformed clip dict
Each clip needs {url: "...", name: "..."}
Failed to download clip {idx}
Invalid/unreachable URL
Verify URL is accessible
Could not determine frame count
Unsupported codec (WebM, etc.)
Re-encode to MP4/H.264
Clips are shorter than ideal
Insufficient frames
Reduce gap_frame_count or context_frame_count
C. Video Processing Failures
Failure
Cause
Solution
Failed to ensure video FPS
ffmpeg issue
Check ffmpeg installation, codec support
Failed to standardize aspect ratio
Dimension detection failed
Verify video has valid streams
Could not detect frame count
OpenCV/ffprobe error
Try different video codec, check file integrity
Extract frame range failed
ffmpeg frame extraction error
Reduce context_frame_count, check video format
D. VACE Generation Failures
Failure
Cause
Solution
Videos too short for requested gap
Gap + context exceeds available frames
Reduce gap_frame_count or context_frame_count
Starting/Ending video too short
Specific clip doesn't have enough frames
Use longer source clips, reduce constraints
Generation timeout
VACE taking >30min
Increase max_wait_time or reduce resolution
Model load failed
GPU OOM or model not available
Reduce resolution, check GPU memory
E. Stitching Failures
Failure
Cause
Solution
Expected N transitions, got M
Mismatched transition count
Verify all transitions completed successfully
Failed to get output for transition
Transition task failed/incomplete
Check transition task status
Frame count mismatch
Clips changed between tasks
Ensure source clips are immutable
Failed to trim clip
ffmpeg trimming error
Check video format, reduce trim amounts
Failed to stitch videos
ffmpeg concat error
Check crossfade parameters, codec compatibility
Final output file is empty
ffmpeg produced no output
Check codec, resolution, fps parameters
F. Parallel vs Chain Pattern Issues
Issue
Pattern
Solution
Re-encoding artifacts
CHAIN (cumulative quality loss)
Switch to PARALLEL pattern
Missing per-join settings
PARALLEL (not propagated)
Verify per_join_settings array
Chain dependency broken
CHAIN (if join_i crashes)
Check intermediate video outputs
Transition output parsing
PARALLEL (JSON parsing)
Ensure transition outputs are valid JSON
G. Frame Alignment Issues
Issue
Root Cause
Detection
Off-by-one frame shifts
Quantization calculation
PIXEL_CHECK logs show offset ≠ 0
Gap frames mismatch
Different calculation paths
ALIGNMENT TABLE shows inconsistent gap values
Context frame corruption
VACE modification
PIXEL_CHECK shows pixel differences >1.0
Trim mismatch
Per-transition gap values differ
Verify all transitions use consistent gap values
4. Key Configuration Parameters
Parameter
Default
Impact
Notes
gap_frame_count
53
Frames generated in transition
Must result in 4n+1 after quantization
context_frame_count
8
Frames from each clip boundary
Auto-reduced if clips too short
replace_mode
False
INSERT (False) vs REPLACE (True)
REPLACE removes boundary frames before gap
fps
16
Output video frame rate
Lower = faster gen, higher = more detail
aspect_ratio
None
Force aspect ratio (e.g., "16:9")
Auto-detects and standardizes if not set
use_input_video_resolution
False
Use source resolution vs override
Detected from first clip
use_input_video_fps
False
Keep source fps vs downsample
Default: downsample to fps param
enhance_prompt
False
Run VLM enhancement
Adds compute but better transition context
use_parallel_joins
True
Parallel vs Chain pattern
Chain is DEPRECATED, avoid
keep_bridging_images
False
Preserve intermediate frames
For debugging
5. Critical Architectural Decisions
VACE Quantization (4n+1)
VACE can only generate 4n+1 frames (45, 49, 53, etc.)
_calculate_vace_quantization() adjusts gap to match nearest valid count
Affects gap split in REPLACE mode
Parallel vs Chain
PARALLEL: transitions generated independently, stitched once
CHAIN: each join compounds previous (legacy, avoid)
Default now uses PARALLEL + final_stitch
Per-Transition Gap Values
Each transition can have different gap_from_clip1/2
Ground truth comes from VACE output, not orchestrator calculation
This architecture enables robust, parallelizable clip joining with extensive frame-level diagnostics and fallback handling. The parallel pattern avoids quality loss from repeated encoding, while comprehensive validation catches frame alignment issues early.
Extract the common-ratio detection logic from generation.py into a standalone helper within this module:
python
def _detect_aspect_ratio_from_video(video_path: Path, task_id: str) -> Optional[str]:
"""
Detect the aspect ratio of a video and return as a standard ratio string.
Returns "16:9", "9:16", "1:1", "4:3", "21:9", or "{w}:{h}" for non-standard.
Returns None if detection fails.
"""
This uses the _get_video_resolution pattern (ffprobe) then maps to standard ratios using the same tolerance logic from generation.py lines 333-345.
3.4 Helper: _get_video_resolution
Move (or duplicate) the resolution detection from orchestrator.py as a private helper:
python
def _get_video_resolution(video_path: str | Path) -> Tuple[int, int] | None:
"""Get video resolution (width, height) using ffprobe."""
This is identical to orchestrator.py:_get_video_resolution -- we can import from orchestrator or inline. I recommend inlining since the orchestrator's version will be removed.
4. Changes to orchestrator.py
4.1 New Import
Add at top of file:
python
from source.task_handlers.join.clip_preprocessor import preprocess_clips_for_join
4.2 Remove Existing Import
Remove:
python
from source.task_handlers.join.clip_validator import validate_clip_frames_for_join
(The validator is folded into the preprocessor.)
4.3 Replace Three Blocks with One
In _handle_join_clips_orchestrator_task, the following three sequential blocks (currently lines 210-259) get replaced by a single preprocessor call:
# === DETECT RESOLUTION FROM INPUT VIDEO (when use_input_video_resolution=True) ===
if join_settings.get("use_input_video_resolution", False):
...download first clip, detect resolution...
REMOVE: _get_video_resolution function (lines 41-64) -- moved to clip_preprocessor.py
ADD: Single preprocessing call (inserted where Block 1 was):
python
# === PREPROCESS CLIPS (FPS normalize, aspect ratio, validate, upload) ===
skip_validation = orchestrator_payload.get("skip_frame_validation", False)
preprocess_result = preprocess_clips_for_join(
clip_list=clip_list,
join_settings=join_settings,
orchestrator_task_id=orchestrator_task_id_str,
work_dir=current_run_output_dir,
)
if isinstance(preprocess_result, tuple):
success, result_or_msg = preprocess_result
if not success:
orchestrator_logger.debug(f"[JOIN_ORCHESTRATOR] PREPROCESSING FAILED: {result_or_msg}")
return False, f"Clip preprocessing failed: {result_or_msg}"
# Update clip_list with preprocessed URLs
clip_list = result_or_msg.clip_list
# Apply detected resolution if use_input_video_resolution was requested
if result_or_msg.detected_resolution and join_settings.get("use_input_video_resolution", False):
join_settings["resolution"] = list(result_or_msg.detected_resolution)
orchestrator_logger.debug(f"[JOIN_ORCHESTRATOR] Detected resolution: {result_or_msg.detected_resolution}")
if result_or_msg.validation_message:
orchestrator_logger.debug(f"[JOIN_ORCHESTRATOR] {result_or_msg.validation_message}")
orchestrator_logger.debug(f"[JOIN_ORCHESTRATOR] Preprocessing complete, frame counts: {result_or_msg.frame_counts}")
4.4 Update __all__
Remove _get_video_resolution from __all__ since it is being moved.