AI Video API Temporary Files: A Python Cleanup Tutorial

Nov 18, 2026·9 min read

A generated video downloads successfully, its transcode stalls, and the next batch fills your worker disk. Managing AI video API temporary files requires an application-owned workspace, bounded processing, and cleanup that runs when a job fails—not scattered calls to delete individual filenames.

This API tutorial builds that processing layer in Python, starting after your application receives a video result. For GenRelay integration context, see the video API overview. Nothing below assumes a particular generation endpoint, response field, hosted-file lifetime, or provider-side cleanup feature.

Updated November 18, 2026. Archetype: API tutorial.

How should you organize temporary video processing?

Give each admitted job a private directory beneath an explicitly configured, application-owned scratch root, then delete that directory when processing exits.

A scratch root is a directory reserved for disposable processing files. A workspace is the per-job directory inside it. Provision the root with restrictive permissions under the worker's service identity; do not point it at a shared uploads directory or accept its path from a request.

Use this sequence:

  1. Obtain the completed generation result through your documented API integration.
  2. Admit the processing job before opening its download connection.
  3. Stream the download into its workspace, enforcing a byte limit.
  4. Run the local conversion with a deadline.
  5. Validate and publish the output to application-owned durable storage.
  6. Exit the workspace context, including on exceptions.

Publication means making a validated artifact available outside disposable storage. Do not save a workspace filename in your database as a permanent asset location. Never return that path to another worker and assume it survives the context manager.

How do you implement bounded downloads and ffmpeg cleanup?

Use tempfile.TemporaryDirectory as a context manager around downloading, conversion, and publication, with explicit subprocess and file-size limits.

Save this first snippet as video_workspace.py. It uses Python's standard library; running the default conversion additionally requires an installed ffmpeg executable. The source argument is an already-open binary stream, not a URL, so download authentication and transport policy stay outside the example.

import os
import shutil
import subprocess
import tempfile
import threading
from pathlib import Path

MAX_INPUT = 64 * 1024 * 1024
MAX_OUTPUT = 96 * 1024 * 1024
SLOTS = threading.BoundedSemaphore(2)


def copy_bounded(source, target, limit):
    total = 0
    while True:
        block = source.read(min(1024 * 1024, limit - total + 1))
        if not block:
            return total
        total += len(block)
        if total > limit:
            raise ValueError("input exceeds byte limit")
        target.write(block)


def ffmpeg_command(source, output):
    return [
        "ffmpeg", "-nostdin", "-hide_banner", "-loglevel", "error",
        "-y", "-i", str(source), "-map", "0:v:0", "-an",
        "-c:v", "libx264", "-pix_fmt", "yuv420p",
        "-movflags", "+faststart", "-fs", str(MAX_OUTPUT), str(output),
    ]


def process_video(source, root, destination, *,
                  command=ffmpeg_command, timeout=120):
    # root and destination are trusted application configuration.
    root = Path(root)
    destination = Path(destination)
    if root.is_symlink() or not root.is_dir():
        raise ValueError("scratch root must be an existing real directory")
    root = root.resolve(strict=True)
    parent = destination.parent.resolve(strict=True)
    if parent == root or root in parent.parents:
        raise ValueError("publication must be outside the scratch root")
    destination = parent / destination.name
    if not SLOTS.acquire(blocking=False):
        raise RuntimeError("processing capacity exhausted")
    try:
        with tempfile.TemporaryDirectory(prefix="video-job-", dir=root) as job:
            workspace = Path(job)
            incoming = workspace / "input.bin"
            output = workspace / "output.mp4"
            with incoming.open("xb") as target:
                if copy_bounded(source, target, MAX_INPUT) == 0:
                    raise ValueError("empty input")
            subprocess.run(
                command(incoming, output),
                check=True, timeout=timeout, shell=False,
                stdin=subprocess.DEVNULL,
                stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
            )
            if output.is_symlink() or not output.is_file():
                raise ValueError("missing regular output")
            if not 0 < output.stat().st_size <= MAX_OUTPUT:
                raise ValueError("invalid output size")
            # Stage on the destination filesystem for atomic replacement.
            stage = None
            try:
                with tempfile.NamedTemporaryFile(
                    dir=parent, prefix=".publish-", delete=False
                ) as target:
                    stage = Path(target.name)
                    with output.open("rb") as result:
                        shutil.copyfileobj(result, target)
                os.replace(stage, destination)
            finally:
                if stage is not None:
                    stage.unlink(missing_ok=True)
            return destination
    finally:
        SLOTS.release()

TemporaryDirectory removes its contents after a conversion failure, timeout, or publication exception during normal Python unwinding. shell=False passes a list of arguments directly to the executable; it does not interpret uploaded names as shell commands. The fixed workspace filenames avoid introducing request-controlled paths.

The command factory is a trusted testing hook, never an API parameter. The destination also needs an application-generated identifier, authorization checks, and a trusted parent directory. This example atomically replaces an existing destination; choose unique object names if overwriting would violate your product's semantics.

Which limits prevent workers from exhausting their disks?

Combine byte limits, processing admission, conversion deadlines, and filesystem quotas; concurrency limits alone cannot bound disk usage.

The sample allows two simultaneous conversions per Python process, caps downloaded input at 64 MiB, and checks output against 96 MiB. These are illustrative application settings, not GenRelay limits. Across four worker processes, the local semaphore would allow eight simultaneous jobs unless you coordinate admission externally.

ffmpeg -fs is not a filesystem quota: output can exceed its requested threshold slightly, and a truncated artifact can still fail validation. The post-process size check rejects oversized files but cannot prevent an earlier disk-full event. Use a dedicated quota-limited scratch volume or container storage limit as the hard boundary. Reserve space for staging, conversion intermediates, logs, and other tenants; free-space checks are advisory because concurrent writers race.

For HTTP downloads, enforce a connect timeout, read timeout, and total wall-clock deadline. Count bytes actually written rather than trusting Content-Length. Permit result URLs through an application-controlled network policy, including redirect checks, so arbitrary URLs cannot reach internal services. Acquire capacity before opening the network stream; close the stream on every outcome.

The subprocess deadline covers the direct converter. If your command launches grandchildren, use process-group supervision or container termination to stop the whole workload. A deadline also does not constrain memory or CPU consumption; configure those limits separately for media parsers handling untrusted input.

How can you test cleanup without generating a real video?

Inject a fake converter launched through sys.executable, then assert that success and failure leave the scratch root empty.

Save this second snippet beside the first as test_video_workspace.py and run python -m unittest -v test_video_workspace.py. It needs neither generation credentials nor ffmpeg. The fake bytes test orchestration, not video validity or codec compatibility.

import io
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
import video_workspace as video


class WorkspaceTests(unittest.TestCase):
    def test_cleanup_and_publication(self):
        with tempfile.TemporaryDirectory() as base:
            root = Path(base) / "scratch"
            root.mkdir(mode=0o700)
            destination = Path(base) / "published.mp4"

            def command(script):
                return lambda source, output: [
                    sys.executable, "-c", script, str(output)
                ]

            cases = [
                ("success", "import pathlib,sys; "
                 "pathlib.Path(sys.argv[1]).write_bytes(b'fixture')",
                 None, 5),
                ("failure", "import sys; sys.exit(7)",
                 subprocess.CalledProcessError, 5),
                ("timeout", "import time; time.sleep(10)",
                 subprocess.TimeoutExpired, 0.1),
                ("missing", "pass", ValueError, 5),
                ("oversized", "import pathlib,sys; "
                 "pathlib.Path(sys.argv[1]).write_bytes(b'x'*33)",
                 ValueError, 5),
            ]
            with patch.object(video, "MAX_OUTPUT", 32):
                for name, script, error, deadline in cases:
                    with self.subTest(case=name):
                        destination.unlink(missing_ok=True)
                        if error:
                            with self.assertRaises(error):
                                video.process_video(
                                    io.BytesIO(b"input"), root, destination,
                                    command=command(script), timeout=deadline,
                                )
                            self.assertFalse(destination.exists())
                        else:
                            video.process_video(
                                io.BytesIO(b"input"), root, destination,
                                command=command(script), timeout=deadline,
                            )
                            self.assertEqual(destination.read_bytes(), b"fixture")
                        self.assertEqual(list(root.iterdir()), [])
                        self.assertEqual(list(Path(base).glob(".publish-*")), [])

            with patch.object(video, "MAX_INPUT", 3):
                with self.assertRaises(ValueError):
                    video.process_video(io.BytesIO(b"four"), root, destination)
            self.assertEqual(list(root.iterdir()), [])

            with patch.object(video, "SLOTS", __import__("threading").BoundedSemaphore(0)):
                with self.assertRaisesRegex(RuntimeError, "capacity"):
                    video.process_video(io.BytesIO(b"x"), root, destination)
            self.assertEqual(list(root.iterdir()), [])


if __name__ == "__main__":
    unittest.main()

Before deploying the real command, add an integration test using a small, known-valid video fixture and your deployed ffmpeg build. Check duration, dimensions, streams, and playback separately: a nonempty MP4 filename does not establish media validity. The output validation guide explains that boundary; the browser playback guide covers delivery compatibility.

How should a janitor handle files left after a crash?

A cleanup janitor should reclaim abandoned application-owned workspaces through coordinated ownership checks, not recursively delete arbitrary old paths.

A janitor is a background cleanup process. A lease is a time-limited claim that a job is still active, renewed by the processing worker. Normal context-manager cleanup cannot run after an abrupt process kill, machine loss, or power failure, so abandoned workspaces need separate recovery.

Record the job identifier, workspace identifier, lease expiry, and worker identity in trusted job state. Directory modification time is insufficient: a long transcode may be active without changing directory entries. Before reclaiming anything, confirm that the job is terminal or its lease has expired, then acquire an exclusive cleanup claim through the same coordination mechanism workers use.

Prevent a paused worker from resuming writes after reclamation, using worker termination or a fencing token—an ownership version that storage operations must validate. A grace period reduces accidental deletion but is not mutual exclusion. For simpler deployments, cleaning a dedicated scratch volume after its worker is confirmed stopped can be safer than concurrent reclamation.

Restrict candidates to registered immediate children of the dedicated root. Reject symlinks, never follow links into other directories, and never feed a request-provided path into recursive deletion. Path checks alone cannot resolve hostile concurrent path replacement; use service-exclusive directory permissions and platform-appropriate descriptor-based operations. Publication staging files require their own ownership-aware recovery policy too.

What do developers ask about temporary video files?

The common questions concern lifetime, cleanup guarantees, and where application responsibilities begin.

Does Python delete temporary files after every worker crash?

No. Context managers clean up during normal exit and exception unwinding, not after every abrupt termination. Use coordinated crash recovery for abandoned workspaces.

Can I put the scratch directory on a memory-backed filesystem?

Yes, if its capacity and memory accounting fit your workload. Memory-backed storage moves pressure from disk to memory; it does not eliminate byte limits or admission control.

Should I keep generated downloads for debugging?

Retain selected artifacts in a separate access-controlled store with an explicit retention policy. Do not disable scratch cleanup globally, and avoid logging signed URLs or user media contents.

Does deleting local scratch remove the provider's hosted result?

No. Application filesystem cleanup and hosted-result retention are separate concerns. Consult the documented API behavior for hosted assets; this tutorial makes no provider-side deletion or retention claim.

Related posts

Join our DiscordAI Video API Temporary Files: A Python Cleanup Tutorial — GenRelay