AI Video API Atomic File Writes: A Python Ingestion Tutorial
A worker downloads a completed video directly into ready.mp4, crashes halfway through, and leaves a filename that another process considers publishable. AI video API atomic file writes prevent that partially written destination from becoming visible: stage bytes privately, validate them, then replace the destination with one filesystem operation.
This API tutorial implements the application-owned ingestion boundary after generation has completed. For applications using the GenRelay video API, the examples accept an existing binary stream; they do not define provider endpoints, response fields, or download behavior. Both snippets run offline using synthetic bytes, without credentials or generation requests.
What does an atomic file write actually guarantee?
An atomic replacement makes the destination name switch from the previous file to the completed new file without exposing intermediate bytes through that name. Atomicity means observers see one completed namespace state or the other; durability means committed changes survive a crash under the filesystem and hardware's guarantees. They are different properties.
A reader that already opened the old file can continue reading that file after replacement. New opens resolve to the new destination. This is not a lock, a database transaction, or a guarantee that the content is playable.
Keep staging and destination on the same filesystem. Creating the temporary file in the destination's directory avoids a cross-filesystem move, which cannot supply this replacement contract. Use an application-controlled directory: the implementation below does not defend against another privileged process changing parent paths or manipulating the directory concurrently.
How should an ingestion worker order its operations?
Write and verify a private temporary file first, synchronize it, replace the destination, and then synchronize the containing directory where supported. This ordering separates incomplete staging data from a name eligible for publication.
Use these steps:
- Select a trusted destination and a positive byte ceiling.
- Create an unpredictable temporary filename in the destination directory.
- Read bounded chunks, count bytes, and compute SHA-256 incrementally.
- Reject empty input, excess bytes, or a supplied digest mismatch.
- Flush Python's buffer and synchronize the temporary file descriptor.
- Run any required media validation before promotion.
- Replace the destination with
os.replace. - Synchronize the parent directory, then record the application result.
SHA-256 is a cryptographic digest that identifies a byte sequence with a fixed-length value. A digest calculated during ingestion creates a baseline; comparing it with an independently trusted expected digest additionally detects disagreement. Neither proves playback quality. The checksum verification guide explains that distinction.
How can Python implement bounded atomic video ingestion?
Use a same-directory temporary file and make post-replacement synchronization failures distinguishable from failures that leave the destination unchanged. Save this complete standard-library implementation as atomic_video.py. It targets Python 3.9 or later and reads blocking binary streams whose read(n) returns at most n bytes.
import hashlib
import hmac
import os
from pathlib import Path
import tempfile
CHUNK = 1024 * 1024
class CommitUncertain(OSError):
"""Replacement happened, but directory synchronization failed."""
def __init__(self, result):
super().__init__("destination replaced; reconcile before retrying")
self.result = result
def sync_directory(parent):
if os.name != "posix":
return False
flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)
descriptor = os.open(parent, flags)
try:
os.fsync(descriptor)
finally:
os.close(descriptor)
return True
def ingest(source, destination, *, max_bytes, expected_sha256=None,
validate=None):
if not isinstance(max_bytes, int) or max_bytes <= 0:
raise ValueError("max_bytes must be a positive integer")
if expected_sha256 is not None:
expected_sha256 = expected_sha256.lower()
if (len(expected_sha256) != 64 or
any(c not in "0123456789abcdef" for c in expected_sha256)):
raise ValueError("expected_sha256 must be 64 hexadecimal digits")
destination = Path(destination).absolute()
parent = destination.parent
digest = hashlib.sha256()
total = 0
temporary = None
try:
with tempfile.NamedTemporaryFile(
mode="wb", dir=parent, prefix=".ingest-", suffix=".part",
delete=False
) as staged:
temporary = Path(staged.name)
while True:
# Read at most one byte beyond the ceiling to detect overflow.
block = source.read(min(CHUNK, max_bytes - total + 1))
if not isinstance(block, bytes):
raise TypeError("source must return bytes")
if not block:
break
if len(block) > max_bytes - total:
raise ValueError("asset exceeds byte ceiling")
staged.write(block)
digest.update(block)
total += len(block)
if total == 0:
raise ValueError("empty asset")
observed = digest.hexdigest()
if (expected_sha256 is not None and
not hmac.compare_digest(observed, expected_sha256)):
raise ValueError("digest mismatch")
staged.flush()
os.fsync(staged.fileno())
# The optional validator must inspect, never modify, the staged file.
if validate is not None:
validate(temporary)
result = {"path": str(destination), "bytes": total,
"sha256": observed, "directory_synced": False}
os.replace(temporary, destination)
temporary = None
try:
result["directory_synced"] = sync_directory(parent)
except OSError as error:
raise CommitUncertain(result) from error
return result
finally:
if temporary is not None:
temporary.unlink(missing_ok=True)
The parent directory must already exist. The returned dictionary is application metadata, not a GenRelay response. Private temporary permissions remain on the promoted file; configure delivery access deliberately rather than making staging files public.
The byte ceiling limits accepted output and temporary disk consumption. It does not impose a network timeout: the upstream stream must enforce connect/read deadlines, cancellation, and resource limits. The optional validator can reject container or decoding failures, but must not alter bytes after the digest is computed. Validate under separate CPU and time limits when processing untrusted media.
How do you test promotion without generating a video?
Run deterministic local unit tests that check successful replacement, rejection cleanup, source failures, and the ambiguous post-replacement failure state. Save the following as test_atomic_video.py beside the implementation and run python3 -m unittest -v test_atomic_video.py.
import hashlib
import io
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
from atomic_video import CommitUncertain, ingest
class BrokenStream:
def __init__(self):
self.first = True
def read(self, count):
if self.first:
self.first = False
return b"partial"[:count]
raise OSError("simulated interrupted read")
class AtomicVideoTests(unittest.TestCase):
def setUp(self):
self.directory = tempfile.TemporaryDirectory()
self.addCleanup(self.directory.cleanup)
self.root = Path(self.directory.name)
self.target = self.root / "ready.mp4"
self.target.write_bytes(b"previous complete artifact")
self.payload = b"synthetic-video-bytes" * 1000
def assert_clean(self):
self.assertEqual(list(self.root.glob(".ingest-*.part")), [])
def test_success(self):
expected = hashlib.sha256(self.payload).hexdigest()
with patch("atomic_video.sync_directory", return_value=True):
result = ingest(io.BytesIO(self.payload), self.target,
max_bytes=len(self.payload),
expected_sha256=expected)
self.assertEqual(self.target.read_bytes(), self.payload)
self.assertEqual(result["sha256"], expected)
self.assertEqual(result["bytes"], len(self.payload))
self.assertTrue(result["directory_synced"])
self.assert_clean()
def test_rejected_input_preserves_previous(self):
cases = [(b"", 100, None), (b"too long", 2, None),
(b"valid bytes", 100, "0" * 64)]
for payload, limit, expected in cases:
with self.subTest(payload=payload):
with self.assertRaises(ValueError):
ingest(io.BytesIO(payload), self.target,
max_bytes=limit, expected_sha256=expected)
self.assertEqual(self.target.read_bytes(),
b"previous complete artifact")
self.assert_clean()
def test_interrupted_read(self):
with self.assertRaises(OSError):
ingest(BrokenStream(), self.target, max_bytes=100)
self.assertEqual(self.target.read_bytes(),
b"previous complete artifact")
self.assert_clean()
def test_validator_rejection(self):
def reject(path):
self.assertEqual(path.read_bytes(), self.payload)
raise ValueError("media validation rejected")
with self.assertRaises(ValueError):
ingest(io.BytesIO(self.payload), self.target,
max_bytes=len(self.payload), validate=reject)
self.assertEqual(self.target.read_bytes(),
b"previous complete artifact")
self.assert_clean()
def test_directory_sync_failure_requires_reconciliation(self):
with patch("atomic_video.sync_directory",
side_effect=OSError("simulated sync failure")):
with self.assertRaises(CommitUncertain) as caught:
ingest(io.BytesIO(self.payload), self.target,
max_bytes=len(self.payload))
self.assertEqual(self.target.read_bytes(), self.payload)
self.assertEqual(caught.exception.result["bytes"], len(self.payload))
self.assert_clean()
if __name__ == "__main__":
unittest.main()
These tests use synthetic content because filesystem promotion does not require a playable MP4. The successful unit test mocks directory synchronization for portability; it does not claim to demonstrate power-loss durability. Add deployment-filesystem checks separately. Tests for media validation should use appropriate media fixtures and a resource-limited validator.
What do flush, fsync, and directory synchronization leave unresolved?
They improve persistence ordering but cannot provide a universal power-loss guarantee across operating systems, filesystems, mounts, and storage hardware. flush() moves Python-buffered data to the operating system; os.fsync() requests synchronization of the open file's data and relevant metadata.
On POSIX systems, synchronizing the containing directory addresses persistence of the replacement's directory entry. Some filesystems reject directory synchronization or implement different crash behavior. The function surfaces such errors after replacement as CommitUncertain, because deleting or blindly overwriting the destination at that point could destroy a completed asset.
On non-POSIX systems this example reports directory_synced=False; it does not implement an equivalent platform-specific durability protocol. Network filesystems and virtualized storage need their own documented guarantees and failure testing. Applications requiring stronger persistence must evaluate platform-specific synchronization mechanisms rather than interpreting a successful rename as proof against every hardware failure.
How should databases, orphan files, and concurrent writers be reconciled?
Treat file promotion and database publication as separate commits, then reconcile their gap explicitly. A database transaction cannot ordinarily commit a local filesystem rename atomically with its own row update.
Create an application ingestion record before writing, with an attempt identifier, intended destination, source artifact reference, and processing state. After promotion, store the observed length and digest, then transition the asset to ready. If the process dies between those operations, a reconciliation worker should examine the recorded destination and verify its bytes before completing the database transition.
An orphan is a file without a corresponding live application reference. Sweep stale .part files and unreferenced promoted artifacts after a retention window, but exclude active attempts through leases or ownership records. Age alone does not establish that a large ingestion has stopped. See the temporary files guide for staging lifecycle considerations.
Unique temporary names do not serialize destination writers: two successful replacements can still produce last-writer-wins behavior. Prefer unique immutable destinations per attempt, then use a database conditional update to choose the published artifact. A conditional update changes the row only if its expected state or version still matches. Losing attempts remain unpublished and become eligible for cleanup. Do not use an existence check followed by replacement as a no-overwrite lock.
Does retrying a local write create another generation charge?
Retrying ingestion of existing output does not itself request another generation. Keep generation submission, output retrieval, local processing, and publication as separate operations, with separate retry decisions.
The user-verified GenRelay Omni Flash prices are $0.10 per generation at 720P and $0.15 per generation at 1080P, explicitly not per second. Thus, 100 generations cost $10 or $15 respectively, excluding infrastructure, storage, transfer, and local processing costs.
After a write failure, recover from a retained source or retrieve the existing output when available. After CommitUncertain, reconcile the destination before retrying. Neither case means the application should automatically submit another generation, which may produce different content and incur another generation charge.
What questions arise when implementing atomic video ingestion?
Does os.replace prevent two workers from overwriting each other?
No. Replacement is atomic, not conditional. Use unique artifact paths plus database coordination, or an appropriately scoped locking protocol.
Can the temporary file live in the system temporary directory?
Not for this contract unless it is on the same filesystem. Creating it beside the destination avoids relying on that deployment assumption.
Is a successful SHA-256 comparison enough to publish a video?
No. It establishes agreement with expected bytes, not media validity, authorization, or database consistency. Complete those application checks before publication.
Should I delete the destination after directory fsync fails?
No. Replacement has already occurred. Record the uncertain state, inspect the destination, and reconcile it with the ingestion attempt instead of treating it as an absent file.