Skip to content

fix(certificates): retry failed issuance under a lease and bound the attempts - #13573

Closed
HarshMN2345 wants to merge 13 commits into
claude/maintenance-renewal-budgetfrom
claude/certificates-issuance-lease
Closed

HarshMN2345 wants to merge 13 commits into
claude/maintenance-renewal-budgetfrom
claude/certificates-issuance-lease

Conversation

@HarshMN2345

@HarshMN2345 HarshMN2345 commented Sep 9, 2026 •

Copy link
Copy Markdown
Member

Stacked on #13572 → #13571 → #13570. Last of the four. Merge in order; GitHub retargets automatically. The diff shown here is only this change. It is the largest of the four because the lease, the scheduler that depends on it, and the retry paths that reset it are one mechanism — splitting them would ship a scheduler with no claim (which Greptile flagged as a P1 on the original #13467) or a claim nothing uses. Happy to split further if it helps review.

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:

  • A failed issuance is revisited only by the daily renewal sweep. A domain that failed at 09:00 waits until the next maintenance window.
  • Nothing prevents two workers issuing for the same domain at once — the scheduler, a console retry and the CLI can all enqueue the same domain, and each job reads the rule, calls the provider, and writes back. Two provider orders, and whichever finally runs last wins.
  • A slow job can overwrite the result of a newer retry: the rule was deleted and recreated, or the console already reset it, and the stale worker's finally writes its old status/certificateId/logs over it.
  • attempts doesn'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 one withTransaction with forUpdate on both rows:

  1. Re-read the rule. Bail if it's gone, is a different $sequence (recreated), belongs to a different project than the message says, or isn't in certificate-generating / verified / certificate-generation-failed.
  2. Read the certificate. Bail if updated is within the last APP_CERTIFICATE_GENERATION_LEASE (900 s) — another worker holds it — or if attempts are exhausted and the rule is a completed failure.
  3. Write certificates.updated = now (the lease) and move a failed rule to certificate-generating.

updated already exists on the collection and nothing on main writes it, so no migration. The lease token is compared in the ISO format the database returns, which is why it's built with DateTime::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 from issueCertificate() does not count it again. A failure before reservation (DNS, provider lookup) counts once in catch. So: exactly one attempt per job, including crashes.

finally saves 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 clears updated.

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

Interval gains a certificateGeneration task (_APP_INTERVAL_CERTIFICATE_GENERATION, default 300 s). It iterates rules in certificate-generation-failed or certificate-generating whose $updatedAt is older than the lease, in this region, oldest first, and for each one re-reads under forUpdate and bumps $updatedAt as 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 in docker-compose.yml for the scheduler container.

The renewal sweep (on top of #13572)

Also selects certificates at the attempt cap whose updated lease 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 the ssl CLI task reset attempts to 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 in Maintenance) and APP_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

Checklist

  • Have you read the Contributing Guidelines on issues?
  • If the PR includes a change to an API's metadata (desc, label, params, etc.), does it also include updated API specs and example docs? — the status endpoint's behaviour changes but its description, params and response model do not.

…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.
@greptile-apps

greptile-apps Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

The PR appears safe to merge; no new actionable defect remains after the latest base merge, and all previous findings are resolved, fixed, or withdrawn.

Summary

This PR adds bounded, lease-protected certificate issuance retries and coordinates scheduler, worker, maintenance, API, and CLI behavior.

  • Claims certificate work transactionally and rejects stale or duplicate workers.
  • Reserves attempts before provider issuance and reconciles interrupted final attempts.
  • Adds periodic retry scheduling with regional, policy, lease, and attempt-budget guards.
  • Makes explicit API and CLI retries reset the budget only after validation and under locking.
  • Adds PostgreSQL-backed coverage for concurrency, stale completion, retry limits, publication failure, and recovery behavior.

Reviews (13) · Last reviewed commit: "Merge branch 'claude/maintenance-renewal..."

@github-actions

github-actions Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing claude/maintenance-renewal-budget (before) → claude/certificates-issuance-lease (after).

Metric Before After Change
🚀 Requests/sec 252.84 247.14 ⚪ -2.3%
⏱️ Latency P50 68.72 ms 70.29 ms ⚪ +2.3%
⏱️ Latency P95 160.63 ms 163.52 ms ⚪ +1.8%
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 70.29 163.52 15,390 247.14 +2.89
Account 132.03 241.12 810 13.44 -10.3
TablesDB 67.78 128.31 8,370 136.69 +5.19
Storage 64.48 147.78 4,050 68.08 +3.76
Functions 99.68 191.31 2,160 36.95 -5.18

Top API waits (after)

API request Max wait (ms)
account.name.update 401.48
account.prefs.update 389.51
functions.create 357.23
functions.delete 348.35
storage.buckets.create 337.19

…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.

HarshMN2345 commented Sep 9, 2026 •

Copy link
Copy Markdown
Member Author

Tests / E2E / General was red on the first push (60609b0). Cause: this PR makes the worker take the domain type from the persisted rule instead of the queue payload, and API rules persist deploymentResourceType as '', which getAttribute() returns as-is — so issueCertificate() received '' where the test (and the previous behaviour via the payload) expected api. Same fallback bug Greptile caught on #13570; fixed the same way in b6a1989. cfb236c then seeds the attributes the canonical rules schema requires, which the fixture change from #13570 made mandatory.

HarshMN2345 commented Sep 9, 2026 •

Copy link
Copy Markdown
Member Author

Tests / E2E / Antivirus (dedicated) went red on dc67ed7 with:

1) Tests\E2E\Services\Storage\StorageCustomServerTest::testCreateBucketFileChunkedUploadWithAntivirus
Failed asserting that 403 matches expected 201.
tests/e2e/Services/Storage/StorageCustomServerTest.php:533

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.

@HarshMN2345
HarshMN2345 force-pushed the claude/certificates-issuance-lease branch from cfb236c to 5e96369 Compare September 9, 2026 11:09
`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)

Copy link
Copy Markdown
Member Author

Tests / E2E / General on the previous head had exactly one error out of 93:

WorkerTest::testConsoleDomainsAcceptCurrentAndLegacyProjectSequence#1 with data (null)
Utopia\Database\Exception\Structure: Missing required attribute "projectInternalId"

That case seeded a console rule with projectInternalId = null to model a legacy row. The canonical rules definition marks the attribute required, so such a row cannot be persisted — the fixture built from the real schema rejected a state production cannot hold, which is the point of using it. Dropped the null case in de02cce; the 'console' and '0' (legacy sequence) cases remain.


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.
@HarshMN2345
HarshMN2345 force-pushed the claude/maintenance-renewal-budget branch from 28faa65 to 60e0899 Compare September 9, 2026 12:17
@HarshMN2345
HarshMN2345 force-pushed the claude/certificates-issuance-lease branch from e1308a1 to ef0177d Compare September 9, 2026 12:17
…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.
HarshMN2345 pushed a commit that referenced this pull request Sep 15, 2026
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

Copy link
Copy Markdown
Member Author

Three checks are red on 97392a8 and I don't believe they belong to this PR. Recording the evidence rather than leaving it unexplained.

Failing: Tests / E2E / PostgreSQL (dedicated) / GraphQL, Tests / E2E / PostgreSQL (dedicated) / Avatars, Tests / E2E / S3 Storage (dedicated).

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: Tests / E2E / General (which runs the new IntervalTest cases), Tests / Unit, and Checks.

The comparison. #13467 carries the identical claim-release commit, cherry-picked, but on a base with current main merged in. All three suites pass there:

Suite #13573 (97392a8, base from Sep 9) #13467 (9c51002, current main merged)
GraphQL failure success
Avatars failure success
S3 Storage failure success

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 main as of Sep 9. main has moved considerably since — among other things it now requires PHP 8.5+. These three suites appear to be failing against the stale base rather than against the diff, which also means #13570–#13572 are likely latently red for the same reason; their green checks predate the drift and simply have not re-run.

Fix. Refreshing the stack's base — merging current main into #13570 and cascading up — rather than anything in this diff. That moves four PRs and resets their review state, so I've left it for the author to sequence rather than doing it unilaterally. Happy to run it on request.


Generated by Claude Code

Copy link
Copy Markdown
Member Author

Follow-up to the comment above: a fourth check went red on 97392a8, Tests / E2E / PostgreSQL (dedicated) / Proxy, and I am not claiming this one is base drift.

The other three (GraphQL, Avatars, S3 Storage) touch nothing this stack changes. Proxy does — ProxyBase.php carries the retry/lease HTTP coverage added here. So it needs to be ruled in or out on its own evidence, not by association.

What I can say:

  • The commit that triggered this run touches three files: src/Appwrite/Platform/Tasks/Interval.php, tests/e2e/General/Certificates/IntervalTest.php, and a new tests/e2e/General/Certificates/Publisher.php. No Proxy file is among them.
  • The behaviour it adds only executes when a queue publish fails. In a healthy e2e stack the publish succeeds, so the new path should never run.
  • The Fix certificate retry recovery and stale worker updates #13467 comparison does not transfer here. That branch's ProxyBase.php differs from this one by ~131 lines, so its green Proxy result proves nothing about this suite.

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

Copy link
Copy Markdown
Member Author

Re-run result, closing the loop on the comment above: Proxy came back green, so it was a flake rather than this PR's.

GraphQL, Avatars and S3 Storage all failed again identically in the same re-run, which is what a stale base looks like and not what a flake looks like. That leaves the picture as described earlier — the three reproduce because the stack is still based on main as of Sep 9, and refreshing the base is the fix.


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