Repository navigation
fix(certificates): retry failed issuance under a lease and bound the attempts - #13573
HarshMN2345 wants to merge 13 commits into
Conversation
…attempts A failed issuance was only revisited by the daily renewal sweep, and nothing stopped two workers from issuing for the same domain at once or a slow job from overwriting the result of a newer retry. Attempts were also counted twice on some paths and never on a crash, so the budget neither bounded anything nor ran out predictably. The worker now claims the rule and its certificate under a row lock before issuing. The certificate's `updated` field holds a 15-minute lease; a claim fails while another worker holds it, when the rule has been recreated or moved to another project, or when a completed failure has spent its attempts. The attempt is reserved before the provider is called so a crash still consumes it, and an issuance failure does not count it twice. On completion the lease is cleared under the same lock, so a stale worker cannot overwrite a newer claim. A five-minute interval task queues failed rules and generating rules whose lease has expired, in region and oldest first, skipping Appwrite-owned domains when automatic issuance is disabled. The renewal sweep includes certificates whose final attempt died holding the lease so the provider's result can still be reconciled. Console and CLI retries reset the attempt budget after DNS validation, under the same lock, and cannot interrupt an active lease. Generation jobs carry the rule's project and resolve the domain type from the persisted rule.
|
✨ Benchmark resultsComparing
Per-scenario breakdown & investigation detailsMetrics below reflect the current branch (after). Δ P95 compares against the base.
Top API waits (after)
|
…is empty The worker now routes issuance by the persisted rule rather than the queue payload, and API rules persist `deploymentResourceType` as '', so the fallback to `type` never fired for them. Fall back on empty, as the deletes worker does.
Replace the captured `updateDocument()` payloads with assertions on the persisted rule and certificate, drop the sparse-update shape check, and seed the attributes the canonical `rules` collection requires. The locking test now builds its collections from the canonical definitions as the shared fixture does.
|
|
|
This PR doesn't touch Storage, uploads or the antivirus path — it's certificate workers, tasks, the proxy rule status endpoint and their tests. A 403 on a chunked upload behind ClamAV is the scanner rejecting or timing out on the chunk, which is independent of this diff. I'll re-run that job once when the run finishes; if it fails the same way again I'll dig into it rather than re-run. |
cfb236c to
5e96369
Compare
`rules.projectInternalId` is required, so a console rule with a null sequence cannot be persisted; the canonical fixture now rejects the seed that assumed it could. (cherry picked from commit af0f12e36803fdf7576b874cf48347b5bcc01d3a)
|
That case seeded a console rule with Generated by Claude Code |
The claim wrote "Processing SSL certificate issuance." into the rule the moment a worker leased it, so a rule created and re-verified back to back could report non-empty logs while still verifying. main only writes logs on completion; match that so an in-flight rule reads unchanged. Also cover a console certificate message without a project sequence.
28faa65 to
60e0899
Compare
e1308a1 to
ef0177d
Compare
…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.
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
|
Three checks are red on Failing: Why they don't look like this change. The diff here is one guarded private method in the certificate scheduler plus two test-only files. The suites that actually exercise it are green on the same commit: The comparison. #13467 carries the identical claim-release commit, cherry-picked, but on a base with current
Same code, different base, opposite results. What it points at. This PR is stacked on #13572 → #13571 → #13570, and that chain is still based on Fix. Refreshing the stack's base — merging current Generated by Claude Code |
|
Follow-up to the comment above: a fourth check went red on The other three ( What I can say:
What I could not do: retrieve the actual assertion. These e2e jobs end with a full container log dump and telemetry graphs, and the log API only returns a tail, so the PHPUnit output is unreachable from tooling — a 400KB tail of this job contains no test output at all. I've re-run the failed jobs once to test reproduction. If Proxy comes back green it was a flake; if it fails identically I'll treat it as this PR's and dig in properly rather than assume the stale base explains it. Generated by Claude Code |
|
Re-run result, closing the loop on the comment above:
Generated by Claude Code |
Picks up main via #13572 -> #13571 -> #13570 so CI runs against current main. Conflict in Certificates.php: main added an inline notifyError() call in catch and gave notifyError() a sixth $console parameter. This branch defers that email to the finally block, which sends only once the lease is confirmed still ours, so a stale worker cannot email an admin about a failure that a newer retry has already superseded. Kept the deferred form, dropped the inline call, and carried main's new parameter into the deferred call site -- git would have merged the signature change without touching the call.
…ssuance Two defects in the scheduler, both found by verifying the refreshed branch against current main. releaseClaim() never released anything. updateDocument() stamps $updatedAt with now() unless the database preserves dates, and the platform database does not -- Factory::platform() and app/cli.php both leave it off. So the rollback wrote now() over the pre-claim timestamp and suppressed the rule for the full 900s lease, the exact outcome the method exists to prevent. Wrapped in withPreserveDates(), matching TimeTravel and the bulk document writes. The regression test did not catch this because the fixture enables preserveDates so seeds can carry an old $updatedAt, which meant the test ran under semantics production never has. runTask() now disables it for the duration of the task, so a write that only works with dates preserved fails here instead of in production. generateCertificate() had no ceiling. iterate() pages until the scan is exhausted, so Query::limit(100) is a page size, not a cap, and one tick enqueued an issuance job for every eligible rule. Renewals already reserve 200 of Let's Encrypt's 300 orders per three hours, so retries are held to the remaining 100, counted on jobs actually enqueued rather than rows scanned. testIssuanceBudgetBoundsOneTick covers it, mirroring the renewal budget case in MaintenanceTest.
The Proxy suite failed on this branch and the cause could not be read back. GitHub's API serves only the last 5000 lines of a job log, and this step dumps every container's full log unbounded -- on a 70-second job that is already more than 5000 lines, so the whole window lands inside the trailing Traefik output and the PHPUnit failure sits just outside it. The junit XML is written inside the container and never uploaded, so there is no second copy. Capping the dump keeps the test output inside the retrievable window. The tail is per container, so a crash loop still shows its last lines.
6647e8b to
01fdcac
Compare
1c437a4 to
3b626cb
Compare
…ates-issuance-lease
What does this PR do?
The retry half of the "SSL generation failed with no error" ticket. #13571 makes a job that runs do the right thing; this PR makes sure a job runs when one is needed, and that only one runs at a time.
On
main:finallyruns last wins.finallywrites its oldstatus/certificateId/logsover it.attemptsdoesn't bound anything predictably. A validation failure counts one, an issuance failure counts one, a crash between them counts zero, and success resets to 0 — so a domain that alternates can retry forever, and one that crashes never runs out.The lease
handleCertificateGenerationAction()now claims before it acts. In onewithTransactionwithforUpdateon both rows:$sequence(recreated), belongs to a different project than the message says, or isn't incertificate-generating/verified/certificate-generation-failed.updatedis within the lastAPP_CERTIFICATE_GENERATION_LEASE(900 s) — another worker holds it — or if attempts are exhausted and the rule is a completed failure.certificates.updated = now(the lease) and move a failed rule tocertificate-generating.updatedalready exists on the collection and nothing onmainwrites it, so no migration. The lease token is compared in the ISO format the database returns, which is why it's built withDateTime::formatTz().Before calling the provider, a second locked transaction reserves the attempt (
attempts + 1,issueDate = now) and re-checks the lease is still ours. A crash after this point has consumed the attempt; an exception fromissueCertificate()does not count it again. A failure before reservation (DNS, provider lookup) counts once incatch. So: exactly one attempt per job, including crashes.finallysaves under the lock too, and only if the rule and lease are still the ones this worker claimed — otherwise it writes nothing and sends no events or admin email. Completion clearsupdated.The domain type comes from the persisted rule, not the message, so a rule that changed type between enqueue and run is routed to the right provider.
The scheduler
Intervalgains acertificateGenerationtask (_APP_INTERVAL_CERTIFICATE_GENERATION, default 300 s). It iterates rules incertificate-generation-failedorcertificate-generatingwhose$updatedAtis older than the lease, in this region, oldest first, and for each one re-reads underforUpdateand bumps$updatedAtas its own claim before enqueueing. It skips exhausted completed failures, generating rules with no lease (delayed issuance the poller owns), rules another worker leases, and Appwrite-owned domains when auto-issue is off. The two new env vars are passed through indocker-compose.ymlfor the scheduler container.The renewal sweep (on top of #13572)
Also selects certificates at the attempt cap whose
updatedlease expired — a worker that died on its final attempt may have left an issued certificate at the provider, and #13571's reconciliation path can pick it up. Completed failures at the cap are still excluded; those need an explicit retry.Explicit retries
PATCH /proxy/rules/:ruleId/status(console) and thesslCLI task resetattemptsto 0 and clear the lease — but only under the same lock, only after DNS validation passes, and never while a worker holds an active lease. Both now enqueue with the rule's own project and domain type rather than the caller's.Constants
APP_LIMIT_CERTIFICATE_ATTEMPTS = 5(was a literal inMaintenance) andAPP_CERTIFICATE_GENERATION_LEASE = 900.Test Plan
All e2e, against a throwaway PostgreSQL schema so the row locks and transaction boundaries are real:
WorkerTest— fix(certificates): issue a certificate when the provider holds none instead of skipping #13571's four cases are kept; one assertion changes because the attempt is now reserved before issuance (0→4, commented inline). 19 new cases: one attempt per issuance for delayed and synchronous failures, a concurrent duplicate does not start a second issuance, lookup failures exhaust retries, a final-attempt crash still reconciles an issued certificate but never issues again, a stale worker cannot overwrite a replacement's lease, a deleted rule is not recreated on completion, an expired lease can recover, console project identity (current and legacy sequence), and stale failures send no admin email.CertificatesTest— the locking itself, with two connections: the claim locks rule and certificate together, a failed claim rolls the lease back, one connection's stale completion cannot clear another's lease.IntervalTest— older failures aren't starved by an exhausted first page, only this region's expired work is queued, a fresh failure is retried within the tick rather than the next day, the auto-issue policy is respected, an expired final attempt is queued for reconciliation.SSLTest— CLI retry resets the budget and enqueues with the rule's project and type, respects an active lease, doesn't queue or recreate a concurrently deleted rule.MaintenanceTest— fix(maintenance): spend the renewal budget on scheduled jobs, not scanned rows #13572's cases kept, plus: expired final-attempt leases are queued, exhausted completed failures don't consume the budget.ProxyBase(HTTP) — retry through the API resets attempts, preserves an active lease, 404s for a foreign project, and a DNS failure keeps attempts while bumping$updatedAt.63 cases across the stack; all load locally and skip without PostgreSQL. Pint clean on every file.
Related PRs and Issues
use DateTime;anduse Utopia\Database\DateTime as DatabaseDateTime;fromInterval.php;generateCertificate()here uses both. The hunks don't overlap, so git will merge silently and fatal. Whichever lands second restores the two imports — I'm watching both and will push the fix.Checklist