World's first open-source, agentic video production system. 12 production pipelines, 100+ tools, 700+ agent skill and production-knowledge files. Turn your AI coding assistant into a full video production studio.
Python agentagentic-aiaiclaudecopilotcursorelevenlabsffmpegfluximage-generationopen-sourceopenaipythonremotionstable-diffusiontext-to-speechtext-to-videovideo-generationvideo-production
fix(video-stitch): isolate temporary files per job (#713)
Rahuld4f4e71c806e
diff --git a/tests/contracts/test_video_stitch_workspaces.py b/tests/contracts/test_video_stitch_workspaces.pynew file mode 100644index 00000000..64cbc0a1--- /dev/null+++ b/tests/contracts/test_video_stitch_workspaces.py@@ -0,0 +1,83 @@+"""Stitch jobs sharing an output folder must not share intermediate files."""++from pathlib import Path+from subprocess import CompletedProcess++import pytest++from tools.video.video_stitch import VideoStitch+++def prepare_job(tmp_path, name, operation):+ clips = []+ for index in range(2):+ clip = tmp_path / f"{name}-{index}.mp4"+ clip.write_bytes(f"{name}-{index}".encode())+ clips.append(str(clip))+ return {+ "operation": operation,+ "clips": clips,+ "output_path": str(tmp_path / f"{name}.mp4"),+ "auto_normalize": True,+ "layout": "side_by_side",+ }+++def stub_probe(monkeypatch):+ monkeypatch.setattr(VideoStitch, "_probe_clip", lambda *_: {+ "width": 160, "height": 90, "fps": 10, "duration": 1,+ "video_codec": "h264", "pixel_format": "yuv420p",+ })+ monkeypatch.setattr(VideoStitch, "_clip_has_audio", lambda *_: False)++[email protected]("operation", ["stitch", "spatial"])+def test_overlapping_jobs_keep_their_own_intermediates(tmp_path, monkeypatch, operation):+ stub_probe(monkeypatch)+ outer_inputs = prepare_job(tmp_path, "outer", operation)+ inner_inputs = prepare_job(tmp_path, "inner", operation)+ inner_finished = False++ def run_command(self, cmd, **kwargs):+ nonlocal inner_finished+ output = Path(cmd[-1])+ if output == Path(outer_inputs["output_path"]) and not inner_finished:+ inner_finished = True+ # Finish another job while this job's final FFmpeg call is pending.+ inner_result = VideoStitch().execute(inner_inputs)+ assert inner_result.success, inner_result.error+ if "concat" in cmd:+ listing = Path(cmd[cmd.index("-i") + 1]).read_text(encoding="utf-8")+ sources = [Path(line[6:-1]) for line in listing.splitlines()]+ else:+ sources = [Path(cmd[index + 1]) for index, arg in enumerate(cmd) if arg == "-i"]+ # Silent audio augmentation also has a lavfi input.+ sources = [path for path in sources if not str(path).startswith("anullsrc=")]+ output.write_bytes(b"|".join(path.read_bytes() for path in sources))+ return CompletedProcess(cmd, 0, stdout="", stderr="")++ monkeypatch.setattr(VideoStitch, "run_command", run_command)+ result = VideoStitch().execute(outer_inputs)+ assert result.success, result.error+ assert Path(outer_inputs["output_path"]).read_bytes() == b"outer-0|outer-1"+ assert Path(inner_inputs["output_path"]).read_bytes() == b"inner-0|inner-1"+ assert not list(tmp_path.glob(".*_tmp*"))+ for inputs in (outer_inputs, inner_inputs):+ assert all(Path(path).exists() for path in inputs["clips"])++[email protected]("operation", ["stitch", "spatial"])+def test_failed_encoding_removes_partial_intermediates(tmp_path, monkeypatch, operation):+ stub_probe(monkeypatch)+ inputs = prepare_job(tmp_path, "failed", operation)++ def fail_encoding(self, cmd, **kwargs):+ Path(cmd[-1]).write_bytes(b"partial output")+ raise RuntimeError("encoding failed")++ monkeypatch.setattr(VideoStitch, "run_command", fail_encoding)+ result = VideoStitch().execute(inputs)+ assert not result.success+ assert "encoding failed" in result.error+ assert not list(tmp_path.glob(".*_tmp*"))+ assert all(Path(path).exists() for path in inputs["clips"])diff --git a/tools/video/video_stitch.py b/tools/video/video_stitch.pyindex 5f742bd2..2702c056 100644--- a/tools/video/video_stitch.py+++ b/tools/video/video_stitch.py@@ -9,6 +9,8 @@ picture-in-picture) for duet-style content.from __future__ import annotationsimport json+import shutil+import tempfileimport timefrom pathlib import Pathfrom typing import Any, Optional@@ -524,8 +526,7 @@ class VideoStitch(BaseTool):),)- temp_dir = output_path.parent / ".stitch_tmp"- temp_dir.mkdir(parents=True, exist_ok=True)+ temp_dir = Path(tempfile.mkdtemp(prefix=".stitch_tmp-", dir=output_path.parent))temp_files: list[Path] = []try:@@ -803,8 +804,7 @@ class VideoStitch(BaseTool):if not Path(clip).exists():return ToolResult(success=False, error=f"Clip not found: {clip}")- temp_dir = output_path.parent / ".spatial_tmp"- temp_dir.mkdir(parents=True, exist_ok=True)+ temp_dir = Path(tempfile.mkdtemp(prefix=".spatial_tmp-", dir=output_path.parent))temp_files: list[Path] = []try:@@ -948,15 +948,5 @@ class VideoStitch(BaseTool):@staticmethoddef _cleanup_temp(temp_dir: Path, temp_files: list[Path]) -> None:- """Remove temporary files and directory."""- for f in temp_files:- if f.exists():- try:- f.unlink()- except OSError:- pass- if temp_dir.exists():- try:- temp_dir.rmdir()- except OSError:- pass+ """Remove this job's workspace, including any partially written files."""+ shutil.rmtree(temp_dir, ignore_errors=True)