Repository navigation
Conversation
emails.batch sends a template made in PostHog, with template_data per recipient, or content your code rendered to up to 100 recipients and 4 MiB per request, one request after another, and returns a result per recipient in order. Each recipient has its own idempotency key, given or made by the client, that every retry reuses. After a lost answer, the client reads each email that may have gone out by its key. A request that fails as a whole stops the batch and raises EmailBatchError with every recipient's result. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
posthog-ruby-sync Compliance ReportDate: 2026-11-25T11:57:42.296792+00:00 ✅ All Tests Passed!47/47 tests passed Capture Tests✅ 30/30 tests passed View Details
Feature_Flags Tests✅ 17/17 tests passed View Details
|
posthog-ruby-async Compliance ReportDate: 2026-11-25T11:57:39.481261+00:00 ✅ All Tests Passed!47/47 tests passed Capture Tests✅ 30/30 tests passed View Details
Feature_Flags Tests✅ 17/17 tests passed View Details
|
SDK performance: posthog-ruby2 changes worth reviewing: 1 observed improvement, 1 observed regression. 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 |
…limits - a status read by key that reads failed keeps the recipient unconfirmed - a refused recipient's error carries no message ID - only the wait for a batch answer gets the 45 s floor - shared content over 4 MiB raises ArgumentError before any request - build each request body when it goes out - Ruby's keyword check refuses unknown batch arguments - the changeset says reruns replay only with stored keys Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…r recipient - a status read by key that reads failed keeps an earlier later_error, and its error has no message ID - shared content too large for a request fails each recipient with content_too_large again, as in Python and Node - specs pin the 4 MiB boundary to the byte and the three batch timeouts Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- the fix names the recipient's template_data or the batch's content, since a single send has its own size limit - a spec covers shared content too large for any request: every recipient fails with content_too_large, and no request goes out Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A request refused with idempotency_key_in_flight leaves its recipients unconfirmed, also after a later refusal. batch_unavailable keeps its code and is named a validation_error, not concurrent_idempotent_requests. The client reads by key every unconfirmed email without a message ID at the end of each batch, on success too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A status read by key marked the email queued on any status but failed, so an unreadable slot could turn queued on an archived read. It now adds the ID and keeps the email unconfirmed. The last retry's error stays each recipient's later_error again, and the 4 MiB split spec keeps each email under 1.5 MiB. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ler's deadline A 409 idempotency_key_in_flight is now the unconfirmed recipient's error, so a failed status read by key can give its reason as later_error. A caller's Timeout::Error deadline during a status read by key now propagates instead of ending the reads. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An unconfirmed recipient keeps its idempotency key and no message ID, and its error's fix says to send it again with the same key. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…e resend fix A retry that refuses an unconfirmed recipient no longer replaces the error that left it unconfirmed, an answer without a result per recipient is its only error, an in-flight refusal with an empty fix still says to resend with the same key, and a logger's reused exception names the failed batch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Takes #370's logger rule into the shared helper: a logger's error propagates when it has no cause or the call's error is among its causes, and an exception object it raised before becomes the cause of the call's error. Also records a retry's 5xx refusal as the later_error of a recipient an earlier attempt left unconfirmed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… refusal Merges the scheduled-send branch, so a failed send or batch no longer calls the logger and carries its warnings on EmailError#warnings. EmailBatchError takes the field from EmailError. A refusal under 500 now becomes the later_error of a recipient an earlier attempt may have queued as it arrives, so a final network error no longer drops it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
emails.batch now sends exactly one request. More than 100 recipients is a local ArgumentError before anything is sent. Server refusals, such as a 413 too_large, come back as the error for every recipient. The chunk loop, not_attempted, later_error and the cross-request sizing are gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…one out A 4xx refused the batch, so its recipients are failed, except a 409 for keys still in flight. No answer, a 5xx and an unreadable 2xx leave them unconfirmed whatever code the reply names. A 413 keeps PostHog's own content_too_large code. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…d it After a lost answer, a 5xx or a 409 for keys in flight, a refused retry can't confirm the recipients: they stay unconfirmed with the same-key advice, whether the retry refused the request or one recipient. The in-flight exception needs a 409. A 413 keeps PostHog's own fix, falls back to the advice to split, and maps an empty code to content_too_large. A 400 content_too_large stays as PostHog sent it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
client_closed means the client sent no retry, so on its own it says nothing about what PostHog queued: a 429 then a shutdown stays failed. A 413 keeps its code and split advice when PostHog's fields aren't text. The docs say a recipient's own oversized data comes back in its result, not as the whole-request 400. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A retry's refusal no longer reads as if no email was sent when an earlier attempt may have queued the batch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A 503 from PostHog that names client_closed may still have queued the batch, so its recipients stay unconfirmed. Only the error the client raises before a retry, which sends no request, says nothing about what PostHog queued. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s carry Also checks that a request error keeps its own message when that attempt alone may have queued the batch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When only an earlier attempt may have queued the batch, EmailBatchError itself now says so and carries the same-key fix, not the refusal's 'no email was sent'. A one-recipient batch refused by a 413 is told to make the email smaller, even when PostHog's reply advises a split. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ves no detail Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Also gives the changeset the advice for a one-recipient batch refused as too large. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
PostHog Review · Standard · reviewed 453ae70: 3 Should fix.
New pushes to this pull request won't start an automatic review. Comment @posthog review to review new changes.
See this review and its findings in PostHog Review. Comment @posthog review --deep for a Deep review. A Deep review takes longer and looks deeper than a Standard review.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A logger that raised a StandardError while logging an accepted batch's warnings lost the results and the derived keys, so a resend sent each email twice. An interrupt still propagates. A 409 without a readable body may be keys in flight, so its recipients stay unconfirmed with their keys. Only batch_unavailable says nothing went out. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The body was built from every recipient's JSON joined into a second string and copied into a third, and the recipients' JSON stayed live. It now copies each recipient into a buffer of the exact size and drops its JSON, so a retry holds only the body. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Timeout.timeout with Timeout::Error as its class raises it in the thread, so the logger rescue swallowed the caller's deadline. The overview also gives a batch of one recipient the advice to make the email smaller. 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
A Ruby app that sends the same transactional email to many people, such as a launch note or an invoice run, has to call
emails.sendonce per recipient. That means one request each, with its own retry and replay handling in the app.This PR adds
emails.batch, stacked on #370. It portsemails.batchfrom Python (PostHog/posthog-python#1291), the reference, and Node (PostHog/posthog-js#5847).Impact
Ruby apps send one email to many recipients in one call, with a result per recipient. The server's batch send event shows whether Ruby senders use it once batch sends are on.
Caution
🔴 Merge risk: high · one-way door once the gem is published:
emails.batch,Emails::BatchResult,Emails::BatchEmailResultandEmailBatchErrorbecome public APIemails.batch: new entry point. They send real emails to every recipient in one request, so a bug in keys or result mapping is silent harm: an email sent twice, or one reported as sent that wasn't. The specs cover it against WebMock. Live on PostHog Cloud US at HEAD: a batch of two with a same-key rerun, the 413 and 400 size refusals, and one key used by feat(emails): schedule a send with scheduled_at #370'semails.sendand this PR'semails.batch, each from its own checkout, in both orders, each returning the first call's message ID withreplayed: true.template_keywith rendered content), a batch where PostHog queues some recipients and refuses others, retries andunconfirmedrecipients (a 409 in flight or without a readable body, a 5xx, a lost answer), and a retry refused after an attempt that may have queued the batch. They run only against WebMock and the mutants; the recipients stayunconfirmedwith the same-key advice, and the message says when an earlier attempt may have queued them. A missed bug there reports an email that went out asfailed, and a rerun with a new key sends it twice.emails.send, its attachment uploads andemails.getkeep their waits. The shadow diff covers send and get; attachment uploads run only in the unchanged email specs.batch_unavailableis namedvalidation_errorfor every method, as in Python. The published spec's error table predates batch and names other 409sconcurrent_idempotent_requests;emails.sendandemails.getnever receivebatch_unavailable.EmailBatchError#warningsholds the reply's warnings. A logger that raises aStandardErrorafter a batch that went through doesn't lose the results; anInterruptor a caller'sTimeout::Errorstill propagates. Uncovered: a caller's own deadline of anotherStandardErrorclass, raised into the thread while the logger writes, is dropped, and the call returns its results.emails.sendandemails.get: unchanged. A stubbed shadow diff of 14 inputs against feat(emails): schedule a send with scheduled_at #370's head matches every request, result, error and log line, and the existing email specs pass unchanged.batch_unavailableor 404, and the SDK raisesEmailBatchErrorwith every recipientfailed, never sending one by one on its own. When an earlier attempt of the same call may have queued the batch, such as a 503 just before the switch went off, its recipients stayunconfirmedwith the same-key advice instead.Rollout
unconfirmed, as in the Elixir SDK (d-99642ec9). A failed batch never calls the logger and carries its warnings on the error (Michael, d-eb82aafc).What changes
emails.batch(recipients:, ...)takes the template form (template_id, sharedtemplate_data) or the code form (template_key,subject,htmlortext, and the optional sender and tracking fields), the same for every recipient.to, and optionallydistinct_id,idempotency_keyand, in the template form only,template_data, sent as the recipient'smessage_data.ArgumentErrorbefore any request, with the advice to split them. The client waits at least 45 seconds for the answer; connecting and writing keep the client's timeout.idempotency_keygets a UUID that every retry reuses. Two recipients with the same key raiseArgumentErrorbefore any request.emails.send: network errors, 429 and 503 retry with backoff, and the client stops retrying once it is shut down. The error is the last attempt's. Once an attempt may have queued the batch, a refused retry can't confirm it, so its recipients stayunconfirmed. ThenEmailBatchErrorand each recipient's error start their message by saying an earlier attempt may have queued the email, and carry the same-key fix. Only the client's own shutdown before a retry reads as no attempt; a 503 from PostHog that namesclient_closedstill may have queued it.BatchResult#resultshas oneBatchEmailResultper recipient, in order. Itsstatusis one of:queuedfailed: PostHog refused it, such as a suppressed address, or refused the whole requestunconfirmed: an answer was lost or PostHog didn't confirm it, also when a later retry refused it. Its error'sfixsays to send it again with the same key within 24 hours of the first request that used it, so it goes out once.unconfirmedemail keeps its key, and a message ID only when PostHog named one.EmailBatchError, whoseresultshold every recipient. The HTTP status decides, not the code: a 4xx refused them, so they arefailedwith it as their error, unless an earlier attempt may have queued them. A 409 other thanbatch_unavailable(idempotency_key_in_flight, or one without a readable body), a 5xx, a lost answer and a 2xx without a result for each recipient may have, so they leave themunconfirmedwith the same-key fix, whatever fix PostHog sent.content_too_largefor a batch too large to take at once, whose fix says to split the recipients into smaller batches (the SDK adds that advice when the reply has none; a batch of one recipient, which can't be split, always gets the advice to make the email smaller); 400content_too_largefor shared content over PostHog's limit, which splitting doesn't change (a recipient whose owntemplate_datais over it comes backfailedwithcontent_too_largein its result, while the others go out);batch_unavailable(409, never retried, namedvalidation_error) and 404 with the fix to send each email withemails.sendand its key, and the rest as PostHog names them. A field such asrecipients__7__tonames the recipient's place in the batch. The SDK checks only the recipient count, not the size of a request.EmailError#message_idstill means PostHog may have accepted the email.StandardErrorother thanTimeout::Errordoesn't lose its results. A failed batch never calls the logger:EmailBatchError#warnings, the same field asEmailError#warnings, holds the reply's warnings.cc,bcc,attachmentsorscheduled_at.Known issues
content_too_large, and nothing goes out. The caller splits it into smaller batches. Shared content over PostHog's limit fails with a 400content_too_large, and the caller makes it smaller.lib/posthog/emails.rb:409: a caller's deadline of a customStandardErrorclass, raised into the thread while the logger writes an accepted batch's warnings, is dropped, andemails.batchreturns the results.Interrupt,Timeout.timeoutandTimeout::Errorstill end the call.💚 How did you test it?
Test-first, in
spec/posthog/emails_batch_spec.rbagainst WebMock, on Ruby 3.2.2:message_dataper recipient, and the secret key as a Bearer tokenfailed; unconfirmed answers, unreadable slots and aqueuedslot without a message ID asunconfirmedwith their keys and no status readIOError, and anInterruptorTimeout::Errorfrom the logger propagatesfailedand the field PostHog namedcontent_too_largewith PostHog's fix or the advice to split, in one request; a one-recipient batch told to make the email smaller after a bare 413 and after PostHog's split fix; a 400content_too_largekept as PostHog sent it, without split advicebatch_unavailableand 404 with their fixesidempotency_key_in_flightwith an empty fix and with PostHog's own fix, and a 409 without a readable body, each leaving every recipientunconfirmedwith the same-key fixclient_closed, each leaving every recipientunconfirmedwith the error's own message; a 403 without a code, and one naming keys in flight, leaving themfailedunconfirmed, and after 429 and 400failedunconfirmedwith the same-key fix, and the batch error and each recipient's error saying an earlier attempt may have queued themclient.shutdownbefore a retry, leaving the recipientsunconfirmedwithclient_closedafter a 503, andfailedafter a 429Net::HTTP; no spec waits them outArgumentErrorbefore any request47 mutants of the batch code, one per behavior above, each fail a spec at the head; the log is saved with the proof.
bundle exec rubocopandbundle exec rake public_api:checkpass.Memory, measured with 100 recipients of 100 KB
template_data: building the request allocates 2x the body, down from 3x, and keeps 1x through the retries, down from 2x. The script and both runs are saved with the proof; the body specs check the bytes.Live, against PostHog Cloud US at this head, through an internal test template:
queuedin order with their keys, and the replay returned the same message IDs withreplayed: true. PostHog's status reads say both delivered.content_too_largewith the advice to make the email smaller in place of PostHog's split fix, the recipientfailed. Shared content over its limit: 400content_too_largewithout a fix, the recipientfailed.emails.sendand thenemails.batch, and another the other way round, in one checkout: each second call returned the first call's message ID, and each ID reads delivered. PostHog marked both second callsreplayed: falsethere, since the marker can lag a replay that follows at once; the docs now say so.emails.sendfrom feat(emails): schedule a send with scheduled_at #370's checkout (nobatchmethod) andemails.batchfrom this head, one key per order. Both orders returned the first call's message ID withreplayed: true, and both IDs read delivered.The mailbox was not checked at this head; at the two heads before, the same runs left one email per recipient and per key.
Shadow diff of the shared send path, #370's head against this head: the same 14 inputs through
emails.sendandemails.getagainst the same stubbed replies, from a plain send to a connection reset and an unconfirmed scheduled send with warnings. Every wire request, result, error and log line matches.📝 Checklist
If releasing new changes
pnpm changesetto generate a changeset file🤖 Agent context
Autonomy: Human-driven (agent-assisted)
Claude Code (Claude Opus 5.5,
claude-opus-5-5) wrote the code as one lane of the cross-SDK transactional email work, porting the Python batch and matching its error codes, retries, replay window and result shape.content_too_large, come back as the error. Replaced chunking into requests of 100 recipients and 4 MiB.unconfirmedwith the same-key advice, as in the Elixir SDK. Replaced: the last attempt deciding the status.EmailBatchError#warningscarries the warnings. Replaced the cause-chain handling of a raising logger.unconfirmedemail stays so with its key, to send again with it. Replaced reading each one by key at the end of the batch.template_data, sent asmessage_data. The server's batch recipient takes onlyto,distinct_id,idempotency_keyandmessage_data, as Python and Node send it. Rejected: a separate event body field the server refuses.idempotency_key_in_flightisunconfirmed, andbatch_unavailablekeeps its code with no retry. Rejected: Python's behavior on these.StandardErrorfrom the logger is dropped, and anInterruptor a caller'sTimeout::Errorpropagates. Replaced: its error propagating, which lost the results.unconfirmedwith their keys, since PostHog's only other 409 isbatch_unavailable. Rejected:failed.Involvement: no grilling rounds, no prototypes; one Hedge review panel, four Codex fixes reviews and seventeen Codex final reads, fourteen of them past the review budget on the agent's call; a cross-SDK check against Node and the server; live proof and a stubbed shadow diff captured.
🤖 Generated with Claude Code
How did you test this code?
Merge card: high, one-way door · 5 rounds, 17 final reads · gaps: judge (🤖 agent d-fe6d4dd1) · 3 known issues · 1756 min opened to ready
6823db26823db26823db2(reused fromee472cc)3b58e48to6823db26823db2Not checked: The code form (template_key with rendered content) live; A batch where PostHog queues some recipients and refuses others, live; Retries, lost answers and unconfirmed recipients live; they run against WebMock and the mutants; The mailbox at this head; PostHog status reads show every message ID delivered
Full receipt: https://artifacts.posthog.com/a/HBhbFkuVnfi9B8SEWM1K2J