Repository navigation
Conversation
emails.batch() sends a template or rendered content to many recipients, one email each. The client splits the recipients into requests of at most 100 recipients and 4 MiB of JSON, sends them one after another, and waits 45 seconds for each answer. Each recipient carries an idempotency key that every retry reuses. Each recipient gets a result: queued, failed, unconfirmed or not_attempted. A recipient whose answer was lost stays unconfirmed until a later answer queues it; a later refusal is kept as later_error. When a request fails as a whole, the batch stops, reads each unconfirmed email by its key, and raises EmailBatchError with every result. A 409 batch_unavailable is not retried. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SDK performance: posthog-pythonBenchmarks completed. No changes flagged for review. Flags require at least a 5% change in the median and all six pairs agreeing on direction. This is a noise filter, not proof of a performance change or a CI gate. View all results
Values are medians of paired measurements. Not flagged does not mean unchanged. Unavailable means a measurement could not be provided, not zero. Estimated allocation measurements retain their instrumentation uncertainty. RSS measures the whole process, not just SDK allocations; observed peaks are sampled checkpoints. Paired ranges in the diagnostics describe variability, not confidence intervals. Each shard uses its own runner; compare Before PR against With PR within a row, not across shards. Compared 102 metric rows; 102 rows shown in all results. Omitted or shortened data remain in |
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…feat/email-batch # Conflicts: # references/public_api_snapshot.txt
Factoring the template fields out for batches put to before template_id in a single template send's body. _template now returns its two values, so each body keeps its own key order. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
EmailBatchError now carries the warnings of the requests that went out, and logs them once. A field PostHog names inside a request maps back to the recipient's position in recipients. Every 404 from the batch route explains itself in why and fix, as the server's own 404 body has a code and detail. A code batch without content names batch(). Tests of the batch path guard one behaviour each. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…tdown A slot answered idempotency_key_in_flight may still be queued by the other request, so it reads unconfirmed, as delivery_unavailable does. A batch checks the client is still open before each later request and stops with client_closed, the rest not_attempted, instead of sending on a new session. The docs say to store keys for a batch that may be rerun. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The timeout tests answered after a set time and check that the batch still reads queued, instead of reading the transport's timeout argument. The shutdown and app-host tests replace the network layer instead of reaching into the client's session. The unconfirmed error docs name all three codes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…emails - Check that the client is still running before each retry of a batch request, so a retry after a 429 doesn't go out after shutdown. - Read a refused recipient's position only from ASCII digits, so an attr such as "recipients__²__to" keeps the batch results. - Say to send only the emails the batch didn't queue, with each recipient's idempotency_key, and that a rerun replays within 24 hours. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Check that the client still runs before each read by key after a lost answer, so a shutdown stops those reads too. The recipients stay unconfirmed. - Map a refused recipient's position only when it fits the chunk, so a huge decimal index can't make int() raise before the batch error. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rmed - a status read by key that reads failed keeps the recipient unconfirmed, since PostHog records a refused recipient as a failed email too - a whole-call 409 idempotency_key_in_flight leaves the chunk unconfirmed and reads it by key, as a lost answer does - 409 batch_unavailable is named validation_error, not concurrent_idempotent_requests Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… batch Match the cross-SDK batch contract: a status read by key fills in only the message ID and leaves the recipient unconfirmed, and the client reads every unconfirmed recipient without an ID when the batch ends, on success as on error. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…try as later_error Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… an in-flight later_error Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ause, and match in-flight only on 409 An unconfirmed recipient stays unconfirmed with its idempotency_key, and the caller resends with that key, which replays the email if it went out. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… and document a reused key's refusal Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…and note racing key reuse Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…confirmed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…d a 413 says to split Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
emails.batch now refuses more than 100 recipients before sending and sends the rest in one request. A server refusal, such as a 413 too_large, comes back as the error; the 413 fix says to split the recipients. The chunk loop, not_attempted, later_error, the 4 MiB sizing and the warnings on EmailBatchError are gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… error Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… send less, and date the resend window Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… lost answer as unconfirmed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…at a 400 gets no split advice Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…empty, and pin a shutdown after a 503 as unconfirmed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…through a later refusal, and use a real nested field Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… has no readable code Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
marandaneto
left a comment
There was a problem hiding this comment.
The code looks good; no qualifying findings. Verdict: correct.
💡 Motivation and Context
Sending the same email to up to 100 people now takes one call and one request:
emails.batch(recipients=[...], template_id=...), one email per recipient, withtemplate_dataper recipient for a template. Today a caller loops oversend, one request per recipient. The server route,POST /api/messaging/send/email_batch/, comes in PostHog/posthog#138258 and PostHog/posthog#138025, behindworkflows-email-batch-sends.Stacked on #1240 (
scheduled_at), since both changeposthog/emails.py.Impact
A batch replaces a loop of single sends for digests, invites and announcements, and keeps each recipient's result readable. The SDK carries no flag of its own; the server flag decides who can send batches, and a project without it answers 404, which the client names.
What changes
emails.batch()onEmailsandAsyncEmails, in the template form (template_id, sharedtemplate_data, per-recipienttemplate_data) and the code form (template_keyand the contentsendtakes). A batch takes nocc,bcc,attachmentsorscheduled_at; the client refuses them, a recipient withoutto, an unknown recipient field and two recipients with one key before any request, naming the recipient's position.ValueErrorbefore anything is sent. The SDK checks only the count: PostHog refuses a body it finds too large with 413content_too_large, which comes back asEmailBatchErrorwith PostHog's ownfix, "Split the recipients into smaller batches." (the SDK's fallback, when PostHog sends no usable fix text, says to split, or to send less data for a lone recipient). A 400content_too_largemeans the shared content or data is too large; itsmessagesays what to send less of, and it gets no split advice.idempotency_key, given or made by the client, that every retry reuses. A key must never be reused for another email: a send with an earlier email's key replays that email instead of sending this one, andBatchRecipient's docstring says so. Each attempt waits 45 seconds, or the client's timeout when longer, since the server waits up to 30 seconds on its email pipeline.queued,failedorunconfirmed, in the order ofrecipients, withmessage_id,replayedanderror.delivery_unavailable,idempotency_key_in_flightorapi_errorisunconfirmed, since PostHog may still queue it; any other slot error isfailed.unconfirmed: that attempt may have queued it. Theerroris the last answer.EmailBatchErrorwith every recipient's result:failedwith the request's error, orunconfirmedonce an attempt got no answer. A whole-call 409idempotency_key_in_flight, on a 409 only, leaves every recipientunconfirmed, since another request may still send them; so does a 409 whose body is lost or has no readable code, which may be that answer. The client reads nothing back after the POST: anunconfirmedrecipient keeps itsidempotency_key, and its error'sfixsays to send it again with the same key within 24 hours of the first request that used it, which replays the email if it went out and sends it once if it didn't.batch_unavailableis not retried, is namedvalidation_error, and itsfixsays to send each email withsend(). A 404, with or without PostHog's error body, says the template doesn't exist or batch sends are off for the project, with the samesend()fix.EmailBatchErrorclient_closed. The docs say to pass stored keys when a batch may be cut off and run again, so the rerun replays what went out.SendBatchResult.warningsand are logged once.No cross-SDK spec in PostHog/sdk-specs covers batch sends yet. The new public names (
emails.batch,BatchRecipient,BatchEmailResult,SendBatchResult,EmailBatchErrorand the three statuses) are open to the Python API review, and posthog-node should match them.Warning
🟡 Merge risk: medium, 🔴 at full rollout · two-way at merge, one-way door once released: the public names
emails.batch,BatchRecipient,BatchEmailResult,SendBatchResult,EmailBatchErrorand the three statusesbatchis new, no existing call changes, and the server flag is on for an internal project only. Once a maintainer approves the release,posthogandposthoganalyticson PyPI fix the names above, so the Python API review comes first.sendandgetkeep their request bytes, timeout and parse:_templateis factored out with the same key order, whichtest_a_template_send_keeps_its_request_bytespins, and onlybatchsets the new per-request timeout.htmlwithsubjectand atemplate_key) builds its own request body and runs on fakes only: no live run on either region.workflows-email-batch-sends, which answers 404 while off. None in the SDK: fix forward.sendandgetbatchAttributeErrorValueErrorbefore any requestbatchon a project without the flagAttributeErrorEmailBatchErrornot_found, no email sentbatchafter a lost answer, a 5xx or an in-flight slotAttributeErrorunconfirmedwith its key and says to resend with the same key; covered by fakes only, not on real Cloud. A caller who resends without the same key, or ignoresunconfirmed, gets a second email or nonebatchon Cloud US, template formAttributeErrorbatchon Cloud EUAttributeErrorbatchcode form, either regionAttributeErrorKnown issues
shutdown()can still reach the transport aftershutdown()returns: admission is a flag check andshutdown()doesn't wait for email work, as withsend()on main (_startthen the request). Reviewers rated it minor to blocker across reads. Closing it meansshutdown()waits for email calls in flight, for every email call, in its own PR.Rollout
failedin the server's email status rows, per project, through each flag stage; batch route 5xx, 409batch_unavailableand 404s from projects that should have the flag; and emails with the same template and recipient a few seconds apart, which would mean a resend without the stored key.💚 How did you test it?
Unit tests in
posthog/test/test_emails_batch.pythrough a fakerequestsadapter andhttpx.MockTransport: the request body of each form; refusals before any request, 101 recipients among them, sync and async; 100 recipients in one request, sync and async; a 413content_too_largeraised with PostHog'sfix, and the SDK's fallback to split or send less when PostHog sends none; a body over 4 MiB going out whole in one request; a 400content_too_largegetting no split advice; a 429 after a lost answer leaving every recipientunconfirmed; the per-attempt timeout; a lost answer or a 503 followed by a refused slot stayingunconfirmed; a whole-call 429, alone and after a 503; exhausted network errors leaving every recipientunconfirmedwith its key and no read, sync and async; 409batch_unavailablenot retried; a 404 without a code; an answer without a result per recipient; an error code that isn't text; a whole-call in-flight 409, alone, before a 429 and after a 503; a 409 with a lost body, a body that isn't JSON or a code that isn't text, leaving recipientsunconfirmed; and the in-flight code on another status; the last answer as theerrorafter three attempts; a successful batch with an unconfirmed slot sending nothing more, sync and async; warnings once; an in-flight slot stayingunconfirmed; a shutdown during a retry's wait, sync and async, and after a 503, leaving recipientsunconfirmed; everyunconfirmederror, whole-call or per recipient, carrying the same-keyfix; a disabled client and a custom host; and the async client. Locally:ruff format --check,ruff checkand the email tests pass; CI runs mypy with the baseline, the full pytest suite,make public_api_checkand.github/scripts/check_strict_types.sh.Live run on PostHog Cloud US, through this branch at the one-request head: 101 recipients raised
ValueErrorwith no request sent; a batch with 6 MiB of shared data got PostHog's 413content_too_largewith its own splitfix, and nothing went out; then one real batch of two recipients in the template form, with per-recipient values and keys, went out as one request. PostHog answered bothqueued, both status rows readdeliveredwithin two seconds, and both emails arrived, each with its own values.📝 Checklist
If releasing new changes
sampo addto generate a changeset file🤖 Agent context
Autonomy: Human-driven (agent-assisted)
Claude Code (Opus 5.5) wrote this test-first against the server PRs' request and answer shapes. Reviews run through a review panel; while Codex was down, its lenses ran on Claude.
unconfirmed, with the last answer as itserror; a laterqueuedsettles it. Rejected: trusting the later refusalunconfirmedrecipient keeps its key, and the caller resends with it, which replays the email if it went out. Rejected: reading each unconfirmed recipient by its key, which only filled in a message id and kept growing edge cases in review. Diverges from spec v8's lost-id reads; Node and Ruby drop them tooidempotency_key_in_flight, on a 409 only, leaves every recipientunconfirmed. Rejected:failed, since another request may still send themcontent_too_largecome back as the error. Rejected: splitting into requests of 100 recipients and 4 MiB, withnot_attemptedand results merged across requestsbatch_unavailablenamevalidation_error, as fortemplate_outdated: the server types itinvalid_request. Rejected: the spec's other-409 nameconcurrent_idempotent_requests, which the server never uses for itapi_error, the request's recipientsunconfirmed, not retried. Rejected: retrying it🤖 Generated with Claude Code
How did you test this code?
f34867e(reused from7e16914)aa54c41to74e8874f34867eEnd table: no gate at HEAD yet. Run hedge proof gate, then hedge proof receipt.
Not checked: none recorded
Full receipt: https://artifacts.posthog.com/a/MiWNOdCz6Yzzh3ncyaqx74