Skip to content

Add batch-enrichment example - #25

Open
R4ph-t wants to merge 5 commits into
mainfrom
rt/batch-enrichment
Open

R4ph-t wants to merge 5 commits into
mainfrom
rt/batch-enrichment

Conversation

@R4ph-t

@R4ph-t R4ph-t commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

Summary

Adds batch-enrichment/: enrich every row of a CSV of companies (industry, size bucket, one-line summary) through the OpenAI Batch API, which costs 50% less than normal calls but can take up to 24 hours.

  • submit_batch(ctx, csv_url=None): reads the CSV (bundled companies.csv or a URL), holds back invalid rows, builds one /v1/responses request per row with a strict JSON schema, uploads the JSONL and creates the batch. Before creating, it looks for a batch with the same job_key (hash of rows + model + prompt version) in the batch metadata and reuses it.
  • wait_for_batch(ctx, batch_id): flex, timeout_seconds=86400. Checks the batch every BATCH_POLL_SECONDS (default 60) and sleeps in between, in one attempt. Errors while checking are logged and tried again on the next check.
  • collect_results(ctx, batch_id, csv_url=None): downloads the output and error files, validates every answer with pydantic, joins by custom_id, and returns enriched rows plus a failed list.
  • enrich_csv(ctx, csv_url=None): chains the three. max_retries=0, 24 h timeout.
  • client.py starts enrich_csv with start_task, then checks it with get_task_run.
  • Root README: table row and section 7.

Motivation

One of the 12 new examples. Trigger.dev (Smart Spreadsheet), Vercel (Lead Agent) and Inngest (CSV import) all ship CSV or lead enrichment. Nothing in Render's examples waits on a slow external job, and Render has no durable sleep, so the example has to show an honest way to wait for hours.

Design notes

How to wait: a sleep loop on flex, not "retry until done". Measured on Render with a throwaway probe workflow (deleted):

  • Sleep loop: a flex task that slept 10 min and made 20 HTTPS checks used 0.153 CPU-s and averaged 35 MB (cgroup counters). That's ≈ $0.0018/h at the published flex rates, or ≈ $0.04 for a 24 h wait.
  • Retry as poll (max_retries=30, wait_duration_ms=20000, backoff_scaling=1.0, raise until ready): 25 attempts (24 retries), then success. Each retry boots a fresh instance about 0.5 s before the code runs (pid 1 age 0.55 s, ~0.54 CPU-s of startup each), so nothing runs during the wait. But the API records each retry attempt as starting when the previous one failed (every retry attempt shows 20.7 s = 20 s wait + 0.7 s of code). The docs don't say whether that wait is billed.
  • max_retries=1000 and wait_duration_ms=86_400_000 both registered (version ready). The docs give no maximum.
  • A deploy of a new version mid-wait didn't interrupt the sleeping run.

Both cost cents. The sleep loop keeps the retry budget for real errors, doesn't show every check as a failed attempt, and a parent awaiting a retry-as-poll task still has an open attempt for the whole wait (status paused; the docs don't say whether a paused attempt is billed). The README has the comparison table.

24 h fit. OpenAI's only window is 24h and it returns partial results on expired, so the batch reaches a final status about when wait_for_batch would time out. If it runs past, enrich_csv times out. Rerunning with the same CSV reuses the batch via the job key, so nothing is paid for twice. That's also why client.py doesn't set a Render idempotency key: a key would hand back the failed run for 24 h instead of resuming.

Arguments stay small. Tasks pass the CSV URL and the batch ID, never rows (4 MB argument cap). enrich_csv returns rows inline; the README says to write to storage for big files.

Retries. submit_batch and collect_results 2× (safe: idempotent submit, read-only collect), wait_for_batch 1×, enrich_csv 0. OpenAI client retries off. Errors a retry can't fix (missing key, unreadable CSV, OpenAI 400/401/403/404/422, batch failed validation) are returned.

Pins: render==1.11.0, openai==3.60.0, pydantic==2.14.4 (same as openai-agents-sdk). Default model gpt-6.2-sol (env OPENAI_MODEL); verified with the Batch API + strict json_schema.

Test plan (real results)

  • Clean venv from requirements.txt (Python 3.12), import OK.
  • render workflows dev --port 8440 --env-file <root .env>, enrich_csv with []: real batch batch_6b099280…, completed after 170 s waiting; 11 of 12 rows enriched, C-011 reported as Row has no company name. Sample: C-001 Manufacturing 51-200, C-004 Fintech 201-1000, C-008 Healthcare 1000+.
  • Rerun enrich_csv [] → reused_batch: true, waited_seconds: 1, same batch, no new batch.
  • ["https://example.com/does-not-exist.csv"] → {"error": "Could not read the CSV: HTTP Error 404: Not Found"}, no retries.
  • wait_for_batch / collect_results with batch_doesnotexist → returned OpenAI error 404.
  • No OPENAI_API_KEY → {"error": "OPENAI_API_KEY is not set"}.
  • OPENAI_MODEL=gpt-does-not-exist → batch fails validation; enrich_csv returns Batch failed validation with OpenAI's per-line model_not_found errors.
  • Template: RENDER_WORKFLOWS_TEMPLATES_PYTHON=<worktree> render workflows init --language python --template batch-enrichment …, followed the steps (port 8444, --env-file instead of pasting the key): enrich_csv [] completed, 11/12.
  • Render playground wfx-batch-enrichment-py: before the key was linked, enrich_csv [] → OPENAI_API_KEY is not set (run trn-08t4gdc4pbgbvdgeg009ba5s0).
  • Linked workflows-examples, released a new version. enrich_csv [] → reused the local batch, completed in 12 s (trn-08t4gdc4pkjqqovrg00c2jcs0).
  • Fresh batch on Render: enrich_csv with a 7-row CSV passed as a data: URL (so the job key differs) → batch batch_6b099a6e5514…, waited 121 s, 6 of 7 enriched, C-011 failed (trn-08t4gdc4pkqf2qerg00bsf4o0). Run tree: 4 runs, each 1 attempt, 0 retries.
  • WORKFLOW_SLUG=wfx-batch-enrichment-py python client.py against Render → Enriched 11 of 12 rows. The first TS client run exposed that a parent waiting on a chained run reports paused; both clients now wait until completed/failed/canceled (third commit) and were rerun green.
  • Cleanup: deleted wfx-batch-enrichment-py, wfx-batch-enrichment-ts and the probe workflow wfx-batch-enrichment-probe (all 204); deleted branch rt/batch-enrichment-probe.
  • Not hit by a real batch: per-request error lines and answers that fail validation (strict schema made all 11 valid). Those branches are covered by code review only.

Commits: Add batch-enrichment example, Add batch-enrichment to the root README, then batch-enrichment: wait through paused runs in the client Please squash-merge.

Risks and rollout

  • New folder only, plus root README lines (row/section number will conflict trivially with other open example PRs).
  • Costs: each run of the sample is one 11-request batch on the default model at batch pricing.
A run whose attempt is waiting on a chained run reports status paused, so the client now waits until the run is completed, failed or canceled. The README no longer claims a parent awaiting a retry-as-poll task keeps running; the docs only say its attempt is paused.
@R4ph-t
R4ph-t requested a review from a team November 27, 2026 15:04

@jacobprall jacobprall left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes. urllib.request.urlopen accepts file:// and ftp://, unlike fetch in the TypeScript version. The download is also uncapped.

Example PRs in this repo edit the root README table and will conflict if merged sequentially. The repo has no CI. Confirm default model IDs before publish.

Comment thread batch-enrichment/main.py Outdated
matter how big the CSV is (a run's arguments are capped at 4 MB).
"""
if csv_url:
with urllib.request.urlopen(csv_url, timeout=30) as resp:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

urllib.request.urlopen accepts file:// and ftp://. A caller-supplied csv_url such as file:///etc/passwd or file:///proc/self/environ is read, parsed as CSV, and sent to OpenAI.

The TypeScript version uses fetch(), which does not read file: URLs. Allow only http/https, as in product-image-import and ffmpeg-transcode. Cap the size, e.g. resp.read(MAX + 1), as in pdf-extraction.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9144448: csv_url must be http or https, including after redirects, and the download stops at 5 MB (MAX_CSV_BYTES). file://, ftp:// and oversized files come back as errors. The default model is gpt-6.2-sol, the same as the other examples, and set by OPENAI_MODEL.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed in 9144448: the scheme is checked on the URL and on redirects; the read is capped at MAX_CSV_BYTES (5 MB); invalid schemes and oversize downloads are returned as results.

urllib.request.urlopen also opens file:// and ftp:// URLs, so a csv_url
like file:///proc/self/environ would be read and sent to OpenAI. Allow
only http and https, including on redirects, and stop reading past
MAX_CSV_BYTES (5 MB).
@R4ph-t
R4ph-t requested a review from jacobprall November 30, 2026 13:20

@jacobprall jacobprall left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approve. 9144448 rejects non-http(s) CSV URLs, including after redirects, and caps the download at MAX_CSV_BYTES (5 MB). Invalid schemes and oversize files are returned as results.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants