Repository navigation
fix(mails): acknowledge custom-SMTP refusals and stop dialling a project whose login keeps failing - #14609
Conversation
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.
|
Review complete. 🟡 4 medium 💬 Inline comments (3)
📍 Findings outside the diff (1) — 🟡 1 medium — defects on lines GitHub can't attach comments to🟡 Medium — SMTP breaker applied only in The PR's breaker stops dialling a project's own SMTP host after repeated refused logins, but it is wired only into The change introduces
Note: the verified finding set includes one observation in Reviewed commit: 4dd7f02 |
🔵 Tier A · Mergeable after minor fixes
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.
Note Not approving while a bug finding is open: Keep the refusal count rolling across window boundaries
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
✅ Fixed since the last review · 1
Reviewed the commits since |
Security rulesNo new WARNING or ERROR findings from security rules. 19 existing findings tracked in
|
There was a problem hiding this comment.
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, notNotifications— Notifications.php - 🟡 Open-breaker skip ACKs mails with no log line — Mails.php:153
| 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; | ||
| } |
There was a problem hiding this comment.
🟡 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.
There was a problem hiding this comment.
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>andmail.smtp_hoston the span and writes aConsole::warningline with the project, host and code. Transient failures and Appwrite's own provider still throw (now decided inRefusal::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.
There was a problem hiding this comment.
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.
✨ Benchmark resultsComparing
Per-scenario breakdown & investigation detailsMetrics below reflect the current branch (after). Δ P95 compares against the base.
Top API waits (after)
|
…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.
|
@tenki-reviewer on the out-of-diff finding, SMTP breaker applied only in
|
|
Review complete. No issues found — approved ✅. This PR introduces
Reviewed commit: 7db0e78 |
| } | ||
|
|
||
| // 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); |
There was a problem hiding this 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.
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.
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]>
What does this PR do?
On 2026-10-16 about 85% of NATS dead letters were
v1-mailsmessages 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.PermanentFailure. It now returns. The span getsmail.status=refusedandmail.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.Appwrite\SMTP\Breakercounts 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 asmail.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-breakerdoesn't fit here: it keeps a per-process failure-rate tally, and this needs a count shared across workers.mail.smtp_hoston every custom-SMTP span, including successes, so the blast radius of a blocked IP can be measured.packages/messaging: each send result now carriescode, 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'sMailssubclass extends them positionally. The breaker gets the cache from$register, and turns itself off when nocacheregister exists.Test Plan
packages/messagingSMTPRefusalTest: 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.testARefusalRecordedConcurrentlyStillCountsruns a second refusal between one's read and write; it fails against the earlier read-modify-write tally. I also checked against a realredis:7throughSharding(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 orpermanentis 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::actionagainst the scripted SMTP sockets:mainPermanentFailurePermanentFailurecomposer lint, PHPStan and Rector on the changed files,bin/monorepo check messagingandbin/monorepo validateall pass.Not covered
cachein its registry, so Cloud gets the ack behaviour but not the breaker until a follow-up registers one.Notificationsworker the same treatment (it still throwsPermanentFailurefor project SMTP).Related PRs and Issues