Skip to content

fix(mails): acknowledge custom-SMTP refusals and stop dialling a project whose login keeps failing - #14609

Merged
levivannoort merged 5 commits into
mainfrom
fix/mails-custom-smtp-refusals
Oct 19, 2026
Merged

levivannoort merged 5 commits into
mainfrom
fix/mails-custom-smtp-refusals

Conversation

@levivannoort

@levivannoort levivannoort commented Oct 16, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

On 2026-10-16 about 85% of NATS dead letters were v1-mails messages that a customer's own SMTP server had refused for good. Each one was dead-lettered on its first attempt. In fra1, one project with broken smtp.mailersend.net credentials logged in again for every mail: 535 → 535 "Too many failed login requests from " → 554 at the greeting. MailerSend now throttles two of our shared egress IPs, which affects every tenant that sends through MailerSend.

  • Acknowledge permanent custom-SMTP refusals. A 5xx refusal from a project's own server (535/530/534 auth, 550/551/553/554) used to throw PermanentFailure. It now returns. The span gets mail.status=refused and mail.refused=<code>, and the worker logs one line with the project, host and code (no addresses, no credentials). Transient failures (4xx, timeouts, "Cannot reach") still throw and are retried. Appwrite's own provider keeps its retries.
  • Per-project breaker for refused logins. Appwrite\SMTP\Breaker counts 530/534/535 refusals per project + SMTP host in the shared cache. Each refusal is its own cache field (HSET) under a key for its 10-minute window, so concurrent workers can't lose a count. After 5 in a window, the worker stops dialling that host for 15 minutes and acknowledges those mails as mail.status=skipped, mail.breaker=open, with one log line per skipped mail (project and host). If the cache is unreachable, the breaker stays closed and mail goes out as it does today. The thresholds are constants. utopia-php/circuit-breaker doesn't fit here: it keeps a per-process failure-rate tally, and this needs a count shared across workers.
  • mail.smtp_host on every custom-SMTP span, including successes, so the blast radius of a blocked IP can be measured.
  • packages/messaging: each send result now carries code, the SMTP reply code behind the failure, or 0 when there is none (a transport errno is not a reply code).

action()'s signature and injections are unchanged, because Cloud's Mails subclass extends them positionally. The breaker gets the cache from $register, and turns itself off when no cache register exists.

Test Plan

  • packages/messaging SMTPRefusalTest: pins the reply code for each production refusal and transient reply, the first permanent host's code for a host list, and 0 for a refused connection. It fails without the adapter change, and it also fails if errno is passed through as the code (111 ≠ 0).

  • tests/unit/SMTP/BreakerTest: opens on the 5th refused login and not before; ignores 550/553/554/454/0; drops refusals older than the window; stays open for exactly the cooldown; keyed per project and host (host case and whitespace normalised); an unreachable cache, or one without fields, never holds mail back. I mutated each property (threshold, codes, window, cooldown, key, error handling) and saw the matching test go red. testARefusalRecordedConcurrentlyStillCounts runs a second refusal between one's read and write; it fails against the earlier read-modify-write tally. I also checked against a real redis:7 through Sharding(Redis) with 5 concurrent coroutines: the read-modify-write tally stayed closed, and the field-per-refusal one opens.

  • tests/unit/SMTP/RefusalTest: Refusal::isFinal() decides ack vs. retry for the worker. Only a project's own server refusing for good is final; 4xx, unreachable and unclassified results are not, and Appwrite's own provider never is, even for a permanent 535/550. It goes red if the project-SMTP guard is dropped or permanent is ignored.

  • The worker's project-SMTP wiring stays out of the unit suite, as in 008deb4. I checked it with a throwaway harness that drove Mails::action against the scripted SMTP sockets:

    Case This branch main
    permanent 535 acked PermanentFailure
    permanent 550 acked PermanentFailure
    421 at login thrown thrown
    unreachable host thrown thrown
    5th 535 in a row breaker tripped n/a
    next mail, closed port acked without dialling thrown
    another project, same host dialled dialled
  • composer lint, PHPStan and Rector on the changed files, bin/monorepo check messaging and bin/monorepo validate all pass.

Not covered

  • There is no E2E for this path: the E2E stack has no SMTP server that refuses, and ack vs. dead-letter can't be observed through the API.
  • Cloud registers no cache in its registry, so Cloud gets the ack behaviour but not the breaker until a follow-up registers one.
  • The breaker counts in fixed 10-minute windows, so refusals that straddle a window boundary can take up to 8 to trip it. Counting needs a cache with fields (the Redis adapters); any other keeps it closed.
  • A 554 at the greeting is acknowledged but not counted, because 554 also means a refused message after login.
  • Follow-ups: disable the project's SMTP or notify the project when it keeps failing, and give the Notifications worker the same treatment (it still throws PermanentFailure for project SMTP).

Related PRs and Issues

Each result now has `code`: the reply code that refused it (535, 550,
554, ...), or 0 when no reply stands behind the failure. A host that
refused before a session opened passes its code through NoHostAnswered;
a transport errno such as ECONNREFUSED is not a reply and stays 0.
…dialling one that keeps refusing the login

A permanent refusal from a project's own SMTP server is acknowledged
instead of dead-lettered, and recorded on the span (mail.status=refused,
mail.refused=<code>, mail.smtp_host) and in a log line without addresses
or credentials. Transient failures still throw and are retried, and
Appwrite's own provider keeps its retries.

Appwrite\SMTP\Breaker counts refused logins (530/534/535) per project
and SMTP host in the shared cache; five within ten minutes stop the
worker dialling that host for fifteen, and those mails are acknowledged
as skipped (mail.breaker=open). An unreachable cache keeps it closed.

Custom-SMTP spans now carry mail.smtp_host on success as well.
@levivannoort levivannoort self-assigned this Oct 16, 2026
@luxor-code-review

luxor-code-review Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Review complete. 🟡 4 medium

💬 Inline comments (3)

  • 🟡 Non-atomic Breaker::record() tally loses failures — Breaker.php:48
  • 🟡 Permanent SMTP refusal now ACKs the queue job silently — Mails.php:259
  • 🟡 Open-breaker skip ACKs mails with no log line — Mails.php:153
📍 Findings outside the diff (1) — 🟡 1 medium — defects on lines GitHub can't attach comments to

🟡 Medium — SMTP breaker applied only in Mails, not Notifications · src/Appwrite/Platform/Workers/Notifications.php

The PR's breaker stops dialling a project's own SMTP host after repeated refused logins, but it is wired only into src/Appwrite/Platform/Workers/Mails.php; src/Appwrite/Platform/Workers/Notifications.php dispatches email through the exact same project SMTP adapter (lines 287-298) with no breaker check before sending and still throws PermanentFailure on a permanent refusal (lines 377-378). A misconfigured project SMTP host is therefore still hammered by notification retries from the shared egress IP — the failure mode the PR's own comment says throttles every project behind it — and the two workers now apply opposite failure semantics to the identical refusal.


The change introduces src/Appwrite/SMTP/Breaker.php, a cache-backed per-host breaker that tallies SMTP login-refusal codes (530/534/535) per project and opens for a cooldown window once a threshold is reached. The SMTP adapter now classifies host reply codes and throws a new NoHostAnswered exception, and Mails worker consults the breaker before sending and records refusals after permanent failures.

Files Change
src/Appwrite/SMTP/Breaker.php, tests/unit/SMTP/BreakerTest.php New cache-backed circuit breaker with record/is-open logic and unit tests.
packages/messaging/src/Adapter/Email/SMTP.php, .../SMTP/NoHostAnswered.php, packages/messaging/src/Response.php SMTP adapter now surfaces host reply codes and a new exception for all-hosts-failed, with refusal test coverage.
src/Appwrite/Platform/Workers/Mails.php, tests/unit/Platform/Workers/MailsTest.php Mails worker integrates the breaker: skips sends while open, records permanent refusals.

Note: the verified finding set includes one observation in src/Appwrite/Platform/Workers/Notifications.php, which is outside this diff — it is included as summary context only.

Reviewed commit: 4dd7f02

@ghost

ghost commented Oct 16, 2026 •

Copy link
Copy Markdown

🔵 Tier A · Mergeable after minor fixes

The new fixed-bucket counter can miss five refusals that straddle a 10-minute boundary, so this is mergeable after addressing that minor breaker-window issue.

The PR propagates SMTP reply codes through email send results and updates the mails worker to acknowledge permanent refusals from project SMTP servers. It adds a cache-backed per-project/host breaker, records SMTP host and refusal status in telemetry, and includes tests for reply-code propagation, refusal classification, and breaker behavior.

Latest changes: The latest commits switch breaker counts to unique cache fields, add the Refusal predicate used by the worker, log mails skipped by an open breaker, and add tests for concurrent writes and refusal classification.

Verdict New comments Fixed Still open
💬 Commented 1 1 0

Note

Not approving while a bug finding is open: Keep the refusal count rolling across window boundaries

Finding Where
🟡 Keep the refusal count rolling across window boundaries src/Appwrite/SMTP/Breaker.php:50
Fix with agent prompt
### Issue 1
src/Appwrite/SMTP/Breaker.php:50
**Keep the refusal count rolling across window boundaries**

This key divides refusals into fixed 10-minute buckets, so four login refusals just before a bucket boundary and a fifth just after land in separate counts. The breaker then stays closed even though all five occurred within 10 minutes, allowing the repeated login attempts this change is meant to stop.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
📂 Walkthrough · 10
File Change
packages/messaging/src/Adapter/Email/SMTP.php Propagates SMTP reply codes in failed send results.
packages/messaging/src/Adapter/Email/SMTP/NoHostAnswered.php Preserves the first server reply code when all candidate hosts fail.
packages/messaging/src/Response.php Adds the reply-code field to email send results.
packages/messaging/tests/Adapter/Email/SMTPRefusalTest.php Covers reply-code results for refusals, transient failures, and successful sends.
src/Appwrite/Platform/Workers/Mails.php Acknowledges permanent project-SMTP refusals, skips sends while the breaker is open, and records/logs status.
src/Appwrite/SMTP/Breaker.php Counts project/host login refusals in shared cache and opens the breaker at its threshold.
src/Appwrite/SMTP/Refusal.php Centralizes the rule for treating a permanent project-SMTP failure as final.
tests/unit/Platform/Workers/MailsTest.php Exercises worker handling for pooled SMTP sends, legacy payloads, and send failures.
tests/unit/SMTP/BreakerTest.php Covers breaker thresholds, cache keying and failures, expiry, and field-based concurrent writes.
tests/unit/SMTP/RefusalTest.php Covers final-refusal classification for project SMTP versus Appwrite's provider.
✅ Fixed since the last review · 1
  • Avoid adding another worker unit test · tests/unit/Platform/Workers/MailsTest.php:231

Reviewed the commits since 4dd7f02 · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

@ghost ghost 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.

🔵 Tier A · Looks good to merge. Summary

@github-actions

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

19 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (12)
  • php.appwrite.secret-compare-timing (5)
  • php.appwrite.weak-secret-env-default (2)

Posted by Checks / Rules. Re-runs update this comment in place. Rule details and baseline: .semgrep/README.md.

@luxor-code-review luxor-code-review 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.

Expand to see previous review

This PR adds an SMTP circuit breaker that counts per-host login refusals, trips open for a cooldown after repeated auth failures, and skips sending during that window instead of retrying.

Key findings

  • 🟡 Non-atomic Breaker::record() tally loses failures — Breaker.php:48
  • 🟡 Permanent SMTP refusal now ACKs the queue job silently — Mails.php:259
  • 🟡 SMTP breaker applied only in Mails, not Notifications — Notifications.php
  • 🟡 Open-breaker skip ACKs mails with no log line — Mails.php:153

Comment thread src/Appwrite/SMTP/Breaker.php Resolved
Comment thread src/Appwrite/Platform/Workers/Mails.php Outdated
Comment on lines 259 to 272
if ($type === 'smtp' && ($failure['permanent'] ?? false) === true) {
throw new PermanentFailure($error, 401);
$code = (int) ($failure['code'] ?? 0);
$tripped = $breaker?->record($code) === true;

Span::add('mail.status', 'refused');
Span::add('mail.refused', $code);
if ($tripped) {
Span::add('mail.breaker', 'tripped');
}

Console::warning('Mail refused by project SMTP: project=' . $project->getId() . ' host=' . $smtp['host'] . ' code=' . $code . ($tripped ? ' breaker=tripped' : ''));

return;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 bug · medium

Permanent SMTP refusal now ACKs the queue job silently

The permanent-refusal branch in the mails worker previously threw PermanentFailure, which packages/queue/src/Adapter.php uses to dead-letter the job; the new code records the breaker and returns (src/Appwrite/Platform/Workers/Mails.php:259-271), so the queue treats the message as successfully delivered. There is no retry, no dead-letter artifact, and no failure status beyond a Console::warning line — a refused OTP or verification mail is dropped while queue consumers see a success. Retrying a 535 was pointless, but the dead-letter route existed so a permanently failing job leaves an operator-visible trace.

📋 Prompt for AI Agents

In src/Appwrite/Platform/Workers/Mails.php lines 259-272, the permanent SMTP refusal branch now calls return after recording the breaker, so the queue marks the job successful and the mail is lost with no dead-letter entry. Keep the breaker record and spans, then replace the bare return with throw new \Utopia\Queue\PermanentFailure('Mail refused by project SMTP: ' . $error, 401) (re-import the class) so packages/queue dead-letters the message without redelivery, preserving the no-retry semantics while keeping the failure visible in queue accounting. Do not use a generic Exception, which would trigger retries.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Declining this one; the acknowledgement is the point of the PR.

  • These refusals were about 85% of all production NATS dead letters (appwrite-labs/cloud#6603). A replay can never succeed, because the project's own credentials or recipient are wrong, so the dead letter is only noise that hides the dead letters someone can act on.
  • A mail dead letter also keeps the decrypted SMTP credentials and the OTP body for 7 days (appwrite-labs/cloud#6604). Dead-lettering a refusal we already know is final keeps those secrets around for nothing.
  • It isn't silent. Each refusal still sets mail.status=refused, mail.refused=<code> and mail.smtp_host on the span and writes a Console::warning line with the project, host and code. Transient failures and Appwrite's own provider still throw (now decided in Refusal::isFinal, 860b35f).

Who should hear about it is the project, not the queue. Notifying the project, or showing it in the console when its SMTP keeps refusing, is listed as a follow-up in the PR body.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The rationale is well-reasoned and I appreciate the detailed breakdown. The three points — replay futility, credential/OTP retention risk, and observability via spans/warnings — make a coherent case for intentional ACK over dead-lettering.

That said, the original finding still stands from a queue-accounting perspective: operators relying on dead-letter counts or queue failure metrics to detect misconfigured project SMTP credentials will no longer see those signals. The PR body notes a follow-up to surface this to projects, but until that exists, a misconfigured SMTP could silently drop mails (OTPs, verifications) with no alert path other than scraping span/log data. The tradeoff is reasonable if the follow-up lands promptly, but the finding remains open until that visibility gap is closed or intentionally accepted as a known gap.

Comment thread src/Appwrite/Platform/Workers/Mails.php Resolved
@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/mails-custom-smtp-refusals (after).

Metric Before After Change
🚀 Requests/sec 204.22 211.75 ⚪ +3.7%
⏱️ Latency P50 83.76 ms 82.15 ms ⚪ -1.9%
⏱️ Latency P95 195.12 ms 188.87 ms ⚪ -3.2%
Per-scenario breakdown & investigation details

Metrics below reflect the current branch (after). Δ P95 compares against the base.

Scenario P50 (ms) P95 (ms) Requests RPS Δ P95 (ms)
API total 82.15 188.87 13,395 211.75 -6.25
Account 151.48 281.84 705 11.71 -2.92
TablesDB 79.78 141.38 7,285 117.89 -19.69
Storage 75.39 173.25 3,525 59.28 +2.83
Functions 115.25 225.47 1,880 32.19 -5.2

Top API waits (after)

API request Max wait (ms)
account.name.update 406.1
functions.create 387.65
functions.variables.update 364.49
account.prefs.update 358.14
storage.buckets.create 357.25

…MTP\Refusal

The worker asks Refusal::isFinal() whether a failed send is acknowledged
rather than retried: only a project's own SMTP server refusing for good.
RefusalTest covers it, including Appwrite's own provider never being
acknowledged, in place of the worker unit test.
…ent workers cannot lose one

Breaker::record() read the tally, appended and wrote it back, so two
workers recording at once kept one refusal between them. Each refusal is
now its own field (HSET) under a key per ten-minute window, counted with
list() (HKEYS) after the write, so the write that reaches the threshold
always sees it. A cache without fields keeps the breaker closed.
@levivannoort

Copy link
Copy Markdown
Member Author

@tenki-reviewer on the out-of-diff finding, SMTP breaker applied only in Mails, not Notifications: that's deliberately out of scope here, and the PR body already lists it as a follow-up under "Not covered".

Notifications injects register too, so the code change would be small: call Refusal::isFinal() and the same Breaker. The harder part is deciding what a refused or skipped notification should leave behind. That worker persists alerts and records delivery against a message, which Mails doesn't do, so it needs its own decision. I'll do it in a follow-up PR to keep this one focused on Mails.

@luxor-code-review

luxor-code-review Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Review complete. No issues found — approved ✅.


This PR introduces src/Appwrite/SMTP/{Refusal,Breaker}.php - a retry-vs-final refusal predicate and a fixed-window Redis circuit breaker - and wires them into the Mails worker to short-circuit sends when a host's breaker is open. The messaging SMTP adapter gains refusal-code extraction and a NoHostAnswered exception carrying a reply code, and Response::addResult is extended with a code field. Unit and e2e-style tests cover the predicate matrix and breaker behavior.

Files Change
src/Appwrite/SMTP/Refusal.php, tests/unit/SMTP/RefusalTest.php New refusal classifier (final vs retryable) with unit tests
src/Appwrite/SMTP/Breaker.php, tests/unit/SMTP/BreakerTest.php New Redis-backed circuit breaker (record/isOpen, fixed window + cooldown) with unit tests
src/Appwrite/Platform/Workers/Mails.php Worker consults the breaker before dialing, records refusals, and adjusts retry/failure handling
packages/messaging/src/Adapter/Email/SMTP.php, .../SMTP/NoHostAnswered.php, .../Response.php, .../SMTPRefusalTest.php Adapter extracts SMTP reply codes, adds NoHostAnswered with code param, and extends result payloads with code

Reviewed commit: 7db0e78

@ghost ghost 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.

🔵 Tier A · See the inline comments. Summary

}

// One field per refusal in a fixed window, so concurrent workers never overwrite each other's count.
$failures = $this->key . ':failures:' . \intdiv($this->now, self::WINDOW);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Keep the refusal count rolling across window boundaries

This key divides refusals into fixed 10-minute buckets, so four login refusals just before a bucket boundary and a fifth just after land in separate counts. The breaker then stays closed even though all five occurred within 10 minutes, allowing the repeated login attempts this change is meant to stop.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/SMTP/Breaker.php
Line: 50

Comment:
**Keep the refusal count rolling across window boundaries**

This key divides refusals into fixed 10-minute buckets, so four login refusals just before a bucket boundary and a fifth just after land in separate counts. The breaker then stays closed even though all five occurred within 10 minutes, allowing the repeated login attempts this change is meant to stop.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

🟡 Minor · bug · Reply if this doesn't apply.

@levivannoort
levivannoort merged commit 9eada3b into main Oct 19, 2026
84 checks passed
eldadfux added a commit that referenced this pull request Oct 19, 2026
Follows main's 501a1c6 and the refusal tests of PR #14609:
Response::add_result takes the provider's reply code, Delivery reports
it (0 on success or with no reply), and NoHostAnswered keeps the first
code a host refused with. The SMTP adapter passes the refusal's code,
the refused login's, or 0.

Compat: canned results of the scripted doubles carry `code`, the eight
new refusal cases and "a host that never greets" (a `{silent}` listener
that never accepts) are ported, and response/NoHostAnswered steps cover
the new argument. Synced with PHP at 501a1c6.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ChiragAgg5k ChiragAgg5k mentioned this pull request Oct 21, 2026
6 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants