Skip to content

feat(emails): send one email to each of many recipients with emails()->batch() - #332

Open
Silthus wants to merge 51 commits into
feat/scheduled-email-sendfrom
feat/email-batch
Open

Silthus wants to merge 51 commits into
feat/scheduled-email-sendfrom
feat/email-batch

Conversation

@Silthus

@Silthus Silthus commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

💡 Motivation and Context

A PHP app that sends the same transactional email to many people, such as a digest or an announcement, has to call emails()->send() once per recipient. PostHog Cloud now takes a batch of up to 100 recipients in one request. This PR adds emails()->batch(), one request per call,, ported from the Python SDK (PostHog/posthog-python#1291), the reference, with the Node SDK (PostHog/posthog-js#5847) as a second source.

Stacked on #330 (scheduled sends).

Impact

The server counts batch sends on its own send events, so the SDK adds no event. This PR adds the PHP path to them.

Caution

🔴 Merge risk: high · one-way door once the release publishes: batch(), SendBatchResult, BatchEmailResult and EmailBatchError become public API

  • batch() is a new entry point. Only apps that call it reach the batch code, on PostHog Cloud US and EU, or a self-hosted app host that serves the endpoint.
  • send() and get() are unchanged. Their recipient checks and reply parsing moved into shared internal classes, and the base's email tests pass against this head (shadow diff).
  • Uncovered: a retry, in-flight or lost-answer path that the fake transport models differently from the server could give a recipient the wrong status. The client never marks a recipient queued without PostHog's answer for it, so the worst case is unconfirmed for an email that went out. The live batch at this head covers a template batch and a code-rendered batch, their same-key replays, and three refusals, not the retry paths.
  • A batch is one request, so it can't stop part-way. PostHog's refusals, such as a 413 for a batch over its size limits, are the thrown EmailBatchError with every recipient failed, and nothing went out. The live run covers a 404, a 413 and a 400.
  • Anything the client throws while it sends a batch, such as a disabled curl function after the request went out, an HTTP-date Retry-After on PHP 8.5 in an app that throws on deprecations, or the retry wait itself, comes back as EmailBatchError with every recipient unconfirmed and keeping its key, and an earlier in-flight answer keeps PostHog's code and fix (tests). If the client failed before the request went out, those recipients are unconfirmed for emails that weren't sent, and a same-key resend sends them once. On symfony/clock 6.2 the retry wait falls back to a monotonic clock, and to hrtime with usleep when that clock can't load either, on 32-bit PHP too. The retry wait is shared, so this also fixes the retries of send(), get() and attachment uploads, and their waits on a working clock are unchanged (shadow diff).
  • Uncovered: the request is encoded in one call that holds the body next to the caller's input. In an app with a tight PHP memory limit, a batch near PostHog's limits can still run out of memory before the request goes out, so nothing is sent (Known issues). Tests cover two near-limit shapes under a tight limit. A value that fails to encode is invalid_form with nothing sent.
  • getErrorName() of a delivery_unavailable error without an HTTP status is now service_unavailable, not application_error. Batch results carry one, and so does an EmailError an app builds itself with that code and no status. send() gets that code with a status, so its errors are unchanged (tests).
  • Uncovered: a malformed answer whose results is an object keyed by numbers reads as a list, so a recipient can read queued that PostHog never confirmed, and the app skips its resend (Known issues, base reply check). PostHog's endpoint answers with a list.
  • Switch-off: none in the SDK. The server's workflows-email-batch-sends flag answers 404 while it is off, and batch() reports not_found without falling back to single sends.
  • Tier: critical (b: high; c: public API; f: SDK release)

Rollout

Changes

  • emails()->batch() takes recipients (each to, and optional distinct_id, idempotency_key and template_data) with one form for the whole batch:
    • a template made in PostHog, template_id with shared template_data that each recipient's template_data merges over;
    • or code-form content, the same for every recipient.
  • A call takes 1 to 100 recipients and sends one request, which waits 45 seconds, or email_request_timeout_ms when that is longer. More than 100 throws invalid_recipients before any request. The SDK checks no byte size: PostHog's refusal is the error, with PostHog's own fix. A 413 content_too_large means the request is too large: send fewer recipients. A 400 content_too_large means the shared content is too large, so fewer recipients won't help. The SDK encodes the request in one call, so it holds only the caller's input and the body, and a batch near PostHog's limit doesn't run out of PHP memory first. A recipient's template_data can nest as deep as it can in send(). When encoding fails, the SDK throws invalid_form with PHP's reason, as send() does, and sends nothing.
  • Each recipient gets its own idempotency key: yours, or one the client generates, which every retry reuses. Two recipients with the same key throw invalid_idempotency_key before any request.
  • SendBatchResult::getResults() returns one BatchEmailResult per recipient, in order, with status queued, failed or unconfirmed, the message ID, isReplayed() and the error.
  • Retries match Python: an error that send() retries, such as a rate limit or a network error, resends the whole request with the same keys.
  • An unconfirmed recipient keeps its idempotency key, and its error says to send it again with the same key within 24 hours of its first use. The client reads nothing back after a batch, so a message ID comes only from PostHog's answer to the batch request.
  • A whole-request 409 idempotency_key_in_flight leaves its recipients unconfirmed with that answer as their error, as in Python. So does a 409 whose body has no readable code. When PostHog gives no fix, the error says to send again with the same idempotency_key within 24 hours of its first use. The same code on any other status doesn't claim the key is in flight.
  • A refusal of the whole request throws EmailBatchError with every recipient: failed, or unconfirmed when an earlier attempt of the call lost its answer and so may have queued them. It uses Python's codes: batch_unavailable (409, named validation_error), not_found (404) and client_closed. After an attempt that lost its answer, a recipient or a whole request that a retry refuses stays unconfirmed with the refusal as its error and the same-key resend advice, since the first attempt may have queued it. Every unconfirmed recipient carries that advice. A warning PostHog repeats in one answer reaches the caller once.
  • A batch refuses cc, bcc, attachments, scheduled_at, and a top-level to, distinct_id or idempotency_key, before any request.
  • README "Batches" section with the 24-hour replay window, the batch() docblock, the public API snapshot and a minor changeset.

💚 How did you test it?

Test-first in test/EmailsBatchTest.php, through emails()->batch() with the fake PostHog transport. The cases cover both forms, the shared and per-recipient template_data merge, 100 recipients in one request and 101 refused before any, generated and explicit keys, duplicate keys, results in order, each status, replays, retries with the same body, unconfirmed recipients that keep their keys with nothing read back, an in-flight answer on a 409 and on a 503, a request that fails as a whole, the 404, 409, 413 and 400 content_too_large answers, a recipient a retry refuses after a lost answer, a client closed before a retry and the refused fields. Two memory-limited child processes cover a batch near PostHog's body limit and shared data over it. A mutation run broke each guarded line, and each break failed a test.

Locally, through PHP 8.5 in Docker: the full PHPUnit suite, phpcs on the changed files and composer api:check pass.

  • Shadow diff: the base branch's whole test suite, unchanged, passes against this head, the git archive test included.
  • Live run on PostHog Cloud US at 5941080, carried to this head because the only commit since changes the docs: three batches PostHog refused as a whole, each with both recipients failed and nothing sent. An unknown template got 404. Shared data over the request limit got 413 content_too_large with PostHog's fix to split the recipients. Shared data over the shared-content limit got 400 content_too_large with no split advice. Then one real batch of two recipients through a test template, and the same batch with the same keys. Both were queued in one request, in order, the replay returned the same message IDs, and the status reads and the mailbox show one email per recipient.

Known issues

  • major: lib/Internal/EmailBatch.php:53 The SDK checks only the recipient count. PostHog counts the shared template_data once per recipient against its own request limits, so a batch over them is refused as a whole with content_too_large before any email goes out, and the error carries PostHog's fix. The client doesn't split.
  • On PHP 8.5, an app that turns deprecations into exceptions gets an ErrorException when PostHog answers with an HTTP-date Retry-After. This is base behavior: the parser uses the deprecated DATE_RFC7231 constant, moved here unchanged. batch() now returns every recipient's result in that case; send() still throws the ErrorException.
  • minor: lib/Internal/EmailBatch.php:85 The SDK holds the request body alongside the caller's input, as emails()->send() does, so a value that grows a lot as JSON, such as one full of control characters, can still exhaust a tight PHP memory limit before PostHog's content_too_large.
  • minor: lib/Internal/EmailBatch.php:184 [base] A terminal 5xx after a lost answer leaves each recipient with the generic unconfirmed error. The thrown EmailBatchError carries the last answer's detail, field and retry timing.
  • minor: lib/Internal/EmailBatch.php:207 [base] A malformed answer whose results is an object keyed by numbers reads as a list.
  • minor: lib/Internal/EmailBatch.php:148 [base] A jsonSerialize() in template_data that throws something other than JsonException escapes batch() as that exception, not invalid_form. Nothing is sent. send() behaves the same.
  • minor: lib/BatchEmailResult.php:68 [base] On idempotency_key_reused, the message ID names the email the key first sent, so get() reports that email's status, not the refused one. The docblock is feat(emails): schedule a transactional email with scheduled_at #330's, unchanged here.

📝 Checklist

  • All commits are signed (see Commit signing)
  • I reviewed the submitted code.
  • I added tests to verify the changes.
  • I updated the docs if needed.
  • No breaking change or entry added to the changelog.

If releasing new changes

  • Ran pnpm change to generate a change intent file

🤖 Agent context

Autonomy: Human-driven (agent-assisted)

Written by Claude Opus 5.5 (claude-opus-5-5) in Claude Code, as an implementation lane under a conductor thread that Michael directs. Python's batch is the reference. PHP has no async client, so there is no async batch(), and bad arguments throw EmailError with invalid_* codes, as send() already does, instead of Python's TypeError and ValueError.

Question Answer Who Where
Split a large batch in the SDK No: one request per call, at most 100 recipients, PostHog's refusals are the error. Replaced: splitting into requests of 100 recipients and 4 MiB. 👤 conductor thread
Build batch in every SDK Build it now, ported from Python. 👍 conductor brief
Retry scope A retry resends the whole request, as Python does. Rejected: Node's resend of only the open recipients. 🤖 this PR
A recipient a retry refuses after a lost answer unconfirmed with the retry's error and the same-key resend advice, as in Python and Elixir. Replaced: failed. 👤 conductor thread
An answer too large to read Counted as a lost answer, so those recipients stay unconfirmed. Rejected: failing the request. 🤖 this PR
Read unconfirmed emails back by key Drop the reads in every SDK: a resend with the same key does their job. Replaced: reading each unconfirmed email by key at the end of the batch. 👍 conductor thread

Involvement: no grilling rounds; tests mutation-checked; one five-lens review panel (Claude fresh eyes, GPT correctness, risk, design and anti-overengineering) and fixes reads.

🤖 Generated with Claude Code

How did you test this code?

Merge card: high, one-way door · 6 rounds, 21 final reads · gaps: judge (🤖 agent d-62ddebf4) · 7 known issues · 1700 min opened to ready

Proof What ran Result Commit
live-run at this head on PostHog Cloud US: a template batch and a code-rendered batch of two each, each sent twice with the same keys, plus three refused batches (unknown template, over the request limit, shared data over the shared limit) all four emails queued, replayed with the same ids, delivered, and arrived once each; the refusals came back as 404, 413 with PostHog's split advice, and 400, every recipient failed, nothing sent 436bc10 (reused from 7cf8fb2)
shadow-diff The base test suite of the scheduled-send PR ran against this head library on PHP 8.5 Every base test passes, and the batch request bodies hash the same as at every earlier head 436bc10
Review 5-lens panel (claude-opus-5-5, gpt-6.2-sol), round 1, round 2, round 3, round 4, round 5, round 6, final read 1, final read 2, final read 3, final read 4, final read 5, final read 6, final read 7, final read 8, final read 9, final read 10, final read 11, final read 12, final read 13, final read 14, final read 15, final read 16, final read 17, final read 18, final read 19, final read 20, final read 21 188 findings: 104 fixed, 84 rejected, 0 other 39c088e to 436bc10
Proof judge an independent model reads the evidence against the diff ❌ failed at 436bc10
PR Review rounds Production lines Sanity pass Skipped proofs
#332 6 rounds, 21 final reads 2,592 → 3,053 (×1.2); docs 33 → 34 not run judge: The judge holds base behavior and answered test-style findings: the object-keyed results check and the HTTP-date Retry-After parser are base code listed under Known issues, and the TESTS items were answered in final reads 17 to 21. The retry, client-failure and in-flight paths it calls unproved each have a red-then-green test at this head, the 32-bit retry has a saved run, and the base suite passes against this library. (🤖 agent d-62ddebf4)

Not checked: none recorded
Full receipt: https://artifacts.posthog.com/a/Z5lDIHD8vsfRWM40K2spbu

Silthus and others added 5 commits November 24, 2026 07:21
…duled_at

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… trait

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…->batch()

emails()->batch() takes a template or code-form email and a list of
recipients, sends them in requests of at most 100 recipients and 4 MiB,
one after another, and returns a result per recipient in input order:
queued, failed, unconfirmed or not_attempted. Each recipient's
idempotency key is given or generated and reused on every retry. A
request that fails as a whole throws EmailBatchError with every
recipient's result, after reading lost emails by their key.

The reply parsing moves to Internal\EmailReplies and the recipient
checks to Internal\EmailRecipient, so send() and batch() share them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

posthog-php-fork_curl Compliance Report

Date: 2026-11-25T12:30:48.713896+00:00
Duration: 118238ms

✅ All Tests Passed!

47/47 tests passed


Capture Tests

✅ 30/30 tests passed

View Details
Test Status Duration
Format Validation.Event Has Required Fields ✅ 31ms
Format Validation.Event Has Uuid ✅ 527ms
Format Validation.Event Has Lib Properties ✅ 528ms
Format Validation.Distinct Id Is String ✅ 527ms
Format Validation.Token Is Present ✅ 528ms
Format Validation.Custom Properties Preserved ✅ 527ms
Format Validation.Event Has Timestamp ✅ 528ms
Format Validation.Non Utc Event Timestamp Is Converted To Utc ✅ 528ms
Retry Behavior.Retries On 503 ✅ 5850ms
Retry Behavior.Does Not Retry On 400 ✅ 2531ms
Retry Behavior.Does Not Retry On 401 ✅ 2531ms
Retry Behavior.Respects Retry After Header ✅ 8540ms
Retry Behavior.Implements Backoff ✅ 16274ms
Retry Behavior.Retries On 500 ✅ 5644ms
Retry Behavior.Retries On 502 ✅ 5643ms
Retry Behavior.Retries On 504 ✅ 5642ms
Retry Behavior.Max Retries Respected ✅ 16267ms
Deduplication.Generates Unique Uuids ✅ 37ms
Deduplication.Preserves Uuid On Retry ✅ 5644ms
Deduplication.Preserves Uuid And Timestamp On Retry ✅ 10855ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 5645ms
Deduplication.No Duplicate Events In Batch ✅ 535ms
Deduplication.Different Events Have Different Uuids ✅ 528ms
Compression.Sends Gzip When Enabled ✅ 530ms
Batch Format.Uses Proper Batch Structure ✅ 529ms
Batch Format.Flush With No Events Sends Nothing ✅ 518ms
Batch Format.Multiple Events Batched Together ✅ 517ms
Error Handling.Does Not Retry On 403 ✅ 2531ms
Error Handling.Does Not Retry On 413 ✅ 2529ms
Error Handling.Retries On 408 ✅ 5644ms

Feature_Flags Tests

✅ 17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id ✅ 522ms
Request Payload.Flags Request Uses V2 Query Param ✅ 520ms
Request Payload.Flags Request Hits Flags Path Not Decide ✅ 520ms
Request Payload.Flags Request Omits Authorization Header ✅ 521ms
Request Payload.Token In Flags Body Matches Init ✅ 521ms
Request Payload.Groups Round Trip ✅ 520ms
Request Payload.Groups Default To Empty Object ✅ 521ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False ✅ 520ms
Request Payload.Disable Geoip Omitted Defaults To False ✅ 521ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key ✅ 521ms
Request Lifecycle.No Flags Request On Init Alone ✅ 517ms
Request Lifecycle.No Flags Request On Normal Capture ✅ 514ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests ✅ 523ms
Request Lifecycle.Mock Response Value Is Returned To Caller ✅ 521ms
Retry Behavior.Retries Flags On 502 ✅ 624ms
Retry Behavior.Retries Flags On 504 ✅ 622ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event ✅ 530ms

@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

posthog-php-socket Compliance Report

Date: 2026-11-25T12:31:01.730525+00:00
Duration: 118285ms

✅ All Tests Passed!

47/47 tests passed


Capture Tests

✅ 30/30 tests passed

View Details
Test Status Duration
Format Validation.Event Has Required Fields ✅ 22ms
Format Validation.Event Has Uuid ✅ 519ms
Format Validation.Event Has Lib Properties ✅ 520ms
Format Validation.Distinct Id Is String ✅ 519ms
Format Validation.Token Is Present ✅ 520ms
Format Validation.Custom Properties Preserved ✅ 519ms
Format Validation.Event Has Timestamp ✅ 520ms
Format Validation.Non Utc Event Timestamp Is Converted To Utc ✅ 520ms
Retry Behavior.Retries On 503 ✅ 5828ms
Retry Behavior.Does Not Retry On 400 ✅ 2522ms
Retry Behavior.Does Not Retry On 401 ✅ 2524ms
Retry Behavior.Respects Retry After Header ✅ 8527ms
Retry Behavior.Implements Backoff ✅ 16242ms
Retry Behavior.Retries On 500 ✅ 5628ms
Retry Behavior.Retries On 502 ✅ 5629ms
Retry Behavior.Retries On 504 ✅ 5628ms
Retry Behavior.Max Retries Respected ✅ 16245ms
Deduplication.Generates Unique Uuids ✅ 526ms
Deduplication.Preserves Uuid On Retry ✅ 5629ms
Deduplication.Preserves Uuid And Timestamp On Retry ✅ 10835ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 5630ms
Deduplication.No Duplicate Events In Batch ✅ 525ms
Deduplication.Different Events Have Different Uuids ✅ 522ms
Compression.Sends Gzip When Enabled ✅ 520ms
Batch Format.Uses Proper Batch Structure ✅ 520ms
Batch Format.Flush With No Events Sends Nothing ✅ 517ms
Batch Format.Multiple Events Batched Together ✅ 512ms
Error Handling.Does Not Retry On 403 ✅ 2522ms
Error Handling.Does Not Retry On 413 ✅ 2523ms
Error Handling.Retries On 408 ✅ 5628ms

Feature_Flags Tests

✅ 17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id ✅ 519ms
Request Payload.Flags Request Uses V2 Query Param ✅ 519ms
Request Payload.Flags Request Hits Flags Path Not Decide ✅ 518ms
Request Payload.Flags Request Omits Authorization Header ✅ 519ms
Request Payload.Token In Flags Body Matches Init ✅ 517ms
Request Payload.Groups Round Trip ✅ 519ms
Request Payload.Groups Default To Empty Object ✅ 518ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False ✅ 519ms
Request Payload.Disable Geoip Omitted Defaults To False ✅ 518ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key ✅ 519ms
Request Lifecycle.No Flags Request On Init Alone ✅ 514ms
Request Lifecycle.No Flags Request On Normal Capture ✅ 508ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests ✅ 522ms
Request Lifecycle.Mock Response Value Is Returned To Caller ✅ 521ms
Retry Behavior.Retries Flags On 502 ✅ 622ms
Retry Behavior.Retries Flags On 504 ✅ 620ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event ✅ 521ms

@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

posthog-php-lib_curl Compliance Report

Date: 2026-11-25T12:30:58.416388+00:00
Duration: 118953ms

✅ All Tests Passed!

47/47 tests passed


Capture Tests

✅ 30/30 tests passed

View Details
Test Status Duration
Format Validation.Event Has Required Fields ✅ 25ms
Format Validation.Event Has Uuid ✅ 522ms
Format Validation.Event Has Lib Properties ✅ 521ms
Format Validation.Distinct Id Is String ✅ 523ms
Format Validation.Token Is Present ✅ 522ms
Format Validation.Custom Properties Preserved ✅ 523ms
Format Validation.Event Has Timestamp ✅ 522ms
Format Validation.Non Utc Event Timestamp Is Converted To Utc ✅ 522ms
Retry Behavior.Retries On 503 ✅ 5831ms
Retry Behavior.Does Not Retry On 400 ✅ 2524ms
Retry Behavior.Does Not Retry On 401 ✅ 2525ms
Retry Behavior.Respects Retry After Header ✅ 8531ms
Retry Behavior.Implements Backoff ✅ 16244ms
Retry Behavior.Retries On 500 ✅ 5634ms
Retry Behavior.Retries On 502 ✅ 5629ms
Retry Behavior.Retries On 504 ✅ 5631ms
Retry Behavior.Max Retries Respected ✅ 17045ms
Deduplication.Generates Unique Uuids ✅ 228ms
Deduplication.Preserves Uuid On Retry ✅ 5630ms
Deduplication.Preserves Uuid And Timestamp On Retry ✅ 10837ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 5634ms
Deduplication.No Duplicate Events In Batch ✅ 527ms
Deduplication.Different Events Have Different Uuids ✅ 524ms
Compression.Sends Gzip When Enabled ✅ 523ms
Batch Format.Uses Proper Batch Structure ✅ 522ms
Batch Format.Flush With No Events Sends Nothing ✅ 519ms
Batch Format.Multiple Events Batched Together ✅ 510ms
Error Handling.Does Not Retry On 403 ✅ 2526ms
Error Handling.Does Not Retry On 413 ✅ 2523ms
Error Handling.Retries On 408 ✅ 5632ms

Feature_Flags Tests

✅ 17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id ✅ 521ms
Request Payload.Flags Request Uses V2 Query Param ✅ 521ms
Request Payload.Flags Request Hits Flags Path Not Decide ✅ 521ms
Request Payload.Flags Request Omits Authorization Header ✅ 521ms
Request Payload.Token In Flags Body Matches Init ✅ 520ms
Request Payload.Groups Round Trip ✅ 522ms
Request Payload.Groups Default To Empty Object ✅ 521ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False ✅ 520ms
Request Payload.Disable Geoip Omitted Defaults To False ✅ 521ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key ✅ 521ms
Request Lifecycle.No Flags Request On Init Alone ✅ 517ms
Request Lifecycle.No Flags Request On Normal Capture ✅ 507ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests ✅ 524ms
Request Lifecycle.Mock Response Value Is Returned To Caller ✅ 521ms
Retry Behavior.Retries Flags On 502 ✅ 624ms
Retry Behavior.Retries Flags On 504 ✅ 623ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event ✅ 522ms

Silthus and others added 22 commits November 24, 2026 08:27
… one body at a time

A status read by key now fills in only the message ID: the recipient
stays unconfirmed, since an email under the key may be a refusal or an
older send. The client reads every unconfirmed email without a message
ID at the end of each batch, on success too. A whole-request
idempotency_key_in_flight leaves the request's recipients unconfirmed,
and a later attempt's answer becomes their later error. The first
malformed answer no longer sets a later error.

The batch keeps each recipient's JSON and the requests' membership, and
builds one request body at a time, reused for its retries. The results'
own unconfirmed status replaces the separate maybe-queued map. Shared
content over 4 MiB throws content_too_large naming html, text or
template_data before any request, and a recipient too large alone names
its template_data.

A single send checks its form and content again before its idempotency
key, as before the batch. The unused Emails::epochSecondsAsFloat is gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…sing a key

The README's batch example names one email of one run with each key,
says never to reuse a key for another email, and says that unconfirmed
emails come back with their message ID when PostHog has them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…errors on every retry

A read by key at the end of a batch is best effort: any Throwable from
it, such as an ErrorException from a promoted deprecation or an Error
from a missing class, now stops the reads, and batch() still returns its
result or throws its EmailBatchError with every recipient.

An attempt that can't confirm a request, a 503, a lost answer or an
answer without a result per recipient, now sets the later error of each
recipient an earlier attempt already left unconfirmed. The first such
attempt still leaves it null.

Shared content over 4 MiB names its largest field, such as from or
reply_to, not only html, text or subject.

The memory test runs a batch of 10,000 recipients in a child process
under a 26 MiB limit, and the shutdown test no longer asserts the
fixture's own flag.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…y best effort

The README and the batch() docblock build each idempotency key from an
ID stored with the job, such as the digest's own ID, so a retry after
midnight makes the same keys. They say the end-of-batch reads by key
stop at the first failure other than a 404.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The batch now encodes each shared field once and builds the request
body's opening from those pieces, so content_too_large names the
largest field from the same encoding. A JsonSerializable value is never
serialized a second time, so one that answers differently, or throws,
on a second call can no longer turn content_too_large into invalid_form
or another exception.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ory test to what PostHog takes

A retry that loses its answer at the transport keeps the recipient
unconfirmed with its first error, and records network_error as its later
error. The memory test shares 150,000 bytes of template_data, which
PostHog accepts for 100 recipients, under a 24 MiB limit that the batch
before it built one body at a time still exhausts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…feat/email-batch

# Conflicts:
#	test/EmailsTest.php
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Silthus and others added 18 commits November 24, 2026 20:01
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…feat/email-batch

# Conflicts:
#	lib/Emails.php
More than 100 recipients is refused before any request. A refusal of the
whole batch, such as a 413, is the error, with every recipient's result.
The chunk loop, not_attempted, getLaterError() and the client-side 4 MiB
sizing are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A recipient a retry refuses after a lost answer stays unconfirmed with
  the same-key resend advice, since the first attempt may have queued it.
- A 413 keeps PostHog's own fix. Without one, the advice covers a smaller
  email as well as fewer recipients. A 400 content_too_large gets no
  split advice.
- The request body is encoded once and grown in place, so a batch near
  PostHog's body limit no longer runs out of PHP memory first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Each recipient is encoded straight into the request body instead of
  being held encoded until the body is built, so a batch near PostHog's
  body limit fits a tighter PHP memory limit.
- Every unconfirmed recipient carries the same-key resend advice, also
  when PostHog's first answer leaves it unconfirmed or unreadable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The request is encoded in one json_encode call, so a batch holds only
  the caller's input and the body. Encoding errors are traced to the
  shared fields or a recipient only when that call fails.
- A whole-request refusal after an attempt that may have queued leaves
  each recipient unconfirmed with the refusal and the resend advice.
- An empty fix from PostHog on a 413 falls back to the SDK's advice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- When encoding the batch fails, the client traces the failing field
  and then throws, instead of encoding again: a value that encodes only
  on a later call no longer goes out.
- A warning PostHog repeats in one answer reaches the caller once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Tracing which field failed to encode can't let a serializer's later
  exception replace the invalid_form error; nothing is sent either way.
- Test lines wrapped to the 120-character limit CI checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…again

A batch whose data fails to encode now fails with invalid_form at once,
without running the caller's serializers a second time. The oversized
answer is tested against the loopback server, and the near-limit memory
test only uses recipients PostHog can queue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ight fix

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Silthus
Silthus marked this pull request as ready for review November 25, 2026 11:28
@Silthus
Silthus requested a review from a team as a code owner November 25, 2026 11:28
@veria-ai

veria-ai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Fixed/addressed: 1 · PR risk: 0/10

Reviews

@posthog posthog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

PostHog Review · Standard · reviewed 7cf8fb2: 2 Should fix. This pull request is large, so the review ran in 4 parts with less depth than usual.

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.

Comment thread lib/Internal/EmailBatch.php Resolved
Comment thread lib/Emails.php Resolved
Comment thread lib/Internal/EmailBatch.php Resolved
Silthus and others added 6 commits November 25, 2026 12:36
A batch now keeps every recipient's result and key when anything in the
retry machinery throws, and the retry wait falls back to a monotonic
clock on symfony/clock 6.2, which has no Clock class. A 409 without a
readable code leaves recipients unconfirmed. Warnings are deduplicated
with a keyed lookup, and the resend advice counts the 24 hours from the
key's first use.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A 503 or in-flight 409 now marks the batch as possibly queued before it
reads the answer, so a Retry-After that throws while parsing leaves the
recipients unconfirmed with their keys. The retry wait falls back to
usleep when symfony/clock 6.2.0 can't build a MonotonicClock either.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Warning dedupe keys on nested arrays instead of serialize(), so an app
that disables serialize() keeps PostHog's queued results. The fallback
retry wait reads hrtime() as seconds and nanoseconds, so a wait longer
than two seconds doesn't overflow on 32-bit PHP.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A project without batch sends isn't a request still in progress, so its
error name matches Python's validation_error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Anything the client throws while it sends a batch, such as a disabled
curl function after the request went out, now leaves every recipient
unconfirmed with its key instead of failed. A recipient's template_data
gets the same JSON depth as a single send, and the retry wait calls
hrtime() only when no clock is available.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A client failure after a recorded in-flight or lost answer no longer
replaces each recipient's error with a generic one, so the caller keeps
PostHog's code and fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@marandaneto marandaneto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The code looks good; no qualifying findings. Verdict: correct.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants