Skip to content

feat(deletes): deployment retention policy as a worker resource - #14685

Merged
ChiragAgg5k merged 6 commits into
mainfrom
feat/deployment-retention-policy
Oct 21, 2026
Merged

ChiragAgg5k merged 6 commits into
mainfrom
feat/deployment-retention-policy

Conversation

@ChiragAgg5k

@ChiragAgg5k ChiragAgg5k commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

Builds on #14663. Tracking appwrite-labs/cloud#6628 (section 2). Deployment cleanup takes a policy resource on top of each resource's deploymentRetention. Self-hosted registers an all-zero policy, so its behaviour is unchanged; Cloud binds a plan-driven one (appwrite-labs/cloud#6680).

readonly class Retention
{
    public function __construct(
        public int $days = 0,      // default age when a resource requests none
        public int $maxDays = 0,   // cap on any age, also applied when neither request nor default is set
        public int $maxCount = 0,  // newest N finished non-kept deployments per function/site
    ) {} // negative values throw InvalidArgumentException

    public function resolve(int $requested): int; // requested ?: days, clamped to maxDays; 0 = forever
    public function passes(Database $dbForProject, array $resource, int $requested, \DateTime $now): \Generator; // yields Pass(Reason, queries)
}

$container->set('deploymentRetention', fn (): Retention => new Retention(), []);
resource ──► request and policy all zero? ──yes──► return (today's behaviour, no extra queries)
                │ no
                ▼
     kept = active deployment + manual rule targets   (never retired)
     now  = one DateTime per resource
                │
     Retention::passes(), each pass disjoint from the others:
     1. Requested  createdAt < now - requested                          when requested > 0
     2. Policy     now - requested <= createdAt < now - resolve(requested)
                   (lower bound only when a request exists)              when resolve(requested) differs
     3. Count      finished (ready|failed|canceled) rows only
                   cutoff = row at offset maxCount by ($createdAt, $sequence) desc, looked up after the age passes
                   retires the cutoff and older, newer than the age cutoff
                │
                ▼
     retireDeployments(Reason, $queries, ...)   protected seam, one call per pass
protected function retireDeployments(Reason $reason, array $queries, Retention $retention, Document $resource, Database $dbForProject, DeletePublisher $publisherForDeletes, Document $project): void

A subclass can handle each Reason differently (Cloud's shadow mode measures policy and count passes instead of retiring them). Because the passes are disjoint by construction, no deployment reaches the seam for two reasons. Builds in progress neither take a count slot nor get retired, so queued builds cannot crowd out rollback targets. A failure for one resource (e.g. the count cutoff lookup) is logged and maintenance carries on with the next resource.

The deploymentRetention param docs now say 0 keeps everything unless the server applies a default retention.

Self-hosted impact

None in behaviour: with the all-zero policy only the requested pass runs, with the same query as before. Two operational differences: a failure while retiring one resource's deployments is logged instead of failing the maintenance job, and each retiring resource logs Retiring deployments of {collection} {id} by requested retention.

Tests

tests/unit/Deployment/RetentionTest.php keeps only the library edge cases no E2E can reach (workers are not unit-tested per AGENTS.md); default, clamp, count cap and kept deployments are covered by Cloud's retention E2E. On the Memory adapter:

  • a clamped request splits deployments between requested and policy with no overlap (regression for the double-enqueue review finding)
  • count breaks a $createdAt tie by insertion order
  • count skips builds in progress
  • count leaves deployments past the age cutoff to the age pass
  • a failed count lookup throws only after the age passes were yielded

tests/unit/Platform/Workers/DeletesTest.php only passes the new deploymentRetention argument.

E2E: SitesConsoleClientTest::testSiteDeploymentRetentionWithMaintenance now asserts which deployments survive maintenance (the active one and the one inside the requested retention), not only the total. No E2E covers a non-zero policy: CE registers all zeros; Cloud's E2E (appwrite-labs/cloud#6680) exercises policy and count through this seam. The queries (or/and on $createdAt + $sequence, offset, equal('status'), greaterThanEqual('$createdAt')) are standard filters every adapter supports.

@luxor-code-review

luxor-code-review Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Review complete. 🟡 2 medium

💬 Inline comments (2)

  • 🟡 Overlapping retention passes double-enqueue deployments — Deletes.php:637
  • 🟡 deploymentRetention is never populated from configuration — message.php:211
🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 Unused Reason and Retention parameters mislead (Deletes.php:698) — deleteDeployments accepts Reason $reason and Retention $retention (src/Appwrite/Platform/Workers/Deletes.php:698) but its body never reads either; the three call sites pass distinct Reason::* values that are never logged, recorded, or used.

This PR introduces deployment retention: a new Retention library with a Reason enum, a retention pass in the Deletes worker that finds deployments matching retention policy and enqueues their deletion, the deploymentRetention message wiring in the worker message init, and unit tests for both the retention library and the worker pass.

Files Change
src/Appwrite/Deployment/Retention.php, src/Appwrite/Deployment/Retention/Reason.php New retention domain library defining the Reason enum and retention matching logic.
src/Appwrite/Platform/Workers/Deletes.php Adds a deploymentRetention worker action that queries deployments per retention reason and enqueues delete messages.
app/init/worker/message.php Registers the new deploymentRetention message type in the worker DI wiring.
tests/unit/Deployment/RetentionTest.php, tests/unit/Platform/Workers/DeletesTest.php Unit tests covering retention matching and the worker's retention pass.

Reviewed commit: ec6dd0d

@ghost

ghost commented Oct 19, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

Adds a worker-scoped deployment retention policy that combines resource-requested age retention with policy defaults, maximum ages, and a finished-deployment count cap, while preserving active and manually kept deployments. It routes each disjoint retention pass through the delete worker seam, documents the updated meaning of a zero request, and adds library and maintenance coverage for retention behavior.

Latest changes: The newest commits extract the count-lookup-failure database into its own test file and trim the retention unit suite to selected edge cases, removing the resolver matrix and several baseline pass tests.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 13
File Change
app/init/worker/message.php Registers a worker-scoped deployment retention policy resource.
src/Appwrite/Deployment/Retention.php Resolves age policy and creates disjoint requested, policy, and count passes.
src/Appwrite/Deployment/Retention/Pass.php Carries a retention reason and its database queries.
src/Appwrite/Deployment/Retention/Reason.php Defines the reasons used to retire deployments.
src/Appwrite/Platform/Workers/Deletes.php Applies retention passes during deployment cleanup and continues maintenance after per-resource failures.
src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php Clarifies requested retention behavior when server defaults apply.
src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php Clarifies requested retention behavior when server defaults apply.
src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php Clarifies requested retention behavior when server defaults apply.
src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php Clarifies requested retention behavior when server defaults apply.
tests/e2e/Services/Sites/SitesConsoleClientTest.php Verifies maintenance preserves the active deployment and one deployment within requested retention.
tests/unit/Deployment/CountLookupFailingDatabase.php Provides a database test double that fails the count cutoff lookup.
tests/unit/Deployment/RetentionTest.php Tests selected disjoint age/count pass behavior and count-lookup failure ordering.
tests/unit/Platform/Workers/DeletesTest.php Updates worker test setup to pass the new deployment retention dependency.

Reviewed the commits since d7f81e9 · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

@ChiragAgg5k ChiragAgg5k self-assigned this Oct 19, 2026

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟢 Tier S · Looks good to merge. Summary

@github-actions

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

19 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (12)
  • php.appwrite.secret-compare-timing (5)
  • php.appwrite.weak-secret-env-default (2)

Posted by Checks / Rules. Re-runs update this comment in place. Rule details and baseline: .semgrep/README.md.

@luxor-code-review luxor-code-review Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Adds a deployment-retention subsystem with an enum of retention reasons and a scheduled Deletes worker pass that enqueues retention-based deployment deletions, plus unit tests.

Key findings

  • 🟡 Overlapping retention passes double-enqueue deployments — Deletes.php:637
  • 🟡 deploymentRetention is never populated from configuration — message.php:211

Comment thread app/init/worker/message.php Resolved
@github-actions

github-actions Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → feat/deployment-retention-policy (after).

Metric Before After Change
🚀 Requests/sec 213.39 216.73 ⚪ +1.6%
⏱️ Latency P50 80.81 ms 80.01 ms ⚪ -1%
⏱️ Latency P95 191.2 ms 185.57 ms ⚪ -2.9%
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 80.01 185.57 13,680 216.73 -5.63
Account 153.71 280.13 720 12.12 +22.58
TablesDB 78.13 144.94 7,440 120.73 -10.89
Storage 71.87 170.04 3,600 60.06 -11.83
Functions 113.73 217.07 1,920 32.73 +5.08

Top API waits (after)

API request Max wait (ms)
account.name.update 526.18
functions.create 425.53
functions.variables.create 381.45
account.prefs.update 368.29
tablesdb.rows.decrement 343.14

@ChiragAgg5k
ChiragAgg5k force-pushed the feat/deployment-retention-policy branch from ec6dd0d to 39f0cac Compare October 19, 2026 16:35

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Tier A · Looks good to merge. Summary

Deployment cleanup only honoured the per-resource deploymentRetention
setting, so an operator had no way to set a default age, cap how long
deployments are kept, or bound how many are kept per function or site.

The policy is a Retention resource injected into the Deletes worker
(default days, max days, max count; negative values are refused). The
worker container registers all zeros, so self-hosted behaviour is
unchanged: resources with no retention still return before the rules
lookup, and a requested retention runs the same query as before. An
integration that registers non-zero values gets the age default, the age
cap and a count cap, and can override the protected retireDeployments
seam per Reason. A clamped request runs as two passes so an override can
tell the request apart from the policy, and the count pass skips rows past
the age cutoff so no deployment is handed over for two reasons.

The count cap finds the deployment at offset maxCount and retires that
one and everything older by ($createdAt, $sequence), so the delete query
never paginates with an offset. The cap counts finished deployments only,
so queued builds cannot crowd out rollback targets, and a build in progress
is never retired. A failed cutoff lookup is logged for that resource
instead of aborting maintenance. The active deployment and
deployments targeted by manual rules are always kept.

The deploymentRetention param docs no longer promise that 0 keeps
everything, since the server may apply a default.
Retention is decided by three passes (requested days, policy days, newest
count) layered over the active and pinned deployments, and a wrong pass
silently deletes builds a domain still serves. These tests drive the real
maintenance message through the worker against in-memory platform and
project databases, and assert both which deployment rows remain and which
deployments were queued for storage cleanup, so a pass that deletes rows
without queueing them, or queues without deleting, fails.

A recording subclass of the worker stands in for an override that only
logs the policy reason, and proves each deployment reaches the seam for
one reason. Further cases pin that a function and a site sharing a
sequence are retained apart, that builds in progress neither take a cap
slot nor get retired, and
that a failed cutoff lookup leaves other resources capped. The suite sets
the encryption key the scheduler needs, so it runs without deprecations.

The zero-policy cases stay green without the worker change, pinning that
self-hosted behaviour is unchanged; the policy and count cases are red
without it. The tie case fails if the count pass breaks a $createdAt tie
in the wrong order.
@ChiragAgg5k
ChiragAgg5k force-pushed the feat/deployment-retention-policy branch from 39f0cac to 66c4ec2 Compare October 19, 2026 16:41

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Tier A · See the inline comments. Summary

When a resource requests more days than the policy maximum, the policy
pass also selected every deployment the requested pass had, so an
override that records reasons without deleting saw them twice. The
policy pass is now bounded at the request cutoff.

The pass queries move into Appwrite\Deployment\Retention so they are
unit-tested as a library, as the test guidelines ask, instead of
through Deletes::action(). The sites maintenance E2E now checks which
deployments survive, not only how many.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Tier A · See the inline comments. Summary

Maintenance now applies whatever Retention::passes() yields, so the
requested, policy and count passes share the worker call the sites
maintenance E2E already exercises. A wiring regression for any pass
breaks that loop, and the library tests cover what each pass selects,
including the passes applied with deletions in between, as
maintenance applies them.

The count cutoff is looked up lazily after the age passes, as before,
and a failed lookup or retire is logged per resource instead of
aborting the remaining resources.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟢 Tier S · Looks good to merge. Summary

Default, clamp, count cap and kept deployments are covered by Cloud's
retention e2e; the remaining cases need tied timestamps, builds in
progress or a failing lookup.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Tier A · Looks good to merge. Summary

Comment thread tests/unit/Deployment/RetentionTest.php Resolved
@ChiragAgg5k
ChiragAgg5k merged commit 0f30fbc into main Oct 21, 2026
68 checks passed
@ChiragAgg5k ChiragAgg5k mentioned this pull request Oct 21, 2026
6 tasks
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