Skip to content

Fix certificate retry recovery and stale worker updates - #13467

Closed
HarshMN2345 wants to merge 26 commits into
mainfrom
claude/domain-ssl-generation-fail-cbysyy
Closed

HarshMN2345 wants to merge 26 commits into
mainfrom
claude/domain-ssl-generation-fail-cbysyy

Conversation

@HarshMN2345

@HarshMN2345 HarshMN2345 commented Sep 3, 2026 •

Copy link
Copy Markdown
Member

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.php covers 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.php adds 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 the AGENTS.md guidance 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.

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

greptile-apps Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 4/5

The PR is not yet safe to merge because an issuance exceeding the fixed lease can still overlap a retry and invoke the certificate provider concurrently.

Fix All in Claude CodeFindings

  1. P1 **Lease expiry permits concurrent issuance** ▶
Fix with agent prompt
### Issue 1
src/Appwrite/Platform/Workers/Certificates.php:275-278
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.

---

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

Summary

The PR adds durable certificate-attempt accounting, scheduler recovery, stale-worker protection, explicit retry resets, renewal pagination, and safer deletion handling. The fixed-duration issuance lease still permits concurrent provider calls when an active issuance exceeds 15 minutes.

  • Adds a five-minute certificate recovery scan with publication-failure claim release.
  • Introduces certificate leases and guarded worker completion.
  • Resets attempt budgets for validated Console and CLI retries.
  • Pages renewal candidates and preserves recreated-domain resources during deletion.

Reviews (24) · Last reviewed commit: "fix(tests): match the deletes worker sig..."

…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.
@github-actions

github-actions Bot commented Sep 3, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → claude/domain-ssl-generation-fail-cbysyy (after).

Metric Before After Change
🚀 Requests/sec 193.61 188.12 ⚪ -2.8%
⏱️ Latency P50 90.16 ms 92.35 ms ⚪ +2.4%
⏱️ Latency P95 211.09 ms 218.74 ms ⚪ +3.6%
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 92.35 218.74 11,742 188.12 +7.65
Account 177.03 334.86 618 10.23 +7.05
TablesDB 89.63 169.69 6,386 104.54 +4.75
Storage 84.55 191.05 3,090 52.56 +9.11
Functions 131.61 265.16 1,648 28.52 +12.48

Top API waits (after)

API request Max wait (ms)
account.name.update 548.37
functions.variables.update 471.53
functions.variables.delete 412.62
functions.create 410.39
tablesdb.rows.create 409.52

Copy link
Copy Markdown
Member Author

Both review findings were valid. Fixed in ce2d457191.

Retries lack a durable claim. Confirmed: the worker sets the rule back to generating in memory, and the only write is in updateRuleAndSendEvents() from the finally block, so the rule stayed durably unverified for the whole of issuance. The scan now holds back any rule touched within one interval:

$claimedUntil = new DateTime('-' . $this->certificateGenerationInterval() . ' seconds');
...
Query::updatedBefore(DatabaseDateTime::format($claimedUntil)),

Since that finally always writes the rule, an in-flight attempt keeps $updatedAt inside the window and the rule is not re-selected. Worth being precise about what this does and does not cover: it closes the case where an attempt runs, or the job waits in the queue, for less than one interval. If the certificates queue is backed up for longer than the interval, a duplicate is still reachable — a genuine claim would need the scan to durably mark the rule before enqueueing, which introduces a worse failure mode (an enqueue that then fails would strand the rule in a state this scan no longer looks at). The pre-existing domainVerification scan above has the same property, so this change leaves the new task strictly tighter than the one it mirrors rather than inventing a different concurrency model for one of the two.

Exhausted retries remain scheduled. Confirmed: attempts lives on the certificate and the scan queries rules, so an exhausted rule produced a no-op job every five minutes until it aged out of the three-day window. The scan now reads the certificate first and stops at the shared limit:

$certificate = $dbForPlatform->getDocument('certificates', $rule->getAttribute('certificateId', ''));

if ($certificate->getAttribute('attempts', 0) >= APP_LIMIT_CERTIFICATE_ATTEMPTS) {
    $skipped++;
    continue;
}

These are counted as interval.certificate_generation.skipped rather than processed, which was the other half of the finding. The read is bounded by the same 100-rule page and only runs for rules already in the failed state. The worker keeps its own check, so a job queued by Maintenance — which enqueues on renewDate without consulting rule status — is still capped.

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.

Copy link
Copy Markdown
Member Author

Fair — the second review is right that filtering on $updatedAt alone did not close the window, only narrow it. The rule's timestamp was still the one from the previous attempt while a job sat in the queue, so a slow issuer call or a backed-up queue could outlast a tick and let the next pass queue the same domain. Fixed properly in d71378e129 by claiming the rule at hand-off:

// 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 Query::updatedBefore(...), so touching the rule here removes it from the next pass's result set immediately, rather than waiting on the worker's finally. The worker's own write then extends the lease to one interval past the end of the attempt, which doubles as the backoff between retries.

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 verifying at hand-off would also claim it, but this scan only selects unverified — so if the enqueue then failed, or the worker never picked the job up, nothing would ever look at that rule again. On self-hosted in particular there is no other scanner of verifying, and the domain would sit showing "in progress" forever. Leaving the status alone means an unused lease simply expires and the rule is retried on a later pass. The claim is bounded and self-healing rather than durable-but-brittle.

Note this is deliberately per-region, matching the scan's Query::equal('region', ...): two regions do not scan the same rules, so the lease does not need to coordinate across them.

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.

Copy link
Copy Markdown
Member Author

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 6d6465d39a by giving the lease its own duration:

/**
 * 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 minutes

The 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 _APP_CERTIFICATES_HTTP_TIMEOUT-bounded issuer call plus queue wait leaves a wide margin.

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 RULE_STATUS_CERTIFICATE_GENERATING before calling the provider — removes the window completely, and I decided against it deliberately:

  • This scan selects unverified. A worker that dies between the status write and the finally leaves the rule in verifying, which nothing scans on self-hosted. The domain would show "in progress" forever, with no retry — precisely the class of bug this PR exists to fix, reintroduced in a new place.
  • On Cloud, verifying is the legitimate long-lived state for a delayed issuer, so the retry scan cannot safely reclaim stale ones without racing genuine in-flight issuance.

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:

  • Cloudflare — duplicate hostname returns error 1406, which the provider treats as success. Idempotent.
  • Fastly — issueCertificate() finds the existing domain record and the existing TLS subscription and returns without creating a second one. Idempotent.
  • Let's Encrypt — genuinely not idempotent, and the case worth protecting. It is also the fast path: certbot issuance is seconds to a couple of minutes, comfortably inside fifteen.

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

Copy link
Copy Markdown
Member Author

This one I'm declining, with reasoning rather than a push.

The fourth pass moves from "issuance outlasts the lease" (fixed in 6d6465d39a) to a different scenario: two concurrent instances of the interval task both selecting and claiming the same rule in the same tick. That would need the scheduler to run more than once per region, and the deployment says it does not:

  • appwrite-task-interval is declared with container_name: appwrite-task-interval. Compose refuses to scale a service that pins a container name, so this cannot be run with replicas as shipped.
  • There is no replicas: or scale: anywhere in docker-compose.yml.
  • The scan is already region-scoped via Query::equal('region', ...), so separate regional deployments do not see each other's rules.

The stronger evidence is what the neighbouring scanners do. Interval::verifyDomain() and Maintenance::renewCertificates() perform no claim of any kind — they select and enqueue directly. If two schedulers really ran side by side, both of those would double-enqueue every rule on every tick, and DNS verification would have been doing so for as long as it has existed. The single-instance assumption is load-bearing across the whole file; this PR is the first code in it to claim anything at all.

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

Copy link
Copy Markdown
Member Author

Tests / E2E / PostgreSQL (dedicated) / Proxy failed on 6d6465d39a. I don't believe it belongs to this PR, and here is the evidence rather than an assertion.

The suite died in setupFunction(), on deployment creation:

http.request · 30.03s · 069b617e

  level              error
  http.method        POST
  http.path          /v1/functions/:functionId/deployments
  http.response.code 500

  OpenRuntimes\Orchestrator\Exception\TimeoutException: Orchestrator request timed out.
    at /usr/src/code/vendor/open-runtimes/sdk-for-php/src/Transport.php:91
    at /usr/src/code/vendor/open-runtimes/sdk-for-php/src/Transport.php:40
    at /usr/src/code/vendor/open-runtimes/sdk-for-php/src/Jobs.php:78
    at /usr/src/code/src/Appwrite/Deployment/Deployments.php:219

A 30-second timeout waiting on the orchestrator, in Deployment/Deployments.php. This PR changes five files — Workers/Certificates.php, Tasks/Interval.php, Tasks/Maintenance.php, Workers/Deletes.php and one constant in app/init/constants.php — and none of them sits on the deployment-creation path or touches the orchestrator client. The proxy rule requests in the same log are healthy throughout: POST /v1/proxy/rules/api 201, GET /v1/proxy/rules/:ruleId 200, DELETE /v1/proxy/rules/:ruleId 204. The 400s present are the suite's own negative assertions.

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 appwrite-task-interval on a five-minute timer and does not run inside the e2e job at all.

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: rerun-failed-jobs is refused with 403 This workflow is already running while the remaining E2E shards finish. I'll spend it as soon as the run completes, and if Proxy fails a second time I'll treat it as real and root-cause it rather than re-running again.


Generated by Claude Code

Copy link
Copy Markdown
Member Author

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 origin/main.

Worker guard — three cases through Certificates::action() with a stubbed Provider (isInstantGeneration: false, i.e. a delayed issuer):

Case Expected vs origin/main
failed rule, attempts under the cap reaches the issuer, rule written back as verifying fails: Failed asserting that false is true — the issuer is never reached
failed rule, attempts at the cap issuer not reached, rule untouched passes vacuously (early return either way)
rule arriving as verifying (Console retry), attempts far past the cap always attempted passes (unchanged behaviour)

The first row is the bug this PR fixes, reproduced: on main the guard rejects the unverified rule and issueCertificate() is never called. The cap branch also demonstrably executes — it prints Certificate generation for retry.example.com is skipped as it ran out of attempts.

Interval task — five cases driving the registered certificateGeneration callback with a stubbed Database and publisher. Four of the five fail against origin/main (the task does not exist there); all pass here. They pin the registration and 5-minute tick, that an eligible rule is leased before hand-off and then queued, that an exhausted certificate is neither leased nor queued, and the shape of the scan itself. The query the code actually builds:

{"method":"greaterThan","attribute":"$createdAt","values":["2026-08-31 12:17:06.808"]}
{"method":"equal","attribute":"status","values":["unverified"]}
{"method":"lessThan","attribute":"$updatedAt","values":["2026-09-03 12:02:06.808"]}
{"method":"orderAsc","attribute":"$updatedAt","values":[]}
{"method":"equal","attribute":"region","values":["default"]}
{"method":"limit","values":[100]}

Against a now of 12:17:06 the lease bound is 12:02:06 — 900 seconds, so the 15-minute lease against the 5-minute tick is confirmed by measurement rather than by reading the constant.

I have deliberately not committed these, because AGENTS.md says workers and CLI tasks are covered by e2e rather than unit tests. That convention's premise does not hold for this particular surface, so I'm flagging the tension rather than resolving it unilaterally: if a maintainer would rather have the regression coverage than the convention here, say so and I'll add them under tests/unit/ in the next push.


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.
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.
@HarshMN2345 HarshMN2345 changed the title fix(certificates): retry failed certificate generation, and route cleanup by domain type Fix certificate retry recovery and stale worker updates Sep 7, 2026
@HarshMN2345
HarshMN2345 force-pushed the claude/domain-ssl-generation-fail-cbysyy branch from 151ce35 to fda4204 Compare September 7, 2026 13:27
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.

Copy link
Copy Markdown
Member Author

Tests / E2E / PostgreSQL (dedicated) / Sites failed on 892b82660c, and again on a re-run of the same job. I don't believe it belongs to this PR, and the argument here is a diff range rather than an opinion about which suites look related.

Sites passed on the three preceding heads and fails on this one:

head Sites
fda42047 pass
357afed6 pass (whole run green)
cdf571b657 pass
892b82660c fail, and fail again on re-run

The delta between the last green head and the failing one contains no production code:

tests/unit/{Fixtures => Platform}/CertificateDatabase.php   |  2 +-
tests/unit/{Fixtures => Platform}/CertificateProvider.php   |  2 +-
tests/unit/Platform/Modules/Proxy/Http/Rules/Status/UpdateTest.php | 13 +++++--
tests/unit/Platform/Tasks/IntervalTest.php                  |  2 +-
tests/unit/Platform/Tasks/SSLTest.php                       |  2 +-
tests/unit/Platform/Workers/CertificatesTest.php            |  4 ++--
tests/unit/Platform/Workers/DeletesCertificatesTest.php     |  4 ++--

Two file renames with a namespace change, one wrapped call, one inlined local. Nothing under src/ or app/ changed, and the e2e testsuite in phpunit.xml enumerates its directories explicitly, so it never loads anything under tests/unit. There is no mechanism by which these commits reach the Sites suite.

Paths I checked in the PR's actual diff before concluding that, since Sites does exercise rule creation and deletion:

  • Deletes.php::deleteRule — the new "skip if the domain has been recreated" guard cannot see the row it is deleting: Database::deleteDocuments() commits the batch in withTransaction() and only then calls onNext, so the rule is already gone when the callback runs.
  • Certificates.php — the new claim rejects a message with no project, but every producer passes one (Rules/{Site,API,Function,Redirect}/Create.php, Functions/Http/Functions/Create.php, Maintenance.php, SSL.php, Interval.php, and general.php, which pairs project: $console with a rule whose projectId is console).
  • Rules/Status/Update.php — the early return for already-verified rules is not reachable from the Sites suite; SitesBase only creates rules and lists them, it never calls the status endpoint.

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 docker compose logs dump, so the tail never reaches it. There are no test-result artifacts on the run either — only benchmark and spec JSON. The 400s and 404s visible in the tail are the suite's own negative-path assertions (Invalid deploymentRetention param, Installation with the requested ID could not be found), not the failure.

I have not ported a fix because there is no change to port — the failing range contains no production code. For context, main is intermittently red at the moment (5 of the last 12 pushes), each time on a different suite, and three e2e flake fixes landed in the last day: test(proxy): isolate deployment archives in parallel tests (#13507), test(usage): wait for schema readiness before E2E queries (#13506), fix(storage): prevent concurrent chunk finalization (#13505). This looks like the same family of parallel-execution flakiness rather than something Sites-specific.

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

Copy link
Copy Markdown
Member Author

Following up on my earlier note about Tests / E2E / PostgreSQL (dedicated) / Sites — there is now direct evidence, and it supersedes the reasoning I gave before.

Sites is failing on main. Run 34167570020 for ce3a85157f (the merge of #13515, feat: add S3-compatible storage service) has Sites as the only failing job out of 45. That commit is this PR's current base, so the failure here is inherited.

commit branch Sites
45a0168a main pass
0ff8fd23 main pass
ce3a85157f main (S3 merge) fail — only failure in the run
a25b3e25 this PR (merges ce3a85157f) fail

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 main and failed again on a new base — so I am replacing it with the direct observation above rather than leaving the weaker argument standing.

There is no fix to port: main is still at ce3a85157f and no change addressing this has landed yet. Nothing in this PR touches the Sites surface — the diff is 14 files, all certificate issuance and its tests, and main's S3 module is not part of it despite appearing in the automated summary above (that review ran against the merge commit and swept in main's content; grep -i s3 over this PR's changed paths returns nothing).

Flagging it here mainly so it is visible to whoever owns #13515: Sites appears to have broken on main with that merge, independently of this PR.


Generated by Claude Code

Copy link
Copy Markdown
Member Author

CI is green — 46/46 on 4c100e036c. Closing out the two failures discussed above, and correcting one thing I got wrong.

Sites. It passed on run 34200247908. My earlier comment said it was "failing on main", which overstated the evidence: main's run for ce3a85157f did have Sites as its only failure of 45 jobs, and it failed three times here, but it has now passed on this branch without any change to the suite. The accurate description is that Sites is intermittent and hits both main and this branch — not that it is deterministically broken. Nothing in this PR touches that surface either way.

Migrations failed once, and it was container startup rather than a test:

"msg":"Error setting up transport layer",
"errmsg":"0.0.0.0:27017 :: caused by :: setup bind :: caused by :: Address already in use"
→ Container appwrite-mongodb  Error
→ dependency failed to start: container appwrite-mongodb is unhealthy
→ Process completed with exit code 1

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 tests/e2e/General/Certificates/Database.php creates certificate_test_<hex> schemas. That was wrong — every test class drops its schema in tearDown(), and the log shows the job never reached the tests.


Generated by Claude Code

Copy link
Copy Markdown
Member Author

Heads up on a merge interaction with #13539, which also edits src/Appwrite/Platform/Tasks/Interval.php.

The two changes are independent in substance — #13539 fixes the DNS verification stage (verifyDomain(), which this PR does not touch), this one fixes issuance after verification succeeds. But #13539 deletes use DateTime; and use Utopia\Database\DateTime as DatabaseDateTime;, since verifyDomain() was their only consumer on main. generateCertificate() here uses both.

Those deletions do not overlap any hunk in this PR, so git will merge them without reporting a conflict and generateCertificate() will hit an undefined-class fatal. Whichever of the two lands second needs the two imports restored — no conflict marker will prompt for it.


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
HarshMN2345 pushed a commit that referenced this pull request Sep 15, 2026
…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
Comment on lines +275 to +278
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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Fix in Claude Code Fix in Codex

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.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

HarshMN2345 added a commit that referenced this pull request Sep 18, 2026
…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.
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