pysndfx developer on retainer: AudioEffectsChain() calls sox subprocess — sox absent in python:3.9-slim Docker — FileNotFoundError for all 15 000 audio segments — broad handler swallows error — segments delivered unprocessed 4 weeks — pysndfx developer on monthly retainer

pysndfx 0.3.0 • Python 3.9; AudioEffectsChain()(audio, sample_in=44100) calls subprocess.run(['sox', ...]) internally • Northfield Pysndfx Ltd. (podcast post-production automation; 15,000 audio segments/month from 300 studios; EQ + compression + loudness normalization; Docker base: python:3.9-slim — no sox; FileNotFoundError: [Errno 2] No such file or directory: 'sox' for every segment; broad except Exception: return audio swallows error; 15,000 segments delivered without effects for 4 weeks; mastering engineers: “loudness inconsistent, compression absent”; fix: RUN apt-get install -y sox + shutil.which('sox') startup check; 1.5h retainer engagement)

Northfield Pysndfx Ltd. built a podcast post-production automation service for independent podcast studios. Studios submitted raw MP3 and WAV recordings and received processed audio back, normalized to −16 LUFS (the podcast platform standard), equalized to cut low-mid mud and boost presence, and lightly compressed to even out dynamics across episodes. The service processed 15,000 audio segments per month from 300 studios. The effects pipeline used pysndfx 0.3.0, whose AudioEffectsChain API provided a fluent, Pythonic interface over SoX: (AudioEffectsChain().equalizer(300, 2.0, -6.0).equalizer(5000, 1.5, 3.0).compress(5, 2, 0.1, 0.5).norm(-16))(audio, sample_in=44100, sample_out=44100). The pipeline worked correctly in local development on macOS, where sox was installed via Homebrew, and in the staging environment, where the engineer had manually run apt-get install sox. The production Docker image was built from python:3.9-slim, the standard slim Debian base image for Python services, which the team chose for its small size (~50 MB vs ~900 MB for the full Debian image). The Dockerfile had no RUN apt-get install sox directive, because no one on the team remembered that pysndfx delegates all audio processing to the sox system binary via subprocess.

When AudioEffectsChain()(audio, sample_in=44100) was called in the production container, pysndfx generated a sox command string and called subprocess.run(['sox', ...], check=True). The operating system raised FileNotFoundError: [Errno 2] No such file or directory: 'sox' immediately. The effects chain call was wrapped in the production pipeline’s standard exception handler: except Exception as e: logger.error(f"Effects chain failed: {e}"); return audio. The FileNotFoundError was caught, logged to the application log at ERROR level, and the raw unprocessed audio was returned as the fallback value. The 15,000 segments per month were delivered to studios without any equalization, compression, or loudness normalization. Because the return value was a valid numpy array of the correct length, no downstream check detected the missing processing. Studios received audio that was identical to what they uploaded. The error log accumulated 15,000 lines of "Effects chain failed: [Errno 2] No such file or directory: 'sox'" per month, but the alert threshold for ERROR-level log entries had been set to 100 per hour (to avoid alert fatigue from an unrelated noisy service), and the sox errors appeared at a rate of roughly 20 per hour, below the threshold. After 4 weeks, 20 studios filed support tickets reporting that episodes uploaded after the deployment were significantly louder or quieter than earlier episodes, and that the compression that had previously smoothed out the dynamics of busy recording environments was no longer being applied. The engineering team investigated the pipeline and found the log entries.

The annotated buggy and fixed pysndfx deployment, with startup sox availability check and correct exception scoping:

# Northfield Pysndfx Ltd. — pysndfx 0.3.0 sox subprocess dependency fix
# pysndfx 0.3.0; Python 3.9; Docker python:3.9-slim
# 15,000 audio segments/month from 300 podcast studios
# Effects: equalizer (mud cut + presence boost) + compress + norm(-16 LUFS)
# Problem: AudioEffectsChain() calls subprocess.run(['sox', ...]) internally
#          python:3.9-slim does not include sox binary
#          FileNotFoundError raised for every segment
#          Broad except handler swallows error, returns raw audio
#          15,000 segments/month delivered unprocessed for 4 weeks
# Fix: RUN apt-get install -y sox in Dockerfile + shutil.which('sox') startup check

import shutil
import logging
import numpy as np
from pysndfx import AudioEffectsChain

logger = logging.getLogger(__name__)


# ── BUGGY pipeline ────────────────────────────────────────────────────────────

def process_segment_buggy(audio: np.ndarray, sr: int = 44100) -> np.ndarray:
    """
    BUG: AudioEffectsChain() calls subprocess.run(['sox', ...]) internally.
    python:3.9-slim Docker does not include sox binary.
    FileNotFoundError raised for every segment.
    Broad except handler catches FileNotFoundError and returns raw audio.
    15,000 segments/month delivered without EQ, compression, or normalization.
    Log fills with: "Effects chain failed: [Errno 2] No such file: 'sox'"
    Alert threshold not breached — 20 errors/hour, threshold 100/hour.
    4 weeks before studio tickets surface the issue.
    """
    try:
        fx = (
            AudioEffectsChain()
            .equalizer(300, 2.0, -6.0)    # -6 dB at 300 Hz, Q=2.0 (cut mud)
            .equalizer(5000, 1.5, 3.0)    # +3 dB at 5 kHz, Q=1.5 (presence)
            .compress(5, 2, 0.1, 0.5)     # gain 5 dB, ratio 2:1, 100ms/500ms
            .norm(-16)                     # normalize to -16 LUFS
        )
        # BUG: calls subprocess.run(['sox', ...]) — sox not in python:3.9-slim
        return fx(audio, sample_in=sr, sample_out=sr)
    except Exception as e:
        # BUG: catches FileNotFoundError, logs it, and returns raw audio
        # Caller receives unprocessed audio — no way to distinguish from processed
        logger.error(f"Effects chain failed: {e}")
        return audio   # 15,000/month returned unprocessed, silently


# ── FIXED: Dockerfile ─────────────────────────────────────────────────────────
#
# Dockerfile — add before CMD:
#
#   RUN apt-get update && apt-get install -y --no-install-recommends sox \
#       && rm -rf /var/lib/apt/lists/*
#
# --no-install-recommends: avoids pulling optional sox plugins (saves ~40 MB)
# The core sox binary + libsox-fmt-base covers MP3, WAV, FLAC, OGG.
#
# Alpine Linux:
#   RUN apk add --no-cache sox
#
# macOS (local dev):
#   brew install sox


# ── FIXED: startup check ──────────────────────────────────────────────────────

def check_sox_at_startup() -> str:
    """
    Call once at application startup (before accepting traffic).
    Raises RuntimeError if sox is not on PATH — surfaces the missing
    dependency at deployment time, not silently at runtime.
    Returns the sox binary path for logging/diagnostics.
    """
    sox_path = shutil.which('sox')
    if sox_path is None:
        raise RuntimeError(
            "sox binary not found on PATH. "
            "pysndfx requires sox installed as a system binary. "
            "Fix options:\n"
            "  Docker (Debian): RUN apt-get update && apt-get install -y sox\n"
            "  Docker (Alpine): RUN apk add --no-cache sox\n"
            "  macOS: brew install sox\n"
            "  Ubuntu/Debian: sudo apt-get install -y sox\n"
            "python:3.9-slim and other slim base images do NOT include sox.\n"
            "The error surfaces only at AudioEffectsChain() call time — not at import."
        )
    return sox_path


# ── FIXED: processing function ────────────────────────────────────────────────

def process_segment_fixed(audio: np.ndarray, sr: int = 44100) -> np.ndarray:
    """
    FIX: sox is now installed in Docker image (see Dockerfile above).
    Startup check confirms sox is on PATH before any traffic is accepted.
    No broad exception suppression — errors propagate and trigger alerts.
    """
    fx = (
        AudioEffectsChain()
        .equalizer(300, 2.0, -6.0)    # -6 dB at 300 Hz, Q=2.0: cut low-mid mud
        .equalizer(5000, 1.5, 3.0)    # +3 dB at 5 kHz, Q=1.5: presence boost
        .compress(5, 2, 0.1, 0.5)     # gain=5 dB, ratio=2:1, attack=100ms, release=500ms
        .norm(-16)                     # EBU R128 loudness: -16 LUFS (podcast standard)
    )
    # No broad except — if sox fails, the error propagates and pages on-call
    processed = fx(audio, sample_in=sr, sample_out=sr)
    return processed


# ── Application entry point ───────────────────────────────────────────────────

def startup():
    sox_path = check_sox_at_startup()
    logger.info(f"sox found at {sox_path} — AudioEffectsChain ready")


# ── Sox version reference ─────────────────────────────────────────────────────
# sox 14.4.2 (Debian stable as of 2024) supports all effects used here.
# Check installed version: subprocess.run(['sox', '--version'], capture_output=True)
# AudioEffectsChain effect → sox command mapping:
#   .equalizer(freq, q, db)      → 'equalizer {freq} {q}q {db}'
#   .compress(gain, ratio, a, r) → 'compand {a},{r} 6:-70,-60,-{ratio} -{gain}'
#   .norm(db)                    → 'norm {db}'
#   .rate(sr)                    → 'rate {sr}'
#   .channels(n)                 → 'channels {n}'

How pysndfx’s subprocess architecture, the absence of an import-time sox check, and broad exception handlers combine to silently bypass audio processing in production Docker deployments — and the correct pattern for pysndfx deployments

pysndfx defers all audio processing to the sox system binary via subprocess because SoX is a mature, battle-tested audio processing tool with a wide range of effects and format support that would take years to reimplement in pure Python. The design decision means pysndfx has no native C audio processing code of its own — it is a command generator and subprocess orchestrator. The consequence is that pysndfx has a runtime system dependency that is invisible at import time. from pysndfx import AudioEffectsChain succeeds regardless of whether sox is installed, because the import only loads the Python module, not the subprocess. The FileNotFoundError appears only when the chain is applied to audio — precisely the moment when a 15,000-segment/month production pipeline is in full operation. This latency between dependency installation and dependency use is the structural reason the failure lasted 4 weeks: the deployment appeared to succeed (Docker build green, container started, health checks passed), and the first indication of the problem was a signal from downstream users (studios noticing inconsistent loudness) rather than an operational alert. The shutil.which('sox') startup check eliminates this latency by converting a silent runtime failure into an explicit startup failure. When the startup check raises RuntimeError, the container fails its readiness probe, the deployment rolls back, and the error is surfaced within seconds of the deployment attempt rather than 4 weeks later. The second structural contributor was the broad except Exception handler. Exception handlers that return a default value for any exception type conflate recoverable errors (a single corrupt audio file) with unrecoverable errors (a missing system binary affecting 100% of files). The correct exception scope for pysndfx calls is to catch only format-specific errors that sox returns as non-zero exit codes (which pysndfx surfaces as subprocess.CalledProcessError with stderr describing the specific file issue), not FileNotFoundError, which always indicates a missing binary and should always propagate. The retainer engagement was 1.5h: 0.5h triage (retrieve logs: 15,000 × “Effects chain failed: [Errno 2] No such file or directory: 'sox'”; confirm FileNotFoundError is sox-not-found by checking subprocess.run(['sox', '--version'], capture_output=True) in the production container — FileNotFoundError; confirm python:3.9-slim does not include sox); 0.25h root cause (pysndfx 0.3.0 AudioEffectsChain confirmed to call subprocess.run(['sox', ...]) via source inspection; python:3.9-slim confirmed to not include sox via apt-cache show sox: “N: Unable to locate package sox”); 0.5h fix (add RUN apt-get update && apt-get install -y --no-install-recommends sox to Dockerfile; add check_sox_at_startup() to application entry point; remove broad exception suppression from effects chain call); 0.25h validation (100-segment test: output LUFS −16.0 ± 0.4 dB confirmed via pyloudnorm; EQ applied confirmed by spectral comparison; compression confirmed by dynamic range measurement; 1.5h total). Hours logged to HourTab with per-session breakdown.

Related retainer posts


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 →