Skip to content

Record why an email send was rejected or failed - #1235

Merged
sidneyswift merged 2 commits into
mainfrom
codex/email-send-reason
Nov 7, 2026
Merged

sidneyswift merged 2 commits into
mainfrom
codex/email-send-reason

Conversation

@sidneyswift

@sidneyswift sidneyswift commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Every rejected or failed POST /api/emails attempt now records why in email_send_log.reason, plus the sending account when auth has resolved it.

Cause reason
Body fails the schema invalid_body: html: a non-empty html or text body is required
Auth fails auth_failed: 401
No recipient given and the account has no email no_account_email
Recipient gate (no payment method) recipient_not_allowed: a@example.com, …
Resend send fails resend_error: …

Why

recoupable/app#1949 F2: 59% of logged sends were rejected and the log could not say why, so scheduled reports that never arrived could not be diagnosed. The response bodies callers receive are unchanged.

Changes

  • validateSendEmailBody: the rejection branch now carries reason and, after auth, accountId.
  • sendEmailHandler: passes reason/accountId on rejected; records resend_error: … on send_failed.
  • logEmailAttempt: writes reason only when set.
  • types/database.types.ts: adds the column.

Merge order

Merge and apply recoupable/database#132 first; this PR writes the new column. As a guard, inserts include reason only when there is one, so successful sends keep logging even if this deploys early. That matters because welcome, valuation and abandoned-checkout emails dedupe on sent rows.

Tests

Tests first: 8 new assertions failed before the change. pnpm vitest run lib/emails → 218 passed. Lint and Prettier clean on changed files.

🤖 Generated with Claude Code

POST /api/emails rejected 59% of logged sends with nothing to say why:
the rejected path stored only the raw body. validateSendEmailBody now
returns a reason (short code then detail) and the account once auth has
resolved it; sendEmailHandler passes both to logEmailAttempt, and the
send_failed path records the Resend error. Needs the email_send_log.reason
column (recoupable/database#132).

Refs recoupable/app#1949

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

vercel Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
api Ready Ready Preview Nov 7, 2026 4:43am UTC

Request Review

@coderabbitai

coderabbitai Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Important

  • Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

Run configuration

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

3 issues found across 8 files

Confidence score: 4/5

  • validateSendEmailBody.test.ts doesn’t verify the returned error response, so these tests could miss a broken caller-facing rejection contract. Assert the error branch, status, and parsed error payload.
  • sendEmailHandler.ts logs a generic Resend reason, making rate limits and other provider failures indistinguishable in email_send_log. Pass through a bounded provider code or detail.
  • validateSendEmailBody.ts treats account-email lookup failures as no_account_email, hiding infrastructure errors as missing data. Preserve the query error and record a distinct reason.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="lib/emails/__tests__/validateSendEmailBody.test.ts">

<violation number="1" location="lib/emails/__tests__/validateSendEmailBody.test.ts:256">
P2: These new error-path tests never assert the returned `NextResponse` envelope, so they do not protect the caller-facing rejection contract. Assert the `error` branch, expected status, and parsed `{ status: "error", error: expect.any(String) }` body in each rejection test (including `disallowed_recipients` for the 403 case).

(Based on your team's feedback about asserting validator error envelopes.) [3bbabfba-f1c6-4e42-9d18-d0036968bf66]</violation>
</file>

<file name="lib/emails/sendEmailHandler.ts">

<violation number="1" location="lib/emails/sendEmailHandler.ts:53">
P2: The logged Resend reason is always generic with the real adapter, so rate limits, validation failures, and other provider causes cannot be distinguished in `email_send_log`. Pass a bounded provider code/detail through `processAndSendEmail` while keeping the caller response redacted.</violation>
</file>

<file name="lib/emails/validateSendEmailBody.ts">

<violation number="1" location="lib/emails/validateSendEmailBody.ts:104">
P2: `no_account_email` also hides account-email lookup failures because `selectAccountEmails` converts database errors to an empty array. Preserve the query error and record a distinct infrastructure reason instead of mislabeling the rejection.</violation>
</file>
Architecture diagram
sequenceDiagram
    participant Client as API Caller
    participant Handler as sendEmailHandler
    participant Validator as validateSendEmailBody
    participant Auth as validateAuthContext
    participant DB as Database
    participant Resend as Resend Adapter

    Client->>Handler: POST /api/emails
    Handler->>Validator: validateSendEmailBody(request)
    Validator->>Validator: parse body against schema
    alt Invalid body
        Validator-->>Handler: rejected + reason: invalid_body
        Handler->>DB: logEmailAttempt(rejected, reason, no accountId)
    else Valid body
        Validator->>Auth: validateAuthContext(request)
        alt Auth fails
            Auth-->>Validator: 401 response
            Validator-->>Handler: rejected + reason: auth_failed: 401
            Handler->>DB: logEmailAttempt(rejected, reason)
        else Auth succeeds
            Auth-->>Validator: authContext (accountId)
            Validator->>Validator: check recipient gate
            alt Recipient not allowed
                Validator-->>Handler: rejected + reason: recipient_not_allowed + accountId
                Handler->>DB: logEmailAttempt(rejected, reason, accountId)
            else Recipient allowed
                alt No account email
                    Validator-->>Handler: rejected + reason: no_account_email + accountId
                    Handler->>DB: logEmailAttempt(rejected, reason, accountId)
                else Account email exists
                    Validator-->>Handler: { rawBody, data }
                    Handler->>Resend: processAndSendEmail(data)
                    alt Resend fails
                        Resend-->>Handler: send_failed + error
                        Handler->>DB: logEmailAttempt(send_failed, reason: resend_error, accountId)
                        Handler-->>Client: 502 response
                    else Resend succeeds
                        Resend-->>Handler: success
                        Handler->>DB: logEmailAttempt(sent, reason: null)
                        Handler-->>Client: 200 success response
                    end
                end
            end
        end
    end
Loading

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

{ "x-api-key": "k" },
);
const result = await validateSendEmailBody(request);
expect(result).toMatchObject({

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: These new error-path tests never assert the returned NextResponse envelope, so they do not protect the caller-facing rejection contract. Assert the error branch, expected status, and parsed { status: "error", error: expect.any(String) } body in each rejection test (including disallowed_recipients for the 403 case).

(Based on your team's feedback about asserting validator error envelopes.) [3bbabfba-f1c6-4e42-9d18-d0036968bf66]

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/emails/__tests__/validateSendEmailBody.test.ts, line 256:

<comment>These new error-path tests never assert the returned `NextResponse` envelope, so they do not protect the caller-facing rejection contract. Assert the `error` branch, expected status, and parsed `{ status: "error", error: expect.any(String) }` body in each rejection test (including `disallowed_recipients` for the 403 case).

(Based on your team's feedback about asserting validator error envelopes.) [3bbabfba-f1c6-4e42-9d18-d0036968bf66]</comment>

<file context>
@@ -240,4 +240,48 @@ describe("validateSendEmailBody", () => {
+        { "x-api-key": "k" },
+      );
+      const result = await validateSendEmailBody(request);
+      expect(result).toMatchObject({
+        reason: "recipient_not_allowed: stranger@example.com, other@example.com",
+        accountId: "account-123",
</file context>

status: "send_failed",
accountId,
chatId: chat_id,
reason: `resend_error: ${result.error}`,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: The logged Resend reason is always generic with the real adapter, so rate limits, validation failures, and other provider causes cannot be distinguished in email_send_log. Pass a bounded provider code/detail through processAndSendEmail while keeping the caller response redacted.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/emails/sendEmailHandler.ts, line 53:

<comment>The logged Resend reason is always generic with the real adapter, so rate limits, validation failures, and other provider causes cannot be distinguished in `email_send_log`. Pass a bounded provider code/detail through `processAndSendEmail` while keeping the caller response redacted.</comment>

<file context>
@@ -46,7 +46,12 @@ export async function sendEmailHandler(request: NextRequest): Promise<NextRespon
+        status: "send_failed",
+        accountId,
+        chatId: chat_id,
+        reason: `resend_error: ${result.error}`,
+      };
     } else {
</file context>

{ status: "error", error: "No email address found for the authenticated account." },
{ status: 400, headers: getCorsHeaders() },
),
reason: "no_account_email",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: no_account_email also hides account-email lookup failures because selectAccountEmails converts database errors to an empty array. Preserve the query error and record a distinct infrastructure reason instead of mislabeling the rejection.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/emails/validateSendEmailBody.ts, line 104:

<comment>`no_account_email` also hides account-email lookup failures because `selectAccountEmails` converts database errors to an empty array. Preserve the query error and record a distinct infrastructure reason instead of mislabeling the rejection.</comment>

<file context>
@@ -97,6 +101,8 @@ export async function validateSendEmailBody(
           { status: "error", error: "No email address found for the authenticated account." },
           { status: 400, headers: getCorsHeaders() },
         ),
+        reason: "no_account_email",
+        accountId: authContext.accountId,
       };
</file context>

Successful sends now leave the reason key out of the insert, so they keep
logging even if this deploys before email_send_log.reason exists. The
sent rows matter: welcome, valuation and abandoned-checkout emails dedupe
on them.

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

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

0 issues found across 2 files (changes from recent commits).

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Requires human review: Auto-approval blocked by 3 unresolved issues from previous reviews.

View guided diff | Turn on auto-fix | Re-trigger cubic

@sidneyswift
sidneyswift merged commit 02f2c5b into main Nov 7, 2026
7 checks passed
sidneyswift added a commit to recoupable/mono that referenced this pull request Nov 8, 2026
Records the merged monthly-onboarding and missed-report work:
recoupable/database#132, recoupable/api#1235 and #1236, and
recoupable/app#2392, #2393 and #2394, plus whatever else landed on those
mains since the last recorded commits.

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

This branch was successfully deployed

1 active deployment
Preview — 630caa3b Deployed Nov 7, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant