Reliability Practices for Agent-Based Batch Delivery
Batch file jobs fail on skipped rows, rewritten extensions, non-resumable downloads, and dirty output folders—not on writing a loop. This article shows how to turn those jobs into checkable contracts, isolate agent execution from independent verification, and iterate only when metrics actually improve.
Batch file work is often treated as simple repetition: read a table, download media, rename by a rule. Anyone who has shipped it knows the real failures are missing files, rewritten extensions, interrupted runs that cannot resume, and delivery folders mixed with scripts and copies. Agents can automate these flows. Whether they “self-iterate” is not a feeling. It is whether they turn failures into repeatable acceptance criteria and close those gaps on the next run.
Write the job as an acceptance card
Vague instructions produce vague results. A batch job should state at least five things.
- Data scope: which columns exist, which rows must be processed, which may be skipped. Example: process only rows with a non-empty media URL; empty URLs go on a skip list instead of vanishing.
- Naming contract: which fields form the target name, the separator, how illegal characters are replaced, and how collisions are handled. Write examples, not adjectives.
- Format fidelity: whether extension case must match the source URL. Lowercasing everything is a common default and can break downstream checks.
- Delivery boundary: what may appear in the output directory. If the contract is “media only,” scripts, logs, source-table copies, and temp shards do not belong in the product folder.
- Failure semantics: on timeout, 404, disk full, or name collision, roll back the batch, skip and record, or resume. Without this, “the run finished” is not “the job is correct.”
A usable card also gives an accounting formula: successes + explicit skips + failures = rows that should have been processed. If the three do not add up, the job is not done.
Why batch jobs fail in the details
Table-driven downloads hit several engineering issues at once.
URLs come from business systems. Extensions may mix case, and query strings may carry signatures. Splitting on the last dot or lowercasing before joining drops the original suffix. Names, IDs, and similar fields may contain spaces, slashes, or control characters and produce illegal paths if concatenated raw.
Downloads are not atomic. If a partial file uses the final name, the next run treats it as complete. Write to a temp name, verify size or checksum, then rename.
Concurrency speeds work and also amplifies rate limits and disk contention. Without backoff and a concurrency cap, the job stalls or saturates the origin. Retries must be idempotent: repeating a row should match running it once.
Delivery hygiene matters. Executors often drop scripts, intermediate CSVs, debug logs, and finished files in one folder. The videos may be present; the process still needs a human cleanup. Downstream, that is still incomplete.
What agents are good for—and what not to trust blindly
A sound split: people define contracts and acceptance; the agent generates and runs the processor; a separate check reviews results. Agents quickly turn rules into runnable steps and can patch scripts from errors. They also treat exit code 0 as success and will not notice three missing files or extra copies in the folder.
Self-iteration is not model weights evolving mid-job. It is a constrained loop:
- Plan: split the card into read, filter, download, name, verify, clean.
- Execute: run in an isolated directory with limited network targets and write paths.
- Observe: record per-source status, HTTP result, byte count, final path.
- Accept: check counts, names, and directory contents with logic separate from the runner.
- Correct: change only what failed acceptance, then re-run full or incremental work. Do not declare “fixed” in chat.
Retrying without independent acceptance is luck. Multi-round fixes behind an acceptance gate are engineering.
A conservative execution structure
The following neutral pseudocode shows the structure: a manifest, temp files, and post-run reconciliation. It is not tied to a framework.
import csv, hashlib, os, tempfilefrom pathlib import Pathfrom urllib.parse import urlparsedef ext_from_url(url: str) -> str:name = os.path.basename(urlparse(url).path)return Path(name).suffix # keep original case, e.g. .mp4 / .MOVdef safe_part(text: str) -> str:bad = '\\/:*?"<>|\n\r\t'return "".join("_" if c in bad else c for c in text).strip()def process(rows, dest: Path, allowed_hosts: set[str]):dest.mkdir(parents=True, exist_ok=True)staging = dest / ".staging"staging.mkdir(exist_ok=True)manifest = []for i, row in enumerate(rows):url = (row.get("media_url") or "").strip()if not url:manifest.append({"i": i, "status": "skipped"})continuehost = urlparse(url).hostname or ""if host not in allowed_hosts:manifest.append({"i": i, "status": "rejected"})continueext = ext_from_url(url)final_name = f"{safe_part(row['name'])}-{safe_part(row['id'])}{ext}"final_path = dest / final_nameif final_path.exists() and final_path.stat().st_size > 0:manifest.append({"i": i, "status": "exists", "path": final_name})continuetmp = Path(tempfile.mkstemp(dir=staging, suffix=".part")[1])# download(url, tmp): timeouts, limited retries, exponential backoffos.replace(tmp, final_path) # prefer atomic replace on the same filesystemmanifest.append({"i": i, "status": "ok", "path": final_name})(dest / ".staging").rmdir() if not any(staging.iterdir()) else Nonereturn manifest
Principles only: take the extension from the URL path, not a forced lowercase; replace illegal characters; download to a temp file first; skip existing non-empty files so runs can resume; use a host allowlist so the script does not follow arbitrary links. Checksums, a concurrency pool, and retry details belong to the runtime. Do not assume one request succeeds.
Do not mix the manifest with finished media. Prefer media in the delivery directory and the manifest, scripts, and source-table copy in a sibling working directory. If handover must be a single folder, delete or move work files after acceptance and scan the directory again.
Acceptance must be independent of the generator
The runner and the judge must not be the same unchecked logic. At minimum, automate:
- Counts: non-empty URL rows equal successes + already-exists + failures. Failures keep a reason.
- Names: recompute expected names with the same rules and compare sets with disk names, not just counts.
- Suffixes: sample or fully compare extension characters so case was not normalized.
- Integrity: size greater than zero; if the origin provides length or a checksum, compare item by item. Partial files fail.
- Purity: the delivery directory’s file set equals the manifest’s final paths.
- Idempotence: a second identical run must not create duplicates or rewrite already-verified content.
- Traceability: each failure maps to a source row for human repair, not only a total.
The agent may write the checker; the rules come from the task card. If it changes both download logic and acceptance, it can “accept” failure as success. Lock acceptance during iteration; allow only execution changes.
Privacy, permissions, and runtime bounds
Name and ID-like fields, plus face or authentication video, are sensitive. Being able to download in bulk does not mean full identifiers should appear in filenames. Safer practice: irreversible internal IDs in names, encrypted mapping tables with separate authorization; time-limited, host-limited links; a runtime account with write access only to the target directory; redacted logs that omit full IDs and signed URLs.
If an agent has shell and network access, restrict directories and allowed hosts. Do not let it copy the source table into the product folder or send it out “for debugging.” Keep secrets in the environment, not the script repo. After the job, clean temp dirs, browser caches, and retry shards.
These constraints are not extras. Once sensitive fields sit in paths, they spread through copy, pack, and object-storage sync. The delivery standard should say which fields may appear in paths.
How to tell an iteration actually improved
Compare two runs by metrics, not by smoother chat: fewer failures, zero accidental suffix rewrites, zero extra files in delivery, no side effects on replay. A round that fixes naming but introduces new misses is a regression, not “better overall.”
Archive each run’s manifest. That answers whether the agent self-iterates: yes, only if failures are structured, fixes are re-accepted, and the bar is not quietly lowered. No, if it explains in conversation and leaves an unreconciled directory.
Professional batch delivery means the recipient does not need another manual spot-check. Task cards, atomic writes, independent acceptance, a clean directory, and minimized sensitive data make the agent a reliable executor. Miss one, and it remains a script-writing assistant.
