From 3b58e486165a41ee109b73280b7713c60b916050 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:01:07 +0100 Subject: [PATCH 01/32] feat(emails): send one email to many recipients with emails.batch 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 --- .changeset/email-batch-sends.md | 5 + lib/posthog/email_batch.rb | 233 +++++++++++++++++++++++ lib/posthog/email_error.rb | 24 ++- lib/posthog/emails.rb | 269 +++++++++++++++++++++++++- public_api_snapshot.txt | 36 ++++ spec/posthog/emails_batch_spec.rb | 303 ++++++++++++++++++++++++++++++ 6 files changed, 862 insertions(+), 8 deletions(-) create mode 100644 .changeset/email-batch-sends.md create mode 100644 lib/posthog/email_batch.rb create mode 100644 spec/posthog/emails_batch_spec.rb diff --git a/.changeset/email-batch-sends.md b/.changeset/email-batch-sends.md new file mode 100644 index 00000000..50822ae1 --- /dev/null +++ b/.changeset/email-batch-sends.md @@ -0,0 +1,5 @@ +--- +"posthog-ruby": minor +--- + +Send the same transactional email to many recipients with `emails.batch`, one email each, from a template made in PostHog with `template_data` per recipient, or from content your code rendered. The client sends at most 100 recipients and 4 MiB per request, one request after another, and returns a result per recipient in order: `queued`, `failed`, `unconfirmed` or `not_attempted`. Each recipient has its own `idempotency_key`, given or made by the client, so a retry or a rerun within 24 hours never sends an email twice. A request that fails as a whole stops the batch and raises `EmailBatchError` with every recipient's result. diff --git a/lib/posthog/email_batch.rb b/lib/posthog/email_batch.rb new file mode 100644 index 00000000..3985cfb2 --- /dev/null +++ b/lib/posthog/email_batch.rb @@ -0,0 +1,233 @@ +# frozen_string_literal: true + +require 'json' +require 'set' + +require 'posthog/email_error' + +module PostHog + # The recipients of one {Emails#batch} call, split into requests, and what PostHog answered for each. + # + # @api private + class EmailBatch + MAX_RECIPIENTS = 100 + MAX_BODY_BYTES = 4 * 1024 * 1024 + UNCONFIRMED_CODES = %w[idempotency_key_in_flight delivery_unavailable api_error].freeze + UNAVAILABLE_FIX = "Until batch sends are on for the project, send each email the batch didn't queue with " \ + "emails.send and its recipient's idempotency_key." + NOT_FOUND = { + 'code' => 'not_found', + 'detail' => 'PostHog found no batch send for this request, so no email was sent.', + 'why' => "The template doesn't exist, or batch sends are off for this project or this PostHog version.", + 'fix' => "Check template_id, or send each email the batch didn't queue with emails.send and its recipient's " \ + 'idempotency_key.' + }.freeze + RESULT_DEFAULTS = { message_id: nil, replayed: false, error: nil, later_error: nil }.freeze + private_constant :UNCONFIRMED_CODES, :UNAVAILABLE_FIX, :NOT_FOUND, :RESULT_DEFAULTS + + Member = Struct.new(:index, :to, :idempotency_key, :wire, keyword_init: true) + Chunk = Struct.new(:body, :indices, keyword_init: true) + + attr_reader :chunks + + # @param shared [Hash] The batch's email without its recipients. + # @param members [Array] Every recipient, with its JSON as the request carries it. + # @param parse_warnings [#call] Turns a reply's warnings into {Emails::Warning}s. + # @param reply_error [#call] Turns a refused reply into an {EmailError}. + def initialize(shared, members, parse_warnings:, reply_error:) + @members = members + @parse_warnings = parse_warnings + @reply_error = reply_error + @results = Array.new(members.size) + @warnings = [] + @maybe_queued = Set.new + @chunks = split(JSON.generate(shared.merge(recipients: []))) + end + + # An attempt that may have queued some of the chunk got no usable answer. + def lost(chunk) + chunk.indices.each do |index| + @maybe_queued << index + message_id = @results[index]&.message_id + set(index, 'unconfirmed', message_id: message_id, error: unconfirmed(message_id)) + end + end + + # Records PostHog's answer to the chunk, or raises the error of a refused request. + def answer(chunk, (status, payload, retry_after)) + fields = payload.is_a?(Hash) ? payload : {} + unless status.between?(200, 299) + lost(chunk) if status >= 500 + raise response_error(fields, status, retry_after, chunk.indices) + end + + slots = fields['results'] + unless slots.is_a?(Array) && slots.size == chunk.indices.size + lost(chunk) + raise EmailError.new(code: 'api_error', status_code: status, + message: 'PostHog answered the batch without a result for each recipient.') + end + chunk.indices.zip(slots) { |index, slot| settle(index, slot.is_a?(Hash) ? slot : {}) } + @parse_warnings.call(fields['warnings']).each do |warning| + @warnings << warning unless @warnings.include?(warning) + end + end + + # The request of the chunk at +position+ failed as a whole, so the batch stops there. + def stop(position, error) + later = error.status_code && error.status_code < 500 ? error : nil + @chunks[position].indices.each do |index| + if !@maybe_queued.include?(index) + set(index, 'failed', error: error) + elsif later + earlier = @results[index] + set(index, 'unconfirmed', message_id: earlier.message_id, error: earlier.error, later_error: later) + end + end + skip_from(position + 1, EmailError.new( + code: 'not_attempted', + message: 'An earlier request of the batch failed, so the client sent nothing for ' \ + 'this recipient.' + )) + end + + # The client shut down before the chunk at +position+ went out. + def closed_at(position) + error = EmailError.new(code: 'client_closed', + message: "The PostHog client is shut down, so the rest of the batch wasn't sent.") + skip_from(position, error) + error + end + + # Recipients a lost answer left without a message ID, with their keys. + def lost_keys + @maybe_queued.sort.filter_map do |index| + [index, @members[index].idempotency_key] if @results[index].message_id.nil? + end + end + + # A status read by key found the email, so PostHog accepted it. + def accepted(index, status) + @maybe_queued.delete(index) + set(index, 'queued', message_id: status.id) + end + + def result + Emails::BatchResult.new(results: @results.dup.freeze, warnings: @warnings.dup.freeze) + end + + def failure(error) + EmailBatchError.new(error, results: @results.dup.freeze, warnings: @warnings.dup.freeze) + end + + private + + def split(empty) + chunks = [] + current = [] + size = empty.bytesize + @members.each do |member| + if empty.bytesize + member.wire.bytesize > MAX_BODY_BYTES + set(member.index, 'failed', error: recipient_too_large) + next + end + added = member.wire.bytesize + (current.empty? ? 0 : 1) + if !current.empty? && (current.size == MAX_RECIPIENTS || size + added > MAX_BODY_BYTES) + chunks << chunk(empty, current) + current = [] + size = empty.bytesize + added = member.wire.bytesize + end + current << member + size += added + end + chunks << chunk(empty, current) unless current.empty? + chunks + end + + def chunk(empty, members) + Chunk.new(body: "#{empty.delete_suffix(']}')}#{members.map(&:wire).join(',')}]}", indices: members.map(&:index)) + end + + def settle(index, slot) + message_id = text(slot['message_id']) + if slot['error'].nil? && slot['status'] == 'queued' && message_id + @maybe_queued.delete(index) + set(index, 'queued', message_id: message_id, replayed: slot['replayed'] == true) + return + end + + answer = slot_error(slot['error'], message_id) + if @maybe_queued.include?(index) + earlier = @results[index] + set(index, 'unconfirmed', message_id: message_id || earlier.message_id, error: earlier.error, + later_error: answer) + elsif UNCONFIRMED_CODES.include?(answer.code) + @maybe_queued << index + set(index, 'unconfirmed', message_id: message_id, error: answer) + else + set(index, 'failed', message_id: message_id, error: answer) + end + end + + def skip_from(position, error) + @chunks.drop(position).each do |chunk| + chunk.indices.each { |index| set(index, 'not_attempted', error: error) } + end + end + + def set(index, status, **fields) + member = @members[index] + identity = { index: index, to: member.to, idempotency_key: member.idempotency_key, status: status } + @results[index] = Emails::BatchEmailResult.new(**RESULT_DEFAULTS, **identity, **fields) + end + + def response_error(fields, status, retry_after, indices) + answered = fields.compact + answered['attr'] = recipients_field(answered['attr'], indices) if answered['attr'].is_a?(String) + fields = status == 404 ? NOT_FOUND.merge(answered) : answered + fields = fields.merge('fix' => UNAVAILABLE_FIX) if fields['code'] == 'batch_unavailable' + @reply_error.call(fields, status, retry_after) + end + + # PostHog names a recipient by its place in the request, and the caller knows it by its place in the batch. + def recipients_field(attr, indices) + parts = /\Arecipients__(\d+)(__.*)?\z/m.match(attr) + return attr if parts.nil? + + position = parts[1] + return 'recipients' if position.size > indices.size.to_s.size || position.to_i >= indices.size + + "recipients__#{indices[position.to_i]}#{parts[2]}" + end + + def slot_error(error, message_id) + unless error.is_a?(Hash) + return EmailError.new(code: 'api_error', message_id: message_id, + message: 'PostHog answered without a readable result for this email, so it may still ' \ + 'go out.') + end + + code = text(error['code']) || 'api_error' + status = error['status'].is_a?(Integer) ? error['status'] : nil + EmailError.new(code: code, status_code: status, message_id: message_id, + message: text(error['detail']) || "PostHog didn't queue this email: #{code}.") + end + + def unconfirmed(message_id) + EmailError.new(code: 'delivery_unavailable', message_id: message_id, + message: "PostHog didn't confirm this email, so it may still go out. Send it again with the " \ + 'same idempotency_key within 24 hours, so it goes out once.') + end + + def recipient_too_large + EmailError.new(code: 'content_too_large', field: 'recipients', + message: "This recipient's email is larger than one batch request takes, so it wasn't sent.", + fix: "Send this recipient's email with emails.send.") + end + + def text(value) + value if value.is_a?(String) && !value.empty? + end + end +end diff --git a/lib/posthog/email_error.rb b/lib/posthog/email_error.rb index 8c544e6b..1a809a21 100644 --- a/lib/posthog/email_error.rb +++ b/lib/posthog/email_error.rb @@ -49,7 +49,9 @@ def initialize(code:, message:, status_code: nil, why: nil, fix: nil, docs_url: 'invalid_attachment' => 'validation_error', 'too_many_attachments' => 'validation_error', 'message_too_large' => 'validation_error', - 'scheduling_requires_cloud' => 'validation_error' + 'scheduling_requires_cloud' => 'validation_error', + 'delivery_unavailable' => 'service_unavailable', + 'content_too_large' => 'validation_error' }.freeze private_constant :SDK_ERROR_NAMES @@ -71,4 +73,24 @@ def self.name_for(status_code, code) end end end + + # A request of {Emails#batch} failed as a whole, so the batch stopped. + # + # The other fields describe that request's error. {#results} holds every recipient: those of earlier requests as + # PostHog answered them, those of the failed request as `failed`, or `unconfirmed` where an earlier attempt may have + # queued them, and the rest as `not_attempted`. + class EmailBatchError < EmailError + # @return [Array] One result per recipient, in the order of the batch's recipients. + attr_reader :results + # @return [Array] Warnings PostHog returned about the requests that went out, each once. + attr_reader :warnings + + # @api private + def initialize(error, results:, warnings:) + super(code: error.code, message: error.message, status_code: error.status_code, why: error.why, fix: error.fix, + docs_url: error.docs_url, field: error.field, retry_after: error.retry_after, message_id: error.message_id) + @results = results + @warnings = warnings + end + end end diff --git a/lib/posthog/emails.rb b/lib/posthog/emails.rb index b7a3e025..dd8c708c 100644 --- a/lib/posthog/emails.rb +++ b/lib/posthog/emails.rb @@ -10,6 +10,7 @@ require 'zlib' require 'posthog/email_attachments' +require 'posthog/email_batch' require 'posthog/email_error' require 'posthog/logging' require 'posthog/utils' @@ -55,6 +56,16 @@ module PostHog # ) # result.status # => "scheduled" # result.scheduled_at # => the time in UTC + # + # @example The same template for many recipients, one email each + # result = posthog.emails.batch( + # template_id: '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b', + # recipients: [ + # { to: 'ada@example.com', idempotency_key: 'launch:ada', template_data: { name: 'Ada' } }, + # { to: 'alan@example.com', idempotency_key: 'launch:alan', template_data: { name: 'Alan' } } + # ] + # ) + # result.results.reject { |email| email.status == 'queued' } # => send these again with the same keys class Emails include PostHog::Logging include PostHog::Utils @@ -91,9 +102,51 @@ def status # of a bounced email: `hard`, `soft` or `unknown`. Status = Struct.new(:id, :status, :created_at, :status_at, :reason, keyword_init: true) + # What happened to one recipient of {Emails#batch}. + # + # @!attribute [r] index + # @return [Integer] The recipient's position in +recipients+. + # @!attribute [r] to + # @return [String] The recipient's email address. + # @!attribute [r] idempotency_key + # @return [String] The recipient's key, given or made by the client. + # @!attribute [r] status + # @return [String] One of: + # - `queued`: PostHog accepted the email. Read it with {Emails#get} to see whether it went out. + # - `failed`: PostHog didn't queue the email, and {#error} says why, such as a suppressed address. + # - `unconfirmed`: the client can't tell whether PostHog queued the email, such as after a lost answer. It may + # still go out. Send it again with the same +idempotency_key+ within 24 hours, so it goes out once. + # - `not_attempted`: an earlier request of the batch failed, so the client sent nothing for this recipient. + # @!attribute [r] message_id + # @return [String, nil] The email's message ID, when PostHog named it. + # @!attribute [r] replayed + # @return [Boolean] Whether an earlier send with the same key had already queued the email, so no new email + # went out. + # @!attribute [r] error + # @return [EmailError, nil] Why the email is not `queued`. For an `unconfirmed` email, {EmailError#code} is + # `delivery_unavailable`, `idempotency_key_in_flight` or `api_error`. + # @!attribute [r] later_error + # @return [EmailError, nil] For an `unconfirmed` email, what a retry in the same call answered about it, which + # describes only that retry. + BatchEmailResult = Struct.new(:index, :to, :idempotency_key, :status, :message_id, :replayed, :error, :later_error, + keyword_init: true) + + # The answer to {Emails#batch}. + # + # @!attribute [r] results + # @return [Array] One result per recipient, in the order of +recipients+. + # @!attribute [r] warnings + # @return [Array] Warnings PostHog returned about the batch, each once. + BatchResult = Struct.new(:results, :warnings, keyword_init: true) + SEND_PATH = '/api/messaging/send/email/' UPLOADS_PATH = '/api/messaging/attachments/uploads/' STATUS_PATH = '/api/messaging/emails/%s/' + BATCH_PATH = '/api/messaging/send/email_batch/' + STATUS_BY_KEY_PATH = '/api/messaging/emails/status/' + # PostHog waits up to 30 seconds for its pipeline before it answers a batch. + BATCH_ATTEMPT_TIMEOUT_SECONDS = 45.0 + BATCH_RECIPIENT_FIELDS = %w[to distinct_id idempotency_key template_data].freeze US_APP_HOST = 'https://us.posthog.com' EU_APP_HOST = 'https://eu.posthog.com' SCHEDULING_APP_HOSTS = [US_APP_HOST, EU_APP_HOST].freeze @@ -130,7 +183,9 @@ def status Timeout::Error, SocketError, SystemCallError, IOError, EOFError, OpenSSL::SSL::SSLError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError, Zlib::Error ].freeze - private_constant :SEND_PATH, :UPLOADS_PATH, :STATUS_PATH, :US_APP_HOST, :EU_APP_HOST, :CLOUD_APP_HOSTS, + private_constant :SEND_PATH, :UPLOADS_PATH, :STATUS_PATH, :BATCH_PATH, :STATUS_BY_KEY_PATH, + :BATCH_ATTEMPT_TIMEOUT_SECONDS, :BATCH_RECIPIENT_FIELDS, :US_APP_HOST, :EU_APP_HOST, + :CLOUD_APP_HOSTS, :SCHEDULING_APP_HOSTS, :MAX_RETRY_DELAY_SECONDS, :UUID_PATTERN, :IDEMPOTENCY_KEY_PATTERN, :TEMPLATE_KEY_PATTERN, :HEADER_TOKEN_PATTERN, :SCHEDULED_AT_PATTERN, :SEND_NOW_TOLERANCE_SECONDS, :SCHEDULED_AT_NEEDED, @@ -277,6 +332,83 @@ def send( result end + # Queues the same email for many recipients, one email each, from a template made in PostHog or from content + # your code rendered. + # + # Pass the template form, with +template_id+, or the code form, with +template_key+, as {#send} takes them. The + # client sends the recipients in requests of at most 100 recipients and 4 MiB of JSON, one after another, and + # waits at least 45 seconds for each answer. A batch takes no +cc+, +bcc+, +attachments+ or +scheduled_at+. + # + # Each recipient has an +idempotency_key+, given or made by the client, that every retry reuses, so a retry never + # queues an email twice. Retries follow {#send}'s. After a lost answer, the client reads each email that may have + # gone out by its key. + # + # @param recipients [Array] 1 or more recipients, each a Hash with: + # - +to+ [String] the recipient's email address; + # - +distinct_id+ [String] optional: the recipient's distinct ID in your product; + # - +idempotency_key+ [String] optional: 1 to 255 visible ASCII characters, a different one for each recipient. + # Without it, the client makes one that covers its own retries but not a second call, so pass keys you store + # when a batch may be cut off and run again: a rerun within 24 hours replays the emails that went out instead + # of sending them twice. A send and a batch recipient with the same key and the same email replay each other. + # Never reuse a key for another email: after a lost answer, the client reads the email by its key, and an + # earlier email with that key reads as this one, `queued`; + # - +template_data+ [Hash] optional, only with +template_id+: values for this recipient, merged over the + # batch's +template_data+. A top-level key set here replaces the same key there. + # @param template_id [String] Template form: the UUID of a template made transactional in PostHog. + # @param template_data [Hash] Template form: values for the template, shared by every recipient. + # @param template_key [String] Code form: names the email, as {#send} takes it. Pass +subject+ and +html+, +text+ + # or both, and optionally +from+, +reply_to+, +sensitive+, +tracking+ and +capture_engagement+, the same for + # every recipient. A recipient can't carry +template_data+: send personalized content with a +template_id+ + # batch, or with {#send}. + # @param max_retries [Integer] Overrides the client's `email_request_max_retries` for each request of the batch. + # +0+ turns retries off. + # @return [BatchResult] A result per recipient, in the order of +recipients+. Check each + # {BatchEmailResult#status}, and send an `unconfirmed` email again with the same key so it goes out once. + # @raise [EmailBatchError] A request failed as a whole, such as a rate limit past its retries, so the batch + # stopped. {EmailBatchError#results} holds every recipient, those not sent as `not_attempted`. + # {EmailError#code} is `batch_unavailable` when the project can't send batches yet, and `not_found` when the + # template doesn't exist or batch sends are off: send each email the batch didn't queue with {#send} and its + # recipient's +idempotency_key+. It is `client_closed` when the client shut down during the batch. When the + # logger raises while it logs the warnings, its error propagates with this one as its +cause+. + # @raise [EmailError] The client sent nothing, such as when it is disabled or has no +secret_key+. + # @raise [ArgumentError] An argument has the wrong type or format, such as two recipients with the same + # +idempotency_key+. + def batch( + recipients:, template_id: nil, template_data: nil, template_key: nil, subject: nil, html: nil, text: nil, + from: nil, reply_to: nil, sensitive: nil, tracking: nil, capture_engagement: nil, max_retries: nil, **unexpected + ) + unless unexpected.empty? + raise ArgumentError, "A batch doesn't take #{unexpected.keys.join(', ')}, so no email was sent. A batch " \ + "takes no scheduled_at, cc, bcc or attachments, and each recipient's to goes in " \ + 'recipients.' + end + unless max_retries.nil? || retry_count?(max_retries) + raise ArgumentError, + 'max_retries must be a nonnegative integer.' + end + + fields = { + template_data: template_data, subject: subject, html: html, text: text, from: from, reply_to: reply_to, + sensitive: sensitive, tracking: tracking, capture_engagement: capture_engagement + }.compact + shared = content(template_id, template_key, fields) + members = batch_members(recipients, template_key.nil?) + run = EmailBatch.new(shared, members, parse_warnings: method(:warnings), reply_error: method(:reply_error)) + + failure = call('no email was sent', SEND_KEY_NEEDED) do |secret_key| + send_chunks(run, secret_key, max_retries || @max_retries) + end + result = failure || run.result + begin + raise failure if failure + ensure + # A logger's own error keeps the batch's error as its cause. + result.warnings.each { |warning| logger.warn("PostHog email warning #{warning.code}: #{warning.message}") } + end + + result + end + # Reads what happened to an email that {#send} queued, for 30 days after the send. # # @param message_id [String] The {SendResult#id} that {#send} returned. @@ -315,6 +447,129 @@ def close(timeout: nil) private + def batch_members(recipients, template_form) + unless recipients.is_a?(Array) + raise ArgumentError, + "recipients must be an Array of recipients, each a Hash with to, such as [{ to: 'user@example.com' }]." + end + raise ArgumentError, 'recipients must hold at least one recipient.' if recipients.empty? + + first_with_key = {} + recipients.each_with_index.map do |recipient, index| + fields = batch_recipient_fields(recipient, index) + member = batch_member(fields, index, template_form) + first = first_with_key[member.idempotency_key] ||= index + unless first == index + raise ArgumentError, "recipients[#{index}] has the same idempotency_key as recipients[#{first}]. Give each " \ + 'recipient its own key.' + end + + member + end + end + + def batch_recipient_fields(recipient, index) + fields = recipient.is_a?(Hash) ? recipient.transform_keys(&:to_s) : {} + unless fields.key?('to') + raise ArgumentError, "recipients[#{index}] must be a Hash with to, such as { to: 'user@example.com' }." + end + + unknown = fields.keys - BATCH_RECIPIENT_FIELDS + return fields if unknown.empty? + + raise ArgumentError, "recipients[#{index}] takes only to, distinct_id, idempotency_key and template_data, not " \ + "#{unknown.join(', ')}." + end + + def batch_member(fields, index, template_form) + to, distinct_id, key, data = fields.values_at('to', 'distinct_id', 'idempotency_key', 'template_data') + begin + check_recipient(to, distinct_id, key, nil) + rescue ArgumentError => e + raise ArgumentError, "recipients[#{index}]: #{e.message}" + end + key ||= SecureRandom.uuid + wire = { to: to, idempotency_key: key } + wire[:distinct_id] = distinct_id unless distinct_id.nil? + unless data.nil? + unless template_form + raise ArgumentError, "recipients[#{index}] has template_data, but a batch with template_key sends the same " \ + 'content to every recipient. Send personalized content with a template_id batch or ' \ + 'with emails.send.' + end + raise ArgumentError, "recipients[#{index}]: template_data must be a Hash." unless data.is_a?(Hash) + + wire[:message_data] = isoify_dates(data) + end + EmailBatch::Member.new(index: index, to: to, idempotency_key: key, wire: JSON.generate(wire)) + end + + # Sends the chunks one after another, and returns the EmailBatchError of the first that fails as a whole. + def send_chunks(run, secret_key, max_retries) + run.chunks.each_with_index do |chunk, position| + return run.failure(run.closed_at(position)) if position.positive? && !still_admitted? + + begin + send_chunk(run, chunk, secret_key, max_retries) + rescue EmailError => e + run.stop(position, e) + read_lost(run, secret_key) + return run.failure(e) + end + end + nil + end + + def send_chunk(run, chunk, secret_key, max_retries) + uri = URI(@app_host + BATCH_PATH) + timeout = [@timeout.to_f, BATCH_ATTEMPT_TIMEOUT_SECONDS].max + attempts = 0 + with_retries(max_retries) do + attempts += 1 + if attempts > 1 && !still_admitted? + raise EmailError.new( + code: 'client_closed', + message: "The PostHog client is shut down, so it didn't retry this request of the batch." + ) + end + + begin + reply = request(Net::HTTP::Post.new(uri), uri, secret_key, JSON_CONTENT, chunk.body, timeout: timeout) + rescue EmailError + run.lost(chunk) + raise + end + run.answer(chunk, reply) + end + end + + # After a lost answer, a status read by key tells whether PostHog accepted the email. It reads each key once and + # stops at the first error but a 404, so a failing PostHog doesn't hold the caller up. + def read_lost(run, secret_key) + run.lost_keys.each do |index, key| + break unless still_admitted? + + status = status_by_key(key, secret_key) + break if status == :stop + + run.accepted(index, status) if status + end + end + + def status_by_key(key, secret_key) + uri = URI("#{@app_host}#{STATUS_BY_KEY_PATH}?#{URI.encode_www_form(idempotency_key: key)}") + parse_status_reply(request(Net::HTTP::Get.new(uri), uri, secret_key, {})) + rescue EmailError => e + e.status_code == 404 ? nil : :stop + end + + def still_admitted? + @mutex.synchronize do + forget_parent_requests + !@closed + end + end + def check_options(timeout, max_retries, migrated_from) raise ArgumentError, 'email_request_timeout_seconds must be a positive number.' unless positive?(timeout) raise ArgumentError, 'email_request_max_retries must be a nonnegative integer.' unless retry_count?(max_retries) @@ -655,21 +910,21 @@ def upload_failed(file, status, answer, retry_after) ) end - def request(request, uri, secret_key, headers, body = nil) + def request(request, uri, secret_key, headers, body = nil, timeout: @timeout) request['Authorization'] = "Bearer #{secret_key}" request['Accept'] = 'application/json' request['User-Agent'] = @user_agent if @user_agent request['X-PostHog-Migrated-From'] = @migrated_from if @migrated_from - status, answer, retry_after = exchange(request, uri, headers, body) + status, answer, retry_after = exchange(request, uri, headers, body, timeout: timeout) [status, parse_json(answer), retry_after] end - def exchange(request, uri, headers, body) + def exchange(request, uri, headers, body, timeout: @timeout) headers.each { |name, value| request[name] = value } request.body = body if body head = nil - response = Net::HTTP.start(uri.hostname, uri.port, connection_options(uri)) do |http| + response = Net::HTTP.start(uri.hostname, uri.port, connection_options(uri, timeout)) do |http| http.request(request) { |started| head = started } end [response.code.to_i, response.body, parse_retry_after(response['Retry-After'])] @@ -679,9 +934,9 @@ def exchange(request, uri, headers, body) retry_after: head && parse_retry_after(head['Retry-After'])) end - def connection_options(uri) + def connection_options(uri, timeout) options = { - use_ssl: uri.scheme == 'https', open_timeout: @timeout, read_timeout: @timeout, write_timeout: @timeout, + use_ssl: uri.scheme == 'https', open_timeout: timeout, read_timeout: timeout, write_timeout: timeout, # Net::HTTP returns a body cut off by a closed connection as if it were whole. Raise instead. max_retries: 0, ignore_eof: false } diff --git a/public_api_snapshot.txt b/public_api_snapshot.txt index 8ff0d5d2..9dc3951f 100644 --- a/public_api_snapshot.txt +++ b/public_api_snapshot.txt @@ -63,6 +63,9 @@ constant PostHog::Defaults::Request::PATH: String constant PostHog::Defaults::Request::PORT: Integer constant PostHog::Defaults::Request::RETRIES: Integer constant PostHog::Defaults::Request::SSL: Boolean +class PostHog::EmailBatchError < PostHog::EmailError +instance_method PostHog::EmailBatchError#results() +instance_method PostHog::EmailBatchError#warnings() class PostHog::EmailError < StandardError instance_method PostHog::EmailError#code() instance_method PostHog::EmailError#docs_url() @@ -74,9 +77,42 @@ instance_method PostHog::EmailError#retry_after() instance_method PostHog::EmailError#status_code() instance_method PostHog::EmailError#why() class PostHog::Emails +instance_method PostHog::Emails#batch(recipients:, template_id: ..., template_data: ..., template_key: ..., subject: ..., html: ..., text: ..., from: ..., reply_to: ..., sensitive: ..., tracking: ..., capture_engagement: ..., max_retries: ..., **unexpected) instance_method PostHog::Emails#get(message_id) instance_method PostHog::Emails#send(to:, template_id: ..., template_data: ..., template_key: ..., subject: ..., html: ..., text: ..., from: ..., reply_to: ..., cc: ..., bcc: ..., attachments: ..., sensitive: ..., tracking: ..., capture_engagement: ..., distinct_id: ..., idempotency_key: ..., max_retries: ..., scheduled_at: ...) class_method PostHog::Emails.logger() +class PostHog::Emails::BatchEmailResult < Struct +instance_method PostHog::Emails::BatchEmailResult#error() +instance_method PostHog::Emails::BatchEmailResult#error=(_) +instance_method PostHog::Emails::BatchEmailResult#idempotency_key() +instance_method PostHog::Emails::BatchEmailResult#idempotency_key=(_) +instance_method PostHog::Emails::BatchEmailResult#index() +instance_method PostHog::Emails::BatchEmailResult#index=(_) +instance_method PostHog::Emails::BatchEmailResult#later_error() +instance_method PostHog::Emails::BatchEmailResult#later_error=(_) +instance_method PostHog::Emails::BatchEmailResult#message_id() +instance_method PostHog::Emails::BatchEmailResult#message_id=(_) +instance_method PostHog::Emails::BatchEmailResult#replayed() +instance_method PostHog::Emails::BatchEmailResult#replayed=(_) +instance_method PostHog::Emails::BatchEmailResult#status() +instance_method PostHog::Emails::BatchEmailResult#status=(_) +instance_method PostHog::Emails::BatchEmailResult#to() +instance_method PostHog::Emails::BatchEmailResult#to=(_) +class_method PostHog::Emails::BatchEmailResult.[](*arg0) +class_method PostHog::Emails::BatchEmailResult.inspect() +class_method PostHog::Emails::BatchEmailResult.keyword_init?() +class_method PostHog::Emails::BatchEmailResult.members() +class_method PostHog::Emails::BatchEmailResult.new(*arg0) +class PostHog::Emails::BatchResult < Struct +instance_method PostHog::Emails::BatchResult#results() +instance_method PostHog::Emails::BatchResult#results=(_) +instance_method PostHog::Emails::BatchResult#warnings() +instance_method PostHog::Emails::BatchResult#warnings=(_) +class_method PostHog::Emails::BatchResult.[](*arg0) +class_method PostHog::Emails::BatchResult.inspect() +class_method PostHog::Emails::BatchResult.keyword_init?() +class_method PostHog::Emails::BatchResult.members() +class_method PostHog::Emails::BatchResult.new(*arg0) class PostHog::Emails::SendResult < Struct instance_method PostHog::Emails::SendResult#id() instance_method PostHog::Emails::SendResult#id=(_) diff --git a/spec/posthog/emails_batch_spec.rb b/spec/posthog/emails_batch_spec.rb new file mode 100644 index 00000000..b00893d6 --- /dev/null +++ b/spec/posthog/emails_batch_spec.rb @@ -0,0 +1,303 @@ +# frozen_string_literal: true + +require 'spec_helper' + +module PostHog + describe Emails do + let(:batch_url) { 'https://us.posthog.com/api/messaging/send/email_batch/' } + let(:status_by_key) { 'https://us.posthog.com/api/messaging/emails/status/?idempotency_key=' } + let(:status_by_key_url) { %r{\Ahttps://us\.posthog\.com/api/messaging/emails/status/\?idempotency_key=} } + let(:template_id) { '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b' } + let(:uuid_v4) { /\A\h{8}-\h{4}-4\h{3}-[89ab]\h{3}-\h{12}\z/ } + let(:options) { { api_key: API_KEY, secret_key: 'phs_test', test_mode: true } } + let(:client) { Client.new(options) } + let(:emails) { client.emails.tap { |emails| allow(emails).to receive(:sleep) { |seconds| delays << seconds } } } + let(:delays) { [] } + let(:ada) { { to: 'ada@example.com', idempotency_key: 'welcome:ada', template_data: { name: 'Ada' } } } + let(:alan) { { to: 'alan@example.com', distinct_id: 'user_2', idempotency_key: 'welcome:alan' } } + + before do + stub_request(:get, %r{/flags/definitions}).to_return(status: 200, body: '{"flags":[]}') + end + + after { client.shutdown(timeout: 1) } + + def queued(message_id, replayed: false) + { message_id: message_id, status: 'queued', replayed: replayed } + end + + def slot_error(code, status, message_id: 'msg_x') + { message_id: message_id, error: { code: code, detail: "PostHog didn't queue it: #{code}.", status: status } } + end + + def answer(*slots, warnings: nil) + { status: 200, body: JSON.generate({ results: slots, warnings: warnings }.compact) } + end + + def refuse(status, code, **fields) + { status: status, body: JSON.generate({ code: code }.merge(fields)) } + end + + def batch_bodies + bodies = [] + expect(a_request(:post, batch_url).with { |request| bodies << JSON.parse(request.body) }) + .to have_been_made.at_least_once + bodies + end + + def batch_template(recipients, **extra) + emails.batch(template_id: template_id, template_data: { product: 'Hog' }, recipients: recipients, **extra) + end + + def statuses(results) + results.map(&:status) + end + + describe '#batch' do + it 'sends one request and returns a result per recipient, in order' do + stub_request(:post, batch_url).to_return(answer(queued('msg_1'), queued('msg_2', replayed: true))) + + result = batch_template([ada, alan]) + + expect(result.results.map(&:to_h)).to eq( + [{ index: 0, to: 'ada@example.com', idempotency_key: 'welcome:ada', status: 'queued', message_id: 'msg_1', + replayed: false, error: nil, later_error: nil }, + { index: 1, to: 'alan@example.com', idempotency_key: 'welcome:alan', status: 'queued', + message_id: 'msg_2', replayed: true, error: nil, later_error: nil }] + ) + expect(batch_bodies).to eq( + [{ 'template_id' => template_id, 'message_data' => { 'product' => 'Hog' }, + 'recipients' => [ + { 'to' => 'ada@example.com', 'idempotency_key' => 'welcome:ada', 'message_data' => { 'name' => 'Ada' } }, + { 'to' => 'alan@example.com', 'idempotency_key' => 'welcome:alan', 'distinct_id' => 'user_2' } + ] }] + ) + expect(a_request(:post, batch_url).with(headers: { 'Authorization' => 'Bearer phs_test' })).to have_been_made + end + + it 'makes a key for each recipient without one, and keeps it on every retry' do + stub_request(:post, batch_url).to_return(refuse(503, 'delivery_unavailable'), + answer(queued('msg_1'), queued('msg_2'))) + + result = batch_template([{ to: 'ada@example.com' }, { 'to' => 'alan@example.com' }]) + + keys = result.results.map(&:idempotency_key) + expect(keys).to all(match(uuid_v4)) + expect(keys.uniq.size).to eq(2) + expect(a_request(:post, batch_url)).to have_been_made.twice + # WebMock records identical requests once, so one body means both attempts sent the same keys. + expect(batch_bodies.map { |body| body['recipients'].map { |recipient| recipient['idempotency_key'] } }) + .to eq([keys]) + expect(statuses(result.results)).to eq(%w[queued queued]) + end + + it 'sends the code form with the same content for every recipient' do + stub_request(:post, batch_url).to_return(answer(queued('msg_1'))) + + emails.batch(template_key: 'launch-news', subject: 'We launched', html: '

Hi

', from: 'a@example.com', + recipients: [{ to: 'ada@example.com', idempotency_key: 'launch:ada' }]) + + expect(batch_bodies.first).to eq( + 'template_key' => 'launch-news', 'subject' => 'We launched', 'html' => '

Hi

', + 'from' => 'a@example.com', + 'recipients' => [{ 'to' => 'ada@example.com', 'idempotency_key' => 'launch:ada' }] + ) + end + + it 'splits more than 100 recipients into requests of at most 100, one after another' do + recipients = Array.new(101) { |index| { to: "user#{index}@example.com", idempotency_key: "key-#{index}" } } + stub_request(:post, batch_url).to_return( + answer(*Array.new(100) { |index| queued("msg_#{index}") }), answer(queued('msg_100')) + ) + + result = batch_template(recipients) + + expect(batch_bodies.map { |body| body['recipients'].size }).to eq([100, 1]) + expect(result.results.map(&:message_id)).to eq(Array.new(101) { |index| "msg_#{index}" }) + expect(result.results.map(&:index)).to eq((0..100).to_a) + end + + it "returns each recipient PostHog refused as failed and one it didn't confirm as unconfirmed" do + stub_request(:post, batch_url).to_return( + answer(slot_error('recipient_suppressed', 422, message_id: 'msg_1'), + slot_error('delivery_unavailable', 503, message_id: 'msg_2'), 'not a result') + ) + + results = batch_template([ada, alan, { to: 'grace@example.com' }]).results + + expect(statuses(results)).to eq(%w[failed unconfirmed unconfirmed]) + expect(results.map { |result| [result.message_id, result.error.code, result.error.name] }).to eq( + [%w[msg_1 recipient_suppressed validation_error], %w[msg_2 delivery_unavailable service_unavailable], + [nil, 'api_error', 'application_error']] + ) + expect(results.first.error.status_code).to eq(422) + expect(results.first.error.message_id).to eq('msg_1') + end + + it 'fails a recipient too large for one request and sends the rest' do + stub_request(:post, batch_url).to_return(answer(queued('msg_2'))) + huge = { to: 'ada@example.com', template_data: { note: 'x' * (4 * 1024 * 1024) } } + + results = batch_template([huge, alan]).results + + expect(statuses(results)).to eq(%w[failed queued]) + expect([results.first.error.code, results.first.error.field]).to eq(%w[content_too_large recipients]) + expect(batch_bodies.map { |body| body['recipients'].map { |recipient| recipient['to'] } }) + .to eq([['alan@example.com']]) + end + + it 'logs each warning once' do + warning = { code: 'unverified_link', detail: 'A link points to an unverified domain.' } + recipients = Array.new(101) { |index| { to: "user#{index}@example.com" } } + stub_request(:post, batch_url).to_return( + answer(*Array.new(100) { |index| queued("msg_#{index}") }, warnings: [warning]), + answer(queued('msg_100'), warnings: [warning]) + ) + logger = Logger.new(File::NULL) + allow(logger).to receive(:warn) + PostHog::Logging.logger = logger + + result = batch_template(recipients) + + expect(result.warnings.map(&:code)).to eq(['unverified_link']) + expect(logger).to have_received(:warn).once + end + + it "lets the logger's error through, with a failed batch's error as its cause" do + recipients = Array.new(101) { |index| { to: "user#{index}@example.com", idempotency_key: "key-#{index}" } } + stub_request(:post, batch_url).to_return( + answer(*Array.new(100) { |index| queued("msg_#{index}") }, warnings: [{ code: 'unverified_link' }]), + refuse(409, 'batch_unavailable') + ) + logger = Logger.new(File::NULL) + allow(logger).to receive(:warn).and_raise(IOError, 'log device closed') + PostHog::Logging.logger = logger + + expect { batch_template(recipients) }.to raise_error(IOError, 'log device closed') { |error| + expect(error.cause).to be_a(EmailBatchError) + expect(error.cause.results.map(&:status).tally).to eq('queued' => 100, 'failed' => 1) + } + end + + context 'when a request fails as a whole' do + let(:recipients) do + Array.new(201) do |index| + { to: "user#{index}@example.com", idempotency_key: "key-#{index}" } + end + end + + it 'stops the batch and raises EmailBatchError with every recipient' do + stub_request(:post, batch_url).to_return( + answer(*Array.new(100) { |index| queued("msg_#{index}") }), + refuse(400, 'invalid_recipient', detail: 'A recipient is invalid.', attr: 'recipients__7__to') + ) + + expect { batch_template(recipients) }.to raise_error(EmailBatchError) { |error| + expect([error.code, error.status_code, + error.field]).to eq(['invalid_recipient', 400, 'recipients__107__to']) + expect(error.results.size).to eq(201) + expect(error.results.map(&:status).tally).to eq('queued' => 100, 'failed' => 100, 'not_attempted' => 1) + expect(error.results[100].error.code).to eq('invalid_recipient') + expect(error.results[200].error.code).to eq('not_attempted') + } + expect(a_request(:post, batch_url)).to have_been_made.twice + end + + it 'raises batch_unavailable with the fix to send each email on its own' do + stub_request(:post, batch_url).to_return(refuse(409, 'batch_unavailable', detail: 'Not yet.')) + + expect { batch_template([ada]) }.to raise_error(EmailBatchError) { |error| + expect([error.code, error.status_code]).to eq(['batch_unavailable', 409]) + expect(error.fix).to include('send', 'idempotency_key') + expect(error.results.map(&:status)).to eq(['failed']) + } + end + + it 'names a 404 as a missing template or batch sends that are off' do + stub_request(:post, batch_url).to_return(status: 404, body: '') + + expect { batch_template([ada]) }.to raise_error(EmailBatchError) { |error| + expect([error.code, error.name]).to eq(%w[not_found not_found]) + expect(error.why).to include("template doesn't exist") + } + end + + it 'keeps a recipient a lost answer may have queued unconfirmed, and reads its status by key' do + stub_request(:post, batch_url).to_raise(Errno::ECONNRESET) + stub_request(:get, "#{status_by_key}welcome%3Aada").to_return(status: 404, body: '{"code":"not_found"}') + stub_request(:get, "#{status_by_key}welcome%3Aalan").to_return( + status: 200, body: JSON.generate(id: 'msg_alan', status: 'queued', created_at: '2026-11-24T08:00:00Z', + status_at: '2026-11-24T08:00:00Z') + ) + + expect { batch_template([ada, alan], max_retries: 1) }.to raise_error(EmailBatchError) { |error| + expect(error.code).to eq('network_error') + expect(error.results.map { |result| [result.status, result.message_id] }) + .to eq([['unconfirmed', nil], %w[queued msg_alan]]) + expect(error.results.first.error.code).to eq('delivery_unavailable') + } + expect(a_request(:post, batch_url)).to have_been_made.twice + expect(a_request(:get, status_by_key_url)).to have_been_made.twice + end + + it 'keeps the first unconfirmed answer and adds what a later retry said' do + stub_request(:post, batch_url).to_return( + refuse(503, 'delivery_unavailable'), + answer(slot_error('idempotency_key_reused', 422, message_id: 'msg_1')) + ) + + result = batch_template([ada]) + + expect(result.results.first.to_h.slice(:status, + :message_id)).to eq(status: 'unconfirmed', message_id: 'msg_1') + expect(result.results.first.error.code).to eq('delivery_unavailable') + expect(result.results.first.later_error.code).to eq('idempotency_key_reused') + end + + it 'stops before the next request once the client shuts down' do + recipients = Array.new(101) { |index| { to: "user#{index}@example.com" } } + stub_request(:post, batch_url).to_return do + emails.close(timeout: 0) + answer(*Array.new(100) { |index| queued("msg_#{index}") }) + end + + expect { batch_template(recipients) }.to raise_error(EmailBatchError) { |error| + expect(error.code).to eq('client_closed') + expect(error.results.map(&:status).tally).to eq('queued' => 100, 'not_attempted' => 1) + } + expect(a_request(:post, batch_url)).to have_been_made.once + end + end + + it 'waits at least 45 seconds for each answer' do + stub_request(:post, batch_url).to_return(answer(queued('msg_1'))) + allow(Net::HTTP).to receive(:start).and_call_original + + batch_template([ada]) + + expect(Net::HTTP).to have_received(:start) + .with('us.posthog.com', 443, hash_including(read_timeout: 45.0, open_timeout: 45.0)) + end + + it 'refuses a bad batch before any request' do + [ + [{ recipients: [] }, /at least one recipient/], + [{ recipients: ada }, /recipients must be an Array/], + [{ recipients: [ada, ada.merge(to: 'b@example.com')] }, + /recipients\[1\] has the same idempotency_key as recipients\[0\]/], + [{ recipients: [{ to: '' }] }, /recipients\[0\]: to must be/], + [{ recipients: [{ to: 'a@example.com', cc: 'b@example.com' }] }, /recipients\[0\] takes only/], + [{ recipients: [ada], scheduled_at: Time.now }, /doesn't take scheduled_at/], + [{ recipients: [ada], cc: 'b@example.com' }, /doesn't take cc/], + [{ recipients: [ada], template_id: 'nope' }, /template_id must be/] + ].each do |args, message| + expect { emails.batch(template_id: template_id, **args) }.to raise_error(ArgumentError, message) + end + expect do + emails.batch(template_key: 'launch', subject: 'Hi', text: 'Hi', recipients: [ada]) + end.to raise_error(ArgumentError, /recipients\[0\] has template_data/) + expect(a_request(:any, %r{/api/messaging/})).not_to have_been_made + end + end + end +end From 101881aa9a2201baebe3f9c2429571f8f28d264d Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:31:28 +0100 Subject: [PATCH 02/32] fix(emails): keep a failed status read unconfirmed and tighten batch 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 --- .changeset/email-batch-sends.md | 2 +- lib/posthog/email_batch.rb | 41 +++++++++++---- lib/posthog/emails.rb | 44 +++++++--------- public_api_snapshot.txt | 2 +- spec/posthog/emails_batch_spec.rb | 87 ++++++++++++++++++++++++++----- 5 files changed, 125 insertions(+), 51 deletions(-) diff --git a/.changeset/email-batch-sends.md b/.changeset/email-batch-sends.md index 50822ae1..a7199056 100644 --- a/.changeset/email-batch-sends.md +++ b/.changeset/email-batch-sends.md @@ -2,4 +2,4 @@ "posthog-ruby": minor --- -Send the same transactional email to many recipients with `emails.batch`, one email each, from a template made in PostHog with `template_data` per recipient, or from content your code rendered. The client sends at most 100 recipients and 4 MiB per request, one request after another, and returns a result per recipient in order: `queued`, `failed`, `unconfirmed` or `not_attempted`. Each recipient has its own `idempotency_key`, given or made by the client, so a retry or a rerun within 24 hours never sends an email twice. A request that fails as a whole stops the batch and raises `EmailBatchError` with every recipient's result. +Send the same transactional email to many recipients with `emails.batch`, one email each, from a template made in PostHog with `template_data` per recipient, or from content your code rendered. The client sends at most 100 recipients and 4 MiB per request, one request after another, and returns a result per recipient in order: `queued`, `failed`, `unconfirmed` or `not_attempted`. Each recipient has its own `idempotency_key`, given or made by the client, so the client's own retries never send an email twice. To rerun a batch that was cut off, pass the keys you stored: a rerun with the same keys within 24 hours replays the emails that went out. A request that fails as a whole stops the batch and raises `EmailBatchError` with every recipient's result. diff --git a/lib/posthog/email_batch.rb b/lib/posthog/email_batch.rb index 3985cfb2..a4bafca7 100644 --- a/lib/posthog/email_batch.rb +++ b/lib/posthog/email_batch.rb @@ -26,7 +26,13 @@ class EmailBatch private_constant :UNCONFIRMED_CODES, :UNAVAILABLE_FIX, :NOT_FOUND, :RESULT_DEFAULTS Member = Struct.new(:index, :to, :idempotency_key, :wire, keyword_init: true) - Chunk = Struct.new(:body, :indices, keyword_init: true) + # The recipients of one request. The body is built when the request goes out, so a large batch holds one at a + # time. + Chunk = Struct.new(:empty, :recipients, :indices, keyword_init: true) do + def body + "#{empty.delete_suffix(']}')}#{recipients.map(&:wire).join(',')}]}" + end + end attr_reader :chunks @@ -44,7 +50,6 @@ def initialize(shared, members, parse_warnings:, reply_error:) @chunks = split(JSON.generate(shared.merge(recipients: []))) end - # An attempt that may have queued some of the chunk got no usable answer. def lost(chunk) chunk.indices.each do |index| @maybe_queued << index @@ -53,7 +58,6 @@ def lost(chunk) end end - # Records PostHog's answer to the chunk, or raises the error of a refused request. def answer(chunk, (status, payload, retry_after)) fields = payload.is_a?(Hash) ? payload : {} unless status.between?(200, 299) @@ -73,7 +77,6 @@ def answer(chunk, (status, payload, retry_after)) end end - # The request of the chunk at +position+ failed as a whole, so the batch stops there. def stop(position, error) later = error.status_code && error.status_code < 500 ? error : nil @chunks[position].indices.each do |index| @@ -91,7 +94,6 @@ def stop(position, error) )) end - # The client shut down before the chunk at +position+ went out. def closed_at(position) error = EmailError.new(code: 'client_closed', message: "The PostHog client is shut down, so the rest of the batch wasn't sent.") @@ -99,15 +101,21 @@ def closed_at(position) error end - # Recipients a lost answer left without a message ID, with their keys. def lost_keys @maybe_queued.sort.filter_map do |index| [index, @members[index].idempotency_key] if @results[index].message_id.nil? end end - # A status read by key found the email, so PostHog accepted it. - def accepted(index, status) + # A status read by key found the email. PostHog records a refusal before queueing, such as a suppressed + # address, as a failed email, so only another status shows that PostHog accepted it. + def found(index, status) + if status.status == 'failed' + earlier = @results[index] + set(index, 'unconfirmed', message_id: status.id, error: earlier.error, later_error: failed_status(status)) + return + end + @maybe_queued.delete(index) set(index, 'queued', message_id: status.id) end @@ -123,6 +131,11 @@ def failure(error) private def split(empty) + if empty.bytesize >= MAX_BODY_BYTES + raise ArgumentError, "The batch's shared content is larger than one batch request takes, 4 MiB, so no email " \ + 'was sent. Make the template_data, subject, html or text smaller.' + end + chunks = [] current = [] size = empty.bytesize @@ -146,7 +159,7 @@ def split(empty) end def chunk(empty, members) - Chunk.new(body: "#{empty.delete_suffix(']}')}#{members.map(&:wire).join(',')}]}", indices: members.map(&:index)) + Chunk.new(empty: empty, recipients: members, indices: members.map(&:index)) end def settle(index, slot) @@ -210,7 +223,8 @@ def slot_error(error, message_id) code = text(error['code']) || 'api_error' status = error['status'].is_a?(Integer) ? error['status'] : nil - EmailError.new(code: code, status_code: status, message_id: message_id, + # EmailError#message_id means PostHog may have accepted the email, so a refusal leaves it on the result only. + EmailError.new(code: code, status_code: status, message_id: (message_id if UNCONFIRMED_CODES.include?(code)), message: text(error['detail']) || "PostHog didn't queue this email: #{code}.") end @@ -220,6 +234,13 @@ def unconfirmed(message_id) 'same idempotency_key within 24 hours, so it goes out once.') end + def failed_status(status) + reason = text(status.reason) + EmailError.new(code: reason || 'failed', message_id: status.id, + message: "PostHog's status of this email reads failed#{" (#{reason})" if reason}, so it may not " \ + 'have gone out.') + end + def recipient_too_large EmailError.new(code: 'content_too_large', field: 'recipients', message: "This recipient's email is larger than one batch request takes, so it wasn't sent.", diff --git a/lib/posthog/emails.rb b/lib/posthog/emails.rb index dd8c708c..4e643581 100644 --- a/lib/posthog/emails.rb +++ b/lib/posthog/emails.rb @@ -144,7 +144,8 @@ def status STATUS_PATH = '/api/messaging/emails/%s/' BATCH_PATH = '/api/messaging/send/email_batch/' STATUS_BY_KEY_PATH = '/api/messaging/emails/status/' - # PostHog waits up to 30 seconds for its pipeline before it answers a batch. + # PostHog waits up to 30 seconds for its pipeline before it answers a batch. Connecting and writing keep the + # client's timeout. BATCH_ATTEMPT_TIMEOUT_SECONDS = 45.0 BATCH_RECIPIENT_FIELDS = %w[to distinct_id idempotency_key template_data].freeze US_APP_HOST = 'https://us.posthog.com' @@ -340,8 +341,8 @@ def send( # waits at least 45 seconds for each answer. A batch takes no +cc+, +bcc+, +attachments+ or +scheduled_at+. # # Each recipient has an +idempotency_key+, given or made by the client, that every retry reuses, so a retry never - # queues an email twice. Retries follow {#send}'s. After a lost answer, the client reads each email that may have - # gone out by its key. + # queues an email twice. Retries follow {#send}'s. When a request of the batch fails as a whole, the client reads + # by its key each email of the batch whose answer was lost. # # @param recipients [Array] 1 or more recipients, each a Hash with: # - +to+ [String] the recipient's email address; @@ -375,13 +376,8 @@ def send( # +idempotency_key+. def batch( recipients:, template_id: nil, template_data: nil, template_key: nil, subject: nil, html: nil, text: nil, - from: nil, reply_to: nil, sensitive: nil, tracking: nil, capture_engagement: nil, max_retries: nil, **unexpected + from: nil, reply_to: nil, sensitive: nil, tracking: nil, capture_engagement: nil, max_retries: nil ) - unless unexpected.empty? - raise ArgumentError, "A batch doesn't take #{unexpected.keys.join(', ')}, so no email was sent. A batch " \ - "takes no scheduled_at, cc, bcc or attachments, and each recipient's to goes in " \ - 'recipients.' - end unless max_retries.nil? || retry_count?(max_retries) raise ArgumentError, 'max_retries must be a nonnegative integer.' @@ -469,7 +465,7 @@ def batch_members(recipients, template_form) end def batch_recipient_fields(recipient, index) - fields = recipient.is_a?(Hash) ? recipient.transform_keys(&:to_s) : {} + fields = recipient.is_a?(Hash) ? Utils.stringify_keys(recipient) : {} unless fields.key?('to') raise ArgumentError, "recipients[#{index}] must be a Hash with to, such as { to: 'user@example.com' }." end @@ -504,7 +500,6 @@ def batch_member(fields, index, template_form) EmailBatch::Member.new(index: index, to: to, idempotency_key: key, wire: JSON.generate(wire)) end - # Sends the chunks one after another, and returns the EmailBatchError of the first that fails as a whole. def send_chunks(run, secret_key, max_retries) run.chunks.each_with_index do |chunk, position| return run.failure(run.closed_at(position)) if position.positive? && !still_admitted? @@ -522,11 +517,10 @@ def send_chunks(run, secret_key, max_retries) def send_chunk(run, chunk, secret_key, max_retries) uri = URI(@app_host + BATCH_PATH) - timeout = [@timeout.to_f, BATCH_ATTEMPT_TIMEOUT_SECONDS].max - attempts = 0 - with_retries(max_retries) do - attempts += 1 - if attempts > 1 && !still_admitted? + read_timeout = [@timeout.to_f, BATCH_ATTEMPT_TIMEOUT_SECONDS].max + body = chunk.body + with_retries(max_retries) do |attempt| + if attempt.positive? && !still_admitted? raise EmailError.new( code: 'client_closed', message: "The PostHog client is shut down, so it didn't retry this request of the batch." @@ -534,7 +528,7 @@ def send_chunk(run, chunk, secret_key, max_retries) end begin - reply = request(Net::HTTP::Post.new(uri), uri, secret_key, JSON_CONTENT, chunk.body, timeout: timeout) + reply = request(Net::HTTP::Post.new(uri), uri, secret_key, JSON_CONTENT, body, read_timeout: read_timeout) rescue EmailError run.lost(chunk) raise @@ -552,7 +546,7 @@ def read_lost(run, secret_key) status = status_by_key(key, secret_key) break if status == :stop - run.accepted(index, status) if status + run.found(index, status) if status end end @@ -805,7 +799,7 @@ def finish def with_retries(max_retries) attempt = 0 begin - yield + yield attempt rescue EmailError => e delay = retry_delay(e, attempt, max_retries) raise if delay.nil? @@ -910,21 +904,21 @@ def upload_failed(file, status, answer, retry_after) ) end - def request(request, uri, secret_key, headers, body = nil, timeout: @timeout) + def request(request, uri, secret_key, headers, body = nil, read_timeout: @timeout) request['Authorization'] = "Bearer #{secret_key}" request['Accept'] = 'application/json' request['User-Agent'] = @user_agent if @user_agent request['X-PostHog-Migrated-From'] = @migrated_from if @migrated_from - status, answer, retry_after = exchange(request, uri, headers, body, timeout: timeout) + status, answer, retry_after = exchange(request, uri, headers, body, read_timeout: read_timeout) [status, parse_json(answer), retry_after] end - def exchange(request, uri, headers, body, timeout: @timeout) + def exchange(request, uri, headers, body, read_timeout: @timeout) headers.each { |name, value| request[name] = value } request.body = body if body head = nil - response = Net::HTTP.start(uri.hostname, uri.port, connection_options(uri, timeout)) do |http| + response = Net::HTTP.start(uri.hostname, uri.port, connection_options(uri, read_timeout)) do |http| http.request(request) { |started| head = started } end [response.code.to_i, response.body, parse_retry_after(response['Retry-After'])] @@ -934,9 +928,9 @@ def exchange(request, uri, headers, body, timeout: @timeout) retry_after: head && parse_retry_after(head['Retry-After'])) end - def connection_options(uri, timeout) + def connection_options(uri, read_timeout) options = { - use_ssl: uri.scheme == 'https', open_timeout: timeout, read_timeout: timeout, write_timeout: timeout, + use_ssl: uri.scheme == 'https', open_timeout: @timeout, read_timeout: read_timeout, write_timeout: @timeout, # Net::HTTP returns a body cut off by a closed connection as if it were whole. Raise instead. max_retries: 0, ignore_eof: false } diff --git a/public_api_snapshot.txt b/public_api_snapshot.txt index 9dc3951f..0b2b7ce5 100644 --- a/public_api_snapshot.txt +++ b/public_api_snapshot.txt @@ -77,7 +77,7 @@ instance_method PostHog::EmailError#retry_after() instance_method PostHog::EmailError#status_code() instance_method PostHog::EmailError#why() class PostHog::Emails -instance_method PostHog::Emails#batch(recipients:, template_id: ..., template_data: ..., template_key: ..., subject: ..., html: ..., text: ..., from: ..., reply_to: ..., sensitive: ..., tracking: ..., capture_engagement: ..., max_retries: ..., **unexpected) +instance_method PostHog::Emails#batch(recipients:, template_id: ..., template_data: ..., template_key: ..., subject: ..., html: ..., text: ..., from: ..., reply_to: ..., sensitive: ..., tracking: ..., capture_engagement: ..., max_retries: ...) instance_method PostHog::Emails#get(message_id) instance_method PostHog::Emails#send(to:, template_id: ..., template_data: ..., template_key: ..., subject: ..., html: ..., text: ..., from: ..., reply_to: ..., cc: ..., bcc: ..., attachments: ..., sensitive: ..., tracking: ..., capture_engagement: ..., distinct_id: ..., idempotency_key: ..., max_retries: ..., scheduled_at: ...) class_method PostHog::Emails.logger() diff --git a/spec/posthog/emails_batch_spec.rb b/spec/posthog/emails_batch_spec.rb index b00893d6..bdc41865 100644 --- a/spec/posthog/emails_batch_spec.rb +++ b/spec/posthog/emails_batch_spec.rb @@ -131,7 +131,7 @@ def statuses(results) [nil, 'api_error', 'application_error']] ) expect(results.first.error.status_code).to eq(422) - expect(results.first.error.message_id).to eq('msg_1') + expect(results.map { |result| result.error.message_id }).to eq([nil, 'msg_2', nil]) end it 'fails a recipient too large for one request and sends the rest' do @@ -146,6 +146,23 @@ def statuses(results) .to eq([['alan@example.com']]) end + it 'splits the recipients so no request is over 4 MiB' do + stub_request(:post, batch_url).to_return(answer(queued('msg_0'), queued('msg_1')), answer(queued('msg_2'))) + note = 'x' * (1536 * 1024) + recipients = Array.new(3) { |index| { to: "user#{index}@example.com", template_data: { note: note } } } + + result = batch_template(recipients) + + expect(statuses(result.results)).to eq(%w[queued queued queued]) + expect(batch_bodies.map { |body| body['recipients'].size }).to eq([2, 1]) + end + + it 'refuses shared content too large for any request before sending' do + expect { batch_template([ada], template_data: { note: 'x' * (4 * 1024 * 1024) }) } + .to raise_error(ArgumentError, /shared content is larger than one batch request takes/) + expect(a_request(:any, %r{/api/messaging/})).not_to have_been_made + end + it 'logs each warning once' do warning = { code: 'unverified_link', detail: 'A link points to an unverified domain.' } recipients = Array.new(101) { |index| { to: "user#{index}@example.com" } } @@ -153,14 +170,13 @@ def statuses(results) answer(*Array.new(100) { |index| queued("msg_#{index}") }, warnings: [warning]), answer(queued('msg_100'), warnings: [warning]) ) - logger = Logger.new(File::NULL) - allow(logger).to receive(:warn) - PostHog::Logging.logger = logger + log = StringIO.new + PostHog::Logging.logger = Logger.new(log) result = batch_template(recipients) expect(result.warnings.map(&:code)).to eq(['unverified_link']) - expect(logger).to have_received(:warn).once + expect(log.string.scan('PostHog email warning unverified_link').size).to eq(1) end it "lets the logger's error through, with a failed batch's error as its cause" do @@ -240,6 +256,20 @@ def statuses(results) expect(a_request(:get, status_by_key_url)).to have_been_made.twice end + it 'keeps a recipient whose status by key reads failed unconfirmed' do + stub_request(:post, batch_url).to_raise(Errno::ECONNRESET) + stub_request(:get, "#{status_by_key}welcome%3Aada").to_return( + status: 200, body: JSON.generate(id: 'msg_ada', status: 'failed', reason: 'recipient_suppressed', + created_at: '2026-11-24T08:00:00Z', status_at: '2026-11-24T08:00:00Z') + ) + + expect { batch_template([ada], max_retries: 0) }.to raise_error(EmailBatchError) { |error| + result = error.results.first + expect([result.status, result.message_id]).to eq(%w[unconfirmed msg_ada]) + expect([result.error.code, result.later_error.code]).to eq(%w[delivery_unavailable recipient_suppressed]) + } + end + it 'keeps the first unconfirmed answer and adds what a later retry said' do stub_request(:post, batch_url).to_return( refuse(503, 'delivery_unavailable'), @@ -254,10 +284,23 @@ def statuses(results) expect(result.results.first.later_error.code).to eq('idempotency_key_reused') end + it "doesn't retry once the client shuts down" do + stub_request(:post, batch_url).to_return do + client.shutdown(timeout: 0) + refuse(503, 'delivery_unavailable') + end + + expect { batch_template([ada]) }.to raise_error(EmailBatchError) { |error| + expect(error.code).to eq('client_closed') + expect(statuses(error.results)).to eq(['unconfirmed']) + } + expect(a_request(:post, batch_url)).to have_been_made.once + end + it 'stops before the next request once the client shuts down' do recipients = Array.new(101) { |index| { to: "user#{index}@example.com" } } stub_request(:post, batch_url).to_return do - emails.close(timeout: 0) + client.shutdown(timeout: 0) answer(*Array.new(100) { |index| queued("msg_#{index}") }) end @@ -269,14 +312,30 @@ def statuses(results) end end - it 'waits at least 45 seconds for each answer' do - stub_request(:post, batch_url).to_return(answer(queued('msg_1'))) - allow(Net::HTTP).to receive(:start).and_call_original + it "waits for an answer that comes after the client's own timeout" do + server = TCPServer.new('127.0.0.1', 0) + responder = Thread.new do + Thread.current.report_on_exception = false + connection = server.accept + request = +'' + request << connection.readpartial(65_536) until request.include?("\r\n\r\n") + sleep 0.5 + body = JSON.generate(results: [queued('msg_1')]) + connection.write("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: #{body.bytesize}\r\n" \ + "Connection: close\r\n\r\n#{body}") + connection.close + end + options.merge!(host: 'http://127.0.0.1:9', app_host: "http://127.0.0.1:#{server.addr[1]}", + email_request_timeout_seconds: 0.2) + WebMock.disable! - batch_template([ada]) + result = batch_template([{ to: 'ada@example.com' }], max_retries: 0) - expect(Net::HTTP).to have_received(:start) - .with('us.posthog.com', 443, hash_including(read_timeout: 45.0, open_timeout: 45.0)) + expect(statuses(result.results)).to eq(['queued']) + expect(responder.join(5)).to be_truthy + ensure + WebMock.enable! + server&.close end it 'refuses a bad batch before any request' do @@ -287,8 +346,8 @@ def statuses(results) /recipients\[1\] has the same idempotency_key as recipients\[0\]/], [{ recipients: [{ to: '' }] }, /recipients\[0\]: to must be/], [{ recipients: [{ to: 'a@example.com', cc: 'b@example.com' }] }, /recipients\[0\] takes only/], - [{ recipients: [ada], scheduled_at: Time.now }, /doesn't take scheduled_at/], - [{ recipients: [ada], cc: 'b@example.com' }, /doesn't take cc/], + [{ recipients: [ada], scheduled_at: Time.now }, /unknown keyword: :scheduled_at/], + [{ recipients: [ada], cc: 'b@example.com' }, /unknown keyword: :cc/], [{ recipients: [ada], template_id: 'nope' }, /template_id must be/] ].each do |args, message| expect { emails.batch(template_id: template_id, **args) }.to raise_error(ArgumentError, message) From 2f1c6e176235a2b4dbdc0f12ea2d9e3772c805c6 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:41:38 +0100 Subject: [PATCH 03/32] fix(emails): keep a batch retry's answer and fail oversize content per 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 --- lib/posthog/email_batch.rb | 10 ++-- spec/posthog/emails_batch_spec.rb | 76 +++++++++++++++++-------------- 2 files changed, 44 insertions(+), 42 deletions(-) diff --git a/lib/posthog/email_batch.rb b/lib/posthog/email_batch.rb index a4bafca7..3e7dc8c1 100644 --- a/lib/posthog/email_batch.rb +++ b/lib/posthog/email_batch.rb @@ -112,7 +112,8 @@ def lost_keys def found(index, status) if status.status == 'failed' earlier = @results[index] - set(index, 'unconfirmed', message_id: status.id, error: earlier.error, later_error: failed_status(status)) + set(index, 'unconfirmed', message_id: status.id, error: earlier.error, + later_error: earlier.later_error || failed_status(status)) return end @@ -131,11 +132,6 @@ def failure(error) private def split(empty) - if empty.bytesize >= MAX_BODY_BYTES - raise ArgumentError, "The batch's shared content is larger than one batch request takes, 4 MiB, so no email " \ - 'was sent. Make the template_data, subject, html or text smaller.' - end - chunks = [] current = [] size = empty.bytesize @@ -236,7 +232,7 @@ def unconfirmed(message_id) def failed_status(status) reason = text(status.reason) - EmailError.new(code: reason || 'failed', message_id: status.id, + EmailError.new(code: reason || 'failed', message: "PostHog's status of this email reads failed#{" (#{reason})" if reason}, so it may not " \ 'have gone out.') end diff --git a/spec/posthog/emails_batch_spec.rb b/spec/posthog/emails_batch_spec.rb index bdc41865..a44ec24b 100644 --- a/spec/posthog/emails_batch_spec.rb +++ b/spec/posthog/emails_batch_spec.rb @@ -146,21 +146,27 @@ def statuses(results) .to eq([['alan@example.com']]) end - it 'splits the recipients so no request is over 4 MiB' do - stub_request(:post, batch_url).to_return(answer(queued('msg_0'), queued('msg_1')), answer(queued('msg_2'))) - note = 'x' * (1536 * 1024) - recipients = Array.new(3) { |index| { to: "user#{index}@example.com", template_data: { note: note } } } - - result = batch_template(recipients) + it 'sends a request of exactly 4 MiB and splits one a byte larger' do + bodies = [] + stub_request(:post, batch_url).to_return do |request| + bodies << request.body + answer(*JSON.parse(request.body)['recipients'].map { |recipient| queued("msg_#{recipient['to']}") }) + end + pair = lambda do |first, second| + [{ to: 'ada@example.com', idempotency_key: 'k-ada', template_data: { note: 'x' * first } }, + { to: 'alan@example.com', idempotency_key: 'k-alan', template_data: { note: 'x' * second } }] + end + batch_template(pair.call(1, 1)) + fill = (4 * 1024 * 1024) - bodies.first.bytesize + 2 - expect(statuses(result.results)).to eq(%w[queued queued queued]) - expect(batch_bodies.map { |body| body['recipients'].size }).to eq([2, 1]) - end + batch_template(pair.call(fill / 2, fill - (fill / 2))) + result = batch_template(pair.call(fill / 2, fill - (fill / 2) + 1)) - it 'refuses shared content too large for any request before sending' do - expect { batch_template([ada], template_data: { note: 'x' * (4 * 1024 * 1024) }) } - .to raise_error(ArgumentError, /shared content is larger than one batch request takes/) - expect(a_request(:any, %r{/api/messaging/})).not_to have_been_made + expect(bodies.drop(1).map(&:bytesize).first).to eq(4 * 1024 * 1024) + expect(bodies.drop(1).map { |body| JSON.parse(body)['recipients'].size }).to eq([2, 1, 1]) + expect(bodies.last(2).map { |body| JSON.parse(body)['recipients'].first['message_data']['note'].size }) + .to eq([fill / 2, fill - (fill / 2) + 1]) + expect(statuses(result.results)).to eq(%w[queued queued]) end it 'logs each warning once' do @@ -267,6 +273,21 @@ def statuses(results) result = error.results.first expect([result.status, result.message_id]).to eq(%w[unconfirmed msg_ada]) expect([result.error.code, result.later_error.code]).to eq(%w[delivery_unavailable recipient_suppressed]) + expect(result.later_error.message_id).to be_nil + } + end + + it "keeps a retry's answer over a status by key that reads failed" do + stub_request(:post, batch_url).to_return(refuse(503, 'delivery_unavailable'), refuse(429, 'rate_limited')) + stub_request(:get, "#{status_by_key}welcome%3Aada").to_return( + status: 200, body: JSON.generate(id: 'msg_ada', status: 'failed', reason: 'recipient_suppressed', + created_at: '2026-11-24T08:00:00Z', status_at: '2026-11-24T08:00:00Z') + ) + + expect { batch_template([ada], max_retries: 1) }.to raise_error(EmailBatchError) { |error| + result = error.results.first + expect([result.status, result.message_id]).to eq(%w[unconfirmed msg_ada]) + expect([result.error.code, result.later_error.code]).to eq(%w[delivery_unavailable rate_limited]) } end @@ -312,30 +333,15 @@ def statuses(results) end end - it "waits for an answer that comes after the client's own timeout" do - server = TCPServer.new('127.0.0.1', 0) - responder = Thread.new do - Thread.current.report_on_exception = false - connection = server.accept - request = +'' - request << connection.readpartial(65_536) until request.include?("\r\n\r\n") - sleep 0.5 - body = JSON.generate(results: [queued('msg_1')]) - connection.write("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: #{body.bytesize}\r\n" \ - "Connection: close\r\n\r\n#{body}") - connection.close - end - options.merge!(host: 'http://127.0.0.1:9', app_host: "http://127.0.0.1:#{server.addr[1]}", - email_request_timeout_seconds: 0.2) - WebMock.disable! + it "waits at least 45 seconds for each answer, and connects and writes within the client's timeout" do + stub_request(:post, batch_url).to_return(answer(queued('msg_1'))) + allow(Net::HTTP).to receive(:start).and_call_original + options[:email_request_timeout_seconds] = 3 - result = batch_template([{ to: 'ada@example.com' }], max_retries: 0) + batch_template([ada]) - expect(statuses(result.results)).to eq(['queued']) - expect(responder.join(5)).to be_truthy - ensure - WebMock.enable! - server&.close + expect(Net::HTTP).to have_received(:start) + .with('us.posthog.com', 443, hash_including(read_timeout: 45.0, open_timeout: 3, write_timeout: 3)) end it 'refuses a bad batch before any request' do From 58c4aa3825c3fccddbe9adbe035be5e3dfafa5ea Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:01:48 +0100 Subject: [PATCH 04/32] fix(emails): tell a too-large batch recipient to shrink its content - 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 --- lib/posthog/email_batch.rb | 2 +- spec/posthog/emails_batch_spec.rb | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/lib/posthog/email_batch.rb b/lib/posthog/email_batch.rb index 3e7dc8c1..98ec9ff0 100644 --- a/lib/posthog/email_batch.rb +++ b/lib/posthog/email_batch.rb @@ -240,7 +240,7 @@ def failed_status(status) def recipient_too_large EmailError.new(code: 'content_too_large', field: 'recipients', message: "This recipient's email is larger than one batch request takes, so it wasn't sent.", - fix: "Send this recipient's email with emails.send.") + fix: "Make this recipient's template_data, or the batch's content, smaller.") end def text(value) diff --git a/spec/posthog/emails_batch_spec.rb b/spec/posthog/emails_batch_spec.rb index a44ec24b..ff1370e2 100644 --- a/spec/posthog/emails_batch_spec.rb +++ b/spec/posthog/emails_batch_spec.rb @@ -146,6 +146,14 @@ def statuses(results) .to eq([['alan@example.com']]) end + it 'fails every recipient when the shared content alone is too large, and sends nothing' do + results = batch_template([ada, alan], template_data: { note: 'x' * (4 * 1024 * 1024) }).results + + expect(statuses(results)).to eq(%w[failed failed]) + expect(results.map { |result| result.error.code }.uniq).to eq(['content_too_large']) + expect(a_request(:any, %r{/api/messaging/})).not_to have_been_made + end + it 'sends a request of exactly 4 MiB and splits one a byte larger' do bodies = [] stub_request(:post, batch_url).to_return do |request| From c109a62ae5ae5a4dce22afb9344da67872293a6b Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:05:49 +0100 Subject: [PATCH 05/32] test(emails): check the fix a too-large batch recipient gets Co-Authored-By: Claude Opus 5.5 --- spec/posthog/emails_batch_spec.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/spec/posthog/emails_batch_spec.rb b/spec/posthog/emails_batch_spec.rb index ff1370e2..efb63c2e 100644 --- a/spec/posthog/emails_batch_spec.rb +++ b/spec/posthog/emails_batch_spec.rb @@ -151,6 +151,7 @@ def statuses(results) expect(statuses(results)).to eq(%w[failed failed]) expect(results.map { |result| result.error.code }.uniq).to eq(['content_too_large']) + expect(results.first.error.fix).to eq("Make this recipient's template_data, or the batch's content, smaller.") expect(a_request(:any, %r{/api/messaging/})).not_to have_been_made end From 5500d508a08472839e0432edb7131a9e8f9ae51a Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:32:21 +0100 Subject: [PATCH 06/32] fix(emails): match the batch contract of Node and the server 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 --- lib/posthog/email_batch.rb | 5 ++-- lib/posthog/email_error.rb | 10 ++++--- lib/posthog/emails.rb | 21 ++++++++------ spec/posthog/emails_batch_spec.rb | 46 ++++++++++++++++++++++++++++++- 4 files changed, 67 insertions(+), 15 deletions(-) diff --git a/lib/posthog/email_batch.rb b/lib/posthog/email_batch.rb index 98ec9ff0..659dd6ef 100644 --- a/lib/posthog/email_batch.rb +++ b/lib/posthog/email_batch.rb @@ -61,7 +61,8 @@ def lost(chunk) def answer(chunk, (status, payload, retry_after)) fields = payload.is_a?(Hash) ? payload : {} unless status.between?(200, 299) - lost(chunk) if status >= 500 + # PostHog holds a key while it sends the email, so a request refused for that may already have queued it. + lost(chunk) if status >= 500 || fields['code'] == 'idempotency_key_in_flight' raise response_error(fields, status, retry_after, chunk.indices) end @@ -78,7 +79,7 @@ def answer(chunk, (status, payload, retry_after)) end def stop(position, error) - later = error.status_code && error.status_code < 500 ? error : nil + later = error.status_code && error.status_code < 500 && !UNCONFIRMED_CODES.include?(error.code) ? error : nil @chunks[position].indices.each do |index| if !@maybe_queued.include?(index) set(index, 'failed', error: error) diff --git a/lib/posthog/email_error.rb b/lib/posthog/email_error.rb index 1a809a21..a9aaf4af 100644 --- a/lib/posthog/email_error.rb +++ b/lib/posthog/email_error.rb @@ -53,7 +53,9 @@ def initialize(code:, message:, status_code: nil, why: nil, fix: nil, docs_url: 'delivery_unavailable' => 'service_unavailable', 'content_too_large' => 'validation_error' }.freeze - private_constant :SDK_ERROR_NAMES + # A 409 PostHog answers before it takes the request, so no idempotency key is in flight. + VALIDATION_CONFLICTS = %w[template_outdated batch_unavailable].freeze + private_constant :SDK_ERROR_NAMES, :VALIDATION_CONFLICTS # @api private def self.name_for(status_code, code) @@ -65,7 +67,7 @@ def self.name_for(status_code, code) when 400 then 'validation_error' when 403 then 'invalid_permission' when 404 then 'not_found' - when 409 then code == 'template_outdated' ? 'validation_error' : 'concurrent_idempotent_requests' + when 409 then VALIDATION_CONFLICTS.include?(code) ? 'validation_error' : 'concurrent_idempotent_requests' when 422 then code == 'idempotency_key_reused' ? 'invalid_idempotent_request' : 'validation_error' when 429 then code == 'quota_limited' ? 'monthly_quota_exceeded' : 'rate_limit_exceeded' when 503 then 'service_unavailable' @@ -77,8 +79,8 @@ def self.name_for(status_code, code) # A request of {Emails#batch} failed as a whole, so the batch stopped. # # The other fields describe that request's error. {#results} holds every recipient: those of earlier requests as - # PostHog answered them, those of the failed request as `failed`, or `unconfirmed` where an earlier attempt may have - # queued them, and the rest as `not_attempted`. + # PostHog answered them, those of the failed request as `failed`, or `unconfirmed` where PostHog may have queued + # them, such as after a lost answer or while it held their key, and the rest as `not_attempted`. class EmailBatchError < EmailError # @return [Array] One result per recipient, in the order of the batch's recipients. attr_reader :results diff --git a/lib/posthog/emails.rb b/lib/posthog/emails.rb index 4e643581..dcb71a31 100644 --- a/lib/posthog/emails.rb +++ b/lib/posthog/emails.rb @@ -341,8 +341,8 @@ def send( # waits at least 45 seconds for each answer. A batch takes no +cc+, +bcc+, +attachments+ or +scheduled_at+. # # Each recipient has an +idempotency_key+, given or made by the client, that every retry reuses, so a retry never - # queues an email twice. Retries follow {#send}'s. When a request of the batch fails as a whole, the client reads - # by its key each email of the batch whose answer was lost. + # queues an email twice. Retries follow {#send}'s. At the end of the batch, the client reads by its key each + # `unconfirmed` email that PostHog answered without a message ID. # # @param recipients [Array] 1 or more recipients, each a Hash with: # - +to+ [String] the recipient's email address; @@ -501,18 +501,23 @@ def batch_member(fields, index, template_form) end def send_chunks(run, secret_key, max_retries) + error = nil run.chunks.each_with_index do |chunk, position| - return run.failure(run.closed_at(position)) if position.positive? && !still_admitted? + if position.positive? && !still_admitted? + error = run.closed_at(position) + break + end begin send_chunk(run, chunk, secret_key, max_retries) rescue EmailError => e run.stop(position, e) - read_lost(run, secret_key) - return run.failure(e) + error = e + break end end - nil + read_lost(run, secret_key) + run.failure(error) if error end def send_chunk(run, chunk, secret_key, max_retries) @@ -537,8 +542,8 @@ def send_chunk(run, chunk, secret_key, max_retries) end end - # After a lost answer, a status read by key tells whether PostHog accepted the email. It reads each key once and - # stops at the first error but a 404, so a failing PostHog doesn't hold the caller up. + # For an email without a message ID, only a status read by key tells whether PostHog accepted it. It reads each + # key once and stops at the first error but a 404, so a failing PostHog doesn't hold the caller up. def read_lost(run, secret_key) run.lost_keys.each do |index, key| break unless still_admitted? diff --git a/spec/posthog/emails_batch_spec.rb b/spec/posthog/emails_batch_spec.rb index efb63c2e..4186764c 100644 --- a/spec/posthog/emails_batch_spec.rb +++ b/spec/posthog/emails_batch_spec.rb @@ -122,6 +122,7 @@ def statuses(results) answer(slot_error('recipient_suppressed', 422, message_id: 'msg_1'), slot_error('delivery_unavailable', 503, message_id: 'msg_2'), 'not a result') ) + stub_request(:get, status_by_key_url).to_return(status: 404, body: '{"code":"not_found"}') results = batch_template([ada, alan, { to: 'grace@example.com' }]).results @@ -134,6 +135,23 @@ def statuses(results) expect(results.map { |result| result.error.message_id }).to eq([nil, 'msg_2', nil]) end + it 'reads by its key each unconfirmed email PostHog answered without an ID' do + stub_request(:post, batch_url).to_return( + answer(slot_error('delivery_unavailable', 503, message_id: 'msg_ada'), + slot_error('delivery_unavailable', 503, message_id: nil)) + ) + stub_request(:get, "#{status_by_key}welcome%3Aalan").to_return( + status: 200, body: JSON.generate(id: 'msg_alan', status: 'queued', created_at: '2026-11-24T08:00:00Z', + status_at: '2026-11-24T08:00:00Z') + ) + + results = batch_template([ada, alan]).results + + expect(results.map { |result| [result.status, result.message_id] }) + .to eq([%w[unconfirmed msg_ada], %w[queued msg_alan]]) + expect(a_request(:get, status_by_key_url)).to have_been_made.once + end + it 'fails a recipient too large for one request and sends the rest' do stub_request(:post, batch_url).to_return(answer(queued('msg_2'))) huge = { to: 'ada@example.com', template_data: { note: 'x' * (4 * 1024 * 1024) } } @@ -238,10 +256,36 @@ def statuses(results) stub_request(:post, batch_url).to_return(refuse(409, 'batch_unavailable', detail: 'Not yet.')) expect { batch_template([ada]) }.to raise_error(EmailBatchError) { |error| - expect([error.code, error.status_code]).to eq(['batch_unavailable', 409]) + expect([error.code, error.name, error.status_code]).to eq(['batch_unavailable', 'validation_error', 409]) expect(error.fix).to include('send', 'idempotency_key') expect(error.results.map(&:status)).to eq(['failed']) } + expect(a_request(:post, batch_url)).to have_been_made.once + end + + it 'keeps a recipient unconfirmed while PostHog holds its key, also after a later refusal' do + stub_request(:post, batch_url).to_return( + refuse(409, 'idempotency_key_in_flight'), refuse(400, 'invalid_recipient', attr: 'recipients__0__to') + ) + stub_request(:get, "#{status_by_key}welcome%3Aada").to_return(status: 404, body: '{"code":"not_found"}') + + expect { batch_template([ada], max_retries: 1) }.to raise_error(EmailBatchError) { |error| + result = error.results.first + expect([error.code, result.status, result.message_id]).to eq(['invalid_recipient', 'unconfirmed', nil]) + expect([result.error.code, result.later_error.code]).to eq(%w[delivery_unavailable invalid_recipient]) + } + expect(a_request(:get, status_by_key_url)).to have_been_made.once + end + + it 'keeps a recipient unconfirmed when PostHog holds its key past the retries' do + stub_request(:post, batch_url).to_return(refuse(409, 'idempotency_key_in_flight')) + stub_request(:get, "#{status_by_key}welcome%3Aada").to_return(status: 404, body: '{"code":"not_found"}') + + expect { batch_template([ada], max_retries: 0) }.to raise_error(EmailBatchError) { |error| + result = error.results.first + expect([error.code, result.status, result.later_error]).to eq(['idempotency_key_in_flight', 'unconfirmed', + nil]) + } end it 'names a 404 as a missing template or batch sends that are off' do From 1b68402fe874afc81474cae6efbe326776591a29 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:06:13 +0100 Subject: [PATCH 07/32] fix(emails): take only the ID from a batch status read by key 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 --- lib/posthog/email_batch.rb | 19 +++++-------- lib/posthog/emails.rb | 7 +++-- spec/posthog/emails_batch_spec.rb | 46 +++++++++++++++++++++---------- 3 files changed, 42 insertions(+), 30 deletions(-) diff --git a/lib/posthog/email_batch.rb b/lib/posthog/email_batch.rb index 659dd6ef..44e8373e 100644 --- a/lib/posthog/email_batch.rb +++ b/lib/posthog/email_batch.rb @@ -79,7 +79,7 @@ def answer(chunk, (status, payload, retry_after)) end def stop(position, error) - later = error.status_code && error.status_code < 500 && !UNCONFIRMED_CODES.include?(error.code) ? error : nil + later = error.status_code && error.status_code < 500 ? error : nil @chunks[position].indices.each do |index| if !@maybe_queued.include?(index) set(index, 'failed', error: error) @@ -108,18 +108,13 @@ def lost_keys end end - # A status read by key found the email. PostHog records a refusal before queueing, such as a suppressed - # address, as a failed email, so only another status shows that PostHog accepted it. + # A status read by key gives the email's ID, so the caller can read it with emails.get, but confirms nothing: an + # earlier email with the same key reads the same way. A failed status, such as a suppressed address, becomes the + # reason. def found(index, status) - if status.status == 'failed' - earlier = @results[index] - set(index, 'unconfirmed', message_id: status.id, error: earlier.error, - later_error: earlier.later_error || failed_status(status)) - return - end - - @maybe_queued.delete(index) - set(index, 'queued', message_id: status.id) + earlier = @results[index] + later = earlier.later_error || (failed_status(status) if status.status == 'failed') + set(index, 'unconfirmed', message_id: status.id, error: earlier.error, later_error: later) end def result diff --git a/lib/posthog/emails.rb b/lib/posthog/emails.rb index 51efb092..c084cf13 100644 --- a/lib/posthog/emails.rb +++ b/lib/posthog/emails.rb @@ -127,7 +127,7 @@ def status # `delivery_unavailable`, `idempotency_key_in_flight` or `api_error`. # @!attribute [r] later_error # @return [EmailError, nil] For an `unconfirmed` email, what a retry in the same call answered about it, which - # describes only that retry. + # describes only that retry, or why a status the client read by its key reads `failed`. BatchEmailResult = Struct.new(:index, :to, :idempotency_key, :status, :message_id, :replayed, :error, :later_error, keyword_init: true) @@ -352,7 +352,8 @@ def send( # # Each recipient has an +idempotency_key+, given or made by the client, that every retry reuses, so a retry never # queues an email twice. Retries follow {#send}'s. At the end of the batch, the client reads by its key each - # `unconfirmed` email that PostHog answered without a message ID. + # `unconfirmed` email that PostHog answered without a message ID, and adds the ID it finds, so you can read the + # email with {#get}. The email stays `unconfirmed`. # # @param recipients [Array] 1 or more recipients, each a Hash with: # - +to+ [String] the recipient's email address; @@ -362,7 +363,7 @@ def send( # when a batch may be cut off and run again: a rerun within 24 hours replays the emails that went out instead # of sending them twice. A send and a batch recipient with the same key and the same email replay each other. # Never reuse a key for another email: after a lost answer, the client reads the email by its key, and an - # earlier email with that key reads as this one, `queued`; + # earlier email with that key gives its message ID as this one's; # - +template_data+ [Hash] optional, only with +template_id+: values for this recipient, merged over the # batch's +template_data+. A top-level key set here replaces the same key there. # @param template_id [String] Template form: the UUID of a template made transactional in PostHog. diff --git a/spec/posthog/emails_batch_spec.rb b/spec/posthog/emails_batch_spec.rb index 4186764c..d6c1eda7 100644 --- a/spec/posthog/emails_batch_spec.rb +++ b/spec/posthog/emails_batch_spec.rb @@ -148,10 +148,22 @@ def statuses(results) results = batch_template([ada, alan]).results expect(results.map { |result| [result.status, result.message_id] }) - .to eq([%w[unconfirmed msg_ada], %w[queued msg_alan]]) + .to eq([%w[unconfirmed msg_ada], %w[unconfirmed msg_alan]]) expect(a_request(:get, status_by_key_url)).to have_been_made.once end + it 'takes only the ID from a status read by key, and keeps the email unconfirmed' do + stub_request(:post, batch_url).to_return(answer('not a result')) + stub_request(:get, "#{status_by_key}welcome%3Aada").to_return( + status: 200, body: JSON.generate(id: 'msg_ada', status: 'archived', created_at: '2026-11-24T08:00:00Z', + status_at: '2026-11-24T08:00:00Z') + ) + + result = batch_template([ada]).results.first + + expect([result.status, result.message_id, result.error.code]).to eq(%w[unconfirmed msg_ada api_error]) + end + it 'fails a recipient too large for one request and sends the rest' do stub_request(:post, batch_url).to_return(answer(queued('msg_2'))) huge = { to: 'ada@example.com', template_data: { note: 'x' * (4 * 1024 * 1024) } } @@ -179,21 +191,25 @@ def statuses(results) bodies << request.body answer(*JSON.parse(request.body)['recipients'].map { |recipient| queued("msg_#{recipient['to']}") }) end - pair = lambda do |first, second| - [{ to: 'ada@example.com', idempotency_key: 'k-ada', template_data: { note: 'x' * first } }, - { to: 'alan@example.com', idempotency_key: 'k-alan', template_data: { note: 'x' * second } }] + # Three recipients, so each stays under the 1.5 MiB PostHog takes for one email. + trio = lambda do |sizes| + sizes.each_with_index.map do |size, index| + { to: "user#{index}@example.com", idempotency_key: "k-#{index}", template_data: { note: 'x' * size } } + end end - batch_template(pair.call(1, 1)) - fill = (4 * 1024 * 1024) - bodies.first.bytesize + 2 + batch_template(trio.call([1, 1, 1])) + fill = (4 * 1024 * 1024) - bodies.first.bytesize + 3 + sizes = [fill / 3, fill / 3, fill - (2 * (fill / 3))] - batch_template(pair.call(fill / 2, fill - (fill / 2))) - result = batch_template(pair.call(fill / 2, fill - (fill / 2) + 1)) + batch_template(trio.call(sizes)) + result = batch_template(trio.call([sizes[0], sizes[1], sizes[2] + 1])) + expect(sizes.max).to be < 1.5 * 1024 * 1024 expect(bodies.drop(1).map(&:bytesize).first).to eq(4 * 1024 * 1024) - expect(bodies.drop(1).map { |body| JSON.parse(body)['recipients'].size }).to eq([2, 1, 1]) - expect(bodies.last(2).map { |body| JSON.parse(body)['recipients'].first['message_data']['note'].size }) - .to eq([fill / 2, fill - (fill / 2) + 1]) - expect(statuses(result.results)).to eq(%w[queued queued]) + expect(bodies.drop(1).map { |body| JSON.parse(body)['recipients'].size }).to eq([3, 2, 1]) + notes = bodies.last(2).flat_map { |body| JSON.parse(body)['recipients'] }.map { |r| r['message_data']['note'] } + expect(notes.map(&:size)).to eq([sizes[0], sizes[1], sizes[2] + 1]) + expect(statuses(result.results)).to eq(%w[queued queued queued]) end it 'logs each warning once' do @@ -283,8 +299,8 @@ def statuses(results) expect { batch_template([ada], max_retries: 0) }.to raise_error(EmailBatchError) { |error| result = error.results.first - expect([error.code, result.status, result.later_error]).to eq(['idempotency_key_in_flight', 'unconfirmed', - nil]) + expect([error.code, result.status, result.later_error.code]) + .to eq(%w[idempotency_key_in_flight unconfirmed idempotency_key_in_flight]) } end @@ -308,7 +324,7 @@ def statuses(results) expect { batch_template([ada, alan], max_retries: 1) }.to raise_error(EmailBatchError) { |error| expect(error.code).to eq('network_error') expect(error.results.map { |result| [result.status, result.message_id] }) - .to eq([['unconfirmed', nil], %w[queued msg_alan]]) + .to eq([['unconfirmed', nil], %w[unconfirmed msg_alan]]) expect(error.results.first.error.code).to eq('delivery_unavailable') } expect(a_request(:post, batch_url)).to have_been_made.twice From 81aa4ccf2d105bec1c13ef649cbca397e37c858b Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:59:36 +0100 Subject: [PATCH 08/32] fix(emails): keep a batch's in-flight refusal as the error, and a caller'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 --- lib/posthog/email_batch.rb | 15 ++++++++++----- lib/posthog/emails.rb | 4 ++++ spec/posthog/emails_batch_spec.rb | 22 +++++++++++++++++----- 3 files changed, 31 insertions(+), 10 deletions(-) diff --git a/lib/posthog/email_batch.rb b/lib/posthog/email_batch.rb index 44e8373e..3d71f766 100644 --- a/lib/posthog/email_batch.rb +++ b/lib/posthog/email_batch.rb @@ -50,20 +50,25 @@ def initialize(shared, members, parse_warnings:, reply_error:) @chunks = split(JSON.generate(shared.merge(recipients: []))) end - def lost(chunk) + def lost(chunk, error = nil) chunk.indices.each do |index| @maybe_queued << index message_id = @results[index]&.message_id - set(index, 'unconfirmed', message_id: message_id, error: unconfirmed(message_id)) + set(index, 'unconfirmed', message_id: message_id, error: error || unconfirmed(message_id)) end end def answer(chunk, (status, payload, retry_after)) fields = payload.is_a?(Hash) ? payload : {} unless status.between?(200, 299) + error = response_error(fields, status, retry_after, chunk.indices) # PostHog holds a key while it sends the email, so a request refused for that may already have queued it. - lost(chunk) if status >= 500 || fields['code'] == 'idempotency_key_in_flight' - raise response_error(fields, status, retry_after, chunk.indices) + if error.code == 'idempotency_key_in_flight' + lost(chunk, error) + elsif status >= 500 + lost(chunk) + end + raise error end slots = fields['results'] @@ -83,7 +88,7 @@ def stop(position, error) @chunks[position].indices.each do |index| if !@maybe_queued.include?(index) set(index, 'failed', error: error) - elsif later + elsif later && !@results[index].error.equal?(later) earlier = @results[index] set(index, 'unconfirmed', message_id: earlier.message_id, error: earlier.error, later_error: later) end diff --git a/lib/posthog/emails.rb b/lib/posthog/emails.rb index c084cf13..5ce7ff8c 100644 --- a/lib/posthog/emails.rb +++ b/lib/posthog/emails.rb @@ -570,6 +570,10 @@ def status_by_key(key, secret_key) uri = URI("#{@app_host}#{STATUS_BY_KEY_PATH}?#{URI.encode_www_form(idempotency_key: key)}") parse_status_reply(request(Net::HTTP::Get.new(uri), uri, secret_key, {})) rescue EmailError => e + # A caller's deadline raised as Timeout::Error itself arrives as a network error. Net::HTTP's own timeouts are + # subclasses of it. + raise e.cause if e.cause.instance_of?(Timeout::Error) + e.status_code == 404 ? nil : :stop end diff --git a/spec/posthog/emails_batch_spec.rb b/spec/posthog/emails_batch_spec.rb index d6c1eda7..d536111b 100644 --- a/spec/posthog/emails_batch_spec.rb +++ b/spec/posthog/emails_batch_spec.rb @@ -164,6 +164,13 @@ def statuses(results) expect([result.status, result.message_id, result.error.code]).to eq(%w[unconfirmed msg_ada api_error]) end + it "lets a caller's deadline through while it reads an email by its key" do + stub_request(:post, batch_url).to_return(answer('not a result')) + stub_request(:get, "#{status_by_key}welcome%3Aada").to_raise(Timeout::Error.new('deadline')) + + expect { batch_template([ada]) }.to raise_error(Timeout::Error, 'deadline') + end + it 'fails a recipient too large for one request and sends the rest' do stub_request(:post, batch_url).to_return(answer(queued('msg_2'))) huge = { to: 'ada@example.com', template_data: { note: 'x' * (4 * 1024 * 1024) } } @@ -288,19 +295,24 @@ def statuses(results) expect { batch_template([ada], max_retries: 1) }.to raise_error(EmailBatchError) { |error| result = error.results.first expect([error.code, result.status, result.message_id]).to eq(['invalid_recipient', 'unconfirmed', nil]) - expect([result.error.code, result.later_error.code]).to eq(%w[delivery_unavailable invalid_recipient]) + expect([result.error.code, result.later_error.code]).to eq(%w[idempotency_key_in_flight invalid_recipient]) } expect(a_request(:get, status_by_key_url)).to have_been_made.once end - it 'keeps a recipient unconfirmed when PostHog holds its key past the retries' do + it 'keeps a recipient unconfirmed when PostHog holds its key past the retries, with what its status says' do stub_request(:post, batch_url).to_return(refuse(409, 'idempotency_key_in_flight')) - stub_request(:get, "#{status_by_key}welcome%3Aada").to_return(status: 404, body: '{"code":"not_found"}') + stub_request(:get, "#{status_by_key}welcome%3Aada").to_return( + status: 200, body: JSON.generate(id: 'msg_ada', status: 'failed', reason: 'recipient_suppressed', + created_at: '2026-11-24T08:00:00Z', status_at: '2026-11-24T08:00:00Z') + ) expect { batch_template([ada], max_retries: 0) }.to raise_error(EmailBatchError) { |error| result = error.results.first - expect([error.code, result.status, result.later_error.code]) - .to eq(%w[idempotency_key_in_flight unconfirmed idempotency_key_in_flight]) + expect([error.code, result.status, result.message_id]) + .to eq(%w[idempotency_key_in_flight unconfirmed msg_ada]) + expect([result.error.code, result.later_error.code]) + .to eq(%w[idempotency_key_in_flight recipient_suppressed]) } end From 6031427224f99b01bd09a97cda4a60e4585f78ad Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:03:31 +0100 Subject: [PATCH 09/32] fix(emails): stop reading a batch's unconfirmed emails back by key 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 --- lib/posthog/email_batch.rb | 37 +++--------- lib/posthog/emails.rb | 39 ++----------- spec/posthog/emails_batch_spec.rb | 94 ++++++++----------------------- 3 files changed, 36 insertions(+), 134 deletions(-) diff --git a/lib/posthog/email_batch.rb b/lib/posthog/email_batch.rb index 3d71f766..a3bbe2a7 100644 --- a/lib/posthog/email_batch.rb +++ b/lib/posthog/email_batch.rb @@ -13,6 +13,7 @@ class EmailBatch MAX_RECIPIENTS = 100 MAX_BODY_BYTES = 4 * 1024 * 1024 UNCONFIRMED_CODES = %w[idempotency_key_in_flight delivery_unavailable api_error].freeze + RESEND_FIX = 'Send it again with the same idempotency_key within 24 hours, so it goes out once.' UNAVAILABLE_FIX = "Until batch sends are on for the project, send each email the batch didn't queue with " \ "emails.send and its recipient's idempotency_key." NOT_FOUND = { @@ -23,7 +24,7 @@ class EmailBatch 'idempotency_key.' }.freeze RESULT_DEFAULTS = { message_id: nil, replayed: false, error: nil, later_error: nil }.freeze - private_constant :UNCONFIRMED_CODES, :UNAVAILABLE_FIX, :NOT_FOUND, :RESULT_DEFAULTS + private_constant :UNCONFIRMED_CODES, :RESEND_FIX, :UNAVAILABLE_FIX, :NOT_FOUND, :RESULT_DEFAULTS Member = Struct.new(:index, :to, :idempotency_key, :wire, keyword_init: true) # The recipients of one request. The body is built when the request goes out, so a large batch holds one at a @@ -107,21 +108,6 @@ def closed_at(position) error end - def lost_keys - @maybe_queued.sort.filter_map do |index| - [index, @members[index].idempotency_key] if @results[index].message_id.nil? - end - end - - # A status read by key gives the email's ID, so the caller can read it with emails.get, but confirms nothing: an - # earlier email with the same key reads the same way. A failed status, such as a suppressed address, becomes the - # reason. - def found(index, status) - earlier = @results[index] - later = earlier.later_error || (failed_status(status) if status.status == 'failed') - set(index, 'unconfirmed', message_id: status.id, error: earlier.error, later_error: later) - end - def result Emails::BatchResult.new(results: @results.dup.freeze, warnings: @warnings.dup.freeze) end @@ -197,6 +183,7 @@ def response_error(fields, status, retry_after, indices) answered['attr'] = recipients_field(answered['attr'], indices) if answered['attr'].is_a?(String) fields = status == 404 ? NOT_FOUND.merge(answered) : answered fields = fields.merge('fix' => UNAVAILABLE_FIX) if fields['code'] == 'batch_unavailable' + fields = fields.merge('fix' => RESEND_FIX) if fields['code'] == 'idempotency_key_in_flight' && !fields['fix'] @reply_error.call(fields, status, retry_after) end @@ -213,7 +200,7 @@ def recipients_field(attr, indices) def slot_error(error, message_id) unless error.is_a?(Hash) - return EmailError.new(code: 'api_error', message_id: message_id, + return EmailError.new(code: 'api_error', message_id: message_id, fix: RESEND_FIX, message: 'PostHog answered without a readable result for this email, so it may still ' \ 'go out.') end @@ -221,21 +208,15 @@ def slot_error(error, message_id) code = text(error['code']) || 'api_error' status = error['status'].is_a?(Integer) ? error['status'] : nil # EmailError#message_id means PostHog may have accepted the email, so a refusal leaves it on the result only. - EmailError.new(code: code, status_code: status, message_id: (message_id if UNCONFIRMED_CODES.include?(code)), + unconfirmed = UNCONFIRMED_CODES.include?(code) + EmailError.new(code: code, status_code: status, message_id: (message_id if unconfirmed), + fix: (RESEND_FIX if unconfirmed), message: text(error['detail']) || "PostHog didn't queue this email: #{code}.") end def unconfirmed(message_id) - EmailError.new(code: 'delivery_unavailable', message_id: message_id, - message: "PostHog didn't confirm this email, so it may still go out. Send it again with the " \ - 'same idempotency_key within 24 hours, so it goes out once.') - end - - def failed_status(status) - reason = text(status.reason) - EmailError.new(code: reason || 'failed', - message: "PostHog's status of this email reads failed#{" (#{reason})" if reason}, so it may not " \ - 'have gone out.') + EmailError.new(code: 'delivery_unavailable', message_id: message_id, fix: RESEND_FIX, + message: "PostHog didn't confirm this email, so it may still go out.") end def recipient_too_large diff --git a/lib/posthog/emails.rb b/lib/posthog/emails.rb index 5385946d..8c6c3a88 100644 --- a/lib/posthog/emails.rb +++ b/lib/posthog/emails.rb @@ -127,7 +127,7 @@ def status # `delivery_unavailable`, `idempotency_key_in_flight` or `api_error`. # @!attribute [r] later_error # @return [EmailError, nil] For an `unconfirmed` email, what a retry in the same call answered about it, which - # describes only that retry, or why a status the client read by its key reads `failed`. + # describes only that retry. BatchEmailResult = Struct.new(:index, :to, :idempotency_key, :status, :message_id, :replayed, :error, :later_error, keyword_init: true) @@ -143,7 +143,6 @@ def status UPLOADS_PATH = '/api/messaging/attachments/uploads/' STATUS_PATH = '/api/messaging/emails/%s/' BATCH_PATH = '/api/messaging/send/email_batch/' - STATUS_BY_KEY_PATH = '/api/messaging/emails/status/' # PostHog waits up to 30 seconds for its pipeline before it answers a batch. Connecting and writing keep the # client's timeout. BATCH_ATTEMPT_TIMEOUT_SECONDS = 45.0 @@ -184,7 +183,7 @@ def status Timeout::Error, SocketError, SystemCallError, IOError, EOFError, OpenSSL::SSL::SSLError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError, Zlib::Error ].freeze - private_constant :SEND_PATH, :UPLOADS_PATH, :STATUS_PATH, :BATCH_PATH, :STATUS_BY_KEY_PATH, + private_constant :SEND_PATH, :UPLOADS_PATH, :STATUS_PATH, :BATCH_PATH, :BATCH_ATTEMPT_TIMEOUT_SECONDS, :BATCH_RECIPIENT_FIELDS, :US_APP_HOST, :EU_APP_HOST, :CLOUD_APP_HOSTS, :SCHEDULING_APP_HOSTS, :MAX_RETRY_DELAY_SECONDS, :UUID_PATTERN, :IDEMPOTENCY_KEY_PATTERN, @@ -359,9 +358,8 @@ def send( # waits at least 45 seconds for each answer. A batch takes no +cc+, +bcc+, +attachments+ or +scheduled_at+. # # Each recipient has an +idempotency_key+, given or made by the client, that every retry reuses, so a retry never - # queues an email twice. Retries follow {#send}'s. At the end of the batch, the client reads by its key each - # `unconfirmed` email that PostHog answered without a message ID, and adds the ID it finds, so you can read the - # email with {#get}. The email stays `unconfirmed`. + # queues an email twice. Retries follow {#send}'s. Send each `unconfirmed` email again with its + # +idempotency_key+ within 24 hours, so it goes out once. # # @param recipients [Array] 1 or more recipients, each a Hash with: # - +to+ [String] the recipient's email address; @@ -369,9 +367,7 @@ def send( # - +idempotency_key+ [String] optional: 1 to 255 visible ASCII characters, a different one for each recipient. # Without it, the client makes one that covers its own retries but not a second call, so pass keys you store # when a batch may be cut off and run again: a rerun within 24 hours replays the emails that went out instead - # of sending them twice. A send and a batch recipient with the same key and the same email replay each other. - # Never reuse a key for another email: after a lost answer, the client reads the email by its key, and an - # earlier email with that key gives its message ID as this one's; + # of sending them twice. A send and a batch recipient with the same key and the same email replay each other; # - +template_data+ [Hash] optional, only with +template_id+: values for this recipient, merged over the # batch's +template_data+. A top-level key set here replaces the same key there. # @param template_id [String] Template form: the UUID of a template made transactional in PostHog. @@ -535,7 +531,6 @@ def send_chunks(run, secret_key, max_retries) break end end - read_lost(run, secret_key) run.failure(error) if error end @@ -561,30 +556,6 @@ def send_chunk(run, chunk, secret_key, max_retries) end end - # For an email without a message ID, only a status read by key tells whether PostHog accepted it. It reads each - # key once and stops at the first error but a 404, so a failing PostHog doesn't hold the caller up. - def read_lost(run, secret_key) - run.lost_keys.each do |index, key| - break unless still_admitted? - - status = status_by_key(key, secret_key) - break if status == :stop - - run.found(index, status) if status - end - end - - def status_by_key(key, secret_key) - uri = URI("#{@app_host}#{STATUS_BY_KEY_PATH}?#{URI.encode_www_form(idempotency_key: key)}") - parse_status_reply(request(Net::HTTP::Get.new(uri), uri, secret_key, {})) - rescue EmailError => e - # A caller's deadline raised as Timeout::Error itself arrives as a network error. Net::HTTP's own timeouts are - # subclasses of it. - raise e.cause if e.cause.instance_of?(Timeout::Error) - - e.status_code == 404 ? nil : :stop - end - def still_admitted? @mutex.synchronize do forget_parent_requests diff --git a/spec/posthog/emails_batch_spec.rb b/spec/posthog/emails_batch_spec.rb index d536111b..93c1a75f 100644 --- a/spec/posthog/emails_batch_spec.rb +++ b/spec/posthog/emails_batch_spec.rb @@ -5,8 +5,6 @@ module PostHog describe Emails do let(:batch_url) { 'https://us.posthog.com/api/messaging/send/email_batch/' } - let(:status_by_key) { 'https://us.posthog.com/api/messaging/emails/status/?idempotency_key=' } - let(:status_by_key_url) { %r{\Ahttps://us\.posthog\.com/api/messaging/emails/status/\?idempotency_key=} } let(:template_id) { '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b' } let(:uuid_v4) { /\A\h{8}-\h{4}-4\h{3}-[89ab]\h{3}-\h{12}\z/ } let(:options) { { api_key: API_KEY, secret_key: 'phs_test', test_mode: true } } @@ -53,6 +51,10 @@ def statuses(results) results.map(&:status) end + def resend_with_key(result) + [result.status, result.idempotency_key, result.error.fix.include?('same idempotency_key')] + end + describe '#batch' do it 'sends one request and returns a result per recipient, in order' do stub_request(:post, batch_url).to_return(answer(queued('msg_1'), queued('msg_2', replayed: true))) @@ -122,7 +124,6 @@ def statuses(results) answer(slot_error('recipient_suppressed', 422, message_id: 'msg_1'), slot_error('delivery_unavailable', 503, message_id: 'msg_2'), 'not a result') ) - stub_request(:get, status_by_key_url).to_return(status: 404, body: '{"code":"not_found"}') results = batch_template([ada, alan, { to: 'grace@example.com' }]).results @@ -135,40 +136,20 @@ def statuses(results) expect(results.map { |result| result.error.message_id }).to eq([nil, 'msg_2', nil]) end - it 'reads by its key each unconfirmed email PostHog answered without an ID' do + it 'leaves an unconfirmed email PostHog answered without an ID to be sent again with its key' do stub_request(:post, batch_url).to_return( answer(slot_error('delivery_unavailable', 503, message_id: 'msg_ada'), - slot_error('delivery_unavailable', 503, message_id: nil)) - ) - stub_request(:get, "#{status_by_key}welcome%3Aalan").to_return( - status: 200, body: JSON.generate(id: 'msg_alan', status: 'queued', created_at: '2026-11-24T08:00:00Z', - status_at: '2026-11-24T08:00:00Z') + slot_error('delivery_unavailable', 503, message_id: nil), 'not a result') ) - results = batch_template([ada, alan]).results + results = batch_template([ada, alan, { to: 'grace@example.com', idempotency_key: 'welcome:grace' }]).results - expect(results.map { |result| [result.status, result.message_id] }) - .to eq([%w[unconfirmed msg_ada], %w[unconfirmed msg_alan]]) - expect(a_request(:get, status_by_key_url)).to have_been_made.once - end - - it 'takes only the ID from a status read by key, and keeps the email unconfirmed' do - stub_request(:post, batch_url).to_return(answer('not a result')) - stub_request(:get, "#{status_by_key}welcome%3Aada").to_return( - status: 200, body: JSON.generate(id: 'msg_ada', status: 'archived', created_at: '2026-11-24T08:00:00Z', - status_at: '2026-11-24T08:00:00Z') + expect(results.map(&:message_id)).to eq(['msg_ada', nil, nil]) + expect(results.map { |result| resend_with_key(result) }).to eq( + [['unconfirmed', 'welcome:ada', true], ['unconfirmed', 'welcome:alan', true], + ['unconfirmed', 'welcome:grace', true]] ) - - result = batch_template([ada]).results.first - - expect([result.status, result.message_id, result.error.code]).to eq(%w[unconfirmed msg_ada api_error]) - end - - it "lets a caller's deadline through while it reads an email by its key" do - stub_request(:post, batch_url).to_return(answer('not a result')) - stub_request(:get, "#{status_by_key}welcome%3Aada").to_raise(Timeout::Error.new('deadline')) - - expect { batch_template([ada]) }.to raise_error(Timeout::Error, 'deadline') + expect(a_request(:get, %r{/api/messaging/emails/status/})).not_to have_been_made end it 'fails a recipient too large for one request and sends the rest' do @@ -290,29 +271,21 @@ def statuses(results) stub_request(:post, batch_url).to_return( refuse(409, 'idempotency_key_in_flight'), refuse(400, 'invalid_recipient', attr: 'recipients__0__to') ) - stub_request(:get, "#{status_by_key}welcome%3Aada").to_return(status: 404, body: '{"code":"not_found"}') expect { batch_template([ada], max_retries: 1) }.to raise_error(EmailBatchError) { |error| result = error.results.first expect([error.code, result.status, result.message_id]).to eq(['invalid_recipient', 'unconfirmed', nil]) expect([result.error.code, result.later_error.code]).to eq(%w[idempotency_key_in_flight invalid_recipient]) } - expect(a_request(:get, status_by_key_url)).to have_been_made.once end - it 'keeps a recipient unconfirmed when PostHog holds its key past the retries, with what its status says' do + it 'keeps a recipient unconfirmed when PostHog holds its key past the retries, to send again with it' do stub_request(:post, batch_url).to_return(refuse(409, 'idempotency_key_in_flight')) - stub_request(:get, "#{status_by_key}welcome%3Aada").to_return( - status: 200, body: JSON.generate(id: 'msg_ada', status: 'failed', reason: 'recipient_suppressed', - created_at: '2026-11-24T08:00:00Z', status_at: '2026-11-24T08:00:00Z') - ) expect { batch_template([ada], max_retries: 0) }.to raise_error(EmailBatchError) { |error| result = error.results.first - expect([error.code, result.status, result.message_id]) - .to eq(%w[idempotency_key_in_flight unconfirmed msg_ada]) - expect([result.error.code, result.later_error.code]) - .to eq(%w[idempotency_key_in_flight recipient_suppressed]) + expect([error.code, result.message_id, result.later_error]).to eq(['idempotency_key_in_flight', nil, nil]) + expect(resend_with_key(result)).to eq(['unconfirmed', 'welcome:ada', true]) } end @@ -325,49 +298,26 @@ def statuses(results) } end - it 'keeps a recipient a lost answer may have queued unconfirmed, and reads its status by key' do + it 'keeps the recipients a lost answer may have queued unconfirmed, to send again with their keys' do stub_request(:post, batch_url).to_raise(Errno::ECONNRESET) - stub_request(:get, "#{status_by_key}welcome%3Aada").to_return(status: 404, body: '{"code":"not_found"}') - stub_request(:get, "#{status_by_key}welcome%3Aalan").to_return( - status: 200, body: JSON.generate(id: 'msg_alan', status: 'queued', created_at: '2026-11-24T08:00:00Z', - status_at: '2026-11-24T08:00:00Z') - ) expect { batch_template([ada, alan], max_retries: 1) }.to raise_error(EmailBatchError) { |error| expect(error.code).to eq('network_error') - expect(error.results.map { |result| [result.status, result.message_id] }) - .to eq([['unconfirmed', nil], %w[unconfirmed msg_alan]]) + expect(error.results.map(&:message_id)).to eq([nil, nil]) + expect(error.results.map { |result| resend_with_key(result) }) + .to eq([['unconfirmed', 'welcome:ada', true], ['unconfirmed', 'welcome:alan', true]]) expect(error.results.first.error.code).to eq('delivery_unavailable') } expect(a_request(:post, batch_url)).to have_been_made.twice - expect(a_request(:get, status_by_key_url)).to have_been_made.twice - end - - it 'keeps a recipient whose status by key reads failed unconfirmed' do - stub_request(:post, batch_url).to_raise(Errno::ECONNRESET) - stub_request(:get, "#{status_by_key}welcome%3Aada").to_return( - status: 200, body: JSON.generate(id: 'msg_ada', status: 'failed', reason: 'recipient_suppressed', - created_at: '2026-11-24T08:00:00Z', status_at: '2026-11-24T08:00:00Z') - ) - - expect { batch_template([ada], max_retries: 0) }.to raise_error(EmailBatchError) { |error| - result = error.results.first - expect([result.status, result.message_id]).to eq(%w[unconfirmed msg_ada]) - expect([result.error.code, result.later_error.code]).to eq(%w[delivery_unavailable recipient_suppressed]) - expect(result.later_error.message_id).to be_nil - } + expect(a_request(:get, %r{/api/messaging/emails/status/})).not_to have_been_made end - it "keeps a retry's answer over a status by key that reads failed" do + it "keeps a retry's refusal as the later answer of a recipient it can't confirm" do stub_request(:post, batch_url).to_return(refuse(503, 'delivery_unavailable'), refuse(429, 'rate_limited')) - stub_request(:get, "#{status_by_key}welcome%3Aada").to_return( - status: 200, body: JSON.generate(id: 'msg_ada', status: 'failed', reason: 'recipient_suppressed', - created_at: '2026-11-24T08:00:00Z', status_at: '2026-11-24T08:00:00Z') - ) expect { batch_template([ada], max_retries: 1) }.to raise_error(EmailBatchError) { |error| result = error.results.first - expect([result.status, result.message_id]).to eq(%w[unconfirmed msg_ada]) + expect([result.status, result.message_id]).to eq(['unconfirmed', nil]) expect([result.error.code, result.later_error.code]).to eq(%w[delivery_unavailable rate_limited]) } end From 568dab6c095f6227e1f78bcc37fb2592745b83a7 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:18:05 +0100 Subject: [PATCH 10/32] fix(emails): keep a batch recipient's first unconfirmed reason and the 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 --- lib/posthog/email_batch.rb | 14 ++++++--- lib/posthog/emails.rb | 48 ++++++++++++++--------------- spec/posthog/emails_batch_spec.rb | 51 ++++++++++++++++++++++++++++++- 3 files changed, 84 insertions(+), 29 deletions(-) diff --git a/lib/posthog/email_batch.rb b/lib/posthog/email_batch.rb index a3bbe2a7..ece99971 100644 --- a/lib/posthog/email_batch.rb +++ b/lib/posthog/email_batch.rb @@ -53,6 +53,9 @@ def initialize(shared, members, parse_warnings:, reply_error:) def lost(chunk, error = nil) chunk.indices.each do |index| + # The first answer that left an email unconfirmed stays its error, and stop adds the last refusal. + next if @maybe_queued.include?(index) + @maybe_queued << index message_id = @results[index]&.message_id set(index, 'unconfirmed', message_id: message_id, error: error || unconfirmed(message_id)) @@ -74,9 +77,10 @@ def answer(chunk, (status, payload, retry_after)) slots = fields['results'] unless slots.is_a?(Array) && slots.size == chunk.indices.size - lost(chunk) - raise EmailError.new(code: 'api_error', status_code: status, - message: 'PostHog answered the batch without a result for each recipient.') + error = EmailError.new(code: 'api_error', status_code: status, fix: RESEND_FIX, + message: 'PostHog answered the batch without a result for each recipient.') + lost(chunk, error) + raise error end chunk.indices.zip(slots) { |index, slot| settle(index, slot.is_a?(Hash) ? slot : {}) } @parse_warnings.call(fields['warnings']).each do |warning| @@ -183,7 +187,9 @@ def response_error(fields, status, retry_after, indices) answered['attr'] = recipients_field(answered['attr'], indices) if answered['attr'].is_a?(String) fields = status == 404 ? NOT_FOUND.merge(answered) : answered fields = fields.merge('fix' => UNAVAILABLE_FIX) if fields['code'] == 'batch_unavailable' - fields = fields.merge('fix' => RESEND_FIX) if fields['code'] == 'idempotency_key_in_flight' && !fields['fix'] + if fields['code'] == 'idempotency_key_in_flight' && !text(fields['fix']) + fields = fields.merge('fix' => RESEND_FIX) + end @reply_error.call(fields, status, retry_after) end diff --git a/lib/posthog/emails.rb b/lib/posthog/emails.rb index 93e32cca..d773e472 100644 --- a/lib/posthog/emails.rb +++ b/lib/posthog/emails.rb @@ -326,28 +326,7 @@ def send( begin raise unconfirmed if unconfirmed ensure - # The client can't tell a failing logger from a caller's deadline, so either propagates. A logger's own error - # keeps schedule_not_confirmed as its cause. - begin - result.warnings.each { |warning| logger.warn("PostHog email warning #{warning.code}: #{warning.message}") } - rescue Exception => e # rubocop:disable Lint/RescueException - raise if unconfirmed.nil? || e.cause.equal?(unconfirmed) - - # Ruby keeps the first cause of an exception object a logger raises again, which names an earlier email. A - # copy names this one and leaves the object an earlier caller holds alone. One that can't be copied - # becomes the cause of this send's error instead, but a caller's deadline that arrives during the copy - # propagates. - copy = begin - e.dup - rescue StandardError => copy_error - raise if copy_error.is_a?(Timeout::Error) - - nil - end - raise copy, cause: unconfirmed if copy - - raise unconfirmed, cause: e - end + log_warnings(result.warnings, unconfirmed) end result @@ -416,8 +395,7 @@ def batch( begin raise failure if failure ensure - # A logger's own error keeps the batch's error as its cause. - result.warnings.each { |warning| logger.warn("PostHog email warning #{warning.code}: #{warning.message}") } + log_warnings(result.warnings, failure) end result @@ -559,6 +537,28 @@ def send_chunk(run, chunk, secret_key, max_retries) end end + # The client can't tell a failing logger from a caller's deadline, so either propagates. A logger's own error + # keeps the call's error as its cause. + def log_warnings(warnings, failure) + warnings.each { |warning| logger.warn("PostHog email warning #{warning.code}: #{warning.message}") } + rescue Exception => e # rubocop:disable Lint/RescueException + raise if failure.nil? || e.cause.equal?(failure) + + # Ruby keeps the first cause of an exception object a logger raises again, which names an earlier call. A copy + # names this one and leaves the object an earlier caller holds alone. One that can't be copied becomes the + # cause of this call's error instead, but a caller's deadline that arrives during the copy propagates. + copy = begin + e.dup + rescue StandardError => copy_error + raise if copy_error.is_a?(Timeout::Error) + + nil + end + raise copy, cause: failure if copy + + raise failure, cause: e + end + def still_admitted? @mutex.synchronize do forget_parent_requests diff --git a/spec/posthog/emails_batch_spec.rb b/spec/posthog/emails_batch_spec.rb index 93c1a75f..7bac7b05 100644 --- a/spec/posthog/emails_batch_spec.rb +++ b/spec/posthog/emails_batch_spec.rb @@ -232,6 +232,25 @@ def resend_with_key(result) } end + it "gives a logger's reused exception the failed batch's error as its cause, and leaves the earlier one alone" do + recipients = Array.new(101) { |index| { to: "user#{index}@example.com", idempotency_key: "key-#{index}" } } + slots = Array.new(100) { |index| queued("msg_#{index}") } + first = answer(*slots, warnings: [{ code: 'unverified_link' }]) + stub_request(:post, batch_url) + .to_return(first, refuse(409, 'batch_unavailable'), first, refuse(404, 'not_found')) + reused = IOError.new('log device closed') + logger = Logger.new(File::NULL) + allow(logger).to receive(:warn).and_raise(reused) + PostHog::Logging.logger = logger + + expect { batch_template(recipients) }.to raise_error(reused) + earlier = reused.cause + expect { batch_template(recipients) }.to raise_error(IOError, 'log device closed') { |error| + expect(error.cause.code).to eq('not_found') + } + expect([reused.cause, earlier.code]).to eq([earlier, 'batch_unavailable']) + end + context 'when a request fails as a whole' do let(:recipients) do Array.new(201) do |index| @@ -276,11 +295,30 @@ def resend_with_key(result) result = error.results.first expect([error.code, result.status, result.message_id]).to eq(['invalid_recipient', 'unconfirmed', nil]) expect([result.error.code, result.later_error.code]).to eq(%w[idempotency_key_in_flight invalid_recipient]) + expect(resend_with_key(result)).to eq(['unconfirmed', 'welcome:ada', true]) } end + [ + [%w[delivery_unavailable idempotency_key_in_flight], [503, 409]], + [['idempotency_key_in_flight', nil], [409, 503]] + ].each do |(error_code, later_code), (first, second)| + it "keeps the first reason it can't confirm a recipient when a #{first} retry answers #{second}" do + stub_request(:post, batch_url).to_return( + refuse(first, first == 409 ? 'idempotency_key_in_flight' : 'delivery_unavailable'), + refuse(second, second == 409 ? 'idempotency_key_in_flight' : 'delivery_unavailable') + ) + + expect { batch_template([ada], max_retries: 1) }.to raise_error(EmailBatchError) { |error| + result = error.results.first + expect([result.status, result.error.code, result.later_error&.code]) + .to eq(['unconfirmed', error_code, later_code]) + } + end + end + it 'keeps a recipient unconfirmed when PostHog holds its key past the retries, to send again with it' do - stub_request(:post, batch_url).to_return(refuse(409, 'idempotency_key_in_flight')) + stub_request(:post, batch_url).to_return(refuse(409, 'idempotency_key_in_flight', fix: '')) expect { batch_template([ada], max_retries: 0) }.to raise_error(EmailBatchError) { |error| result = error.results.first @@ -312,6 +350,17 @@ def resend_with_key(result) expect(a_request(:get, %r{/api/messaging/emails/status/})).not_to have_been_made end + it 'makes an answer without a result for each recipient their only error, since nothing retried it' do + stub_request(:post, batch_url).to_return(answer) + + expect { batch_template([ada]) }.to raise_error(EmailBatchError) { |error| + result = error.results.first + expect([error.code, result.error.code, result.later_error]).to eq(['api_error', 'api_error', nil]) + expect(resend_with_key(result)).to eq(['unconfirmed', 'welcome:ada', true]) + } + expect(a_request(:post, batch_url)).to have_been_made.once + end + it "keeps a retry's refusal as the later answer of a recipient it can't confirm" do stub_request(:post, batch_url).to_return(refuse(503, 'delivery_unavailable'), refuse(429, 'rate_limited')) From 231777bc4302629c3f236a2fba0258b235e1934b Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:22:16 +0100 Subject: [PATCH 11/32] chore(emails): name a failed batch's warnings in the changeset Co-Authored-By: Claude Opus 5.5 --- .changeset/email-batch-sends.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/email-batch-sends.md b/.changeset/email-batch-sends.md index a7199056..4f635cff 100644 --- a/.changeset/email-batch-sends.md +++ b/.changeset/email-batch-sends.md @@ -2,4 +2,4 @@ "posthog-ruby": minor --- -Send the same transactional email to many recipients with `emails.batch`, one email each, from a template made in PostHog with `template_data` per recipient, or from content your code rendered. The client sends at most 100 recipients and 4 MiB per request, one request after another, and returns a result per recipient in order: `queued`, `failed`, `unconfirmed` or `not_attempted`. Each recipient has its own `idempotency_key`, given or made by the client, so the client's own retries never send an email twice. To rerun a batch that was cut off, pass the keys you stored: a rerun with the same keys within 24 hours replays the emails that went out. A request that fails as a whole stops the batch and raises `EmailBatchError` with every recipient's result. +Send the same transactional email to many recipients with `emails.batch`, one email each, from a template made in PostHog with `template_data` per recipient, or from content your code rendered. The client sends at most 100 recipients and 4 MiB per request, one request after another, and returns a result per recipient in order: `queued`, `failed`, `unconfirmed` or `not_attempted`. Each recipient has its own `idempotency_key`, given or made by the client, so the client's own retries never send an email twice. To rerun a batch that was cut off, pass the keys you stored: a rerun with the same keys within 24 hours replays the emails that went out. A request that fails as a whole stops the batch and raises `EmailBatchError` with every recipient's result and the warnings of the requests that went out, which the client doesn't log. From df77a2f111519789861965daf5c4580b123eeab6 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:46:28 +0100 Subject: [PATCH 12/32] feat(emails): send a batch as one request of at most 100 recipients 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 --- .changeset/email-batch-sends.md | 2 +- lib/posthog/email_batch.rb | 216 ++++++----------------- lib/posthog/email_error.rb | 7 +- lib/posthog/emails.rb | 99 +++++------ public_api_snapshot.txt | 2 - spec/posthog/emails_batch_spec.rb | 278 ++++++++++-------------------- 6 files changed, 191 insertions(+), 413 deletions(-) diff --git a/.changeset/email-batch-sends.md b/.changeset/email-batch-sends.md index 4f635cff..a851ba14 100644 --- a/.changeset/email-batch-sends.md +++ b/.changeset/email-batch-sends.md @@ -2,4 +2,4 @@ "posthog-ruby": minor --- -Send the same transactional email to many recipients with `emails.batch`, one email each, from a template made in PostHog with `template_data` per recipient, or from content your code rendered. The client sends at most 100 recipients and 4 MiB per request, one request after another, and returns a result per recipient in order: `queued`, `failed`, `unconfirmed` or `not_attempted`. Each recipient has its own `idempotency_key`, given or made by the client, so the client's own retries never send an email twice. To rerun a batch that was cut off, pass the keys you stored: a rerun with the same keys within 24 hours replays the emails that went out. A request that fails as a whole stops the batch and raises `EmailBatchError` with every recipient's result and the warnings of the requests that went out, which the client doesn't log. +Send the same transactional email to many recipients with `emails.batch`, one email each, from a template made in PostHog with `template_data` per recipient, or from content your code rendered. The client sends at most 100 recipients in one request, refusing more before anything is sent, and returns a result per recipient in order: `queued`, `failed` or `unconfirmed`. Each recipient has its own `idempotency_key`, given or made by the client, so the client's own retries never send an email twice. To rerun a batch that was cut off, pass the keys you stored: a rerun with the same keys within 24 hours replays the emails that went out. A request that fails as a whole raises `EmailBatchError` with every recipient's result, such as `too_large` when PostHog finds the batch too large, with the fix to split it into smaller batches. A failed batch never calls the logger. diff --git a/lib/posthog/email_batch.rb b/lib/posthog/email_batch.rb index cd50abd9..652a9a89 100644 --- a/lib/posthog/email_batch.rb +++ b/lib/posthog/email_batch.rb @@ -1,19 +1,20 @@ # frozen_string_literal: true require 'json' -require 'set' require 'posthog/email_error' module PostHog - # The recipients of one {Emails#batch} call, split into requests, and what PostHog answered for each. + # The recipients of one {Emails#batch} call, sent in one request, and what PostHog answered. # # @api private class EmailBatch MAX_RECIPIENTS = 100 - MAX_BODY_BYTES = 4 * 1024 * 1024 UNCONFIRMED_CODES = %w[idempotency_key_in_flight delivery_unavailable api_error].freeze - RESEND_FIX = 'Send it again with the same idempotency_key within 24 hours, so it goes out once.' + # Codes of a whole request that may have queued its emails although the call failed. + MAYBE_QUEUED_CODES = (UNCONFIRMED_CODES + %w[network_error client_closed]).freeze + RESEND_FIX = 'Send it again with the same idempotency_key within 24 hours of the first request that used it, so ' \ + 'it goes out once.' UNAVAILABLE_FIX = "Until batch sends are on for the project, send each email the batch didn't queue with " \ "emails.send and its recipient's idempotency_key." NOT_FOUND = { @@ -23,19 +24,18 @@ class EmailBatch 'fix' => "Check template_id, or send each email the batch didn't queue with emails.send and its recipient's " \ 'idempotency_key.' }.freeze - RESULT_DEFAULTS = { message_id: nil, replayed: false, error: nil, later_error: nil }.freeze - private_constant :UNCONFIRMED_CODES, :RESEND_FIX, :UNAVAILABLE_FIX, :NOT_FOUND, :RESULT_DEFAULTS + TOO_LARGE = { + 'code' => 'too_large', + 'detail' => 'PostHog refused the batch as too large, so no email was sent.', + 'fix' => 'Split the recipients into smaller batches, or make the shared template_data smaller.' + }.freeze + RESULT_DEFAULTS = { message_id: nil, replayed: false, error: nil }.freeze + private_constant :UNCONFIRMED_CODES, :MAYBE_QUEUED_CODES, :RESEND_FIX, :UNAVAILABLE_FIX, :NOT_FOUND, :TOO_LARGE, + :RESULT_DEFAULTS Member = Struct.new(:index, :to, :idempotency_key, :wire, keyword_init: true) - # The recipients of one request. The body is built when the request goes out, so a large batch holds one at a - # time. - Chunk = Struct.new(:empty, :recipients, :indices, keyword_init: true) do - def body - "#{empty.delete_suffix(']}')}#{recipients.map(&:wire).join(',')}]}" - end - end - attr_reader :chunks + attr_reader :body # @param shared [Hash] The batch's email without its recipients. # @param members [Array] Every recipient, with its JSON as the request carries it. @@ -45,173 +45,80 @@ def initialize(shared, members, parse_warnings:, reply_error:) @members = members @parse_warnings = parse_warnings @reply_error = reply_error - @results = Array.new(members.size) @warnings = [] - @maybe_queued = Set.new - @chunks = split(JSON.generate(shared.merge(recipients: []))) + empty = JSON.generate(shared.merge(recipients: [])) + @body = "#{empty.delete_suffix(']}')}#{members.map(&:wire).join(',')}]}" end - # A refusal that may have queued the chunk is its recipients' error, or the later one of a recipient an earlier - # attempt already left unconfirmed. - def lost(chunk, error = nil, refusal = error) - refused(chunk, refusal) if refusal - chunk.indices.each do |index| - next if @maybe_queued.include?(index) - - @maybe_queued << index - message_id = @results[index]&.message_id - set(index, 'unconfirmed', message_id: message_id, error: error || unconfirmed(message_id)) - end - end - - def answer(chunk, (status, payload, retry_after)) + # @return [Emails::BatchResult] The result of an answer with a result for each recipient. + # @raise [EmailError] PostHog refused the request, or answered without a result for each recipient. + def answer((status, payload, retry_after)) fields = payload.is_a?(Hash) ? payload : {} - unless status.between?(200, 299) - error = response_error(fields, status, retry_after, chunk.indices) - # PostHog holds a key while it sends the email, so a request refused for that may already have queued it. - if error.code == 'idempotency_key_in_flight' - lost(chunk, error) - elsif status >= 500 - lost(chunk, nil, error) - else - refused(chunk, error) - end - raise error - end + raise response_error(fields, status, retry_after) unless status.between?(200, 299) + @warnings = @parse_warnings.call(fields['warnings']).uniq slots = fields['results'] - unless slots.is_a?(Array) && slots.size == chunk.indices.size - error = EmailError.new(code: 'api_error', status_code: status, fix: RESEND_FIX, - message: 'PostHog answered the batch without a result for each recipient.') - lost(chunk, error) - raise error - end - chunk.indices.zip(slots) { |index, slot| settle(index, slot.is_a?(Hash) ? slot : {}) } - @parse_warnings.call(fields['warnings']).each do |warning| - @warnings << warning unless @warnings.include?(warning) + unless slots.is_a?(Array) && slots.size == @members.size + raise EmailError.new(code: 'api_error', status_code: status, fix: RESEND_FIX, + message: 'PostHog answered the batch without a result for each recipient.') end - end - - def stop(position, error) - @chunks[position].indices.each do |index| - set(index, 'failed', error: error) unless @maybe_queued.include?(index) - end - skip_from(position + 1, EmailError.new( - code: 'not_attempted', - message: 'An earlier request of the batch failed, so the client sent nothing for ' \ - 'this recipient.' - )) - end - - def closed_at(position) - error = EmailError.new(code: 'client_closed', - message: "The PostHog client is shut down, so the rest of the batch wasn't sent.") - skip_from(position, error) - error - end - def result - Emails::BatchResult.new(results: @results.dup.freeze, warnings: @warnings.dup.freeze) + results = @members.zip(slots).map { |member, slot| settle(member, slot.is_a?(Hash) ? slot : {}) } + Emails::BatchResult.new(results: results.freeze, warnings: @warnings.dup.freeze) end + # Every recipient of a request that failed as a whole is `unconfirmed` when the request may have queued it, and + # `failed` otherwise. def failure(error) - EmailBatchError.new(error, results: @results.dup.freeze, warnings: @warnings.dup.freeze) - end - - private - - # A refusal of a chunk that an earlier attempt may have queued is the later error of its recipients. - def refused(chunk, refusal) - chunk.indices.each do |index| - next unless @maybe_queued.include?(index) - - earlier = @results[index] - set(index, 'unconfirmed', message_id: earlier.message_id, error: earlier.error, later_error: refusal) - end - end - - def split(empty) - chunks = [] - current = [] - size = empty.bytesize - @members.each do |member| - if empty.bytesize + member.wire.bytesize > MAX_BODY_BYTES - set(member.index, 'failed', error: recipient_too_large) - next - end - added = member.wire.bytesize + (current.empty? ? 0 : 1) - if !current.empty? && (current.size == MAX_RECIPIENTS || size + added > MAX_BODY_BYTES) - chunks << chunk(empty, current) - current = [] - size = empty.bytesize - added = member.wire.bytesize + results = @members.map do |member| + if MAYBE_QUEUED_CODES.include?(error.code) + result(member, 'unconfirmed', error: resend(error)) + else + result(member, 'failed', error: error) end - current << member - size += added end - chunks << chunk(empty, current) unless current.empty? - chunks + EmailBatchError.new(error, results: results.freeze, warnings: @warnings.dup.freeze) end - def chunk(empty, members) - Chunk.new(empty: empty, recipients: members, indices: members.map(&:index)) - end + private - def settle(index, slot) + def settle(member, slot) message_id = text(slot['message_id']) if slot['error'].nil? && slot['status'] == 'queued' && message_id - @maybe_queued.delete(index) - set(index, 'queued', message_id: message_id, replayed: slot['replayed'] == true) - return + return result(member, 'queued', message_id: message_id, replayed: slot['replayed'] == true) end answer = slot_error(slot['error'], message_id) - if @maybe_queued.include?(index) - earlier = @results[index] - set(index, 'unconfirmed', message_id: message_id || earlier.message_id, error: earlier.error, - later_error: answer) - elsif UNCONFIRMED_CODES.include?(answer.code) - @maybe_queued << index - set(index, 'unconfirmed', message_id: message_id, error: answer) - else - set(index, 'failed', message_id: message_id, error: answer) - end + status = UNCONFIRMED_CODES.include?(answer.code) ? 'unconfirmed' : 'failed' + result(member, status, message_id: message_id, error: answer) end - def skip_from(position, error) - @chunks.drop(position).each do |chunk| - chunk.indices.each { |index| set(index, 'not_attempted', error: error) } - end + def result(member, status, **fields) + identity = { index: member.index, to: member.to, idempotency_key: member.idempotency_key, status: status } + Emails::BatchEmailResult.new(**RESULT_DEFAULTS, **identity, **fields) end - def set(index, status, **fields) - member = @members[index] - identity = { index: index, to: member.to, idempotency_key: member.idempotency_key, status: status } - @results[index] = Emails::BatchEmailResult.new(**RESULT_DEFAULTS, **identity, **fields) + # A caller who follows PostHog's own advice without the key sends a second email. + def resend(error) + return error if error.fix == RESEND_FIX + + EmailError.new(code: error.code, message: error.message, status_code: error.status_code, why: error.why, + fix: RESEND_FIX, docs_url: error.docs_url, field: error.field, retry_after: error.retry_after) end - def response_error(fields, status, retry_after, indices) + def response_error(fields, status, retry_after) answered = fields.compact - answered['attr'] = recipients_field(answered['attr'], indices) if answered['attr'].is_a?(String) - fields = status == 404 ? NOT_FOUND.merge(answered) : answered + fields = if status == 404 + NOT_FOUND.merge(answered) + elsif status == 413 + TOO_LARGE.merge(answered).merge('fix' => TOO_LARGE['fix']) + else + answered + end fields = fields.merge('fix' => UNAVAILABLE_FIX) if fields['code'] == 'batch_unavailable' - if fields['code'] == 'idempotency_key_in_flight' && !text(fields['fix']) - fields = fields.merge('fix' => RESEND_FIX) - end @reply_error.call(fields, status, retry_after) end - # PostHog names a recipient by its place in the request, and the caller knows it by its place in the batch. - def recipients_field(attr, indices) - parts = /\Arecipients__(\d+)(__.*)?\z/m.match(attr) - return attr if parts.nil? - - position = parts[1] - return 'recipients' if position.size > indices.size.to_s.size || position.to_i >= indices.size - - "recipients__#{indices[position.to_i]}#{parts[2]}" - end - def slot_error(error, message_id) unless error.is_a?(Hash) return EmailError.new(code: 'api_error', message_id: message_id, fix: RESEND_FIX, @@ -228,17 +135,6 @@ def slot_error(error, message_id) message: text(error['detail']) || "PostHog didn't queue this email: #{code}.") end - def unconfirmed(message_id) - EmailError.new(code: 'delivery_unavailable', message_id: message_id, fix: RESEND_FIX, - message: "PostHog didn't confirm this email, so it may still go out.") - end - - def recipient_too_large - EmailError.new(code: 'content_too_large', field: 'recipients', - message: "This recipient's email is larger than one batch request takes, so it wasn't sent.", - fix: "Make this recipient's template_data, or the batch's content, smaller.") - end - def text(value) value if value.is_a?(String) && !value.empty? end diff --git a/lib/posthog/email_error.rb b/lib/posthog/email_error.rb index d15904cf..447e771c 100644 --- a/lib/posthog/email_error.rb +++ b/lib/posthog/email_error.rb @@ -81,11 +81,10 @@ def self.name_for(status_code, code) end end - # A request of {Emails#batch} failed as a whole, so the batch stopped. + # The request of {Emails#batch} failed as a whole. # - # The other fields describe that request's error. {#results} holds every recipient: those of earlier requests as - # PostHog answered them, those of the failed request as `failed`, or `unconfirmed` where PostHog may have queued - # them, such as after a lost answer or while it held their key, and the rest as `not_attempted`. + # The other fields describe its error. {#results} holds every recipient: `unconfirmed` where PostHog may have queued + # them, such as after a lost answer or while it held their keys, and `failed` otherwise. class EmailBatchError < EmailError # @return [Array] One result per recipient, in the order of the batch's recipients. attr_reader :results diff --git a/lib/posthog/emails.rb b/lib/posthog/emails.rb index 88cd645a..739a98c6 100644 --- a/lib/posthog/emails.rb +++ b/lib/posthog/emails.rb @@ -115,20 +115,18 @@ def status # - `queued`: PostHog accepted the email. Read it with {Emails#get} to see whether it went out. # - `failed`: PostHog didn't queue the email, and {#error} says why, such as a suppressed address. # - `unconfirmed`: the client can't tell whether PostHog queued the email, such as after a lost answer. It may - # still go out. Send it again with the same +idempotency_key+ within 24 hours, so it goes out once. - # - `not_attempted`: an earlier request of the batch failed, so the client sent nothing for this recipient. + # still go out. Send it again with the same +idempotency_key+ within 24 hours of the first request that + # used it, so it goes out once. # @!attribute [r] message_id # @return [String, nil] The email's message ID, when PostHog named it. # @!attribute [r] replayed # @return [Boolean] Whether an earlier send with the same key had already queued the email, so no new email # went out. # @!attribute [r] error - # @return [EmailError, nil] Why the email is not `queued`. For an `unconfirmed` email, {EmailError#code} is - # `delivery_unavailable`, `idempotency_key_in_flight` or `api_error`. - # @!attribute [r] later_error - # @return [EmailError, nil] For an `unconfirmed` email, the last refusal a retry in the same call answered - # about it, which describes only that retry. A retry that got no answer leaves it as it was. - BatchEmailResult = Struct.new(:index, :to, :idempotency_key, :status, :message_id, :replayed, :error, :later_error, + # @return [EmailError, nil] Why the email is not `queued`. For an `unconfirmed` email, {EmailError#code} names + # what left it so, such as `idempotency_key_in_flight`, `delivery_unavailable`, `api_error` or + # `network_error`, and {EmailError#fix} says to send it again with the same key. + BatchEmailResult = Struct.new(:index, :to, :idempotency_key, :status, :message_id, :replayed, :error, keyword_init: true) # The answer to {Emails#batch}. @@ -333,14 +331,15 @@ def send( # your code rendered. # # Pass the template form, with +template_id+, or the code form, with +template_key+, as {#send} takes them. The - # client sends the recipients in requests of at most 100 recipients and 4 MiB of JSON, one after another, and - # waits at least 45 seconds for each answer. A batch takes no +cc+, +bcc+, +attachments+ or +scheduled_at+. + # client sends at most 100 recipients in one request and waits at least 45 seconds for the answer. PostHog + # refuses a batch it finds too large with `too_large`: split the recipients into smaller batches. A batch takes + # no +cc+, +bcc+, +attachments+ or +scheduled_at+. # # Each recipient has an +idempotency_key+, given or made by the client, that every retry reuses, so a retry never # queues an email twice. Retries follow {#send}'s. Send each `unconfirmed` email again with its - # +idempotency_key+ within 24 hours, so it goes out once. + # +idempotency_key+ within 24 hours of the first request that used it, so it goes out once. # - # @param recipients [Array] 1 or more recipients, each a Hash with: + # @param recipients [Array] 1 to 100 recipients, each a Hash with: # - +to+ [String] the recipient's email address; # - +distinct_id+ [String] optional: the recipient's distinct ID in your product; # - +idempotency_key+ [String] optional: 1 to 255 visible ASCII characters, a different one for each recipient. @@ -355,19 +354,21 @@ def send( # or both, and optionally +from+, +reply_to+, +sensitive+, +tracking+ and +capture_engagement+, the same for # every recipient. A recipient can't carry +template_data+: send personalized content with a +template_id+ # batch, or with {#send}. - # @param max_retries [Integer] Overrides the client's `email_request_max_retries` for each request of the batch. - # +0+ turns retries off. + # @param max_retries [Integer] Overrides the client's `email_request_max_retries` for the batch's request. +0+ + # turns retries off. # @return [BatchResult] A result per recipient, in the order of +recipients+. Check each # {BatchEmailResult#status}, and send an `unconfirmed` email again with the same key so it goes out once. - # @raise [EmailBatchError] A request failed as a whole, such as a rate limit past its retries, so the batch - # stopped. {EmailBatchError#results} holds every recipient, those not sent as `not_attempted`. - # {EmailError#code} is `batch_unavailable` when the project can't send batches yet, and `not_found` when the - # template doesn't exist or batch sends are off: send each email the batch didn't queue with {#send} and its - # recipient's +idempotency_key+. It is `client_closed` when the client shut down during the batch. The warnings - # of the requests that went out are on {EmailError#warnings}, and the client logs none of them. + # @raise [EmailBatchError] The request failed as a whole, such as a rate limit past its retries. The last attempt + # decides the error. {EmailBatchError#results} holds every recipient: `unconfirmed` with a fix to send it again + # with the same key when the request may have queued it, such as `idempotency_key_in_flight`, a 5xx, a lost + # answer or `client_closed` when the client shut down before a retry, and `failed` otherwise. + # {EmailError#code} is `too_large` (413) when PostHog finds the batch too large, `batch_unavailable` when the + # project can't send batches yet, and `not_found` when the template doesn't exist or batch sends are off: send + # each email the batch didn't queue with {#send} and its recipient's +idempotency_key+. The warnings of an + # answer without a result for each recipient are on {EmailError#warnings}, and the client logs none of them. # @raise [EmailError] The client sent nothing, such as when it is disabled or has no +secret_key+. - # @raise [ArgumentError] An argument has the wrong type or format, such as two recipients with the same - # +idempotency_key+. + # @raise [ArgumentError] An argument has the wrong type or format, such as more than 100 recipients or two + # recipients with the same +idempotency_key+. No email was sent. def batch( recipients:, template_id: nil, template_data: nil, template_key: nil, subject: nil, html: nil, text: nil, from: nil, reply_to: nil, sensitive: nil, tracking: nil, capture_engagement: nil, max_retries: nil @@ -385,12 +386,11 @@ def batch( members = batch_members(recipients, template_key.nil?) run = EmailBatch.new(shared, members, parse_warnings: method(:warnings), reply_error: method(:reply_error)) - failure = call('no email was sent', SEND_KEY_NEEDED) do |secret_key| - send_chunks(run, secret_key, max_retries || @max_retries) + result, failure = call('no email was sent', SEND_KEY_NEEDED) do |secret_key| + send_batch(run, secret_key, max_retries || @max_retries) end raise failure if failure - result = run.result log_warnings(result.warnings) result @@ -440,6 +440,10 @@ def batch_members(recipients, template_form) "recipients must be an Array of recipients, each a Hash with to, such as [{ to: 'user@example.com' }]." end raise ArgumentError, 'recipients must hold at least one recipient.' if recipients.empty? + if recipients.size > EmailBatch::MAX_RECIPIENTS + raise ArgumentError, "recipients must hold at most #{EmailBatch::MAX_RECIPIENTS} recipients, not " \ + "#{recipients.size}. Split them into smaller batches." + end first_with_key = {} recipients.each_with_index.map do |recipient, index| @@ -491,49 +495,24 @@ def batch_member(fields, index, template_form) EmailBatch::Member.new(index: index, to: to, idempotency_key: key, wire: JSON.generate(wire)) end - def send_chunks(run, secret_key, max_retries) - error = nil - run.chunks.each_with_index do |chunk, position| - if position.positive? && !still_admitted? - error = run.closed_at(position) - break - end - - begin - send_chunk(run, chunk, secret_key, max_retries) - rescue EmailError => e - run.stop(position, e) - error = e - break - end - end - run.failure(error) if error - end - - def send_chunk(run, chunk, secret_key, max_retries) + def send_batch(run, secret_key, max_retries) uri = URI(@app_host + BATCH_PATH) read_timeout = [@timeout.to_f, BATCH_ATTEMPT_TIMEOUT_SECONDS].max - body = chunk.body - with_retries(max_retries) do |attempt| + result = with_retries(max_retries) do |attempt| if attempt.positive? && !still_admitted? - raise EmailError.new( - code: 'client_closed', - message: "The PostHog client is shut down, so it didn't retry this request of the batch." - ) + raise EmailError.new(code: 'client_closed', + message: "The PostHog client is shut down, so it didn't retry the batch.") end - begin - reply = request(Net::HTTP::Post.new(uri), uri, secret_key, JSON_CONTENT, body, read_timeout: read_timeout) - rescue EmailError - run.lost(chunk) - raise - end - run.answer(chunk, reply) + run.answer(request(Net::HTTP::Post.new(uri), uri, secret_key, JSON_CONTENT, run.body, + read_timeout: read_timeout)) end + [result, nil] + rescue EmailError => e + [nil, run.failure(e)] end - # The client can't tell a failing logger from a caller's deadline, so either propagates. A logger's own error - # keeps the call's error as its cause. + # The client can't tell a failing logger from a caller's deadline, so either propagates. def log_warnings(warnings) warnings.each { |warning| logger.warn("PostHog email warning #{warning.code}: #{warning.message}") } end diff --git a/public_api_snapshot.txt b/public_api_snapshot.txt index c8cc107a..04fa4d02 100644 --- a/public_api_snapshot.txt +++ b/public_api_snapshot.txt @@ -88,8 +88,6 @@ instance_method PostHog::Emails::BatchEmailResult#idempotency_key() instance_method PostHog::Emails::BatchEmailResult#idempotency_key=(_) instance_method PostHog::Emails::BatchEmailResult#index() instance_method PostHog::Emails::BatchEmailResult#index=(_) -instance_method PostHog::Emails::BatchEmailResult#later_error() -instance_method PostHog::Emails::BatchEmailResult#later_error=(_) instance_method PostHog::Emails::BatchEmailResult#message_id() instance_method PostHog::Emails::BatchEmailResult#message_id=(_) instance_method PostHog::Emails::BatchEmailResult#replayed() diff --git a/spec/posthog/emails_batch_spec.rb b/spec/posthog/emails_batch_spec.rb index 8d1addc6..5ea49c22 100644 --- a/spec/posthog/emails_batch_spec.rb +++ b/spec/posthog/emails_batch_spec.rb @@ -52,9 +52,9 @@ def statuses(results) end def resend_with_key(result) - [result.status, result.idempotency_key, result.error.fix.include?('same idempotency_key')] + [result.status, result.idempotency_key, + result.error.fix.include?('same idempotency_key within 24 hours of the first request that used it')] end - describe '#batch' do it 'sends one request and returns a result per recipient, in order' do stub_request(:post, batch_url).to_return(answer(queued('msg_1'), queued('msg_2', replayed: true))) @@ -63,9 +63,9 @@ def resend_with_key(result) expect(result.results.map(&:to_h)).to eq( [{ index: 0, to: 'ada@example.com', idempotency_key: 'welcome:ada', status: 'queued', message_id: 'msg_1', - replayed: false, error: nil, later_error: nil }, + replayed: false, error: nil }, { index: 1, to: 'alan@example.com', idempotency_key: 'welcome:alan', status: 'queued', - message_id: 'msg_2', replayed: true, error: nil, later_error: nil }] + message_id: 'msg_2', replayed: true, error: nil }] ) expect(batch_bodies).to eq( [{ 'template_id' => template_id, 'message_data' => { 'product' => 'Hog' }, @@ -106,17 +106,18 @@ def resend_with_key(result) ) end - it 'splits more than 100 recipients into requests of at most 100, one after another' do - recipients = Array.new(101) { |index| { to: "user#{index}@example.com", idempotency_key: "key-#{index}" } } - stub_request(:post, batch_url).to_return( - answer(*Array.new(100) { |index| queued("msg_#{index}") }), answer(queued('msg_100')) - ) + it 'sends 100 recipients in one request, and refuses 101 before any request' do + hundred = Array.new(100) { |index| { to: "user#{index}@example.com", idempotency_key: "key-#{index}" } } + stub_request(:post, batch_url).to_return(answer(*Array.new(100) { |index| queued("msg_#{index}") })) - result = batch_template(recipients) + expect { batch_template(hundred + [{ to: 'user100@example.com' }]) } + .to raise_error(ArgumentError, /at most 100 recipients/) + expect(a_request(:post, batch_url)).not_to have_been_made - expect(batch_bodies.map { |body| body['recipients'].size }).to eq([100, 1]) - expect(result.results.map(&:message_id)).to eq(Array.new(101) { |index| "msg_#{index}" }) - expect(result.results.map(&:index)).to eq((0..100).to_a) + result = batch_template(hundred) + + expect(batch_bodies.map { |body| body['recipients'].size }).to eq([100]) + expect(result.results.map(&:message_id)).to eq(Array.new(100) { |index| "msg_#{index}" }) end it "returns each recipient PostHog refused as failed and one it didn't confirm as unconfirmed" do @@ -139,7 +140,7 @@ def resend_with_key(result) it 'leaves an unconfirmed email PostHog answered without an ID to be sent again with its key' do stub_request(:post, batch_url).to_return( answer(slot_error('delivery_unavailable', 503, message_id: 'msg_ada'), - slot_error('delivery_unavailable', 503, message_id: nil), 'not a result') + slot_error('delivery_unavailable', 503, message_id: nil), { status: 'queued' }) ) results = batch_template([ada, alan, { to: 'grace@example.com', idempotency_key: 'welcome:grace' }]).results @@ -152,121 +153,68 @@ def resend_with_key(result) expect(a_request(:get, %r{/api/messaging/emails/status/})).not_to have_been_made end - it 'fails a recipient too large for one request and sends the rest' do - stub_request(:post, batch_url).to_return(answer(queued('msg_2'))) - huge = { to: 'ada@example.com', template_data: { note: 'x' * (4 * 1024 * 1024) } } - - results = batch_template([huge, alan]).results - - expect(statuses(results)).to eq(%w[failed queued]) - expect([results.first.error.code, results.first.error.field]).to eq(%w[content_too_large recipients]) - expect(batch_bodies.map { |body| body['recipients'].map { |recipient| recipient['to'] } }) - .to eq([['alan@example.com']]) - end - - it 'fails every recipient when the shared content alone is too large, and sends nothing' do - results = batch_template([ada, alan], template_data: { note: 'x' * (4 * 1024 * 1024) }).results - - expect(statuses(results)).to eq(%w[failed failed]) - expect(results.map { |result| result.error.code }.uniq).to eq(['content_too_large']) - expect(results.first.error.fix).to eq("Make this recipient's template_data, or the batch's content, smaller.") - expect(a_request(:any, %r{/api/messaging/})).not_to have_been_made - end - - it 'sends a request of exactly 4 MiB and splits one a byte larger' do - bodies = [] - stub_request(:post, batch_url).to_return do |request| - bodies << request.body - answer(*JSON.parse(request.body)['recipients'].map { |recipient| queued("msg_#{recipient['to']}") }) - end - # Three recipients, so each stays under the 1.5 MiB PostHog takes for one email. - trio = lambda do |sizes| - sizes.each_with_index.map do |size, index| - { to: "user#{index}@example.com", idempotency_key: "k-#{index}", template_data: { note: 'x' * size } } - end - end - batch_template(trio.call([1, 1, 1])) - fill = (4 * 1024 * 1024) - bodies.first.bytesize + 3 - sizes = [fill / 3, fill / 3, fill - (2 * (fill / 3))] - - batch_template(trio.call(sizes)) - result = batch_template(trio.call([sizes[0], sizes[1], sizes[2] + 1])) - - expect(sizes.max).to be < 1.5 * 1024 * 1024 - expect(bodies.drop(1).map(&:bytesize).first).to eq(4 * 1024 * 1024) - expect(bodies.drop(1).map { |body| JSON.parse(body)['recipients'].size }).to eq([3, 2, 1]) - notes = bodies.last(2).flat_map { |body| JSON.parse(body)['recipients'] }.map { |r| r['message_data']['note'] } - expect(notes.map(&:size)).to eq([sizes[0], sizes[1], sizes[2] + 1]) - expect(statuses(result.results)).to eq(%w[queued queued queued]) - end - - it 'logs each warning once' do + it "logs the reply's warnings" do warning = { code: 'unverified_link', detail: 'A link points to an unverified domain.' } - recipients = Array.new(101) { |index| { to: "user#{index}@example.com" } } - stub_request(:post, batch_url).to_return( - answer(*Array.new(100) { |index| queued("msg_#{index}") }, warnings: [warning]), - answer(queued('msg_100'), warnings: [warning]) - ) + stub_request(:post, batch_url).to_return(answer(queued('msg_1'), warnings: [warning])) log = StringIO.new - PostHog::Logging.logger = Logger.new(log) + PostHog::Logging.logger = Logger.new(log, level: Logger::WARN) - result = batch_template(recipients) + result = batch_template([ada]) expect(result.warnings.map(&:code)).to eq(['unverified_link']) expect(log.string.scan('PostHog email warning unverified_link').size).to eq(1) end it "carries a failed batch's warnings on its error and never logs them" do - recipients = Array.new(101) { |index| { to: "user#{index}@example.com", idempotency_key: "key-#{index}" } } - stub_request(:post, batch_url).to_return( - answer(*Array.new(100) { |index| queued("msg_#{index}") }, warnings: [{ code: 'unverified_link' }]), - refuse(409, 'batch_unavailable') - ) - logger = Logger.new(File::NULL) - allow(logger).to receive(:warn).and_raise(IOError, 'log device closed') - PostHog::Logging.logger = logger - - expect { batch_template(recipients) }.to raise_error(EmailBatchError) { |error| - expect([error.code, error.cause, - error.warnings.map(&:code)]).to eq(['batch_unavailable', nil, ['unverified_link']]) - expect(error.results.map(&:status).tally).to eq('queued' => 100, 'failed' => 1) + stub_request(:post, batch_url).to_return(answer(warnings: [{ code: 'unverified_link' }])) + log = StringIO.new + PostHog::Logging.logger = Logger.new(log, level: Logger::WARN) + + expect { batch_template([ada]) }.to raise_error(EmailBatchError) { |error| + expect([error.code, error.cause, error.warnings.map(&:code)]).to eq(['api_error', nil, ['unverified_link']]) } - expect(logger).not_to have_received(:warn) + expect(log.string).to be_empty end it 'lets a failing logger stop a batch that succeeded with its own error' do stub_request(:post, batch_url).to_return(answer(queued('msg_0'), warnings: [{ code: 'unverified_link' }])) - logger = Logger.new(File::NULL) - allow(logger).to receive(:warn).and_raise(IOError, 'log device closed') - PostHog::Logging.logger = logger + PostHog::Logging.logger = Logger.new(StringIO.new, level: Logger::WARN, + formatter: ->(*) { raise IOError, 'log device closed' }) expect { batch_template([{ to: 'user@example.com' }]) }.to raise_error(IOError, 'log device closed') { |error| expect(error.cause).to be_nil } end - context 'when a request fails as a whole' do - let(:recipients) do - Array.new(201) do |index| - { to: "user#{index}@example.com", idempotency_key: "key-#{index}" } - end - end - - it 'stops the batch and raises EmailBatchError with every recipient' do + context 'when the request fails as a whole' do + it 'raises EmailBatchError with every recipient failed and the field PostHog named' do stub_request(:post, batch_url).to_return( - answer(*Array.new(100) { |index| queued("msg_#{index}") }), - refuse(400, 'invalid_recipient', detail: 'A recipient is invalid.', attr: 'recipients__7__to') + refuse(400, 'invalid_recipient', detail: 'A recipient is invalid.', attr: 'recipients__1__to') ) - expect { batch_template(recipients) }.to raise_error(EmailBatchError) { |error| - expect([error.code, error.status_code, - error.field]).to eq(['invalid_recipient', 400, 'recipients__107__to']) - expect(error.results.size).to eq(201) - expect(error.results.map(&:status).tally).to eq('queued' => 100, 'failed' => 100, 'not_attempted' => 1) - expect(error.results[100].error.code).to eq('invalid_recipient') - expect(error.results[200].error.code).to eq('not_attempted') + expect { batch_template([ada, alan]) }.to raise_error(EmailBatchError) { |error| + expect([error.code, error.status_code, error.field]).to eq(['invalid_recipient', 400, 'recipients__1__to']) + expect(error.results.map { |result| [result.status, result.error.code] }) + .to eq([%w[failed invalid_recipient], %w[failed invalid_recipient]]) } - expect(a_request(:post, batch_url)).to have_been_made.twice + expect(a_request(:post, batch_url)).to have_been_made.once + end + + { + 'a 413 with its code' => { status: 413, body: JSON.generate(code: 'too_large', detail: 'Too large.') }, + 'a 413 without a JSON body' => { status: 413, body: 'Request Entity Too Large' }, + 'a 413 with its own fix' => { status: 413, body: JSON.generate(code: 'too_large', fix: 'Send less.') } + }.each do |name, reply| + it "surfaces #{name} as the error, with the fix to split the recipients" do + stub_request(:post, batch_url).to_return(reply) + + expect { batch_template([ada, alan]) }.to raise_error(EmailBatchError) { |error| + expect([error.code, error.status_code]).to eq(['too_large', 413]) + expect(error.fix).to include('smaller batches') + expect(statuses(error.results)).to eq(%w[failed failed]) + } + expect(a_request(:post, batch_url)).to have_been_made.once + end end it 'raises batch_unavailable with the fix to send each email on its own' do @@ -280,49 +228,19 @@ def resend_with_key(result) expect(a_request(:post, batch_url)).to have_been_made.once end - it 'keeps a recipient unconfirmed while PostHog holds its key, also after a later refusal' do - stub_request(:post, batch_url).to_return( - refuse(409, 'idempotency_key_in_flight'), refuse(400, 'invalid_recipient', attr: 'recipients__0__to') - ) - - expect { batch_template([ada], max_retries: 1) }.to raise_error(EmailBatchError) { |error| - result = error.results.first - expect([error.code, result.status, result.message_id]).to eq(['invalid_recipient', 'unconfirmed', nil]) - expect([result.error.code, result.later_error.code]).to eq(%w[idempotency_key_in_flight invalid_recipient]) - expect(resend_with_key(result)).to eq(['unconfirmed', 'welcome:ada', true]) - } - end + ['', 'Wait a few seconds and try again.'].each do |fix| + it "keeps every recipient unconfirmed while PostHog holds the keys, with fix #{fix.inspect}" do + stub_request(:post, batch_url).to_return(refuse(409, 'idempotency_key_in_flight', fix: fix)) - { - [503, 409] => %w[delivery_unavailable idempotency_key_in_flight], - [409, 503] => %w[idempotency_key_in_flight delivery_unavailable], - [409, 429, 503] => %w[idempotency_key_in_flight delivery_unavailable], - [409, 429, :reset] => %w[idempotency_key_in_flight rate_limited] - }.each do |statuses, (error_code, later_code)| - it "keeps the first reason it can't confirm a recipient and the last refusal after #{statuses.join(', ')}" do - codes = { 409 => 'idempotency_key_in_flight', 429 => 'rate_limited', 503 => 'delivery_unavailable' } - stub = stub_request(:post, batch_url) - .to_return(*statuses.grep(Integer).map { |status| refuse(status, codes[status]) }) - stub.then.to_raise(Errno::ECONNRESET) if statuses.last == :reset - - expect { batch_template([ada], max_retries: statuses.size - 1) }.to raise_error(EmailBatchError) { |error| - result = error.results.first - expect([result.status, result.error.code, result.later_error&.code]) - .to eq(['unconfirmed', error_code, later_code]) + expect { batch_template([ada, alan], max_retries: 0) }.to raise_error(EmailBatchError) { |error| + expect([error.code, error.results.map(&:message_id)]).to eq(['idempotency_key_in_flight', [nil, nil]]) + expect(error.results.map { |result| resend_with_key(result) }) + .to eq([['unconfirmed', 'welcome:ada', true], ['unconfirmed', 'welcome:alan', true]]) } + expect(a_request(:post, batch_url)).to have_been_made.once end end - it 'keeps a recipient unconfirmed when PostHog holds its key past the retries, to send again with it' do - stub_request(:post, batch_url).to_return(refuse(409, 'idempotency_key_in_flight', fix: '')) - - expect { batch_template([ada], max_retries: 0) }.to raise_error(EmailBatchError) { |error| - result = error.results.first - expect([error.code, result.message_id, result.later_error]).to eq(['idempotency_key_in_flight', nil, nil]) - expect(resend_with_key(result)).to eq(['unconfirmed', 'welcome:ada', true]) - } - end - it 'names a 404 as a missing template or batch sends that are off' do stub_request(:post, batch_url).to_return(status: 404, body: '') @@ -337,51 +255,53 @@ def resend_with_key(result) expect { batch_template([ada, alan], max_retries: 1) }.to raise_error(EmailBatchError) { |error| expect(error.code).to eq('network_error') - expect(error.results.map(&:message_id)).to eq([nil, nil]) + expect(error.results.map { |result| [result.message_id, result.error.code] }) + .to eq([[nil, 'network_error'], [nil, 'network_error']]) expect(error.results.map { |result| resend_with_key(result) }) .to eq([['unconfirmed', 'welcome:ada', true], ['unconfirmed', 'welcome:alan', true]]) - expect(error.results.first.error.code).to eq('delivery_unavailable') } expect(a_request(:post, batch_url)).to have_been_made.twice expect(a_request(:get, %r{/api/messaging/emails/status/})).not_to have_been_made end - it 'makes an answer without a result for each recipient their only error, since nothing retried it' do - stub_request(:post, batch_url).to_return(answer) + it 'keeps every recipient unconfirmed when the answer has no result for each, and never retries it' do + stub_request(:post, batch_url).to_return(answer(queued('msg_1'))) - expect { batch_template([ada]) }.to raise_error(EmailBatchError) { |error| - result = error.results.first - expect([error.code, result.error.code, result.later_error]).to eq(['api_error', 'api_error', nil]) - expect(resend_with_key(result)).to eq(['unconfirmed', 'welcome:ada', true]) + expect { batch_template([ada, alan]) }.to raise_error(EmailBatchError) { |error| + expect(error.code).to eq('api_error') + expect(error.results.map { |result| resend_with_key(result) }) + .to eq([['unconfirmed', 'welcome:ada', true], ['unconfirmed', 'welcome:alan', true]]) } expect(a_request(:post, batch_url)).to have_been_made.once end - it "keeps a retry's refusal as the later answer of a recipient it can't confirm" do - stub_request(:post, batch_url).to_return(refuse(503, 'delivery_unavailable'), refuse(429, 'rate_limited')) - - expect { batch_template([ada], max_retries: 1) }.to raise_error(EmailBatchError) { |error| - result = error.results.first - expect([result.status, result.message_id]).to eq(['unconfirmed', nil]) - expect([result.error.code, result.later_error.code]).to eq(%w[delivery_unavailable rate_limited]) - } + { + [503, 503] => %w[unconfirmed delivery_unavailable], + [503, 400] => %w[failed invalid_recipient], + [503, 429] => %w[failed rate_limited] + }.each do |statuses, (status, code)| + it "reports what the last attempt answered after #{statuses.join(', ')}" do + codes = { 400 => 'invalid_recipient', 429 => 'rate_limited', 503 => 'delivery_unavailable' } + stub_request(:post, batch_url).to_return(*statuses.map { |answered| refuse(answered, codes[answered]) }) + + expect { batch_template([ada], max_retries: 1) }.to raise_error(EmailBatchError) { |error| + result = error.results.first + expect([error.code, result.status, result.error.code]).to eq([code, status, code]) + } + expect(a_request(:post, batch_url)).to have_been_made.twice + end end - it 'keeps the first unconfirmed answer and adds what a later retry said' do - stub_request(:post, batch_url).to_return( - refuse(503, 'delivery_unavailable'), - answer(slot_error('idempotency_key_reused', 422, message_id: 'msg_1')) - ) + it 'keeps every recipient unconfirmed after a 5xx without a code, to send again with its key' do + stub_request(:post, batch_url).to_return(status: 502, body: 'Bad gateway') - result = batch_template([ada]) - - expect(result.results.first.to_h.slice(:status, - :message_id)).to eq(status: 'unconfirmed', message_id: 'msg_1') - expect(result.results.first.error.code).to eq('delivery_unavailable') - expect(result.results.first.later_error.code).to eq('idempotency_key_reused') + expect { batch_template([ada], max_retries: 0) }.to raise_error(EmailBatchError) { |error| + expect(error.status_code).to eq(502) + expect(resend_with_key(error.results.first)).to eq(['unconfirmed', 'welcome:ada', true]) + } end - it "doesn't retry once the client shuts down" do + it "doesn't retry once the client shuts down, and leaves the recipients unconfirmed" do stub_request(:post, batch_url).to_return do client.shutdown(timeout: 0) refuse(503, 'delivery_unavailable') @@ -389,21 +309,7 @@ def resend_with_key(result) expect { batch_template([ada]) }.to raise_error(EmailBatchError) { |error| expect(error.code).to eq('client_closed') - expect(statuses(error.results)).to eq(['unconfirmed']) - } - expect(a_request(:post, batch_url)).to have_been_made.once - end - - it 'stops before the next request once the client shuts down' do - recipients = Array.new(101) { |index| { to: "user#{index}@example.com" } } - stub_request(:post, batch_url).to_return do - client.shutdown(timeout: 0) - answer(*Array.new(100) { |index| queued("msg_#{index}") }) - end - - expect { batch_template(recipients) }.to raise_error(EmailBatchError) { |error| - expect(error.code).to eq('client_closed') - expect(error.results.map(&:status).tally).to eq('queued' => 100, 'not_attempted' => 1) + expect(resend_with_key(error.results.first)).to eq(['unconfirmed', 'welcome:ada', true]) } expect(a_request(:post, batch_url)).to have_been_made.once end From 3d96c42aa67c96b6826fdcf2ae5ee321d3683a65 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:00:28 +0100 Subject: [PATCH 13/32] fix(emails): let a failed batch's status decide whether it may have gone 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 --- .changeset/email-batch-sends.md | 2 +- lib/posthog/email_batch.rb | 17 ++++++++++++----- lib/posthog/emails.rb | 19 ++++++++++--------- spec/posthog/emails_batch_spec.rb | 28 ++++++++++++++++++---------- 4 files changed, 41 insertions(+), 25 deletions(-) diff --git a/.changeset/email-batch-sends.md b/.changeset/email-batch-sends.md index a851ba14..9bf8d54c 100644 --- a/.changeset/email-batch-sends.md +++ b/.changeset/email-batch-sends.md @@ -2,4 +2,4 @@ "posthog-ruby": minor --- -Send the same transactional email to many recipients with `emails.batch`, one email each, from a template made in PostHog with `template_data` per recipient, or from content your code rendered. The client sends at most 100 recipients in one request, refusing more before anything is sent, and returns a result per recipient in order: `queued`, `failed` or `unconfirmed`. Each recipient has its own `idempotency_key`, given or made by the client, so the client's own retries never send an email twice. To rerun a batch that was cut off, pass the keys you stored: a rerun with the same keys within 24 hours replays the emails that went out. A request that fails as a whole raises `EmailBatchError` with every recipient's result, such as `too_large` when PostHog finds the batch too large, with the fix to split it into smaller batches. A failed batch never calls the logger. +Send the same transactional email to many recipients with `emails.batch`, one email each, from a template made in PostHog with `template_data` per recipient, or from content your code rendered. The client sends at most 100 recipients in one request, refusing more before anything is sent, and returns a result per recipient in order: `queued`, `failed` or `unconfirmed`. Each recipient has its own `idempotency_key`, given or made by the client, so the client's own retries never send an email twice. To rerun a batch that was cut off, pass the keys you stored: a rerun with the same keys within 24 hours replays the emails that went out. A request that fails as a whole raises `EmailBatchError` with every recipient's result, such as `content_too_large` when PostHog finds the batch too large, with the fix to split it into smaller batches. A failed batch never calls the logger. diff --git a/lib/posthog/email_batch.rb b/lib/posthog/email_batch.rb index 652a9a89..dae4746b 100644 --- a/lib/posthog/email_batch.rb +++ b/lib/posthog/email_batch.rb @@ -11,8 +11,6 @@ module PostHog class EmailBatch MAX_RECIPIENTS = 100 UNCONFIRMED_CODES = %w[idempotency_key_in_flight delivery_unavailable api_error].freeze - # Codes of a whole request that may have queued its emails although the call failed. - MAYBE_QUEUED_CODES = (UNCONFIRMED_CODES + %w[network_error client_closed]).freeze RESEND_FIX = 'Send it again with the same idempotency_key within 24 hours of the first request that used it, so ' \ 'it goes out once.' UNAVAILABLE_FIX = "Until batch sends are on for the project, send each email the batch didn't queue with " \ @@ -25,12 +23,12 @@ class EmailBatch 'idempotency_key.' }.freeze TOO_LARGE = { - 'code' => 'too_large', + 'code' => 'content_too_large', 'detail' => 'PostHog refused the batch as too large, so no email was sent.', 'fix' => 'Split the recipients into smaller batches, or make the shared template_data smaller.' }.freeze RESULT_DEFAULTS = { message_id: nil, replayed: false, error: nil }.freeze - private_constant :UNCONFIRMED_CODES, :MAYBE_QUEUED_CODES, :RESEND_FIX, :UNAVAILABLE_FIX, :NOT_FOUND, :TOO_LARGE, + private_constant :UNCONFIRMED_CODES, :RESEND_FIX, :UNAVAILABLE_FIX, :NOT_FOUND, :TOO_LARGE, :RESULT_DEFAULTS Member = Struct.new(:index, :to, :idempotency_key, :wire, keyword_init: true) @@ -71,7 +69,7 @@ def answer((status, payload, retry_after)) # `failed` otherwise. def failure(error) results = @members.map do |member| - if MAYBE_QUEUED_CODES.include?(error.code) + if maybe_queued?(error) result(member, 'unconfirmed', error: resend(error)) else result(member, 'failed', error: error) @@ -82,6 +80,15 @@ def failure(error) private + # The status, not the code, says whether PostHog may have queued the emails: a 4xx refused them, except a 409 for + # keys still in flight. No answer, a 5xx and a 2xx without a result for each recipient leave them unknown. + def maybe_queued?(error) + status = error.status_code.to_i + return true unless status.between?(400, 499) + + error.code == 'idempotency_key_in_flight' + end + def settle(member, slot) message_id = text(slot['message_id']) if slot['error'].nil? && slot['status'] == 'queued' && message_id diff --git a/lib/posthog/emails.rb b/lib/posthog/emails.rb index 739a98c6..f59ffcdd 100644 --- a/lib/posthog/emails.rb +++ b/lib/posthog/emails.rb @@ -332,8 +332,8 @@ def send( # # Pass the template form, with +template_id+, or the code form, with +template_key+, as {#send} takes them. The # client sends at most 100 recipients in one request and waits at least 45 seconds for the answer. PostHog - # refuses a batch it finds too large with `too_large`: split the recipients into smaller batches. A batch takes - # no +cc+, +bcc+, +attachments+ or +scheduled_at+. + # refuses a batch it finds too large with `content_too_large`: split the recipients into smaller batches. A batch + # takes no +cc+, +bcc+, +attachments+ or +scheduled_at+. # # Each recipient has an +idempotency_key+, given or made by the client, that every retry reuses, so a retry never # queues an email twice. Retries follow {#send}'s. Send each `unconfirmed` email again with its @@ -359,13 +359,14 @@ def send( # @return [BatchResult] A result per recipient, in the order of +recipients+. Check each # {BatchEmailResult#status}, and send an `unconfirmed` email again with the same key so it goes out once. # @raise [EmailBatchError] The request failed as a whole, such as a rate limit past its retries. The last attempt - # decides the error. {EmailBatchError#results} holds every recipient: `unconfirmed` with a fix to send it again - # with the same key when the request may have queued it, such as `idempotency_key_in_flight`, a 5xx, a lost - # answer or `client_closed` when the client shut down before a retry, and `failed` otherwise. - # {EmailError#code} is `too_large` (413) when PostHog finds the batch too large, `batch_unavailable` when the - # project can't send batches yet, and `not_found` when the template doesn't exist or batch sends are off: send - # each email the batch didn't queue with {#send} and its recipient's +idempotency_key+. The warnings of an - # answer without a result for each recipient are on {EmailError#warnings}, and the client logs none of them. + # decides the error. {EmailBatchError#results} holds every recipient: `failed` when PostHog refused the request + # with a 4xx, and `unconfirmed` with a fix to send it again with the same key when the request may have queued + # it: a 409 `idempotency_key_in_flight`, a 5xx, a lost answer, or `client_closed` when the client shut down + # before a retry. {EmailError#code} is `content_too_large` (413) when PostHog finds the batch too large, + # `batch_unavailable` when the project can't send batches yet, and `not_found` when the template doesn't + # exist or batch sends are off: send each email the batch didn't queue with {#send} and its recipient's + # +idempotency_key+. The warnings of an answer without a result for each recipient are on + # {EmailError#warnings}, and the client logs none of them. # @raise [EmailError] The client sent nothing, such as when it is disabled or has no +secret_key+. # @raise [ArgumentError] An argument has the wrong type or format, such as more than 100 recipients or two # recipients with the same +idempotency_key+. No email was sent. diff --git a/spec/posthog/emails_batch_spec.rb b/spec/posthog/emails_batch_spec.rb index 5ea49c22..fa560396 100644 --- a/spec/posthog/emails_batch_spec.rb +++ b/spec/posthog/emails_batch_spec.rb @@ -53,7 +53,7 @@ def statuses(results) def resend_with_key(result) [result.status, result.idempotency_key, - result.error.fix.include?('same idempotency_key within 24 hours of the first request that used it')] + result.error.fix.to_s.include?('same idempotency_key within 24 hours of the first request that used it')] end describe '#batch' do it 'sends one request and returns a result per recipient, in order' do @@ -201,15 +201,17 @@ def resend_with_key(result) end { - 'a 413 with its code' => { status: 413, body: JSON.generate(code: 'too_large', detail: 'Too large.') }, + 'a 413 with its code' => { + status: 413, body: JSON.generate(code: 'content_too_large', detail: 'Too large.', fix: 'Split them.') + }, 'a 413 without a JSON body' => { status: 413, body: 'Request Entity Too Large' }, - 'a 413 with its own fix' => { status: 413, body: JSON.generate(code: 'too_large', fix: 'Send less.') } + 'a 413 with another fix' => { status: 413, body: JSON.generate(code: 'content_too_large', fix: 'Send less.') } }.each do |name, reply| it "surfaces #{name} as the error, with the fix to split the recipients" do stub_request(:post, batch_url).to_return(reply) expect { batch_template([ada, alan]) }.to raise_error(EmailBatchError) { |error| - expect([error.code, error.status_code]).to eq(['too_large', 413]) + expect([error.code, error.status_code]).to eq(['content_too_large', 413]) expect(error.fix).to include('smaller batches') expect(statuses(error.results)).to eq(%w[failed failed]) } @@ -292,13 +294,19 @@ def resend_with_key(result) end end - it 'keeps every recipient unconfirmed after a 5xx without a code, to send again with its key' do - stub_request(:post, batch_url).to_return(status: 502, body: 'Bad gateway') + { + 'a 502 without a code' => [{ status: 502, body: 'Bad gateway' }, 'unconfirmed'], + 'a 504 with a code' => [{ status: 504, body: JSON.generate(code: 'gateway_timeout') }, 'unconfirmed'], + 'a 403 without a code' => [{ status: 403, body: 'Forbidden' }, 'failed'] + }.each do |name, (reply, status)| + it "leaves every recipient #{status} after #{name}, the status deciding whether it may have gone out" do + stub_request(:post, batch_url).to_return(reply) - expect { batch_template([ada], max_retries: 0) }.to raise_error(EmailBatchError) { |error| - expect(error.status_code).to eq(502) - expect(resend_with_key(error.results.first)).to eq(['unconfirmed', 'welcome:ada', true]) - } + expect { batch_template([ada], max_retries: 0) }.to raise_error(EmailBatchError) { |error| + expect(error.status_code).to eq(reply[:status]) + expect(resend_with_key(error.results.first)).to eq([status, 'welcome:ada', status == 'unconfirmed']) + } + end end it "doesn't retry once the client shuts down, and leaves the recipients unconfirmed" do From ee472cc27f6070b2fb44df4c19d1bfd32b53db3a Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:14:19 +0100 Subject: [PATCH 14/32] fix(emails): keep a batch unconfirmed once any attempt may have queued 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 --- .changeset/email-batch-sends.md | 2 +- lib/posthog/email_batch.rb | 25 ++++++++---- lib/posthog/email_error.rb | 2 +- lib/posthog/emails.rb | 32 ++++++++++------ spec/posthog/emails_batch_spec.rb | 64 +++++++++++++++++++++++++------ 5 files changed, 92 insertions(+), 33 deletions(-) diff --git a/.changeset/email-batch-sends.md b/.changeset/email-batch-sends.md index 9bf8d54c..a7201f75 100644 --- a/.changeset/email-batch-sends.md +++ b/.changeset/email-batch-sends.md @@ -2,4 +2,4 @@ "posthog-ruby": minor --- -Send the same transactional email to many recipients with `emails.batch`, one email each, from a template made in PostHog with `template_data` per recipient, or from content your code rendered. The client sends at most 100 recipients in one request, refusing more before anything is sent, and returns a result per recipient in order: `queued`, `failed` or `unconfirmed`. Each recipient has its own `idempotency_key`, given or made by the client, so the client's own retries never send an email twice. To rerun a batch that was cut off, pass the keys you stored: a rerun with the same keys within 24 hours replays the emails that went out. A request that fails as a whole raises `EmailBatchError` with every recipient's result, such as `content_too_large` when PostHog finds the batch too large, with the fix to split it into smaller batches. A failed batch never calls the logger. +Send the same transactional email to many recipients with `emails.batch`, one email each, from a template made in PostHog with `template_data` per recipient, or from content your code rendered. The client sends at most 100 recipients in one request, refusing more before anything is sent, and returns a result per recipient in order: `queued`, `failed` or `unconfirmed`. Each recipient has its own `idempotency_key`, given or made by the client, so the client's own retries never send an email twice. To rerun a batch that was cut off, pass the keys you stored: a rerun with the same keys within 24 hours replays the emails that went out. A request that fails as a whole raises `EmailBatchError` with every recipient's result, such as a 413 `content_too_large` when PostHog finds the batch too large to take at once, with PostHog's fix to split it into smaller batches. A recipient that any attempt may have queued stays `unconfirmed`, also when a retry is refused. A failed batch never calls the logger. diff --git a/lib/posthog/email_batch.rb b/lib/posthog/email_batch.rb index dae4746b..95de1f11 100644 --- a/lib/posthog/email_batch.rb +++ b/lib/posthog/email_batch.rb @@ -25,7 +25,7 @@ class EmailBatch TOO_LARGE = { 'code' => 'content_too_large', 'detail' => 'PostHog refused the batch as too large, so no email was sent.', - 'fix' => 'Split the recipients into smaller batches, or make the shared template_data smaller.' + 'fix' => 'Split the recipients into smaller batches.' }.freeze RESULT_DEFAULTS = { message_id: nil, replayed: false, error: nil }.freeze private_constant :UNCONFIRMED_CODES, :RESEND_FIX, :UNAVAILABLE_FIX, :NOT_FOUND, :TOO_LARGE, @@ -44,6 +44,7 @@ def initialize(shared, members, parse_warnings:, reply_error:) @parse_warnings = parse_warnings @reply_error = reply_error @warnings = [] + @maybe_queued = false empty = JSON.generate(shared.merge(recipients: [])) @body = "#{empty.delete_suffix(']}')}#{members.map(&:wire).join(',')}]}" end @@ -65,11 +66,17 @@ def answer((status, payload, retry_after)) Emails::BatchResult.new(results: results.freeze, warnings: @warnings.dup.freeze) end - # Every recipient of a request that failed as a whole is `unconfirmed` when the request may have queued it, and + # Remembers an attempt that failed, so a later attempt's refusal can't confirm what this one may have queued. + def attempt_failed(error) + @maybe_queued = true if maybe_queued?(error) + end + + # Every recipient of a request that failed as a whole is `unconfirmed` when any attempt may have queued it, and # `failed` otherwise. def failure(error) + attempt_failed(error) results = @members.map do |member| - if maybe_queued?(error) + if @maybe_queued result(member, 'unconfirmed', error: resend(error)) else result(member, 'failed', error: error) @@ -86,7 +93,7 @@ def maybe_queued?(error) status = error.status_code.to_i return true unless status.between?(400, 499) - error.code == 'idempotency_key_in_flight' + status == 409 && error.code == 'idempotency_key_in_flight' end def settle(member, slot) @@ -96,8 +103,12 @@ def settle(member, slot) end answer = slot_error(slot['error'], message_id) - status = UNCONFIRMED_CODES.include?(answer.code) ? 'unconfirmed' : 'failed' - result(member, status, message_id: message_id, error: answer) + # A refusal can't confirm an email that an earlier attempt of the request may have queued. + if UNCONFIRMED_CODES.include?(answer.code) || @maybe_queued + return result(member, 'unconfirmed', message_id: message_id, error: resend(answer)) + end + + result(member, 'failed', message_id: message_id, error: answer) end def result(member, status, **fields) @@ -118,7 +129,7 @@ def response_error(fields, status, retry_after) fields = if status == 404 NOT_FOUND.merge(answered) elsif status == 413 - TOO_LARGE.merge(answered).merge('fix' => TOO_LARGE['fix']) + TOO_LARGE.merge(answered.reject { |_, value| value == '' }) else answered end diff --git a/lib/posthog/email_error.rb b/lib/posthog/email_error.rb index 447e771c..66d5c9f8 100644 --- a/lib/posthog/email_error.rb +++ b/lib/posthog/email_error.rb @@ -84,7 +84,7 @@ def self.name_for(status_code, code) # The request of {Emails#batch} failed as a whole. # # The other fields describe its error. {#results} holds every recipient: `unconfirmed` where PostHog may have queued - # them, such as after a lost answer or while it held their keys, and `failed` otherwise. + # them in any attempt, such as after a lost answer or while it held their keys, and `failed` otherwise. class EmailBatchError < EmailError # @return [Array] One result per recipient, in the order of the batch's recipients. attr_reader :results diff --git a/lib/posthog/emails.rb b/lib/posthog/emails.rb index f59ffcdd..065f90a8 100644 --- a/lib/posthog/emails.rb +++ b/lib/posthog/emails.rb @@ -114,9 +114,9 @@ def status # @return [String] One of: # - `queued`: PostHog accepted the email. Read it with {Emails#get} to see whether it went out. # - `failed`: PostHog didn't queue the email, and {#error} says why, such as a suppressed address. - # - `unconfirmed`: the client can't tell whether PostHog queued the email, such as after a lost answer. It may - # still go out. Send it again with the same +idempotency_key+ within 24 hours of the first request that - # used it, so it goes out once. + # - `unconfirmed`: the client can't tell whether PostHog queued the email, such as after a lost answer, also + # when a retry's answer refused it. It may still go out. Send it again with the same +idempotency_key+ + # within 24 hours of the first request that used it, so it goes out once. # @!attribute [r] message_id # @return [String, nil] The email's message ID, when PostHog named it. # @!attribute [r] replayed @@ -332,8 +332,10 @@ def send( # # Pass the template form, with +template_id+, or the code form, with +template_key+, as {#send} takes them. The # client sends at most 100 recipients in one request and waits at least 45 seconds for the answer. PostHog - # refuses a batch it finds too large with `content_too_large`: split the recipients into smaller batches. A batch - # takes no +cc+, +bcc+, +attachments+ or +scheduled_at+. + # refuses a batch too large to take at once with a 413 `content_too_large`: split the recipients into smaller + # batches. A 400 `content_too_large` means the shared content or one recipient's +template_data+ is over + # PostHog's limit, which splitting doesn't change: make it smaller. A batch takes no +cc+, +bcc+, +attachments+ + # or +scheduled_at+. # # Each recipient has an +idempotency_key+, given or made by the client, that every retry reuses, so a retry never # queues an email twice. Retries follow {#send}'s. Send each `unconfirmed` email again with its @@ -358,11 +360,12 @@ def send( # turns retries off. # @return [BatchResult] A result per recipient, in the order of +recipients+. Check each # {BatchEmailResult#status}, and send an `unconfirmed` email again with the same key so it goes out once. - # @raise [EmailBatchError] The request failed as a whole, such as a rate limit past its retries. The last attempt - # decides the error. {EmailBatchError#results} holds every recipient: `failed` when PostHog refused the request - # with a 4xx, and `unconfirmed` with a fix to send it again with the same key when the request may have queued - # it: a 409 `idempotency_key_in_flight`, a 5xx, a lost answer, or `client_closed` when the client shut down - # before a retry. {EmailError#code} is `content_too_large` (413) when PostHog finds the batch too large, + # @raise [EmailBatchError] The request failed as a whole, such as a rate limit past its retries. The error is the + # last attempt's. {EmailBatchError#results} holds every recipient: `unconfirmed` with a fix to send it again + # with the same key when any attempt may have queued it (a 409 `idempotency_key_in_flight`, a 5xx, a lost + # answer, or `client_closed` when the client shut down before a retry), and `failed` when PostHog refused the + # request with a 4xx and no earlier attempt may have queued it. {EmailError#code} is `content_too_large` with + # PostHog's fix: a 413 for a batch to split into smaller batches, a 400 for content to make smaller. It is # `batch_unavailable` when the project can't send batches yet, and `not_found` when the template doesn't # exist or batch sends are off: send each email the batch didn't queue with {#send} and its recipient's # +idempotency_key+. The warnings of an answer without a result for each recipient are on @@ -505,8 +508,13 @@ def send_batch(run, secret_key, max_retries) message: "The PostHog client is shut down, so it didn't retry the batch.") end - run.answer(request(Net::HTTP::Post.new(uri), uri, secret_key, JSON_CONTENT, run.body, - read_timeout: read_timeout)) + begin + run.answer(request(Net::HTTP::Post.new(uri), uri, secret_key, JSON_CONTENT, run.body, + read_timeout: read_timeout)) + rescue EmailError => e + run.attempt_failed(e) + raise + end end [result, nil] rescue EmailError => e diff --git a/spec/posthog/emails_batch_spec.rb b/spec/posthog/emails_batch_spec.rb index fa560396..8776fc3e 100644 --- a/spec/posthog/emails_batch_spec.rb +++ b/spec/posthog/emails_batch_spec.rb @@ -137,6 +137,18 @@ def resend_with_key(result) expect(results.map { |result| result.error.message_id }).to eq([nil, 'msg_2', nil]) end + it 'keeps a recipient the retry refused unconfirmed when a lost answer may have queued it' do + stub_request(:post, batch_url).to_raise(Errno::ECONNRESET).then.to_return( + answer(queued('msg_ada'), slot_error('recipient_suppressed', 422, message_id: nil)) + ) + + results = batch_template([ada, alan], max_retries: 1).results + + expect(results.map(&:status)).to eq(%w[queued unconfirmed]) + expect([results.last.error.code, resend_with_key(results.last)]) + .to eq(['recipient_suppressed', ['unconfirmed', 'welcome:alan', true]]) + end + it 'leaves an unconfirmed email PostHog answered without an ID to be sent again with its key' do stub_request(:post, batch_url).to_return( answer(slot_error('delivery_unavailable', 503, message_id: 'msg_ada'), @@ -201,24 +213,37 @@ def resend_with_key(result) end { - 'a 413 with its code' => { - status: 413, body: JSON.generate(code: 'content_too_large', detail: 'Too large.', fix: 'Split them.') - }, - 'a 413 without a JSON body' => { status: 413, body: 'Request Entity Too Large' }, - 'a 413 with another fix' => { status: 413, body: JSON.generate(code: 'content_too_large', fix: 'Send less.') } - }.each do |name, reply| - it "surfaces #{name} as the error, with the fix to split the recipients" do + 'a 413 with its code and fix' => [ + { status: 413, body: JSON.generate(code: 'content_too_large', detail: 'Too large.', fix: 'Split them.') }, + 'Split them.' + ], + 'a 413 without a JSON body' => [{ status: 413, body: 'Request Entity Too Large' }, 'smaller'], + 'a 413 with an empty code and fix' => [{ status: 413, body: JSON.generate(code: '', fix: '') }, 'smaller'] + }.each do |name, (reply, fix)| + it "surfaces #{name} as content_too_large, with PostHog's fix or the advice to split the recipients" do stub_request(:post, batch_url).to_return(reply) expect { batch_template([ada, alan]) }.to raise_error(EmailBatchError) { |error| expect([error.code, error.status_code]).to eq(['content_too_large', 413]) - expect(error.fix).to include('smaller batches') + expect(error.fix).to include(fix) expect(statuses(error.results)).to eq(%w[failed failed]) } expect(a_request(:post, batch_url)).to have_been_made.once end end + it "keeps a 400 content_too_large for content over PostHog's limit as PostHog sent it, without split advice" do + stub_request(:post, batch_url).to_return( + refuse(400, 'content_too_large', fix: 'Make template_data smaller.', attr: 'template_data') + ) + + expect { batch_template([ada]) }.to raise_error(EmailBatchError) { |error| + expect([error.code, error.status_code, error.fix]) + .to eq(['content_too_large', 400, 'Make template_data smaller.']) + expect(statuses(error.results)).to eq(%w[failed]) + } + end + it 'raises batch_unavailable with the fix to send each email on its own' do stub_request(:post, batch_url).to_return(refuse(409, 'batch_unavailable', detail: 'Not yet.')) @@ -266,6 +291,17 @@ def resend_with_key(result) expect(a_request(:get, %r{/api/messaging/emails/status/})).not_to have_been_made end + it 'keeps the recipients a lost answer may have queued unconfirmed when the retry is refused' do + stub_request(:post, batch_url).to_raise(Errno::ECONNRESET).then.to_return(refuse(429, 'rate_limited')) + + expect { batch_template([ada, alan], max_retries: 1) }.to raise_error(EmailBatchError) { |error| + expect(error.code).to eq('rate_limited') + expect(error.results.map { |result| resend_with_key(result) }) + .to eq([['unconfirmed', 'welcome:ada', true], ['unconfirmed', 'welcome:alan', true]]) + } + expect(a_request(:post, batch_url)).to have_been_made.twice + end + it 'keeps every recipient unconfirmed when the answer has no result for each, and never retries it' do stub_request(:post, batch_url).to_return(answer(queued('msg_1'))) @@ -279,10 +315,11 @@ def resend_with_key(result) { [503, 503] => %w[unconfirmed delivery_unavailable], - [503, 400] => %w[failed invalid_recipient], - [503, 429] => %w[failed rate_limited] + [503, 400] => %w[unconfirmed invalid_recipient], + [503, 429] => %w[unconfirmed rate_limited], + [429, 400] => %w[failed invalid_recipient] }.each do |statuses, (status, code)| - it "reports what the last attempt answered after #{statuses.join(', ')}" do + it "reports the last attempt's error after #{statuses.join(', ')}, unconfirmed if one may have queued" do codes = { 400 => 'invalid_recipient', 429 => 'rate_limited', 503 => 'delivery_unavailable' } stub_request(:post, batch_url).to_return(*statuses.map { |answered| refuse(answered, codes[answered]) }) @@ -297,7 +334,10 @@ def resend_with_key(result) { 'a 502 without a code' => [{ status: 502, body: 'Bad gateway' }, 'unconfirmed'], 'a 504 with a code' => [{ status: 504, body: JSON.generate(code: 'gateway_timeout') }, 'unconfirmed'], - 'a 403 without a code' => [{ status: 403, body: 'Forbidden' }, 'failed'] + 'a 403 without a code' => [{ status: 403, body: 'Forbidden' }, 'failed'], + 'a 403 naming keys in flight' => [ + { status: 403, body: JSON.generate(code: 'idempotency_key_in_flight') }, 'failed' + ] }.each do |name, (reply, status)| it "leaves every recipient #{status} after #{name}, the status deciding whether it may have gone out" do stub_request(:post, batch_url).to_return(reply) From 78c23191455ebe7beb29fdf9eede1c44fa72e831 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:27:26 +0100 Subject: [PATCH 15/32] fix(emails): keep a refused batch failed when the client shuts down 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 --- lib/posthog/email_batch.rb | 5 ++++- lib/posthog/emails.rb | 9 +++++---- spec/posthog/emails_batch_spec.rb | 17 ++++++++++++++++- 3 files changed, 25 insertions(+), 6 deletions(-) diff --git a/lib/posthog/email_batch.rb b/lib/posthog/email_batch.rb index 95de1f11..0a7ae23e 100644 --- a/lib/posthog/email_batch.rb +++ b/lib/posthog/email_batch.rb @@ -90,6 +90,9 @@ def failure(error) # The status, not the code, says whether PostHog may have queued the emails: a 4xx refused them, except a 409 for # keys still in flight. No answer, a 5xx and a 2xx without a result for each recipient leave them unknown. def maybe_queued?(error) + # The client raises client_closed instead of sending a retry, so it says nothing about what PostHog queued. + return false if error.code == 'client_closed' + status = error.status_code.to_i return true unless status.between?(400, 499) @@ -129,7 +132,7 @@ def response_error(fields, status, retry_after) fields = if status == 404 NOT_FOUND.merge(answered) elsif status == 413 - TOO_LARGE.merge(answered.reject { |_, value| value == '' }) + TOO_LARGE.merge(answered.select { |_, value| text(value) }) else answered end diff --git a/lib/posthog/emails.rb b/lib/posthog/emails.rb index 065f90a8..e907e14f 100644 --- a/lib/posthog/emails.rb +++ b/lib/posthog/emails.rb @@ -333,9 +333,10 @@ def send( # Pass the template form, with +template_id+, or the code form, with +template_key+, as {#send} takes them. The # client sends at most 100 recipients in one request and waits at least 45 seconds for the answer. PostHog # refuses a batch too large to take at once with a 413 `content_too_large`: split the recipients into smaller - # batches. A 400 `content_too_large` means the shared content or one recipient's +template_data+ is over - # PostHog's limit, which splitting doesn't change: make it smaller. A batch takes no +cc+, +bcc+, +attachments+ - # or +scheduled_at+. + # batches. A 400 `content_too_large` means the shared content is over PostHog's limit, which splitting doesn't + # change: make it smaller. A recipient whose own +template_data+ is over it comes back `failed` with + # `content_too_large` in its result, while the others go out. A batch takes no +cc+, +bcc+, +attachments+ or + # +scheduled_at+. # # Each recipient has an +idempotency_key+, given or made by the client, that every retry reuses, so a retry never # queues an email twice. Retries follow {#send}'s. Send each `unconfirmed` email again with its @@ -365,7 +366,7 @@ def send( # with the same key when any attempt may have queued it (a 409 `idempotency_key_in_flight`, a 5xx, a lost # answer, or `client_closed` when the client shut down before a retry), and `failed` when PostHog refused the # request with a 4xx and no earlier attempt may have queued it. {EmailError#code} is `content_too_large` with - # PostHog's fix: a 413 for a batch to split into smaller batches, a 400 for content to make smaller. It is + # PostHog's fix: a 413 for a batch to split into smaller batches, a 400 for shared content to make smaller. It is # `batch_unavailable` when the project can't send batches yet, and `not_found` when the template doesn't # exist or batch sends are off: send each email the batch didn't queue with {#send} and its recipient's # +idempotency_key+. The warnings of an answer without a result for each recipient are on diff --git a/spec/posthog/emails_batch_spec.rb b/spec/posthog/emails_batch_spec.rb index 8776fc3e..8ef752db 100644 --- a/spec/posthog/emails_batch_spec.rb +++ b/spec/posthog/emails_batch_spec.rb @@ -218,7 +218,10 @@ def resend_with_key(result) 'Split them.' ], 'a 413 without a JSON body' => [{ status: 413, body: 'Request Entity Too Large' }, 'smaller'], - 'a 413 with an empty code and fix' => [{ status: 413, body: JSON.generate(code: '', fix: '') }, 'smaller'] + 'a 413 with an empty code and fix' => [{ status: 413, body: JSON.generate(code: '', fix: '') }, 'smaller'], + 'a 413 with fields that are not text' => [ + { status: 413, body: JSON.generate(code: 413, fix: false) }, 'smaller' + ] }.each do |name, (reply, fix)| it "surfaces #{name} as content_too_large, with PostHog's fix or the advice to split the recipients" do stub_request(:post, batch_url).to_return(reply) @@ -349,6 +352,18 @@ def resend_with_key(result) end end + it 'leaves the recipients failed when the client shuts down after PostHog refused the only request' do + stub_request(:post, batch_url).to_return do + client.shutdown(timeout: 0) + refuse(429, 'rate_limited') + end + + expect { batch_template([ada], max_retries: 1) }.to raise_error(EmailBatchError) { |error| + expect([error.code, error.results.map(&:status)]).to eq(['client_closed', ['failed']]) + } + expect(a_request(:post, batch_url)).to have_been_made.once + end + it "doesn't retry once the client shuts down, and leaves the recipients unconfirmed" do stub_request(:post, batch_url).to_return do client.shutdown(timeout: 0) From 517819edab75c6a584b8dfb4eaddb66a55bf4042 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:32:11 +0100 Subject: [PATCH 16/32] test(emails): check a batch logs a repeated warning once Co-Authored-By: Claude Opus 5.5 --- spec/posthog/emails_batch_spec.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spec/posthog/emails_batch_spec.rb b/spec/posthog/emails_batch_spec.rb index 8ef752db..b3bce99d 100644 --- a/spec/posthog/emails_batch_spec.rb +++ b/spec/posthog/emails_batch_spec.rb @@ -165,9 +165,9 @@ def resend_with_key(result) expect(a_request(:get, %r{/api/messaging/emails/status/})).not_to have_been_made end - it "logs the reply's warnings" do + it "logs the reply's warnings once each" do warning = { code: 'unverified_link', detail: 'A link points to an unverified domain.' } - stub_request(:post, batch_url).to_return(answer(queued('msg_1'), warnings: [warning])) + stub_request(:post, batch_url).to_return(answer(queued('msg_1'), warnings: [warning, warning])) log = StringIO.new PostHog::Logging.logger = Logger.new(log, level: Logger::WARN) From d661708b7936fb4a0061507613307a28e674212b Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:45:23 +0100 Subject: [PATCH 17/32] fix(emails): say an earlier attempt may have queued a refused batch 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 --- lib/posthog/email_batch.rb | 20 +++++++++++++------- spec/posthog/emails_batch_spec.rb | 2 ++ 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/lib/posthog/email_batch.rb b/lib/posthog/email_batch.rb index 0a7ae23e..a5bdebc0 100644 --- a/lib/posthog/email_batch.rb +++ b/lib/posthog/email_batch.rb @@ -27,8 +27,10 @@ class EmailBatch 'detail' => 'PostHog refused the batch as too large, so no email was sent.', 'fix' => 'Split the recipients into smaller batches.' }.freeze + EARLIER_ATTEMPT = 'An earlier attempt of this batch may have queued this email, so it may still go out. ' \ + "PostHog's last answer:" RESULT_DEFAULTS = { message_id: nil, replayed: false, error: nil }.freeze - private_constant :UNCONFIRMED_CODES, :RESEND_FIX, :UNAVAILABLE_FIX, :NOT_FOUND, :TOO_LARGE, + private_constant :UNCONFIRMED_CODES, :RESEND_FIX, :EARLIER_ATTEMPT, :UNAVAILABLE_FIX, :NOT_FOUND, :TOO_LARGE, :RESULT_DEFAULTS Member = Struct.new(:index, :to, :idempotency_key, :wire, keyword_init: true) @@ -74,10 +76,11 @@ def attempt_failed(error) # Every recipient of a request that failed as a whole is `unconfirmed` when any attempt may have queued it, and # `failed` otherwise. def failure(error) + refused = !maybe_queued?(error) attempt_failed(error) results = @members.map do |member| if @maybe_queued - result(member, 'unconfirmed', error: resend(error)) + result(member, 'unconfirmed', error: resend(error, earlier: refused)) else result(member, 'failed', error: error) end @@ -108,7 +111,8 @@ def settle(member, slot) answer = slot_error(slot['error'], message_id) # A refusal can't confirm an email that an earlier attempt of the request may have queued. if UNCONFIRMED_CODES.include?(answer.code) || @maybe_queued - return result(member, 'unconfirmed', message_id: message_id, error: resend(answer)) + earlier = !UNCONFIRMED_CODES.include?(answer.code) + return result(member, 'unconfirmed', message_id: message_id, error: resend(answer, earlier: earlier)) end result(member, 'failed', message_id: message_id, error: answer) @@ -119,11 +123,13 @@ def result(member, status, **fields) Emails::BatchEmailResult.new(**RESULT_DEFAULTS, **identity, **fields) end - # A caller who follows PostHog's own advice without the key sends a second email. - def resend(error) - return error if error.fix == RESEND_FIX + # A caller who follows PostHog's own advice without the key sends a second email. A refusal that follows an + # attempt that may have queued the email can't say no email was sent, so its message says so first. + def resend(error, earlier: false) + return error if error.fix == RESEND_FIX && !earlier - EmailError.new(code: error.code, message: error.message, status_code: error.status_code, why: error.why, + message = earlier ? "#{EARLIER_ATTEMPT} #{error.message}" : error.message + EmailError.new(code: error.code, message: message, status_code: error.status_code, why: error.why, fix: RESEND_FIX, docs_url: error.docs_url, field: error.field, retry_after: error.retry_after) end diff --git a/spec/posthog/emails_batch_spec.rb b/spec/posthog/emails_batch_spec.rb index b3bce99d..5dd241fd 100644 --- a/spec/posthog/emails_batch_spec.rb +++ b/spec/posthog/emails_batch_spec.rb @@ -147,6 +147,7 @@ def resend_with_key(result) expect(results.map(&:status)).to eq(%w[queued unconfirmed]) expect([results.last.error.code, resend_with_key(results.last)]) .to eq(['recipient_suppressed', ['unconfirmed', 'welcome:alan', true]]) + expect(results.last.error.message).to start_with('An earlier attempt of this batch may have queued') end it 'leaves an unconfirmed email PostHog answered without an ID to be sent again with its key' do @@ -299,6 +300,7 @@ def resend_with_key(result) expect { batch_template([ada, alan], max_retries: 1) }.to raise_error(EmailBatchError) { |error| expect(error.code).to eq('rate_limited') + expect(error.results.first.error.message).to start_with('An earlier attempt of this batch may have queued') expect(error.results.map { |result| resend_with_key(result) }) .to eq([['unconfirmed', 'welcome:ada', true], ['unconfirmed', 'welcome:alan', true]]) } From 8697230927ad5f292d3c09d4f1e4fbf4b281e930 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:50:41 +0100 Subject: [PATCH 18/32] fix(emails): only the client's own shutdown leaves a batch failed 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 --- lib/posthog/email_batch.rb | 13 ++++++------- lib/posthog/emails.rb | 14 +++++++------- spec/posthog/emails_batch_spec.rb | 2 ++ 3 files changed, 15 insertions(+), 14 deletions(-) diff --git a/lib/posthog/email_batch.rb b/lib/posthog/email_batch.rb index a5bdebc0..f950fc52 100644 --- a/lib/posthog/email_batch.rb +++ b/lib/posthog/email_batch.rb @@ -28,7 +28,7 @@ class EmailBatch 'fix' => 'Split the recipients into smaller batches.' }.freeze EARLIER_ATTEMPT = 'An earlier attempt of this batch may have queued this email, so it may still go out. ' \ - "PostHog's last answer:" + 'The last attempt ended with:' RESULT_DEFAULTS = { message_id: nil, replayed: false, error: nil }.freeze private_constant :UNCONFIRMED_CODES, :RESEND_FIX, :EARLIER_ATTEMPT, :UNAVAILABLE_FIX, :NOT_FOUND, :TOO_LARGE, :RESULT_DEFAULTS @@ -47,6 +47,7 @@ def initialize(shared, members, parse_warnings:, reply_error:) @reply_error = reply_error @warnings = [] @maybe_queued = false + @attempt_error = nil empty = JSON.generate(shared.merge(recipients: [])) @body = "#{empty.delete_suffix(']}')}#{members.map(&:wire).join(',')}]}" end @@ -70,14 +71,15 @@ def answer((status, payload, retry_after)) # Remembers an attempt that failed, so a later attempt's refusal can't confirm what this one may have queued. def attempt_failed(error) + @attempt_error = error @maybe_queued = true if maybe_queued?(error) end # Every recipient of a request that failed as a whole is `unconfirmed` when any attempt may have queued it, and # `failed` otherwise. def failure(error) - refused = !maybe_queued?(error) - attempt_failed(error) + # Only an attempt's error says what PostHog may have queued; the client raises client_closed without a request. + refused = !(@attempt_error.equal?(error) && maybe_queued?(error)) results = @members.map do |member| if @maybe_queued result(member, 'unconfirmed', error: resend(error, earlier: refused)) @@ -93,9 +95,6 @@ def failure(error) # The status, not the code, says whether PostHog may have queued the emails: a 4xx refused them, except a 409 for # keys still in flight. No answer, a 5xx and a 2xx without a result for each recipient leave them unknown. def maybe_queued?(error) - # The client raises client_closed instead of sending a retry, so it says nothing about what PostHog queued. - return false if error.code == 'client_closed' - status = error.status_code.to_i return true unless status.between?(400, 499) @@ -126,7 +125,7 @@ def result(member, status, **fields) # A caller who follows PostHog's own advice without the key sends a second email. A refusal that follows an # attempt that may have queued the email can't say no email was sent, so its message says so first. def resend(error, earlier: false) - return error if error.fix == RESEND_FIX && !earlier + return error if error.fix == RESEND_FIX message = earlier ? "#{EARLIER_ATTEMPT} #{error.message}" : error.message EmailError.new(code: error.code, message: message, status_code: error.status_code, why: error.why, diff --git a/lib/posthog/emails.rb b/lib/posthog/emails.rb index e907e14f..e520ba74 100644 --- a/lib/posthog/emails.rb +++ b/lib/posthog/emails.rb @@ -363,13 +363,13 @@ def send( # {BatchEmailResult#status}, and send an `unconfirmed` email again with the same key so it goes out once. # @raise [EmailBatchError] The request failed as a whole, such as a rate limit past its retries. The error is the # last attempt's. {EmailBatchError#results} holds every recipient: `unconfirmed` with a fix to send it again - # with the same key when any attempt may have queued it (a 409 `idempotency_key_in_flight`, a 5xx, a lost - # answer, or `client_closed` when the client shut down before a retry), and `failed` when PostHog refused the - # request with a 4xx and no earlier attempt may have queued it. {EmailError#code} is `content_too_large` with - # PostHog's fix: a 413 for a batch to split into smaller batches, a 400 for shared content to make smaller. It is - # `batch_unavailable` when the project can't send batches yet, and `not_found` when the template doesn't - # exist or batch sends are off: send each email the batch didn't queue with {#send} and its recipient's - # +idempotency_key+. The warnings of an answer without a result for each recipient are on + # with the same key when any attempt may have queued it (a 409 `idempotency_key_in_flight`, a 5xx, or a lost + # answer), and `failed` when PostHog refused the request with a 4xx and no earlier attempt may have queued it. + # The error is `client_closed` when the client shut down before a retry. {EmailError#code} is + # `content_too_large` with PostHog's fix: a 413 for a batch to split into smaller batches, a 400 for shared + # content to make smaller. It is `batch_unavailable` when the project can't send batches yet, and `not_found` + # when the template doesn't exist or batch sends are off: send each email the batch didn't queue with {#send} + # and its recipient's +idempotency_key+. The warnings of an answer without a result for each recipient are on # {EmailError#warnings}, and the client logs none of them. # @raise [EmailError] The client sent nothing, such as when it is disabled or has no +secret_key+. # @raise [ArgumentError] An argument has the wrong type or format, such as more than 100 recipients or two diff --git a/spec/posthog/emails_batch_spec.rb b/spec/posthog/emails_batch_spec.rb index 5dd241fd..36e754de 100644 --- a/spec/posthog/emails_batch_spec.rb +++ b/spec/posthog/emails_batch_spec.rb @@ -339,6 +339,7 @@ def resend_with_key(result) { 'a 502 without a code' => [{ status: 502, body: 'Bad gateway' }, 'unconfirmed'], 'a 504 with a code' => [{ status: 504, body: JSON.generate(code: 'gateway_timeout') }, 'unconfirmed'], + 'a 503 with client_closed' => [{ status: 503, body: JSON.generate(code: 'client_closed') }, 'unconfirmed'], 'a 403 without a code' => [{ status: 403, body: 'Forbidden' }, 'failed'], 'a 403 naming keys in flight' => [ { status: 403, body: JSON.generate(code: 'idempotency_key_in_flight') }, 'failed' @@ -375,6 +376,7 @@ def resend_with_key(result) expect { batch_template([ada]) }.to raise_error(EmailBatchError) { |error| expect(error.code).to eq('client_closed') expect(resend_with_key(error.results.first)).to eq(['unconfirmed', 'welcome:ada', true]) + expect(error.results.first.error.message).to start_with('An earlier attempt of this batch may have queued') } expect(a_request(:post, batch_url)).to have_been_made.once end From ea1cea654ec82913104c66e42d45a8a5b32cd101 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:53:34 +0100 Subject: [PATCH 19/32] refactor(emails): settle an in-flight slot before an earlier attempt'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 --- lib/posthog/email_batch.rb | 9 +++++---- spec/posthog/emails_batch_spec.rb | 1 + 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/lib/posthog/email_batch.rb b/lib/posthog/email_batch.rb index f950fc52..168c8ff6 100644 --- a/lib/posthog/email_batch.rb +++ b/lib/posthog/email_batch.rb @@ -108,10 +108,11 @@ def settle(member, slot) end answer = slot_error(slot['error'], message_id) - # A refusal can't confirm an email that an earlier attempt of the request may have queued. - if UNCONFIRMED_CODES.include?(answer.code) || @maybe_queued - earlier = !UNCONFIRMED_CODES.include?(answer.code) - return result(member, 'unconfirmed', message_id: message_id, error: resend(answer, earlier: earlier)) + if UNCONFIRMED_CODES.include?(answer.code) + return result(member, 'unconfirmed', message_id: message_id, error: answer) + elsif @maybe_queued + # A refusal can't confirm an email that an earlier attempt of the request may have queued. + return result(member, 'unconfirmed', message_id: message_id, error: resend(answer, earlier: true)) end result(member, 'failed', message_id: message_id, error: answer) diff --git a/spec/posthog/emails_batch_spec.rb b/spec/posthog/emails_batch_spec.rb index 36e754de..9485c16b 100644 --- a/spec/posthog/emails_batch_spec.rb +++ b/spec/posthog/emails_batch_spec.rb @@ -351,6 +351,7 @@ def resend_with_key(result) expect { batch_template([ada], max_retries: 0) }.to raise_error(EmailBatchError) { |error| expect(error.status_code).to eq(reply[:status]) expect(resend_with_key(error.results.first)).to eq([status, 'welcome:ada', status == 'unconfirmed']) + expect(error.results.first.error.message).to eq(error.message) } end end From a7a777aee7ab175ba5b486d03a343e4315974638 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:56:52 +0100 Subject: [PATCH 20/32] fix(emails): don't tell a one-recipient batch to split on a bare 413 Co-Authored-By: Claude Opus 5.5 --- lib/posthog/email_batch.rb | 6 ++++-- spec/posthog/emails_batch_spec.rb | 10 ++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/lib/posthog/email_batch.rb b/lib/posthog/email_batch.rb index 168c8ff6..3c7752b1 100644 --- a/lib/posthog/email_batch.rb +++ b/lib/posthog/email_batch.rb @@ -27,11 +27,13 @@ class EmailBatch 'detail' => 'PostHog refused the batch as too large, so no email was sent.', 'fix' => 'Split the recipients into smaller batches.' }.freeze + # One recipient can't be split, so only a smaller email gets through. + TOO_LARGE_ALONE = TOO_LARGE.merge('fix' => 'Make the email smaller, such as its template_data.').freeze EARLIER_ATTEMPT = 'An earlier attempt of this batch may have queued this email, so it may still go out. ' \ 'The last attempt ended with:' RESULT_DEFAULTS = { message_id: nil, replayed: false, error: nil }.freeze private_constant :UNCONFIRMED_CODES, :RESEND_FIX, :EARLIER_ATTEMPT, :UNAVAILABLE_FIX, :NOT_FOUND, :TOO_LARGE, - :RESULT_DEFAULTS + :TOO_LARGE_ALONE, :RESULT_DEFAULTS Member = Struct.new(:index, :to, :idempotency_key, :wire, keyword_init: true) @@ -138,7 +140,7 @@ def response_error(fields, status, retry_after) fields = if status == 404 NOT_FOUND.merge(answered) elsif status == 413 - TOO_LARGE.merge(answered.select { |_, value| text(value) }) + (@members.size > 1 ? TOO_LARGE : TOO_LARGE_ALONE).merge(answered.select { |_, value| text(value) }) else answered end diff --git a/spec/posthog/emails_batch_spec.rb b/spec/posthog/emails_batch_spec.rb index 9485c16b..23360eb5 100644 --- a/spec/posthog/emails_batch_spec.rb +++ b/spec/posthog/emails_batch_spec.rb @@ -236,6 +236,16 @@ def resend_with_key(result) end end + it 'tells a one-recipient batch refused by a 413 without a fix to make the email smaller, not to split it' do + stub_request(:post, batch_url).to_return(status: 413, body: 'Request Entity Too Large') + + expect { batch_template([ada]) }.to raise_error(EmailBatchError) { |error| + expect([error.code, error.status_code]).to eq(['content_too_large', 413]) + expect(error.fix).to include('smaller') + expect(error.fix).not_to include('Split') + } + end + it "keeps a 400 content_too_large for content over PostHog's limit as PostHog sent it, without split advice" do stub_request(:post, batch_url).to_return( refuse(400, 'content_too_large', fix: 'Make template_data smaller.', attr: 'template_data') From f0d8628e45fc80806c996489d5a96e380354fd92 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:07:52 +0100 Subject: [PATCH 21/32] fix(emails): carry an earlier attempt's doubt onto the batch error 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 --- lib/posthog/email_batch.rb | 16 +++++++++----- lib/posthog/emails.rb | 12 ++++++----- spec/posthog/emails_batch_spec.rb | 35 ++++++++++++++++++++++++------- 3 files changed, 46 insertions(+), 17 deletions(-) diff --git a/lib/posthog/email_batch.rb b/lib/posthog/email_batch.rb index 3c7752b1..c8d11c90 100644 --- a/lib/posthog/email_batch.rb +++ b/lib/posthog/email_batch.rb @@ -27,13 +27,12 @@ class EmailBatch 'detail' => 'PostHog refused the batch as too large, so no email was sent.', 'fix' => 'Split the recipients into smaller batches.' }.freeze - # One recipient can't be split, so only a smaller email gets through. - TOO_LARGE_ALONE = TOO_LARGE.merge('fix' => 'Make the email smaller, such as its template_data.').freeze + SMALLER_FIX = 'Make the email smaller, such as its template_data.' EARLIER_ATTEMPT = 'An earlier attempt of this batch may have queued this email, so it may still go out. ' \ 'The last attempt ended with:' RESULT_DEFAULTS = { message_id: nil, replayed: false, error: nil }.freeze private_constant :UNCONFIRMED_CODES, :RESEND_FIX, :EARLIER_ATTEMPT, :UNAVAILABLE_FIX, :NOT_FOUND, :TOO_LARGE, - :TOO_LARGE_ALONE, :RESULT_DEFAULTS + :SMALLER_FIX, :RESULT_DEFAULTS Member = Struct.new(:index, :to, :idempotency_key, :wire, keyword_init: true) @@ -82,9 +81,10 @@ def attempt_failed(error) def failure(error) # Only an attempt's error says what PostHog may have queued; the client raises client_closed without a request. refused = !(@attempt_error.equal?(error) && maybe_queued?(error)) + error = resend(error, earlier: true) if @maybe_queued && refused results = @members.map do |member| if @maybe_queued - result(member, 'unconfirmed', error: resend(error, earlier: refused)) + result(member, 'unconfirmed', error: resend(error)) else result(member, 'failed', error: error) end @@ -140,7 +140,7 @@ def response_error(fields, status, retry_after) fields = if status == 404 NOT_FOUND.merge(answered) elsif status == 413 - (@members.size > 1 ? TOO_LARGE : TOO_LARGE_ALONE).merge(answered.select { |_, value| text(value) }) + too_large(answered) else answered end @@ -148,6 +148,12 @@ def response_error(fields, status, retry_after) @reply_error.call(fields, status, retry_after) end + def too_large(answered) + fields = TOO_LARGE.merge(answered.select { |_, value| text(value) }) + # One recipient can't be split, so only a smaller email gets through, whatever the reply advises. + @members.size > 1 ? fields : fields.merge('fix' => SMALLER_FIX) + end + def slot_error(error, message_id) unless error.is_a?(Hash) return EmailError.new(code: 'api_error', message_id: message_id, fix: RESEND_FIX, diff --git a/lib/posthog/emails.rb b/lib/posthog/emails.rb index e520ba74..a1ccbe8a 100644 --- a/lib/posthog/emails.rb +++ b/lib/posthog/emails.rb @@ -365,11 +365,13 @@ def send( # last attempt's. {EmailBatchError#results} holds every recipient: `unconfirmed` with a fix to send it again # with the same key when any attempt may have queued it (a 409 `idempotency_key_in_flight`, a 5xx, or a lost # answer), and `failed` when PostHog refused the request with a 4xx and no earlier attempt may have queued it. - # The error is `client_closed` when the client shut down before a retry. {EmailError#code} is - # `content_too_large` with PostHog's fix: a 413 for a batch to split into smaller batches, a 400 for shared - # content to make smaller. It is `batch_unavailable` when the project can't send batches yet, and `not_found` - # when the template doesn't exist or batch sends are off: send each email the batch didn't queue with {#send} - # and its recipient's +idempotency_key+. The warnings of an answer without a result for each recipient are on + # When only an earlier attempt may have queued them, the error's message says so, and its fix is the same-key + # one. The error is `client_closed` when the client shut down before a retry. {EmailError#code} is + # `content_too_large` with PostHog's fix: a 413 for a batch to split into smaller batches, or for one recipient + # an email to make smaller, and a 400 for shared content to make smaller. It is `batch_unavailable` when the + # project can't send batches yet, and `not_found` when the template doesn't exist or batch sends are off: send + # each email the batch didn't queue with {#send} and its recipient's +idempotency_key+. The warnings of an + # answer without a result for each recipient are on # {EmailError#warnings}, and the client logs none of them. # @raise [EmailError] The client sent nothing, such as when it is disabled or has no +secret_key+. # @raise [ArgumentError] An argument has the wrong type or format, such as more than 100 recipients or two diff --git a/spec/posthog/emails_batch_spec.rb b/spec/posthog/emails_batch_spec.rb index 23360eb5..7c62c6c8 100644 --- a/spec/posthog/emails_batch_spec.rb +++ b/spec/posthog/emails_batch_spec.rb @@ -236,14 +236,22 @@ def resend_with_key(result) end end - it 'tells a one-recipient batch refused by a 413 without a fix to make the email smaller, not to split it' do - stub_request(:post, batch_url).to_return(status: 413, body: 'Request Entity Too Large') - - expect { batch_template([ada]) }.to raise_error(EmailBatchError) { |error| - expect([error.code, error.status_code]).to eq(['content_too_large', 413]) - expect(error.fix).to include('smaller') - expect(error.fix).not_to include('Split') + { + 'without a fix' => { status: 413, body: 'Request Entity Too Large' }, + "with PostHog's split fix" => { + status: 413, + body: JSON.generate(code: 'content_too_large', fix: 'Split the recipients into smaller batches.') } + }.each do |name, reply| + it "tells a one-recipient batch refused by a 413 #{name} to make the email smaller, not to split it" do + stub_request(:post, batch_url).to_return(reply) + + expect { batch_template([ada]) }.to raise_error(EmailBatchError) { |error| + expect([error.code, error.status_code]).to eq(['content_too_large', 413]) + expect(error.fix).to include('smaller') + expect(error.fix).not_to include('Split') + } + end end it "keeps a 400 content_too_large for content over PostHog's limit as PostHog sent it, without split advice" do @@ -310,6 +318,7 @@ def resend_with_key(result) expect { batch_template([ada, alan], max_retries: 1) }.to raise_error(EmailBatchError) { |error| expect(error.code).to eq('rate_limited') + expect(error.message).to start_with('An earlier attempt of this batch may have queued') expect(error.results.first.error.message).to start_with('An earlier attempt of this batch may have queued') expect(error.results.map { |result| resend_with_key(result) }) .to eq([['unconfirmed', 'welcome:ada', true], ['unconfirmed', 'welcome:alan', true]]) @@ -317,6 +326,18 @@ def resend_with_key(result) expect(a_request(:post, batch_url)).to have_been_made.twice end + it "doesn't say no email was sent, or advise a split, when a size refusal follows a lost answer" do + stub_request(:post, batch_url).to_raise(Errno::ECONNRESET) + .then.to_return(status: 413, body: 'Request Entity Too Large') + + expect { batch_template([ada, alan], max_retries: 1) }.to raise_error(EmailBatchError) { |error| + expect([error.code, error.status_code]).to eq(['content_too_large', 413]) + expect(error.message).to start_with('An earlier attempt of this batch may have queued') + expect(error.fix).to include('same idempotency_key within 24 hours') + expect(statuses(error.results)).to eq(%w[unconfirmed unconfirmed]) + } + end + it 'keeps every recipient unconfirmed when the answer has no result for each, and never retries it' do stub_request(:post, batch_url).to_return(answer(queued('msg_1'))) From 3306f5a27f749e013150f068b9f78ea48b480974 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:17:22 +0100 Subject: [PATCH 22/32] fix(emails): don't call an unconfirmed email unqueued when PostHog gives no detail Co-Authored-By: Claude Opus 5.5 --- lib/posthog/email_batch.rb | 8 ++++++-- spec/posthog/emails_batch_spec.rb | 12 ++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/lib/posthog/email_batch.rb b/lib/posthog/email_batch.rb index c8d11c90..3320571b 100644 --- a/lib/posthog/email_batch.rb +++ b/lib/posthog/email_batch.rb @@ -165,9 +165,13 @@ def slot_error(error, message_id) status = error['status'].is_a?(Integer) ? error['status'] : nil # EmailError#message_id means PostHog may have accepted the email, so a refusal leaves it on the result only. unconfirmed = UNCONFIRMED_CODES.include?(code) + fallback = if unconfirmed + "PostHog couldn't confirm this email (#{code}), so it may still go out." + else + "PostHog didn't queue this email: #{code}." + end EmailError.new(code: code, status_code: status, message_id: (message_id if unconfirmed), - fix: (RESEND_FIX if unconfirmed), - message: text(error['detail']) || "PostHog didn't queue this email: #{code}.") + fix: (RESEND_FIX if unconfirmed), message: text(error['detail']) || fallback) end def text(value) diff --git a/spec/posthog/emails_batch_spec.rb b/spec/posthog/emails_batch_spec.rb index 7c62c6c8..bff3aeaa 100644 --- a/spec/posthog/emails_batch_spec.rb +++ b/spec/posthog/emails_batch_spec.rb @@ -166,6 +166,17 @@ def resend_with_key(result) expect(a_request(:get, %r{/api/messaging/emails/status/})).not_to have_been_made end + it "doesn't tell an unconfirmed email without PostHog's detail that it wasn't queued" do + stub_request(:post, batch_url).to_return( + answer({ message_id: 'msg_ada', error: { code: 'delivery_unavailable', status: 503 } }) + ) + + error = batch_template([ada]).results.first.error + + expect(error.message).to include('may still go out') + expect(error.message).not_to include("didn't queue") + end + it "logs the reply's warnings once each" do warning = { code: 'unverified_link', detail: 'A link points to an unverified domain.' } stub_request(:post, batch_url).to_return(answer(queued('msg_1'), warnings: [warning, warning])) @@ -383,6 +394,7 @@ def resend_with_key(result) expect(error.status_code).to eq(reply[:status]) expect(resend_with_key(error.results.first)).to eq([status, 'welcome:ada', status == 'unconfirmed']) expect(error.results.first.error.message).to eq(error.message) + expect(error.message).not_to start_with('An earlier attempt') } end end From 453ae7043f7a85fdf5aa5eff378c1a31a4e43026 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:37:15 +0100 Subject: [PATCH 23/32] docs(emails): say replayed can read false right after the first send Also gives the changeset the advice for a one-recipient batch refused as too large. Co-Authored-By: Claude Opus 5.5 --- .changeset/email-batch-sends.md | 2 +- lib/posthog/emails.rb | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/.changeset/email-batch-sends.md b/.changeset/email-batch-sends.md index a7201f75..152c779e 100644 --- a/.changeset/email-batch-sends.md +++ b/.changeset/email-batch-sends.md @@ -2,4 +2,4 @@ "posthog-ruby": minor --- -Send the same transactional email to many recipients with `emails.batch`, one email each, from a template made in PostHog with `template_data` per recipient, or from content your code rendered. The client sends at most 100 recipients in one request, refusing more before anything is sent, and returns a result per recipient in order: `queued`, `failed` or `unconfirmed`. Each recipient has its own `idempotency_key`, given or made by the client, so the client's own retries never send an email twice. To rerun a batch that was cut off, pass the keys you stored: a rerun with the same keys within 24 hours replays the emails that went out. A request that fails as a whole raises `EmailBatchError` with every recipient's result, such as a 413 `content_too_large` when PostHog finds the batch too large to take at once, with PostHog's fix to split it into smaller batches. A recipient that any attempt may have queued stays `unconfirmed`, also when a retry is refused. A failed batch never calls the logger. +Send the same transactional email to many recipients with `emails.batch`, one email each, from a template made in PostHog with `template_data` per recipient, or from content your code rendered. The client sends at most 100 recipients in one request, refusing more before anything is sent, and returns a result per recipient in order: `queued`, `failed` or `unconfirmed`. Each recipient has its own `idempotency_key`, given or made by the client, so the client's own retries never send an email twice. To rerun a batch that was cut off, pass the keys you stored: a rerun with the same keys within 24 hours replays the emails that went out. A request that fails as a whole raises `EmailBatchError` with every recipient's result, such as a 413 `content_too_large` when PostHog finds the batch too large to take at once, with PostHog's fix to split it into smaller batches, or, for a batch of one recipient, the advice to make the email smaller. A recipient that any attempt may have queued stays `unconfirmed`, also when a retry is refused. A failed batch never calls the logger. diff --git a/lib/posthog/emails.rb b/lib/posthog/emails.rb index a1ccbe8a..06c943cc 100644 --- a/lib/posthog/emails.rb +++ b/lib/posthog/emails.rb @@ -120,8 +120,9 @@ def status # @!attribute [r] message_id # @return [String, nil] The email's message ID, when PostHog named it. # @!attribute [r] replayed - # @return [Boolean] Whether an earlier send with the same key had already queued the email, so no new email - # went out. + # @return [Boolean] PostHog's marker that an earlier send with the same key had already queued the email, so + # no new email went out. A replay that follows the first send at once can read +false+ even then; the same + # {#message_id} is what shows it is the same email. # @!attribute [r] error # @return [EmailError, nil] Why the email is not `queued`. For an `unconfirmed` email, {EmailError#code} names # what left it so, such as `idempotency_key_in_flight`, `delivery_unavailable`, `api_error` or From c6ac3631884589c96ba55d3435f2211eb7b58b94 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:39:29 +0100 Subject: [PATCH 24/32] fix(emails): keep batch results past a raising logger or a bare 409 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 --- lib/posthog/email_batch.rb | 3 ++- lib/posthog/emails.rb | 12 +++++++++--- spec/posthog/emails_batch_spec.rb | 18 ++++++++++++++---- 3 files changed, 25 insertions(+), 8 deletions(-) diff --git a/lib/posthog/email_batch.rb b/lib/posthog/email_batch.rb index 3320571b..383ea6d4 100644 --- a/lib/posthog/email_batch.rb +++ b/lib/posthog/email_batch.rb @@ -100,7 +100,8 @@ def maybe_queued?(error) status = error.status_code.to_i return true unless status.between?(400, 499) - status == 409 && error.code == 'idempotency_key_in_flight' + # PostHog's only other 409 is batch_unavailable, so a 409 whose body didn't name it may hold keys in flight. + status == 409 && error.code != 'batch_unavailable' end def settle(member, slot) diff --git a/lib/posthog/emails.rb b/lib/posthog/emails.rb index 39e1091d..9a9a8e79 100644 --- a/lib/posthog/emails.rb +++ b/lib/posthog/emails.rb @@ -361,10 +361,11 @@ def send( # @param max_retries [Integer] Overrides the client's `email_request_max_retries` for the batch's request. +0+ # turns retries off. # @return [BatchResult] A result per recipient, in the order of +recipients+. Check each - # {BatchEmailResult#status}, and send an `unconfirmed` email again with the same key so it goes out once. + # {BatchEmailResult#status}, and send an `unconfirmed` email again with the same key so it goes out once. A + # logger that raises a StandardError while logging the warnings doesn't lose the result. # @raise [EmailBatchError] The request failed as a whole, such as a rate limit past its retries. The error is the # last attempt's. {EmailBatchError#results} holds every recipient: `unconfirmed` with a fix to send it again - # with the same key when any attempt may have queued it (a 409 `idempotency_key_in_flight`, a 5xx, or a lost + # with the same key when any attempt may have queued it (a 409 other than `batch_unavailable`, a 5xx, or a lost # answer), and `failed` when PostHog refused the request with a 4xx and no earlier attempt may have queued it. # When only an earlier attempt may have queued them, the error's message says so, and its fix is the same-key # one. The error is `client_closed` when the client shut down before a retry. {EmailError#code} is @@ -399,7 +400,12 @@ def batch( end raise failure if failure - log_warnings(result.warnings) + begin + log_warnings(result.warnings) + rescue StandardError + # PostHog queued the emails and the result holds the warnings. Raising here loses the derived keys, and a + # resend without them sends each email twice. + end result end diff --git a/spec/posthog/emails_batch_spec.rb b/spec/posthog/emails_batch_spec.rb index bff3aeaa..3c2951de 100644 --- a/spec/posthog/emails_batch_spec.rb +++ b/spec/posthog/emails_batch_spec.rb @@ -200,14 +200,23 @@ def resend_with_key(result) expect(log.string).to be_empty end - it 'lets a failing logger stop a batch that succeeded with its own error' do + it 'returns a batch that went through whatever error the logger raises, so no resend gets new keys' do stub_request(:post, batch_url).to_return(answer(queued('msg_0'), warnings: [{ code: 'unverified_link' }])) PostHog::Logging.logger = Logger.new(StringIO.new, level: Logger::WARN, formatter: ->(*) { raise IOError, 'log device closed' }) - expect { batch_template([{ to: 'user@example.com' }]) }.to raise_error(IOError, 'log device closed') { |error| - expect(error.cause).to be_nil - } + result = batch_template([{ to: 'user@example.com' }]) + + expect(result.results.map { |email| [email.status, email.message_id] }).to eq([%w[queued msg_0]]) + expect(result.results.first.idempotency_key).to match(/\A\h{8}-/) + expect(result.warnings.map(&:code)).to eq(['unverified_link']) + end + + it 'lets an interrupt raised while logging stop a batch that went through' do + stub_request(:post, batch_url).to_return(answer(queued('msg_0'), warnings: [{ code: 'unverified_link' }])) + PostHog::Logging.logger = Logger.new(StringIO.new, level: Logger::WARN, formatter: ->(*) { raise Interrupt }) + + expect { batch_template([ada]) }.to raise_error(Interrupt) end context 'when the request fails as a whole' do @@ -382,6 +391,7 @@ def resend_with_key(result) 'a 502 without a code' => [{ status: 502, body: 'Bad gateway' }, 'unconfirmed'], 'a 504 with a code' => [{ status: 504, body: JSON.generate(code: 'gateway_timeout') }, 'unconfirmed'], 'a 503 with client_closed' => [{ status: 503, body: JSON.generate(code: 'client_closed') }, 'unconfirmed'], + 'a 409 without a readable body' => [{ status: 409, body: 'Conflict' }, 'unconfirmed'], 'a 403 without a code' => [{ status: 403, body: 'Forbidden' }, 'failed'], 'a 403 naming keys in flight' => [ { status: 403, body: JSON.generate(code: 'idempotency_key_in_flight') }, 'failed' From cbbf15e5b38a64ca563089fb18b0b84f6f4e67d6 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:43:17 +0100 Subject: [PATCH 25/32] fix(emails): hold one serialized copy of a batch through its retries 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 --- lib/posthog/email_batch.rb | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/lib/posthog/email_batch.rb b/lib/posthog/email_batch.rb index 383ea6d4..9a60446a 100644 --- a/lib/posthog/email_batch.rb +++ b/lib/posthog/email_batch.rb @@ -39,7 +39,8 @@ class EmailBatch attr_reader :body # @param shared [Hash] The batch's email without its recipients. - # @param members [Array] Every recipient, with its JSON as the request carries it. + # @param members [Array] Every recipient, with its JSON as the request carries it. The body takes it + # over, so each member's +wire+ is +nil+ afterwards. # @param parse_warnings [#call] Turns a reply's warnings into {Emails::Warning}s. # @param reply_error [#call] Turns a refused reply into an {EmailError}. def initialize(shared, members, parse_warnings:, reply_error:) @@ -49,8 +50,17 @@ def initialize(shared, members, parse_warnings:, reply_error:) @warnings = [] @maybe_queued = false @attempt_error = nil - empty = JSON.generate(shared.merge(recipients: [])) - @body = "#{empty.delete_suffix(']}')}#{members.map(&:wire).join(',')}]}" + head = JSON.generate(shared.merge(recipients: [])).delete_suffix(']}') + # A buffer of the exact size, and each recipient's JSON dropped once copied, so the request body is the only copy + # of the batch through every retry. + size = head.bytesize + members.sum { |member| member.wire.bytesize + 1 } + 1 + @body = String.new(head, capacity: size, encoding: Encoding::UTF_8) + members.each_with_index do |member, index| + @body << ',' unless index.zero? + @body << member.wire + member.wire = nil + end + @body << ']}' end # @return [Emails::BatchResult] The result of an answer with a result for each recipient. From 81c152c270b6b49ba460f2dd387816ed98ae9ec9 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:43:27 +0100 Subject: [PATCH 26/32] docs(emails): say a raising logger keeps an accepted batch's results Co-Authored-By: Claude Opus 5.5 --- .changeset/email-batch-sends.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/email-batch-sends.md b/.changeset/email-batch-sends.md index 152c779e..00a64940 100644 --- a/.changeset/email-batch-sends.md +++ b/.changeset/email-batch-sends.md @@ -2,4 +2,4 @@ "posthog-ruby": minor --- -Send the same transactional email to many recipients with `emails.batch`, one email each, from a template made in PostHog with `template_data` per recipient, or from content your code rendered. The client sends at most 100 recipients in one request, refusing more before anything is sent, and returns a result per recipient in order: `queued`, `failed` or `unconfirmed`. Each recipient has its own `idempotency_key`, given or made by the client, so the client's own retries never send an email twice. To rerun a batch that was cut off, pass the keys you stored: a rerun with the same keys within 24 hours replays the emails that went out. A request that fails as a whole raises `EmailBatchError` with every recipient's result, such as a 413 `content_too_large` when PostHog finds the batch too large to take at once, with PostHog's fix to split it into smaller batches, or, for a batch of one recipient, the advice to make the email smaller. A recipient that any attempt may have queued stays `unconfirmed`, also when a retry is refused. A failed batch never calls the logger. +Send the same transactional email to many recipients with `emails.batch`, one email each, from a template made in PostHog with `template_data` per recipient, or from content your code rendered. The client sends at most 100 recipients in one request, refusing more before anything is sent, and returns a result per recipient in order: `queued`, `failed` or `unconfirmed`. Each recipient has its own `idempotency_key`, given or made by the client, so the client's own retries never send an email twice. To rerun a batch that was cut off, pass the keys you stored: a rerun with the same keys within 24 hours replays the emails that went out. A request that fails as a whole raises `EmailBatchError` with every recipient's result, such as a 413 `content_too_large` when PostHog finds the batch too large to take at once, with PostHog's fix to split it into smaller batches, or, for a batch of one recipient, the advice to make the email smaller. A recipient that any attempt may have queued stays `unconfirmed`, also when a retry is refused. A failed batch never calls the logger, and a logger that raises while logging an accepted batch's warnings doesn't lose its results. From 6823db283274e1076754aee45d41cbe1f4e9f6a6 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:54:50 +0100 Subject: [PATCH 27/32] fix(emails): let a caller's Timeout::Error end a batch while it logs 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 --- lib/posthog/emails.rb | 14 +++++++++----- spec/posthog/emails_batch_spec.rb | 11 +++++++---- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/lib/posthog/emails.rb b/lib/posthog/emails.rb index 9a9a8e79..f6cb4096 100644 --- a/lib/posthog/emails.rb +++ b/lib/posthog/emails.rb @@ -334,10 +334,10 @@ def send( # Pass the template form, with +template_id+, or the code form, with +template_key+, as {#send} takes them. The # client sends at most 100 recipients in one request and waits at least 45 seconds for the answer. PostHog # refuses a batch too large to take at once with a 413 `content_too_large`: split the recipients into smaller - # batches. A 400 `content_too_large` means the shared content is over PostHog's limit, which splitting doesn't - # change: make it smaller. A recipient whose own +template_data+ is over it comes back `failed` with - # `content_too_large` in its result, while the others go out. A batch takes no +cc+, +bcc+, +attachments+ or - # +scheduled_at+. + # batches, or, for one recipient, make the email smaller. A 400 `content_too_large` means the shared content is + # over PostHog's limit, which splitting doesn't change: make it smaller. A recipient whose own +template_data+ is + # over it comes back `failed` with `content_too_large` in its result, while the others go out. A batch takes no + # +cc+, +bcc+, +attachments+ or +scheduled_at+. # # Each recipient has an +idempotency_key+, given or made by the client, that every retry reuses, so a retry never # queues an email twice. Retries follow {#send}'s. Send each `unconfirmed` email again with its @@ -362,7 +362,8 @@ def send( # turns retries off. # @return [BatchResult] A result per recipient, in the order of +recipients+. Check each # {BatchEmailResult#status}, and send an `unconfirmed` email again with the same key so it goes out once. A - # logger that raises a StandardError while logging the warnings doesn't lose the result. + # logger that raises a StandardError other than Timeout::Error while logging the warnings doesn't lose the + # result. # @raise [EmailBatchError] The request failed as a whole, such as a rate limit past its retries. The error is the # last attempt's. {EmailBatchError#results} holds every recipient: `unconfirmed` with a fix to send it again # with the same key when any attempt may have queued it (a 409 other than `batch_unavailable`, a 5xx, or a lost @@ -402,6 +403,9 @@ def batch( begin log_warnings(result.warnings) + rescue Timeout::Error + # A caller's deadline, from Timeout.timeout with this class, still ends the call. + raise rescue StandardError # PostHog queued the emails and the result holds the warnings. Raising here loses the derived keys, and a # resend without them sends each email twice. diff --git a/spec/posthog/emails_batch_spec.rb b/spec/posthog/emails_batch_spec.rb index 3c2951de..1d974898 100644 --- a/spec/posthog/emails_batch_spec.rb +++ b/spec/posthog/emails_batch_spec.rb @@ -212,11 +212,14 @@ def resend_with_key(result) expect(result.warnings.map(&:code)).to eq(['unverified_link']) end - it 'lets an interrupt raised while logging stop a batch that went through' do - stub_request(:post, batch_url).to_return(answer(queued('msg_0'), warnings: [{ code: 'unverified_link' }])) - PostHog::Logging.logger = Logger.new(StringIO.new, level: Logger::WARN, formatter: ->(*) { raise Interrupt }) + # Timeout.timeout with Timeout::Error as its class raises it in the thread, here in the logger. + [Interrupt, Timeout::Error].each do |deadline| + it "lets #{deadline} raised while logging stop a batch that went through" do + stub_request(:post, batch_url).to_return(answer(queued('msg_0'), warnings: [{ code: 'unverified_link' }])) + PostHog::Logging.logger = Logger.new(StringIO.new, level: Logger::WARN, formatter: ->(*) { raise deadline }) - expect { batch_template([ada]) }.to raise_error(Interrupt) + expect { batch_template([ada]) }.to raise_error(deadline) + end end context 'when the request fails as a whole' do From 4d1805e5a734b63571c7b7738bf89e6c75dc310a Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:07:27 +0100 Subject: [PATCH 28/32] fix(emails): name the template ID first after a batch 404 without a field PostHog answers an unknown template_id, batch sends that are off and a server without the batch route with the same 404, and its detail replaced the SDK's message. A 404 not_found that names no field now says PostHog found no template with this ID or batch sends aren't available for the project, and says to check template_id, then send each recipient on its own. A template_key batch gets the advice without template_id, and no message suggests updating PostHog. Co-Authored-By: Claude Opus 5.5 --- lib/posthog/email_batch.rb | 30 ++++++++++++++++------ lib/posthog/emails.rb | 9 ++++--- spec/posthog/emails_batch_spec.rb | 41 ++++++++++++++++++++++++++++--- 3 files changed, 64 insertions(+), 16 deletions(-) diff --git a/lib/posthog/email_batch.rb b/lib/posthog/email_batch.rb index 9a60446a..5802a8ac 100644 --- a/lib/posthog/email_batch.rb +++ b/lib/posthog/email_batch.rb @@ -15,12 +15,18 @@ class EmailBatch 'it goes out once.' UNAVAILABLE_FIX = "Until batch sends are on for the project, send each email the batch didn't queue with " \ "emails.send and its recipient's idempotency_key." - NOT_FOUND = { + NO_TEMPLATE = { 'code' => 'not_found', - 'detail' => 'PostHog found no batch send for this request, so no email was sent.', - 'why' => "The template doesn't exist, or batch sends are off for this project or this PostHog version.", - 'fix' => "Check template_id, or send each email the batch didn't queue with emails.send and its recipient's " \ - 'idempotency_key.' + 'detail' => "PostHog found no template with this ID, or batch sends aren't available for this project, so it " \ + 'sent no email of this request.', + 'fix' => "Check template_id. If it's right, send each recipient on its own with emails.send and its " \ + 'idempotency_key until batch sends are available.' + }.freeze + NO_CODE_BATCH = { + 'code' => 'not_found', + 'detail' => "Batch sends from code aren't available for this project, so PostHog sent no email of this request.", + 'fix' => 'Send each recipient on its own with emails.send and its idempotency_key until batch sends are ' \ + 'available.' }.freeze TOO_LARGE = { 'code' => 'content_too_large', @@ -31,7 +37,8 @@ class EmailBatch EARLIER_ATTEMPT = 'An earlier attempt of this batch may have queued this email, so it may still go out. ' \ 'The last attempt ended with:' RESULT_DEFAULTS = { message_id: nil, replayed: false, error: nil }.freeze - private_constant :UNCONFIRMED_CODES, :RESEND_FIX, :EARLIER_ATTEMPT, :UNAVAILABLE_FIX, :NOT_FOUND, :TOO_LARGE, + private_constant :UNCONFIRMED_CODES, :RESEND_FIX, :EARLIER_ATTEMPT, :UNAVAILABLE_FIX, :NO_TEMPLATE, :NO_CODE_BATCH, + :TOO_LARGE, :SMALLER_FIX, :RESULT_DEFAULTS Member = Struct.new(:index, :to, :idempotency_key, :wire, keyword_init: true) @@ -50,6 +57,7 @@ def initialize(shared, members, parse_warnings:, reply_error:) @warnings = [] @maybe_queued = false @attempt_error = nil + @template_form = shared.key?(:template_id) head = JSON.generate(shared.merge(recipients: [])).delete_suffix(']}') # A buffer of the exact size, and each recipient's JSON dropped once copied, so the request body is the only copy # of the batch through every retry. @@ -148,8 +156,10 @@ def resend(error, earlier: false) def response_error(fields, status, retry_after) answered = fields.compact - fields = if status == 404 - NOT_FOUND.merge(answered) + fields = if status == 404 && unnamed_not_found?(answered) + # An unknown template, batch sends that are off and a server without the route answer alike, and + # after launch a wrong template ID is the likely one. + @template_form ? NO_TEMPLATE : NO_CODE_BATCH elsif status == 413 too_large(answered) else @@ -159,6 +169,10 @@ def response_error(fields, status, retry_after) @reply_error.call(fields, status, retry_after) end + def unnamed_not_found?(answered) + %w[not_found api_error].include?(text(answered['code']) || 'api_error') && text(answered['attr']).nil? + end + def too_large(answered) fields = TOO_LARGE.merge(answered.select { |_, value| text(value) }) # One recipient can't be split, so only a smaller email gets through, whatever the reply advises. diff --git a/lib/posthog/emails.rb b/lib/posthog/emails.rb index f6cb4096..c9fdde7d 100644 --- a/lib/posthog/emails.rb +++ b/lib/posthog/emails.rb @@ -372,10 +372,11 @@ def send( # one. The error is `client_closed` when the client shut down before a retry. {EmailError#code} is # `content_too_large` with PostHog's fix: a 413 for a batch to split into smaller batches, or for one recipient # an email to make smaller, and a 400 for shared content to make smaller. It is `batch_unavailable` when the - # project can't send batches yet, and `not_found` when the template doesn't exist or batch sends are off: send - # each email the batch didn't queue with {#send} and its recipient's +idempotency_key+. The warnings of an - # answer without a result for each recipient are on - # {EmailError#warnings}, and the client logs none of them. + # project can't send batches yet: send each email the batch didn't queue with {#send} and its recipient's + # +idempotency_key+. It is `not_found` with no {EmailError#field} when PostHog found no template with the + # +template_id+ or batch sends aren't available for the project, which PostHog answers alike: check + # +template_id+, and if it's right, send each recipient on its own the same way. The warnings of an answer + # without a result for each recipient are on {EmailError#warnings}, and the client logs none of them. # @raise [EmailError] The client sent nothing, such as when it is disabled or has no +secret_key+. # @raise [ArgumentError] An argument has the wrong type or format, such as more than 100 recipients or two # recipients with the same +idempotency_key+. No email was sent. diff --git a/spec/posthog/emails_batch_spec.rb b/spec/posthog/emails_batch_spec.rb index 1d974898..3852faaf 100644 --- a/spec/posthog/emails_batch_spec.rb +++ b/spec/posthog/emails_batch_spec.rb @@ -313,12 +313,45 @@ def resend_with_key(result) end end - it 'names a 404 as a missing template or batch sends that are off' do - stub_request(:post, batch_url).to_return(status: 404, body: '') + # PostHog answers an unknown template_id, batch sends that are off and a server without the route alike. + { + 'an unknown template or batch sends off' => JSON.generate(code: 'not_found', attr: nil, detail: 'Not found.'), + 'a server without the route' => JSON.generate(code: 'not_found', detail: 'Endpoint not found.'), + 'no body' => '' + }.each do |name, body| + it "names the template ID first after a 404 for #{name}" do + stub_request(:post, batch_url).to_return(status: 404, body: body) + + expect { batch_template([ada, alan]) }.to raise_error(EmailBatchError) { |error| + expect([error.code, error.name, error.status_code, error.field]) + .to eq(['not_found', 'not_found', 404, nil]) + expect(error.message) + .to include('no template with this ID', "batch sends aren't available for this project") + expect(error.fix).to include('Check template_id', 'on its own') + expect("#{error.message} #{error.why} #{error.fix}").not_to match(/update|upgrade|server|version/i) + expect(error.results.map(&:status)).to eq(%w[failed failed]) + } + end + + it "names batch sends from code after a 404 for #{name}" do + stub_request(:post, batch_url).to_return(status: 404, body: body) + + code = { template_key: 'launch', subject: 'Hi', text: 'Hi', recipients: [{ to: 'ada@example.com' }] } + expect { emails.batch(**code) }.to raise_error(EmailBatchError) { |error| + expect([error.code, error.status_code]).to eq(['not_found', 404]) + expect(error.message).to include("aren't available for this project") + expect(error.fix).to include('on its own') + expect("#{error.message} #{error.why} #{error.fix}") + .not_to match(/template_id|update|upgrade|server|version/i) + } + end + end + + it 'keeps the answer of a 404 that names a field' do + stub_request(:post, batch_url).to_return(refuse(404, 'not_found', detail: 'No such sender.', attr: 'from')) expect { batch_template([ada]) }.to raise_error(EmailBatchError) { |error| - expect([error.code, error.name]).to eq(%w[not_found not_found]) - expect(error.why).to include("template doesn't exist") + expect([error.code, error.field, error.message]).to eq(['not_found', 'from', 'No such sender.']) } end From 47629d68cdd6dc33e0fe94e4d5aba36216ef5db4 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:14:53 +0100 Subject: [PATCH 29/32] docs(emails): drop log_warnings' stale note that a logger error propagates emails.batch now keeps an accepted batch's results when the logger raises, so the note misstated the behavior. Co-Authored-By: Claude Opus 5.5 --- lib/posthog/emails.rb | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/posthog/emails.rb b/lib/posthog/emails.rb index c9fdde7d..d26f1a6c 100644 --- a/lib/posthog/emails.rb +++ b/lib/posthog/emails.rb @@ -536,7 +536,6 @@ def send_batch(run, secret_key, max_retries) [nil, run.failure(e)] end - # The client can't tell a failing logger from a caller's deadline, so either propagates. def log_warnings(warnings) warnings.each { |warning| logger.warn("PostHog email warning #{warning.code}: #{warning.message}") } end From 75c0024f55619c627e4ff8249e8bfd902a1977fb Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:35:29 +0100 Subject: [PATCH 30/32] fix(emails): advise a code batch's 404 to send alone only where code sends work A template_key batch's 404 can mean the project can't send from code at all, so the advice to send each recipient on its own now applies only where it can. A spec also shows a 404 after a lost answer leaves the recipients unconfirmed with their keys. Co-Authored-By: Claude Opus 5.5 --- lib/posthog/email_batch.rb | 7 ++++--- spec/posthog/emails_batch_spec.rb | 32 +++++++++++++++++++------------ 2 files changed, 24 insertions(+), 15 deletions(-) diff --git a/lib/posthog/email_batch.rb b/lib/posthog/email_batch.rb index 5802a8ac..fe4ffafa 100644 --- a/lib/posthog/email_batch.rb +++ b/lib/posthog/email_batch.rb @@ -24,9 +24,10 @@ class EmailBatch }.freeze NO_CODE_BATCH = { 'code' => 'not_found', - 'detail' => "Batch sends from code aren't available for this project, so PostHog sent no email of this request.", - 'fix' => 'Send each recipient on its own with emails.send and its idempotency_key until batch sends are ' \ - 'available.' + 'detail' => "Batch sends, or sends from code, aren't available for this project, so PostHog sent no email of " \ + 'this request.', + 'fix' => 'If this project can send email from code, send each recipient on its own with emails.send and its ' \ + 'idempotency_key until batch sends are available.' }.freeze TOO_LARGE = { 'code' => 'content_too_large', diff --git a/spec/posthog/emails_batch_spec.rb b/spec/posthog/emails_batch_spec.rb index 3852faaf..85a75c8c 100644 --- a/spec/posthog/emails_batch_spec.rb +++ b/spec/posthog/emails_batch_spec.rb @@ -340,7 +340,7 @@ def resend_with_key(result) expect { emails.batch(**code) }.to raise_error(EmailBatchError) { |error| expect([error.code, error.status_code]).to eq(['not_found', 404]) expect(error.message).to include("aren't available for this project") - expect(error.fix).to include('on its own') + expect(error.fix).to include('If this project can send email from code', 'on its own') expect("#{error.message} #{error.why} #{error.fix}") .not_to match(/template_id|update|upgrade|server|version/i) } @@ -369,17 +369,25 @@ def resend_with_key(result) expect(a_request(:get, %r{/api/messaging/emails/status/})).not_to have_been_made end - it 'keeps the recipients a lost answer may have queued unconfirmed when the retry is refused' do - stub_request(:post, batch_url).to_raise(Errno::ECONNRESET).then.to_return(refuse(429, 'rate_limited')) - - expect { batch_template([ada, alan], max_retries: 1) }.to raise_error(EmailBatchError) { |error| - expect(error.code).to eq('rate_limited') - expect(error.message).to start_with('An earlier attempt of this batch may have queued') - expect(error.results.first.error.message).to start_with('An earlier attempt of this batch may have queued') - expect(error.results.map { |result| resend_with_key(result) }) - .to eq([['unconfirmed', 'welcome:ada', true], ['unconfirmed', 'welcome:alan', true]]) - } - expect(a_request(:post, batch_url)).to have_been_made.twice + { + 'a 429' => [{ status: 429, body: JSON.generate(code: 'rate_limited') }, 'rate_limited'], + 'a 404 without a field' => [ + { status: 404, body: JSON.generate(code: 'not_found', detail: 'Not found.') }, 'not_found' + ] + }.each do |name, (refusal, code)| + it "keeps the recipients a lost answer may have queued unconfirmed when the retry gets #{name}" do + stub_request(:post, batch_url).to_raise(Errno::ECONNRESET).then.to_return(refusal) + + expect { batch_template([ada, alan], max_retries: 1) }.to raise_error(EmailBatchError) { |error| + expect(error.code).to eq(code) + expect(error.message).to start_with('An earlier attempt of this batch may have queued') + expect(error.results.first.error.message) + .to start_with('An earlier attempt of this batch may have queued') + expect(error.results.map { |result| resend_with_key(result) }) + .to eq([['unconfirmed', 'welcome:ada', true], ['unconfirmed', 'welcome:alan', true]]) + } + expect(a_request(:post, batch_url)).to have_been_made.twice + end end it "doesn't say no email was sent, or advise a split, when a size refusal follows a lost answer" do From 08d50896ee13401efcca9f67a00c6f758bf988cc Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:48:02 +0100 Subject: [PATCH 31/32] fix(emails): give a batch error the same-key fix when any attempt may have queued PostHog's in-flight refusal tells the caller to retry, and a retry without the stored keys sends each email twice. The error now carries the same-key fix whenever any attempt may have queued the batch, as its recipients do. Co-Authored-By: Claude Opus 5.5 --- lib/posthog/email_batch.rb | 11 +++-------- lib/posthog/emails.rb | 20 ++++++++++---------- spec/posthog/emails_batch_spec.rb | 1 + 3 files changed, 14 insertions(+), 18 deletions(-) diff --git a/lib/posthog/email_batch.rb b/lib/posthog/email_batch.rb index fe4ffafa..2808af37 100644 --- a/lib/posthog/email_batch.rb +++ b/lib/posthog/email_batch.rb @@ -100,14 +100,9 @@ def attempt_failed(error) def failure(error) # Only an attempt's error says what PostHog may have queued; the client raises client_closed without a request. refused = !(@attempt_error.equal?(error) && maybe_queued?(error)) - error = resend(error, earlier: true) if @maybe_queued && refused - results = @members.map do |member| - if @maybe_queued - result(member, 'unconfirmed', error: resend(error)) - else - result(member, 'failed', error: error) - end - end + error = resend(error, earlier: refused) if @maybe_queued + status = @maybe_queued ? 'unconfirmed' : 'failed' + results = @members.map { |member| result(member, status, error: error) } EmailBatchError.new(error, results: results.freeze, warnings: @warnings.dup.freeze) end diff --git a/lib/posthog/emails.rb b/lib/posthog/emails.rb index d26f1a6c..01307b9f 100644 --- a/lib/posthog/emails.rb +++ b/lib/posthog/emails.rb @@ -365,17 +365,17 @@ def send( # logger that raises a StandardError other than Timeout::Error while logging the warnings doesn't lose the # result. # @raise [EmailBatchError] The request failed as a whole, such as a rate limit past its retries. The error is the - # last attempt's. {EmailBatchError#results} holds every recipient: `unconfirmed` with a fix to send it again - # with the same key when any attempt may have queued it (a 409 other than `batch_unavailable`, a 5xx, or a lost + # last attempt's. {EmailBatchError#results} holds every recipient: `unconfirmed` with a fix to send it again with + # the same key when any attempt may have queued it (a 409 other than `batch_unavailable`, a 5xx, or a lost # answer), and `failed` when PostHog refused the request with a 4xx and no earlier attempt may have queued it. - # When only an earlier attempt may have queued them, the error's message says so, and its fix is the same-key - # one. The error is `client_closed` when the client shut down before a retry. {EmailError#code} is - # `content_too_large` with PostHog's fix: a 413 for a batch to split into smaller batches, or for one recipient - # an email to make smaller, and a 400 for shared content to make smaller. It is `batch_unavailable` when the - # project can't send batches yet: send each email the batch didn't queue with {#send} and its recipient's - # +idempotency_key+. It is `not_found` with no {EmailError#field} when PostHog found no template with the - # +template_id+ or batch sends aren't available for the project, which PostHog answers alike: check - # +template_id+, and if it's right, send each recipient on its own the same way. The warnings of an answer + # When any attempt may have queued them, the error's fix is the same-key one, and when only an earlier attempt may + # have, its message says so. The error is `client_closed` when the client shut down before a retry. + # {EmailError#code} is `content_too_large` with PostHog's fix: a 413 for a batch to split into smaller batches, or + # for one recipient an email to make smaller, and a 400 for shared content to make smaller. It is + # `batch_unavailable` when the project can't send batches yet: send each email the batch didn't queue with {#send} + # and its recipient's +idempotency_key+. It is `not_found` with no {EmailError#field} when PostHog found no + # template with the +template_id+ or batch sends aren't available for the project, which PostHog answers alike: + # check +template_id+, and if it's right, send each recipient on its own the same way. The warnings of an answer # without a result for each recipient are on {EmailError#warnings}, and the client logs none of them. # @raise [EmailError] The client sent nothing, such as when it is disabled or has no +secret_key+. # @raise [ArgumentError] An argument has the wrong type or format, such as more than 100 recipients or two diff --git a/spec/posthog/emails_batch_spec.rb b/spec/posthog/emails_batch_spec.rb index 85a75c8c..a6225a68 100644 --- a/spec/posthog/emails_batch_spec.rb +++ b/spec/posthog/emails_batch_spec.rb @@ -306,6 +306,7 @@ def resend_with_key(result) expect { batch_template([ada, alan], max_retries: 0) }.to raise_error(EmailBatchError) { |error| expect([error.code, error.results.map(&:message_id)]).to eq(['idempotency_key_in_flight', [nil, nil]]) + expect(error.fix).to eq(error.results.first.error.fix) expect(error.results.map { |result| resend_with_key(result) }) .to eq([['unconfirmed', 'welcome:ada', true], ['unconfirmed', 'welcome:alan', true]]) } From 0b4447fcbab5745a3d5cf0481492f44967628278 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:11:31 +0100 Subject: [PATCH 32/32] fix(emails): never tell a recipient that may have gone out it wasn't sent After an attempt that may have queued the batch, a refused retry now says some emails may have gone out and to read each recipient's result, with same-key advice for the batch, instead of PostHog's text for that one attempt. Every unconfirmed recipient says PostHog didn't confirm it and it may still go out. Co-Authored-By: Claude Opus 5.5 --- .changeset/email-batch-sends.md | 2 +- lib/posthog/email_batch.rb | 65 +++++++++++++++++---------- lib/posthog/emails.rb | 19 ++++---- spec/posthog/emails_batch_spec.rb | 75 ++++++++++++++++++++----------- 4 files changed, 102 insertions(+), 59 deletions(-) diff --git a/.changeset/email-batch-sends.md b/.changeset/email-batch-sends.md index 00a64940..8924a2e8 100644 --- a/.changeset/email-batch-sends.md +++ b/.changeset/email-batch-sends.md @@ -2,4 +2,4 @@ "posthog-ruby": minor --- -Send the same transactional email to many recipients with `emails.batch`, one email each, from a template made in PostHog with `template_data` per recipient, or from content your code rendered. The client sends at most 100 recipients in one request, refusing more before anything is sent, and returns a result per recipient in order: `queued`, `failed` or `unconfirmed`. Each recipient has its own `idempotency_key`, given or made by the client, so the client's own retries never send an email twice. To rerun a batch that was cut off, pass the keys you stored: a rerun with the same keys within 24 hours replays the emails that went out. A request that fails as a whole raises `EmailBatchError` with every recipient's result, such as a 413 `content_too_large` when PostHog finds the batch too large to take at once, with PostHog's fix to split it into smaller batches, or, for a batch of one recipient, the advice to make the email smaller. A recipient that any attempt may have queued stays `unconfirmed`, also when a retry is refused. A failed batch never calls the logger, and a logger that raises while logging an accepted batch's warnings doesn't lose its results. +Send the same transactional email to many recipients with `emails.batch`, one email each, from a template made in PostHog with `template_data` per recipient, or from content your code rendered. The client sends at most 100 recipients in one request, refusing more before anything is sent, and returns a result per recipient in order: `queued`, `failed` or `unconfirmed`. Each recipient has its own `idempotency_key`, given or made by the client, so the client's own retries never send an email twice. To rerun a batch that was cut off, pass the keys you stored: a rerun with the same keys within 24 hours replays the emails that went out. A request that fails as a whole raises `EmailBatchError` with every recipient's result, such as a 413 `content_too_large` when PostHog finds the batch too large to take at once, with PostHog's fix to split it into smaller batches, or, for a batch of one recipient, the advice to make the email smaller. A recipient that any attempt may have queued stays `unconfirmed`, also when a retry is refused, and its message says PostHog didn't confirm it and it may still go out. A failed batch never calls the logger, and a logger that raises while logging an accepted batch's warnings doesn't lose its results. diff --git a/lib/posthog/email_batch.rb b/lib/posthog/email_batch.rb index 2808af37..9b6ea0d3 100644 --- a/lib/posthog/email_batch.rb +++ b/lib/posthog/email_batch.rb @@ -13,6 +13,8 @@ class EmailBatch UNCONFIRMED_CODES = %w[idempotency_key_in_flight delivery_unavailable api_error].freeze RESEND_FIX = 'Send it again with the same idempotency_key within 24 hours of the first request that used it, so ' \ 'it goes out once.' + BATCH_RESEND_FIX = 'Send each recipient again with the same idempotency_key within 24 hours of the first request ' \ + 'that used it, so each email goes out once.' UNAVAILABLE_FIX = "Until batch sends are on for the project, send each email the batch didn't queue with " \ "emails.send and its recipient's idempotency_key." NO_TEMPLATE = { @@ -35,10 +37,14 @@ class EmailBatch 'fix' => 'Split the recipients into smaller batches.' }.freeze SMALLER_FIX = 'Make the email smaller, such as its template_data.' - EARLIER_ATTEMPT = 'An earlier attempt of this batch may have queued this email, so it may still go out. ' \ - 'The last attempt ended with:' + MAY_HAVE_GONE_OUT = "so some of its emails may have gone out: read each recipient's result." + EARLIER_REFUSED = 'PostHog refused a retry of this batch with %s. An earlier attempt may have queued it, ' \ + "#{MAY_HAVE_GONE_OUT}".freeze + EARLIER_CLOSED = 'The PostHog client shut down before a retry of this batch. An earlier attempt may have queued ' \ + "it, #{MAY_HAVE_GONE_OUT}".freeze RESULT_DEFAULTS = { message_id: nil, replayed: false, error: nil }.freeze - private_constant :UNCONFIRMED_CODES, :RESEND_FIX, :EARLIER_ATTEMPT, :UNAVAILABLE_FIX, :NO_TEMPLATE, :NO_CODE_BATCH, + private_constant :UNCONFIRMED_CODES, :RESEND_FIX, :BATCH_RESEND_FIX, :MAY_HAVE_GONE_OUT, :EARLIER_REFUSED, + :EARLIER_CLOSED, :UNAVAILABLE_FIX, :NO_TEMPLATE, :NO_CODE_BATCH, :TOO_LARGE, :SMALLER_FIX, :RESULT_DEFAULTS @@ -98,11 +104,12 @@ def attempt_failed(error) # Every recipient of a request that failed as a whole is `unconfirmed` when any attempt may have queued it, and # `failed` otherwise. def failure(error) - # Only an attempt's error says what PostHog may have queued; the client raises client_closed without a request. - refused = !(@attempt_error.equal?(error) && maybe_queued?(error)) - error = resend(error, earlier: refused) if @maybe_queued + if @maybe_queued + recipient_error = restate(error, unconfirmed_message(error.code), RESEND_FIX) + error = restate(error, earlier_message(error), BATCH_RESEND_FIX) + end status = @maybe_queued ? 'unconfirmed' : 'failed' - results = @members.map { |member| result(member, status, error: error) } + results = @members.map { |member| result(member, status, error: recipient_error || error) } EmailBatchError.new(error, results: results.freeze, warnings: @warnings.dup.freeze) end @@ -129,7 +136,9 @@ def settle(member, slot) return result(member, 'unconfirmed', message_id: message_id, error: answer) elsif @maybe_queued # A refusal can't confirm an email that an earlier attempt of the request may have queued. - return result(member, 'unconfirmed', message_id: message_id, error: resend(answer, earlier: true)) + message = "PostHog didn't confirm this email: it refused a retry with #{answer.code}, but an earlier attempt " \ + 'of this batch may have queued it, so it may still go out.' + return result(member, 'unconfirmed', message_id: message_id, error: restate(answer, message, RESEND_FIX)) end result(member, 'failed', message_id: message_id, error: answer) @@ -140,14 +149,23 @@ def result(member, status, **fields) Emails::BatchEmailResult.new(**RESULT_DEFAULTS, **identity, **fields) end - # A caller who follows PostHog's own advice without the key sends a second email. A refusal that follows an - # attempt that may have queued the email can't say no email was sent, so its message says so first. - def resend(error, earlier: false) - return error if error.fix == RESEND_FIX + # PostHog's text speaks for the last attempt only: it can say nothing was sent, or advise a split or new keys, while + # an earlier attempt may have queued every email. A caller who follows it without the keys sends a second email. + def earlier_message(error) + # The client raises client_closed itself, without a request. + return EARLIER_CLOSED unless @attempt_error.equal?(error) + + maybe_queued?(error) ? error.message : format(EARLIER_REFUSED, error.code) + end + + def unconfirmed_message(code) + "PostHog didn't confirm this email (#{code}), so it may still go out." + end - message = earlier ? "#{EARLIER_ATTEMPT} #{error.message}" : error.message - EmailError.new(code: error.code, message: message, status_code: error.status_code, why: error.why, - fix: RESEND_FIX, docs_url: error.docs_url, field: error.field, retry_after: error.retry_after) + def restate(error, message, fix) + EmailError.new(code: error.code, message: message, status_code: error.status_code, why: error.why, fix: fix, + docs_url: error.docs_url, field: error.field, retry_after: error.retry_after, + message_id: error.message_id) end def response_error(fields, status, retry_after) @@ -178,21 +196,22 @@ def too_large(answered) def slot_error(error, message_id) unless error.is_a?(Hash) return EmailError.new(code: 'api_error', message_id: message_id, fix: RESEND_FIX, - message: 'PostHog answered without a readable result for this email, so it may still ' \ - 'go out.') + message: "PostHog didn't confirm this email: its answer had no readable result for it, " \ + 'so it may still go out.') end code = text(error['code']) || 'api_error' status = error['status'].is_a?(Integer) ? error['status'] : nil # EmailError#message_id means PostHog may have accepted the email, so a refusal leaves it on the result only. unconfirmed = UNCONFIRMED_CODES.include?(code) - fallback = if unconfirmed - "PostHog couldn't confirm this email (#{code}), so it may still go out." - else - "PostHog didn't queue this email: #{code}." - end + # PostHog's detail for these codes can read as a refusal or advise a retry, while the email may still go out. + message = if unconfirmed + unconfirmed_message(code) + else + text(error['detail']) || "PostHog didn't queue this email: #{code}." + end EmailError.new(code: code, status_code: status, message_id: (message_id if unconfirmed), - fix: (RESEND_FIX if unconfirmed), message: text(error['detail']) || fallback) + fix: (RESEND_FIX if unconfirmed), message: message) end def text(value) diff --git a/lib/posthog/emails.rb b/lib/posthog/emails.rb index 01307b9f..0ee1a932 100644 --- a/lib/posthog/emails.rb +++ b/lib/posthog/emails.rb @@ -368,15 +368,16 @@ def send( # last attempt's. {EmailBatchError#results} holds every recipient: `unconfirmed` with a fix to send it again with # the same key when any attempt may have queued it (a 409 other than `batch_unavailable`, a 5xx, or a lost # answer), and `failed` when PostHog refused the request with a 4xx and no earlier attempt may have queued it. - # When any attempt may have queued them, the error's fix is the same-key one, and when only an earlier attempt may - # have, its message says so. The error is `client_closed` when the client shut down before a retry. - # {EmailError#code} is `content_too_large` with PostHog's fix: a 413 for a batch to split into smaller batches, or - # for one recipient an email to make smaller, and a 400 for shared content to make smaller. It is - # `batch_unavailable` when the project can't send batches yet: send each email the batch didn't queue with {#send} - # and its recipient's +idempotency_key+. It is `not_found` with no {EmailError#field} when PostHog found no - # template with the +template_id+ or batch sends aren't available for the project, which PostHog answers alike: - # check +template_id+, and if it's right, send each recipient on its own the same way. The warnings of an answer - # without a result for each recipient are on {EmailError#warnings}, and the client logs none of them. + # When any attempt may have queued them, the error's fix is to send each recipient again with its key, each + # recipient's message says PostHog didn't confirm it and it may still go out, and when only an earlier attempt may + # have, the error's message says some emails may have gone out. The error is `client_closed` when the client shut + # down before a retry. {EmailError#code} is `content_too_large` with PostHog's fix: a 413 for a batch to split + # into smaller batches, or for one recipient an email to make smaller, and a 400 for shared content to make + # smaller. It is `batch_unavailable` when the project can't send batches yet: send each email the batch didn't + # queue with {#send} and its recipient's +idempotency_key+. It is `not_found` with no {EmailError#field} when + # PostHog found no template with the +template_id+ or batch sends aren't available for the project, which PostHog + # answers alike: check +template_id+, and if it's right, send each recipient on its own the same way. The warnings + # of an answer without a result for each recipient are on {EmailError#warnings}, and the client logs none of them. # @raise [EmailError] The client sent nothing, such as when it is disabled or has no +secret_key+. # @raise [ArgumentError] An argument has the wrong type or format, such as more than 100 recipients or two # recipients with the same +idempotency_key+. No email was sent. diff --git a/spec/posthog/emails_batch_spec.rb b/spec/posthog/emails_batch_spec.rb index a6225a68..9eba4323 100644 --- a/spec/posthog/emails_batch_spec.rb +++ b/spec/posthog/emails_batch_spec.rb @@ -55,6 +55,13 @@ def resend_with_key(result) [result.status, result.idempotency_key, result.error.fix.to_s.include?('same idempotency_key within 24 hours of the first request that used it')] end + + def expect_unconfirmed_message(result) + expect(result.status).to eq('unconfirmed') + expect(result.error.message).to include("PostHog didn't confirm this email").and include('may still go out') + expect(result.error.message) + .not_to match(/not queued|didn't queue|not sent|no email was sent|sent no email|failed/i) + end describe '#batch' do it 'sends one request and returns a result per recipient, in order' do stub_request(:post, batch_url).to_return(answer(queued('msg_1'), queued('msg_2', replayed: true))) @@ -147,7 +154,7 @@ def resend_with_key(result) expect(results.map(&:status)).to eq(%w[queued unconfirmed]) expect([results.last.error.code, resend_with_key(results.last)]) .to eq(['recipient_suppressed', ['unconfirmed', 'welcome:alan', true]]) - expect(results.last.error.message).to start_with('An earlier attempt of this batch may have queued') + expect_unconfirmed_message(results.last) end it 'leaves an unconfirmed email PostHog answered without an ID to be sent again with its key' do @@ -163,6 +170,7 @@ def resend_with_key(result) [['unconfirmed', 'welcome:ada', true], ['unconfirmed', 'welcome:alan', true], ['unconfirmed', 'welcome:grace', true]] ) + results.each { |result| expect_unconfirmed_message(result) } expect(a_request(:get, %r{/api/messaging/emails/status/})).not_to have_been_made end @@ -302,11 +310,13 @@ def resend_with_key(result) ['', 'Wait a few seconds and try again.'].each do |fix| it "keeps every recipient unconfirmed while PostHog holds the keys, with fix #{fix.inspect}" do - stub_request(:post, batch_url).to_return(refuse(409, 'idempotency_key_in_flight', fix: fix)) + detail = 'A request with this Idempotency-Key is still being processed. Retry in a few seconds.' + stub_request(:post, batch_url).to_return(refuse(409, 'idempotency_key_in_flight', detail: detail, fix: fix)) expect { batch_template([ada, alan], max_retries: 0) }.to raise_error(EmailBatchError) { |error| expect([error.code, error.results.map(&:message_id)]).to eq(['idempotency_key_in_flight', [nil, nil]]) - expect(error.fix).to eq(error.results.first.error.fix) + expect(error.fix).to start_with('Send each recipient again with the same idempotency_key within 24 hours') + error.results.each { |result| expect_unconfirmed_message(result) } expect(error.results.map { |result| resend_with_key(result) }) .to eq([['unconfirmed', 'welcome:ada', true], ['unconfirmed', 'welcome:alan', true]]) } @@ -370,20 +380,34 @@ def resend_with_key(result) expect(a_request(:get, %r{/api/messaging/emails/status/})).not_to have_been_made end + nothing_sent = /no emails? (?:was|were) (?:sent|queued)|sent no email|nothing was sent|not sent|split|smaller/i { - 'a 429' => [{ status: 429, body: JSON.generate(code: 'rate_limited') }, 'rate_limited'], - 'a 404 without a field' => [ - { status: 404, body: JSON.generate(code: 'not_found', detail: 'Not found.') }, 'not_found' - ] + 'a 400' => [ + { status: 400, body: JSON.generate(code: 'invalid_request', detail: 'Invalid, so no email was sent.') }, + 'invalid_request' + ], + 'a 404 without a field' => [{ status: 404, body: JSON.generate(code: 'not_found', detail: 'Not found.') }, + 'not_found'], + 'a 409 batch_unavailable' => [{ status: 409, body: JSON.generate(code: 'batch_unavailable') }, + 'batch_unavailable'], + 'a 413 without a body' => [{ status: 413, body: 'Request Entity Too Large' }, + 'content_too_large'], + 'a 413 content_too_large' => [ + { status: 413, + body: JSON.generate(code: 'content_too_large', detail: 'Nothing was sent.', fix: 'Split it.') }, + 'content_too_large' + ], + 'a 429' => [{ status: 429, body: JSON.generate(code: 'rate_limited') }, 'rate_limited'] }.each do |name, (refusal, code)| - it "keeps the recipients a lost answer may have queued unconfirmed when the retry gets #{name}" do + it "says some emails may have gone out, with same-key advice, when #{name} follows a lost answer" do stub_request(:post, batch_url).to_raise(Errno::ECONNRESET).then.to_return(refusal) expect { batch_template([ada, alan], max_retries: 1) }.to raise_error(EmailBatchError) { |error| expect(error.code).to eq(code) - expect(error.message).to start_with('An earlier attempt of this batch may have queued') - expect(error.results.first.error.message) - .to start_with('An earlier attempt of this batch may have queued') + expect(error.message).to include('some of its emails may have gone out', "read each recipient's result") + expect(error.fix).to start_with('Send each recipient again with the same idempotency_key within 24 hours') + expect([error.message, error.fix]).to all(satisfy { |text| !text.match?(nothing_sent) }) + error.results.each { |result| expect_unconfirmed_message(result) } expect(error.results.map { |result| resend_with_key(result) }) .to eq([['unconfirmed', 'welcome:ada', true], ['unconfirmed', 'welcome:alan', true]]) } @@ -391,18 +415,6 @@ def resend_with_key(result) end end - it "doesn't say no email was sent, or advise a split, when a size refusal follows a lost answer" do - stub_request(:post, batch_url).to_raise(Errno::ECONNRESET) - .then.to_return(status: 413, body: 'Request Entity Too Large') - - expect { batch_template([ada, alan], max_retries: 1) }.to raise_error(EmailBatchError) { |error| - expect([error.code, error.status_code]).to eq(['content_too_large', 413]) - expect(error.message).to start_with('An earlier attempt of this batch may have queued') - expect(error.fix).to include('same idempotency_key within 24 hours') - expect(statuses(error.results)).to eq(%w[unconfirmed unconfirmed]) - } - end - it 'keeps every recipient unconfirmed when the answer has no result for each, and never retries it' do stub_request(:post, batch_url).to_return(answer(queued('msg_1'))) @@ -437,6 +449,12 @@ def resend_with_key(result) 'a 504 with a code' => [{ status: 504, body: JSON.generate(code: 'gateway_timeout') }, 'unconfirmed'], 'a 503 with client_closed' => [{ status: 503, body: JSON.generate(code: 'client_closed') }, 'unconfirmed'], 'a 409 without a readable body' => [{ status: 409, body: 'Conflict' }, 'unconfirmed'], + 'a 409 with another code' => [{ status: 409, body: JSON.generate(code: 'conflict') }, 'unconfirmed'], + "a 503 with PostHog's detail" => [ + { status: 503, + body: JSON.generate(code: 'delivery_unavailable', detail: 'The email pipeline is unavailable.') }, + 'unconfirmed' + ], 'a 403 without a code' => [{ status: 403, body: 'Forbidden' }, 'failed'], 'a 403 naming keys in flight' => [ { status: 403, body: JSON.generate(code: 'idempotency_key_in_flight') }, 'failed' @@ -448,8 +466,12 @@ def resend_with_key(result) expect { batch_template([ada], max_retries: 0) }.to raise_error(EmailBatchError) { |error| expect(error.status_code).to eq(reply[:status]) expect(resend_with_key(error.results.first)).to eq([status, 'welcome:ada', status == 'unconfirmed']) - expect(error.results.first.error.message).to eq(error.message) - expect(error.message).not_to start_with('An earlier attempt') + if status == 'unconfirmed' + expect_unconfirmed_message(error.results.first) + else + expect(error.results.first.error.message).to eq(error.message) + end + expect(error.message).not_to include('may have gone out') } end end @@ -474,8 +496,9 @@ def resend_with_key(result) expect { batch_template([ada]) }.to raise_error(EmailBatchError) { |error| expect(error.code).to eq('client_closed') + expect(error.message).to include('some of its emails may have gone out') expect(resend_with_key(error.results.first)).to eq(['unconfirmed', 'welcome:ada', true]) - expect(error.results.first.error.message).to start_with('An earlier attempt of this batch may have queued') + expect_unconfirmed_message(error.results.first) } expect(a_request(:post, batch_url)).to have_been_made.once end