Repository navigation
Fix certificate retry recovery and stale worker updates - #13467
HarshMN2345 wants to merge 26 commits into
Conversation
Deletes::deleteRule handed Provider::deleteCertificate only the hostname, so the certificate proxy fell back to the custom-domain providers. Since the move to utopia-php/cdn those providers skip domains owned by another Fastly service, which left site and redirect domains with their remote certificate and domain record after the rule was deleted. Pass the same domain type the issue path uses so cleanup reaches the provider that issued the certificate.
DNS verification retries on its own interval, but issuance had no equivalent: a rule whose generation failed was left at 'unverified', a status nothing scans, so a single transient issuer error stranded the domain until someone pressed retry in the Console. The maintenance renewal loop could not help either, because it re-queues certificates by renewDate and a delayed issuer stores none until the certificate is actually issued. Even when something did re-queue such a rule, the worker refused it: the guard accepted only 'verifying' and 'verified', so every retry was a silent no-op. Accept a failed rule and move it back to generating for the attempt, so a delayed issuer that leaves the status untouched on success still ends up in the state the Console and the status sync read as in progress. Automatic retries are capped by the attempt limit the renewal loop already used, now shared as a constant; a retry asked for from the Console resets the rule first and is always attempted.
|
…ones Two problems with the retry scan, both raised in review. An attempt writes the rule only when it finishes, so a rule stayed durably failed for the whole of issuance and the next scan could queue a second job for the same domain. Two workers then called the issuer concurrently, racing the certificate write and double-counting the attempt. Hold back rules touched within one interval, which is the window an in-flight attempt occupies. An exhausted certificate also kept producing a job every five minutes for the rest of the window, which the worker could only skip. Read the certificate before queueing and stop at the shared attempt limit, and count those separately from the ones actually queued.
✨ Benchmark resultsComparing
Per-scenario breakdown & investigation detailsMetrics below reflect the current branch (after). Δ P95 compares against the base.
Top API waits (after)
|
|
Both review findings were valid. Fixed in Retries lack a durable claim. Confirmed: the worker sets the rule back to generating in memory, and the only write is in $claimedUntil = new DateTime('-' . $this->certificateGenerationInterval() . ' seconds');
...
Query::updatedBefore(DatabaseDateTime::format($claimedUntil)),Since that Exhausted retries remain scheduled. Confirmed: $certificate = $dbForPlatform->getDocument('certificates', $rule->getAttribute('certificateId', ''));
if ($certificate->getAttribute('attempts', 0) >= APP_LIMIT_CERTIFICATE_ATTEMPTS) {
$skipped++;
continue;
}These are counted as Pint and PHPStan (level 4) pass on the changed file. Generated by Claude Code |
Filtering on the rule's last write narrowed the duplicate-enqueue window but did not close it: the worker writes the rule only once the issuer answers, and an issuer call or a queue wait can outlast a tick, so a second pass could still queue the same domain and race the first. Claim the rule when the job is handed off instead. The status is left alone, so a lease that is never used simply lapses and the rule returns on a later pass, rather than moving to a state nothing scans and stranding it there.
|
Fair — the second review is right that filtering on // Take the lease before handing the job off. The worker writes the
// rule only once the issuer answers, which can outlast a tick, so
// claiming here is what keeps a second pass from queueing the same
// domain. The rule keeps its failed status, so a lease that is
// never used lapses and the rule comes back on a later pass
// instead of being stranded in a state nothing scans.
$dbForPlatform->updateDocument('rules', $rule->getId(), new Document([
'$updatedAt' => DatabaseDateTime::now(),
]));The scan already selects on The reason this is a timestamp lease rather than a status transition is worth stating, since a status claim is the more obvious design. Moving the rule to Note this is deliberately per-region, matching the scan's Pint and PHPStan (level 4) pass on the changed file. Generated by Claude Code |
Deriving the lease from the scan interval tied two unrelated things together: how often failed domains are looked for, and how long one attempt may take. A five minute lease expired under any issuance that ran longer, putting the rule back in the result set while its job was still in flight. Give the lease its own duration, long enough to cover a queue wait plus an issuer call. Scanning stays frequent, so a domain that has just failed is still found quickly.
|
Third pass is right about the residual, and it pointed at a real design mistake rather than the same thing again: I had derived the lease from the scan interval, which ties together two unrelated quantities — how often we look for failed domains, and how long one attempt may take. A five-minute lease expires under any issuance that runs longer. Fixed in /**
* How long a queued retry holds its rule. It has to outlast a whole attempt
* — the queue wait plus the issuer call — or a slow attempt becomes eligible
* again while it is still running and picks up a second job. It is also the
* gap between attempts, since finishing one writes the rule too.
*/
private const int CERTIFICATE_GENERATION_LEASE = 900; // 15 minutesThe scan still ticks every five minutes, so a domain that has just failed is found quickly; the lease is now sized to an attempt instead. Fifteen minutes against a On the remaining theoretical window, and why I am not closing it with a status claim. Any timestamp lease can be outlived by a sufficiently pathological attempt. The alternative — having the worker persist
So the trade is: a bounded, self-healing lease that can in principle double-issue under a pathological delay, versus a precise claim that can strand a domain permanently. Given what the providers actually do on a duplicate, the lease is the safer end:
The one provider a duplicate would actually hurt is the one least able to outlive the lease. I would rather leave that narrow window open than trade it for a state a domain cannot get out of. Pint and PHPStan (level 4) pass on the changed file. Generated by Claude Code |
|
This one I'm declining, with reasoning rather than a push. The fourth pass moves from "issuance outlasts the lease" (fixed in
The stronger evidence is what the neighbouring scanners do. So the accurate statement is that the new task is already strictly more defensive than the two scanners it sits beside. Making it atomically claim while its siblings do not would be inconsistent, and a real fix for multi-instance scheduling belongs in one change covering all three — with a compare-and-swap or an advisory lock — not bolted onto the one task that happens to be under review. I'd rather leave a documented, bounded window than add machinery for a topology the repo does not deploy. Happy to be overruled by anyone who knows of a deployment that does run the interval task with replicas — that would change the answer, and I'd take the follow-up across all three scanners. Generated by Claude Code |
|
The suite died in A 30-second timeout waiting on the orchestrator, in Worth being explicit about what the change can and cannot reach in this environment: self-hosted CI issues through Let's Encrypt, which is an instant issuer, so the delayed-issuance branch this PR modifies is never taken. The new interval task runs in I have not ported a fix, because there is nothing to port — this is an infrastructure timeout, not a defect with a known change behind it. The one re-run I'm allowed is not yet spent: Generated by Claude Code |
|
Correcting my own Test Plan above. I wrote that no test can reach these paths and left it there, which meant nothing in this PR had actually executed the changed code — CI is green, but the delayed-issuance branch and the interval task are both unreachable from e2e, so green says nothing about this change. I've now driven both against stubs locally and checked each is non-vacuous by reverting the file to Worker guard — three cases through
The first row is the bug this PR fixes, reproduced: on Interval task — five cases driving the registered Against a I have deliberately not committed these, because Generated by Claude Code |
The attempt cap could never be reached on a delayed issuer. Accepting the request is not the same as issuing the certificate: Fastly answers "pending" and the worker took that as success, resetting attempts to 0. The status sync then failed the rule, the retry task picked it up again, and the next attempt reset the counter once more. Every failure that resolves outside the worker — the customer never adding the ACME challenge record being the common one — therefore retried forever, at the lease interval, for as long as the rule stayed inside the scan window. Only a first or Console-driven issuance clears the counter now; an automatic retry increments it, so the cap engages and the loop terminates. Instant generation is unchanged: the certificate exists, so the counter still resets.
The added comments were prose paragraphs where this file uses terse single-line notes. Same meaning, a third of the lines.
…y' into domain-ssl-generation-fail-cbysyy
The env lookup went through a single-use private method and a class constant, while the domain verification task three lines above reads its own interval inline with a literal default. Two idioms for one job.
e8c64cf to
fa44bbf
Compare
151ce35 to
fda4204
Compare
Import Status instead of repeating its fully qualified name, restore the skip warning when a rule is missing, and follow the sibling task's quoting and counter style.
Wrap the action call to match the sibling worker tests, and name the queued-domain projection that both interval assertions repeat.
Every other shared double in tests/unit sits in a directory that also holds tests rather than in a separate bucket, so follow that here.
Two call sites do not justify a helper; read the events where they are asserted instead.
|
Sites passed on the three preceding heads and fails on this one:
The delta between the last green head and the failing one contains no production code: Two file renames with a namespace change, one wrapped call, one inlined local. Nothing under Paths I checked in the PR's actual diff before concluding that, since Sites does exercise rule creation and deletion:
Blocking issue on evidence. I could not read the failing assertion. The job log API returns at most ~5000 lines from the end, and the PHPUnit block sits behind a much larger I have not ported a fix because there is no change to port — the failing range contains no production code. For context, My one re-run is spent and it reproduced, so I am not re-running again. If someone with access to the full log can pull the failing test name I will take it from there; otherwise I will keep watching the PR until it is green. Generated by Claude Code |
|
Following up on my earlier note about Sites is failing on
My previous comment argued this from the diff range instead, on the grounds that the delta between the last green head and the failing one contained no production code. That reasoning no longer covers it — the PR has since merged There is no fix to port: Flagging it here mainly so it is visible to whoever owns #13515: Sites appears to have broken on Generated by Claude Code |
The CLI returned silently when another issuance held the lease, leaving an operator with no output between the two Console::info branches.
|
CI is green — 46/46 on Sites. It passed on run 34200247908. My earlier comment said it was "failing on Migrations failed once, and it was container startup rather than a test: MongoDB could not bind its port on the runner, so the job exited after 62 seconds without running a single test. Re-ran it once and it passed. I had guessed the cause was the new PostgreSQL test fixture leaking schemas, since Generated by Claude Code |
|
Heads up on a merge interaction with #13539, which also edits The two changes are independent in substance — #13539 fixes the DNS verification stage ( Those deletions do not overlap any hunk in this PR, so git will merge them without reporting a conflict and Generated by Claude Code |
Resolves the one conflict in src/Appwrite/Platform/Workers/Certificates.php.
main still calls notifyError() inline from the catch block; this branch
defers it to the finally block so a stale worker that loses the lease
sends no admin email. Kept the branch's `$error = $e;` and dropped main's
inline call.
main also added a sixth `Document $console` parameter to notifyError().
The deferred call now passes `$dbForPlatform->getDocument('projects',
'console')` to match, which the merge would otherwise have left one
argument short.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MeytoiisEusFMCU44PDYav
…the queue generateCertificate() commits the $updatedAt claim in its own transaction and then publishes. If the publish fails the claim stays, so Query::updatedBefore() skips the rule until the full 15-minute lease expires even though no worker was ever given the job — the 5-minute scheduler misses two passes for nothing. Publisher::enqueue() returns string|bool, so a rejected publish returns false without throwing. That path also counted toward interval.certificate_generation .processed, making the span say a job was dispatched when none was. Both cases now hand the claim back: $updatedAt is restored to the value it held before the claim, under the same forUpdate lock and only when the row is still the one this tick claimed, so a concurrent retry or status poll is never clobbered. A release that itself fails is swallowed — the lease expiry remains the backstop. Reported by Greptile on #13467. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01MeytoiisEusFMCU44PDYav
…the queue generateCertificate() commits the $updatedAt claim in its own transaction and then publishes. If the publish fails the claim stays, so Query::updatedBefore() skips the rule until the full 15-minute lease expires even though no worker was ever given the job — the 5-minute scheduler misses two passes for nothing. Publisher::enqueue() returns string|bool, so a rejected publish returns false without throwing. That path also counted toward interval.certificate_generation .processed, making the span say a job was dispatched when none was. Both cases now hand the claim back: $updatedAt is restored to the value it held before the claim, under the same forUpdate lock and only when the row is still the one this tick claimed, so a concurrent retry or status poll is never clobbered. A release that itself fails is swallowed — the lease expiry remains the backstop. Reported by Greptile on #13467. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01MeytoiisEusFMCU44PDYav
main dropped one of the getDB callables from Deletes::action(), leaving it at 18 parameters. DeletesTest still passed 19, so every argument from the sixth onward landed one position early — a closure arrived where Device $deviceForFiles was expected. PHPStan caught it in CI as "invoked with 19 parameters, 18 required"; it was invisible locally because this container cannot install composer.lock (the project now needs PHP 8.5+ and the sandbox has 8.4), so the vendored dependencies still carry the old signature. The split PRs #13570-#13573 drive this worker through the registered worker and the real DI container instead of a hand-written argument list, so none of them had to change. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01MeytoiisEusFMCU44PDYav
| if ((!empty($previous) && new \DateTime($previous) > new \DateTime('-' . APP_CERTIFICATE_GENERATION_LEASE . ' seconds')) | ||
| || ($certificate->getAttribute('attempts', 0) >= APP_LIMIT_CERTIFICATE_ATTEMPTS | ||
| && $current->getAttribute('status') === RULE_STATUS_CERTIFICATE_GENERATION_FAILED)) { | ||
| return null; |
There was a problem hiding this comment.
If provider issuance remains in progress for more than 15 minutes, the next worker replaces the expired lease and calls
issueCertificate while the first worker is still active, causing duplicate provider orders and racing attempt and completion state.
Knowledge Base Used: Background processing and scheduling
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/Platform/Workers/Certificates.php
Line: 275-278
Comment:
If provider issuance remains in progress for more than 15 minutes, the next worker replaces the expired lease and calls `issueCertificate` while the first worker is still active, causing duplicate provider orders and racing attempt and completion state.
**Knowledge Base Used:** [Background processing and scheduling](https://app.greptile.com/appwrite/-/custom-context/knowledge-base/appwrite/appwrite/-/docs/background-processing.md)
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.There was a problem hiding this comment.
The mechanism is real, but the consequence is narrower than described, and I'm not changing it here — reasoning below so a reviewer can overrule me.
Confirmed: the lease is a fixed APP_CERTIFICATE_GENERATION_LEASE (900s) token written at claim time and never renewed. The attempt reservation just before the provider call re-checks the lease but deliberately does not refresh it, because the original token has to survive for the finally comparison. So an issueCertificate() that runs longer than the remaining lease does let a second worker claim and call the provider again.
Not confirmed — "racing attempt and completion state". Completion is gated on the claim token:
$latest = $dbForPlatform->getDocument('certificates', $certificate->getId(), forUpdate: true);
if ($latest->isEmpty()
|| $latest->getSequence() !== $certificate->getSequence()
|| $latest->getAttribute('updated') !== $lease) {
return null;
}An overtaken worker writes no status, no certificateId, no logs, and sends no events or admin email. Attempt accounting is likewise reserved under the lock against the same token. The residual cost is a duplicate provider order — real, but it cannot corrupt rule or certificate state.
Why the expiry stays. It is the crash-recovery mechanism this PR exists to add: without it, a worker that dies mid-issuance holds the domain forever, which is the original bug. Removing the expiry or making it unbounded reinstates exactly that.
Closing the overlap properly means renewing the lease during a synchronous provider call — a timer or coroutine heartbeat. That's a design addition rather than a patch, so I'd rather surface it than bolt it on unilaterally. In the meantime _APP_CERTIFICATE_GENERATION_LEASE is configurable, and it needs to exceed worst-case provider issuance time; for the Fastly TLS path issueCertificate() creates a subscription and returns rather than blocking for the order.
Worth noting the same lease logic reviewed as 5/5 with no finding on #13573, which is the PR that actually ships this change; this one is superseded by #13570–#13573.
Generated by Claude Code
There was a problem hiding this comment.
You're right — my original wording overstated the impact. The sequence and lease-token checks in finally prevent an overtaken worker from persisting attempts, status, certificateId, or logs, and the notification/event path is also gated on a successful save. The confirmed residual issue is duplicate provider issuance when issueCertificate() outlives the fixed lease, not corrupted application state. Given the Fastly provider returns after creating the subscription and the lease is configurable, this is an operational constraint rather than a correctness issue for this PR. I withdraw the finding; no change is needed here.
…the queue generateCertificate() commits the $updatedAt claim in its own transaction and then publishes. If the publish fails the claim stays, so Query::updatedBefore() skips the rule until the full 15-minute lease expires even though no worker was ever given the job — the 5-minute scheduler misses two passes for nothing. Publisher::enqueue() returns string|bool, so a rejected publish returns false without throwing. That path also counted toward interval.certificate_generation .processed, making the span say a job was dispatched when none was. Both cases now hand the claim back: $updatedAt is restored to the value it held before the claim, under the same forUpdate lock and only when the row is still the one this tick claimed, so a concurrent retry or status poll is never clobbered. A release that itself fails is swallowed — the lease expiry remains the backstop. Reported by Greptile on #13467.
Failed certificate issuance could stay permanently unverified, and retries could be skipped behind old or exhausted records. This change retries eligible failures regardless of rule creation age, counts each provider issuance once, and lets explicit Console/CLI retries start a fresh attempt budget after validation.
A row-locked, 15-minute issuance lease prevents duplicate generation and stale completion from overwriting a newer retry or recreated rule. A five-minute scheduler recovers failed rules and generating jobs whose lease expired, skipping Appwrite-owned domains when automatic issuance is disabled. Completion clears the lease; confirmed issuance resets attempts.
Attempt accounting reserves the try before calling the provider, so a crash still consumes it, while a failure before issuance counts once rather than twice. A crash on the final attempt is still reconciled — the certificate may exist at the provider — but cannot start another issuance; that requires an explicit retry. Renewal scans page through due certificates and spend the 200-job Let's Encrypt budget on jobs actually scheduled rather than on rows skipped.
Deletion preserves provider TLS and routing when a domain has been recreated, and removes the certificate record only once no rule references it, so a replaced certificate stops scheduling renewals.
Testing
All coverage is e2e.
tests/e2e/General/Certificates/drives the worker, the interval and maintenance tasks, the CLI task and the deletes worker against a real PostgreSQL schema, with an in-process provider standing in for the CDN — so the row locks, transaction boundaries and the real datetime schema are exercised rather than simulated.tests/e2e/General/CertificatesTest.phpcovers the locking semantics themselves: claim atomicity across the rule and certificate rows, rollback of a failed claim, and one connection's lease surviving another's stale completion.tests/e2e/Services/Proxy/ProxyBase.phpadds rule-creation coverage through the HTTP surface.42 test methods plus data-provider cases: attempt accounting and exhaustion, lease claim and expiry, duplicate and stale jobs, pagination, renewal budget, Console and CLI retries, provider status reconciliation, project identity, and deletion. No reflection and no external provider calls.
Nothing sits in
tests/unit/for a worker, task or HTTP action, so theAGENTS.mdguidance on test placement is satisfied without an exception.Related
This is the server portion of the certificate repair. Fastly orphan association and blocked DNS details are handled by utopia-php/monorepo#222; Cloud status polling and integration are handled by https://github.com/appwrite-labs/cloud/pull/5639. Cloud currently uses an older CE worker interface, so its preview uses a certificate-only backport rather than unrelated current-main changes. No production code rollout is part of this PR.
Merge order matters: the CDN change must land first. Without it, the retry loop added here will re-attempt an orphaned domain, fail identically each time, and stop at the attempt cap — recovery is only possible once issuance can succeed.