pysox developer on retainer: Transformer.build() with identical input and output path truncates input file before reading — SoX exits with code 0 — all 50 000 audio files per month replaced with 0-byte WAV — no runtime error — 3 weeks — pysox developer on monthly retainer
pysox 1.4.2 • Python 3.9 • SoX 14.4.2; Transformer.build(input_fp, input_fp) same input and output path; SoX truncates output file (= input file) to 0 bytes before reading; processes 0 samples; writes 44-byte WAV header; exitcode 0; pysox raises no exception; • Westfield Pysox Ltd. (audio normalisation pipeline; 50,000 WAV files/month; all files replaced with 0-byte headers; no error logged; 3 weeks; fix: temp file + os.replace(); 2.0h retainer engagement)
Westfield Pysox Ltd. built an audio normalisation pipeline that pre-processed podcast recordings before ingesting them into a speech recognition training system. The pipeline applied peak normalisation to −3 dBFS and resampled to 16 000 Hz using pysox 1.4.2. Because the processed files were intended to replace the originals in the same directory structure, the developer passed the input filepath as the output filepath: tfm.build(fp, fp) for each of the 50,000 WAV files processed per month. The pipeline ran without raising any exception, logged no errors, and appeared to complete successfully. Three weeks after the pipeline went to production, the downstream ASR model training job failed on a spot-check batch that explicitly validated frame counts: soundfile.LibsndfileError: ‘Error opening file: No data in file’. All 50,000 files in the processed directory had been replaced with 44-byte WAV headers containing zero audio samples, and the original unprocessed recordings had been permanently overwritten with no backup in place.
pysox 1.4.2 Transformer.build(input_filepath, output_filepath) constructs a SoX command of the form sox input_filepath [effects] output_filepath and executes it via subprocess.run(). SoX’s standard processing model opens the output file for writing before it opens the input file for reading: the output file is created (or truncated if it already exists) at the start of execution, so that SoX can begin writing the WAV header and stream output samples incrementally. When input_filepath and output_filepath are the same filesystem path, the output-open step truncates the file to 0 bytes before SoX reads a single audio sample. SoX then opens the now-empty file as the input, reads 0 bytes of audio data, processes 0 samples through the effect chain (norm -3 and rate 16000), and writes a WAV file containing only the 44-byte standard WAV header with NumSamples=0. SoX exits with code 0 because it has successfully executed every effect against an empty input stream — no effect in the chain produced an error. pysox receives the subprocess return code 0, checks for SoxError (none raised), and returns None normally. The calling loop logs nothing anomalous, increments its processed-file counter, and moves to the next file. The 44-byte output files are valid WAV files in the sense that they have a correctly-formed header; soundfile.info(fp) opens them without error and returns a valid SoundFileInfo object with frames=0 and samplerate=16000. Only a check of info.frames would reveal the problem — and no such check existed in the pipeline.
The annotated buggy and fixed pysox normalisation pipeline, with safe in-place update and post-build validation:
# Westfield Pysox Ltd. — pysox 1.4.2 in-place build() fix
# pysox 1.4.2; Python 3.9; SoX 14.4.2
# Audio normalisation pipeline; 50,000 WAV files/month
#
# Problem: Transformer.build(input_fp, input_fp) — same input and output path
# SoX opens output for writing (truncates file to 0 bytes) before reading
# SoX reads 0 bytes from truncated input; writes 44-byte WAV header
# exitcode 0; pysox raises no exception; file = 44-byte 0-sample WAV
# 50,000 files corrupted; original recordings permanently overwritten
# Fix: write to .tmp path; validate frames > 0; os.replace() atomically
import os
import tempfile
import pathlib
import soundfile as sf
import pysox
def make_transformer() -> pysox.Transformer:
tfm = pysox.Transformer()
tfm.norm(-3.0)
tfm.rate(16000)
return tfm
# ── BUGGY in-place normalisation ───────────────────────────────────────────────
def normalise_inplace_buggy(filepath: str) -> None:
"""Normalise a WAV file in-place — BUGGY: same input and output path."""
tfm = make_transformer()
# BUG: input_fp == output_fp
# SoX truncates filepath to 0 bytes before reading
# Processes 0 samples; writes 44-byte header; exitcode 0; no exception
tfm.build(filepath, filepath)
# NOTE: file is now 44 bytes; soundfile.info(filepath).frames == 0
# No error raised; calling code believes processing succeeded
# ── FIXED in-place normalisation ────────────────────────────────────────────────
def normalise_inplace_fixed(filepath: str) -> None:
"""Normalise a WAV file in-place — FIXED: temp file + atomic rename."""
# Safety guard: prevent accidental in-place build at call site
filepath = str(pathlib.Path(filepath).resolve())
# Write to a sibling temp file in the same directory
# (same filesystem = rename is atomic; avoids cross-device rename failure)
dir_path = os.path.dirname(filepath)
with tempfile.NamedTemporaryFile(
dir=dir_path, suffix='.tmp.wav', delete=False
) as tmp_f:
tmp_path = tmp_f.name
try:
tfm = make_transformer()
# FIX: distinct input and output paths
tfm.build(filepath, tmp_path)
# Validate output before committing
info = sf.info(tmp_path)
if info.frames == 0:
raise RuntimeError(
f"pysox produced 0-frame output for {filepath}. "
"Check that input_filepath != output_filepath and that "
"the input file is not empty or corrupt."
)
expected_sr = 16000
if info.samplerate != expected_sr:
raise RuntimeError(
f"Output sample rate {info.samplerate} != {expected_sr} "
f"for {filepath}. Check tfm.rate({expected_sr}) is in effect chain."
)
# Atomic replace: original is overwritten only if output is valid
os.replace(tmp_path, filepath)
except Exception:
# Clean up temp file on any failure; original file is untouched
if os.path.exists(tmp_path):
os.unlink(tmp_path)
raise
def normalise_batch_fixed(filepaths: list) -> dict:
"""Normalise a list of WAV files safely; return per-file status."""
results = {}
for fp in filepaths:
try:
# Guard: reject in-place path at the batch level
if not os.path.isfile(fp):
results[fp] = 'error: file not found'
continue
pre_frames = sf.info(fp).frames
normalise_inplace_fixed(fp)
post_frames = sf.info(fp).frames
assert post_frames == pre_frames, (
f"Frame count changed: {pre_frames} -> {post_frames}. "
"Duration must not change under norm() + rate(original_sr)."
)
results[fp] = 'ok'
except Exception as exc:
results[fp] = f'error: {exc}'
return results
How in-place build(fp, fp), SoX’s write-before-read file model, a missing post-build frame check, and an absent backup combine to silently destroy 3 weeks of podcast audio — and the correct pysox pattern for safe in-place normalisation
The core failure is a combination of four independent gaps: in-place paths are not prohibited by the pysox API (no exception, no warning, no documentation note in the build() docstring); SoX’s standard I/O model truncates the output file at open time for all formats, which is the correct behaviour for distinct input/output paths but becomes catastrophic when they are the same; the pipeline logged only the pysox return value (always None) and not the output file size or frame count; and the processed files were written back to the same directory as the originals with no backup. Any one of these gaps fixed independently would have prevented or immediately detected the corruption: a post-build check of soundfile.info(output_fp).frames > 0 would catch the truncation on the first file; a filesystem snapshot before the pipeline runs would allow recovery; pysox raising a warning (or the developer asserting input_fp != output_fp) would prevent the truncation. The safe pattern is to write to a sibling temp file in the same directory and then use os.replace(tmp_path, original_path) to atomically commit the update: on POSIX filesystems, os.replace() is a rename syscall that is atomic and instantaneous, so at no point is the original file absent or partially overwritten. If pysox.build() fails or the output is 0 frames, the original file at original_path is left untouched and the temp file is cleaned up in the except block. The recovery effort was substantial: 50,000 files corrupted across 3 weeks had to be re-requested from 20 podcast production studios, some of which no longer had the original recordings. Five studios could only provide re-encoded MP3 instead of the original lossless WAV. The retainer engagement was 2.0h: 0.5h triage (soundfile.info(fp).frames == 0 for all 50,000 files; WAV header 44 bytes; trace to build(fp, fp)); 0.5h root cause (SoX truncates output at open; exits 0; pysox no exception; temp-file-and-rename pattern); 0.5h fix (temp path + os.replace(); post-build frames > 0 assertion; assert input_fp != output_fp guard); 0.5h validation (100-file test run; frames preserved; RMS at −3 dBFS; 2.0h total). Hours logged to HourTab with per-session breakdown.
Related retainer posts
- pysndfx developer on retainer — pysndfx 0.3.0; Python 3.9; Docker python:3.9-slim; podcast post-production; 15,000 segments/month;
AudioEffectsChain()callssubprocess.run(['sox', ...]); slim image missing sox binary;FileNotFoundErrorswallowed; fix:RUN apt-get install -y sox— 1.5h - pesq developer on retainer — pesq 0.0.4; Python 3.9; voice call QA; 25,000 recordings/month; 44100 Hz raises
BadSamplingRateError; broad handler returns 4.5; 100% pass; fix:scipy.signal.resample_poly→ 16000 Hz — 2.0h - nnresample developer on retainer — nnresample 0.0.3; Python 3.9; podcast search indexing; 30,000 segments/month; stereo input raises
ValueError; fallback returns 44100 Hz labeled as 22050 Hz; fix:.mean(axis=1)— 1.5h
Track retainer hours without a client portal
HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.
See pricing →