Skip to content

fix(certificates): issue a certificate when the provider holds none instead of skipping - #13571

Closed
HarshMN2345 wants to merge 7 commits into
mainfrom
claude/certificates-reconcile-provider-status
Closed

HarshMN2345 wants to merge 7 commits into
mainfrom
claude/certificates-reconcile-provider-status

Conversation

@HarshMN2345

@HarshMN2345 HarshMN2345 commented Sep 9, 2026 •

Copy link
Copy Markdown
Member

#13570 has merged, so this now targets main. #13572 → #13573 → #13751 → #13752 are stacked on it, in that order.

What does this PR do?

This is the root cause of the "SSL generation failed with no error" ticket. On main, the generation worker does:

if (!$certificates->isRenewRequired($domain->get(), $domainType)) {
    Console::info("Skipping, renew isn't required");
    return;
}

It never asks the provider whether a certificate actually exists — "no renewal due" is taken as "all good". With the Fastly provider in the pinned utopia-php/cdn 0.0.8, isRenewRequired() returns false for a classic domain on the active service version without checking for a TLS subscription at all:

// Fastly::isRenewRequired
$serviceId = $domainInfo['service_id'] ?? null;
if (!\is_string($serviceId) || $serviceId === '') {
    return !$this->isOnActiveServiceVersion($domain);   // ← true → "no renewal" → worker returns
}

So a rule whose TLS subscription was never created, or was deleted, sits in certificate-generating forever. Every job the scheduler, the console retry, or the CLI queues hits the same early return, nothing is issued, and the rule's logs show nothing because the worker exits before writing anything useful. The status poller then reads UNKNOWN (FastlyTls::getCertificateStatus() returns that when no subscription exists), and there is no path back.

The fix asks for the certificate status before standing down:

getCertificateStatus() Rule Attempts Issue?
ISSUED verified reset to 0 no
PENDING / PROCESSING / RENEWING certificate-generating untouched no
UNKNOWN / FAILED — — yes, falls through to issueCertificate()

Instant providers (Let's Encrypt) have no status to report, so a valid certificate there is treated as ISSUED. That's the isInstantGeneration() ternary; without it the instant path would fall through and re-issue a perfectly good certificate.

Two side benefits: a rule stuck in certificate-generating whose subscription actually completed is now moved to verified on the next job rather than left as-is, and each stand-down writes a line to the rule logs so the console shows why nothing happened.

finally already persists $rule and $certificate via upsertCertificate() / updateRuleAndSendEvents(), so the two early returns need no extra writes. Nothing else in the worker changes — no lease, no attempt accounting; those are a separate PR.

Test Plan

tests/e2e/General/Certificates/WorkerTest.php drives the real worker against a throwaway PostgreSQL schema and a recording certificate provider. Both fixtures — Certificates/Database.php (throwaway schema built from the canonical app/config/collections/platform.php definitions) and Certificates/Provider.php — now belong to this PR: #13570 introduced them, then dropped them along with its own worker-level test before merging, so this branch carries them.

Every case sets renew = false — the exact state where main returns early — and seeds attempts = 3 so resets are observable:

  • ISSUED → rule verified, attempts 0, provider not asked to issue
  • instant provider, no renewal due → same, without consulting status
  • PENDING, PROCESSING, RENEWING → rule stays certificate-generating, attempts stay 3, nothing issued
  • UNKNOWN, FAILED → provider is asked to issue for example.com / api, attempts reset to 0 — on main these two cases never reach issueCertificate()

validateDomain() is a no-op here because the message's validationDomain equals the domain, so nothing touches DNS.

$ composer lint src/Appwrite/Platform/Workers/Certificates.php tests/e2e/General/Certificates/
{"tool":"pint","result":"passed"}

Runs in Tests / E2E / General; skips locally without PostgreSQL.

On the provider fake: #13570 dropped its worker-level test on the grounds that a deletion race against a real CDN cannot be exercised in CI. That reasoning applies less directly here — this PR's logic is a decision table over getCertificateStatus() return values, and what is faked is one interface returning one of five enum values, not a race. Happy to drop it if the preference is that no worker test should stand in for the provider at all; say so and it goes.

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? — no API metadata changed.

🤖 Generated with Claude Code

https://claude.ai/code/session_01MeytoiisEusFMCU44PDYav

…nstead of skipping

When a generation job found no renewal due it stood down without ever
asking the provider whether a certificate existed. With the Fastly
provider that answer is also what a domain on the active service
version reports when it has no TLS subscription at all, so a rule whose
subscription was never created, or was deleted, stayed in
certificate-generating for good: every job skipped, nothing was issued
and nothing surfaced in the rule logs.

Ask for the provider's certificate status before standing down. An
issued certificate verifies the rule and resets attempts; an in-flight
one keeps the rule generating; anything else falls through to issuance
so the missing subscription is repaired. Instant providers have no
status to report, so a valid certificate there is treated as issued.
@greptile-apps

greptile-apps Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 4/5

The PR is not yet safe to merge because certificates without a stored renewal date can be rescheduled indefinitely, and the implementation-coupled unit test violates an explicit repository requirement.

Fix All in Claude CodeFindings

  1. P1 Renewal Jobs Repeat Forever ▶
  2. P2 Test Mirrors Status Implementation ▶
Fix with agent prompt
### Issue 1
src/Appwrite/Platform/Workers/Certificates.php:341
When an already-issued certificate has no stored `renewDate`, this writes the current time even though the provider says renewal is not required. The maintenance scan selects certificates whose `renewDate` is at or before the current time, so it will enqueue the certificate again on every cycle. This branch also resets `attempts` while preserving the overdue timestamp, causing unbounded generation-job churn. Persist a genuine future renewal date or otherwise avoid making an issued certificate immediately eligible for renewal.

### Issue 2
tests/unit/Certificates/CertificatesTest.php:36-55
This unit test repeats the helpers' complete status-to-boolean classification table instead of testing externally observable certificate behavior. That violates the repository directive not to mirror source code in assertions and creates redundant, refactor-coupled coverage alongside the worker tests, which already verify persisted rule state, attempt counts, and issuance behavior. This repository requirement must be satisfied before merging.

```suggestion

```

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

---

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

Summary

This PR reconciles certificate-provider status before skipping generation when renewal is not due.

  • Marks issued and renewing certificates as verified.
  • Leaves pending and processing certificates in the generating state.
  • Falls through to issuance for unknown and failed statuses.
  • Adds worker-level database/provider fixtures and status behavior coverage.
  • Introduces an immediately overdue fallback renewal timestamp that can repeatedly reschedule already-issued certificates.

Reviews (9) · Last reviewed commit: "fix(certificates): treat a renewing cert..."

@github-actions

github-actions Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → claude/certificates-reconcile-provider-status (after).

Metric Before After Change
🚀 Requests/sec 281.66 283.91 ⚪ +0.8%
⏱️ Latency P50 62.14 ms 61.13 ms ⚪ -1.6%
⏱️ Latency P95 145.1 ms 145.18 ms ⚪ +0.1%
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 61.13 145.18 17,613 283.91 +0.08
Account 112.62 214.24 927 15.4 -15.04
TablesDB 58.24 113.07 9,579 156.87 -1.48
Storage 56.21 127.7 4,635 77.54 -4.76
Functions 88.99 177.44 2,472 41.93 +3.02

Top API waits (after)

API request Max wait (ms)
tablesdb.rows.delete 396.03
account.name.update 345.07
functions.variables.update 344.52
functions.delete 310.88
functions.create 297.42

Copy link
Copy Markdown
Member Author

Benchmark went red on 143b577 before any benchmark ran — the compose stack failed to come up:

Container appwrite-mongodb  Error
dependency failed to start: container appwrite-mongodb is unhealthy
##[error]Process completed with exit code 1.

This PR touches only Workers/Certificates.php and the certificate test fixtures; nothing near MongoDB, compose, or startup. Same runner hiccup that hit #13467 last week. Re-running the failed job once; if it fails the same way again I'll dig further rather than re-run.


Generated by Claude Code

…ertificates-reconcile-provider-status

# Conflicts:
#	tests/e2e/General/Certificates/Database.php
@HarshMN2345
HarshMN2345 force-pushed the claude/certificates-reconcile-provider-status branch from 55392c8 to ff91d29 Compare September 9, 2026 12:17
@HarshMN2345
HarshMN2345 force-pushed the claude/deletes-preserve-recreated-domain branch from ad1305f to b667f6c Compare September 9, 2026 12:17
HarshMN2345 pushed a commit that referenced this pull request Sep 17, 2026
HarshMN2345 pushed a commit that referenced this pull request Sep 17, 2026
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.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MeytoiisEusFMCU44PDYav
@HarshMN2345
HarshMN2345 force-pushed the claude/deletes-preserve-recreated-domain branch from 75b6731 to 193ce56 Compare September 18, 2026 09:06
@HarshMN2345
HarshMN2345 force-pushed the claude/certificates-reconcile-provider-status branch from bdb52ee to 51abda3 Compare September 18, 2026 09:06
HarshMN2345 added a commit that referenced this pull request Sep 18, 2026
Picks up main via #13571 -> #13570 so CI runs against
current main.
HarshMN2345 added a commit that referenced this pull request Sep 18, 2026
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.
main dropped the worker-level deletion test from #13570 before merging, and
with it the Certificates/ fixtures. This branch still needs two of them:
Database.php builds the throwaway schema every certificate test runs against,
and Provider.php is the recording certificate provider WorkerTest drives. Both
are kept; DeletesTest.php and Deletion.php belonged to the deletion test and go
with it.
@HarshMN2345
HarshMN2345 changed the base branch from claude/deletes-preserve-recreated-domain to main September 18, 2026 11:05
… renewable

RENEWING sat with PENDING and PROCESSING, so a rule that was already verified
got written back as verifying for the whole provider-side renewal window. The
certificate is live and serving the entire time. It also dropped the domain out
of the migration source check, which selects on a verified rule.

Neither early return set renewDate. Maintenance selects renewals on a non-null
renewDate, so reconciling a stuck rule to verified retired its certificate from
renewal for good: the console read healthy while the certificate expired. Both
paths now keep the existing date, or stamp one so the next cycle re-examines it.

Move the status decision onto the Certificates library next to isAutoIssueEnabled
and inject certificateIssuer into the worker, as Maintenance and the rule creates
already do. The decision is a pure function of the provider's answer, so it is
covered by the existing unit suite rather than through the worker.

Refresh the log timestamp after the provider round trip, and restore the full
wording on the in-flight message so both paths say the same thing.
// Keep the document eligible for the renewal scan. Maintenance
// filters on a non-null renewDate, so leaving it unset would
// retire this certificate from renewal for good.
'renewDate' => $certificate->getAttribute('renewDate') ?? DateTime::now(),

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 Renewal Jobs Repeat Forever

When an already-issued certificate has no stored renewDate, this writes the current time even though the provider says renewal is not required. The maintenance scan selects certificates whose renewDate is at or before the current time, so it will enqueue the certificate again on every cycle. This branch also resets attempts while preserving the overdue timestamp, causing unbounded generation-job churn. Persist a genuine future renewal date or otherwise avoid making an issued certificate immediately eligible for renewal.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/Platform/Workers/Certificates.php
Line: 341

Comment:
**Renewal Jobs Repeat Forever**

When an already-issued certificate has no stored `renewDate`, this writes the current time even though the provider says renewal is not required. The maintenance scan selects certificates whose `renewDate` is at or before the current time, so it will enqueue the certificate again on every cycle. This branch also resets `attempts` while preserving the overdue timestamp, causing unbounded generation-job churn. Persist a genuine future renewal date or otherwise avoid making an issued certificate immediately eligible for renewal.

---

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

Comment on lines +36 to +55
#[DataProvider('statusProvider')]
public function testProviderStatus(string $status, bool $issued, bool $inFlight): void
{
$certificates = new Certificates();

$this->assertSame($issued, $certificates->isIssued($status));
$this->assertSame($inFlight, $certificates->isInFlight($status));
}

public static function statusProvider(): \Iterator
{
// A renewing certificate is still live, so it counts as issued, not in flight.
yield 'issued' => [Status::ISSUED, true, false];
yield 'renewing' => [Status::RENEWING, true, false];
yield 'pending' => [Status::PENDING, false, true];
yield 'processing' => [Status::PROCESSING, false, true];
// Neither: the provider holds nothing, so the worker issues.
yield 'unknown' => [Status::UNKNOWN, false, false];
yield 'failed' => [Status::FAILED, false, false];
}

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.

P2 Test Mirrors Status Implementation

This unit test repeats the helpers' complete status-to-boolean classification table instead of testing externally observable certificate behavior. That violates the repository directive not to mirror source code in assertions and creates redundant, refactor-coupled coverage alongside the worker tests, which already verify persisted rule state, attempt counts, and issuance behavior. This repository requirement must be satisfied before merging.

Suggested change
#[DataProvider('statusProvider')]
public function testProviderStatus(string $status, bool $issued, bool $inFlight): void
{
$certificates = new Certificates();
$this->assertSame($issued, $certificates->isIssued($status));
$this->assertSame($inFlight, $certificates->isInFlight($status));
}
public static function statusProvider(): \Iterator
{
// A renewing certificate is still live, so it counts as issued, not in flight.
yield 'issued' => [Status::ISSUED, true, false];
yield 'renewing' => [Status::RENEWING, true, false];
yield 'pending' => [Status::PENDING, false, true];
yield 'processing' => [Status::PROCESSING, false, true];
// Neither: the provider holds nothing, so the worker issues.
yield 'unknown' => [Status::UNKNOWN, false, false];
yield 'failed' => [Status::FAILED, false, false];
}

Context Used: Call out and harshly judge implementation-coupled tests. We don't mirror source code, configuration, or version pins in assertions. We test observable behavior; use linters for syntax and schema checks. (source)

Prompt To Fix With AI
This is a comment left during a code review.
Path: tests/unit/Certificates/CertificatesTest.php
Line: 36-55

Comment:
**Test Mirrors Status Implementation**

This unit test repeats the helpers' complete status-to-boolean classification table instead of testing externally observable certificate behavior. That violates the repository directive not to mirror source code in assertions and creates redundant, refactor-coupled coverage alongside the worker tests, which already verify persisted rule state, attempt counts, and issuance behavior. This repository requirement must be satisfied before merging.

```suggestion

```

**Context Used:** Call out and harshly judge implementation-coupled tests. We don't mirror source code, configuration, or version pins in assertions. We test observable behavior; use linters for syntax and schema checks. ([source](https://app.greptile.com/review/custom-context?memory=instruction-0))

---

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

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Fix in Claude Code Fix in Codex

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