Skip to content

fix(deletes): protect branch-pinned deployments during retention - #15075

Merged
ChiragAgg5k merged 6 commits into
mainfrom
cursor/fix-vcs-retention-branch-rule-race-21e8
Oct 29, 2026
Merged

ChiragAgg5k merged 6 commits into
mainfrom
cursor/fix-vcs-retention-branch-rule-race-21e8

Conversation

@ChiragAgg5k

@ChiragAgg5k ChiragAgg5k commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

Evidence

Flaky E2E: Tests\E2E\Services\VCSGitea\VCSGiteaConsoleClientTest::testDeploymentRetentionKeepsTheBuildBehindABranchDomain (PostgreSQL dedicated VCSGitea lane).

  • 4 failures on 4 distinct SHAs (2026-10-19 → 2026-10-24), 1 pass on rerun
  • Example runs: 39288990051, 39253858358, 40091148658
  • Assertion: the build behind the custom domain is kept — $pinnedId missing from deployments after maintenance retention (~line 268)

Before fix (historical): 4/4 failing runs on unique commits; ~0% pass rate on those attempts (1/1 pass on manual rerun only).

After fix: local 20× E2E loop was not feasible in this cloud agent VM (no Docker daemon). Validation is via CI on this PR (VCSGitea lane) and the existing E2E test that reproduces the scenario.

Root cause

Retention kept deployments only from a one-time snapshot of manual rules’ deploymentId. Branch-pinned domains serve the newest ready VCS build on that branch, but the build worker repoints rules on the platform DB after the deployment is ready, so maintenance could retire the pinned build while the rule row still pointed at the active deployment (or while a concurrent build finished mid-retention).

Fix

  • Deletes: deploymentIdsProtectedFromRetention() keeps deployments referenced by manual rules and resolves branch-pinned rules via the same newest-ready VCS query used when creating branch rules. The keep list is recomputed before each retention pass (with a fresh resource read) so repoints during maintenance are honored.
  • Jobs: activateBranchRule() stays after the project DB transaction commits (avoids platform rule writes surviving a rollback of ready). The Deletes-side branch lookup closes the original E2E race.

Tests

  • VCSGiteaConsoleClientTest::testDeploymentRetentionKeepsTheBuildBehindABranchDomain (existing E2E).
Open in Web Open in Cursor 

Related: appwrite-labs/cloud#6673

Retention only kept deployments listed on manual rules' deploymentId.
Branch-pinned domains follow the newest ready VCS build on that branch,
but activateBranchRule ran after the deployment was marked ready, so
maintenance could retire the build before the rule row was repointed.

Resolve the protected deployment from the branch build query used when
creating branch rules, and repoint branch rules in the same transaction
that marks a function build ready.

Co-authored-by: Chirag Aggarwal <[email protected]>
@luxor-code-review

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

Copy link
Copy Markdown

Review complete. 🟡 2 medium

💬 Inline comments (2)

  • 🟡 Retention kept-list races build worker rule repoint — Deletes.php:650
  • 🟡 Branch-rule repoint inside transaction can outlive rollback — Jobs.php:812
🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 Per-rule findOne in retention scan adds N+1 (Deletes.php:721) — The new deploymentIdsProtectedFromRetention() issues a findOne('deployments') query per branch-pinned rule inside the listByGroup('rules', ...) callback (src/Appwrite/Platform/Workers/Deletes.php:721).

The change keeps the latest ready deployment for each branch-rule alive during retention sweeps and repoints those rules transactionally. One producer artifact (the high-recall diff sweep) never published, so its coverage is absent from this review.

Files Change
src/Appwrite/Platform/Workers/Deletes.php Retention now computes a kept-list of newest ready branch builds and skips deleting them, via per-rule lookups.
src/Appwrite/Platform/Modules/Functions/Workers/Jobs.php Branch-rule activation/repointing wrapped in a transaction on build completion.
tests/unit/Platform/Workers/DeletesTest.php Unit coverage for the retention kept-list behavior.

Reviewed commit: da23f61

@ChiragAgg5k ChiragAgg5k self-assigned this Oct 28, 2026
@ghost

ghost commented Oct 28, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

The new regression exercises the pre-count refresh behavior, and I found no remaining issues in the incremental changes.

Deployment retention now excludes active deployments, deployments referenced by manual rules, and the newest ready VCS build for branch-pinned rules. The protection query is refreshed for retention passes and before the count cutoff, while successful VCS builds update branch rules only after the ready-state transaction commits. The added unit regression verifies that refreshed protection keeps a deployment out of the count-cap calculation.

Latest changes: The latest commit adds a RetentionTest regression that supplies the pre-count refresh callback and verifies a protected deployment does not consume a retention slot.

Verdict New comments Fixed Still open
✅ Approved 0 1 0
📂 Walkthrough · 4
File Change
src/Appwrite/Deployment/Retention.php Adds a callback to refresh resource queries before calculating the count-retention cutoff.
src/Appwrite/Platform/Workers/Deletes.php Excludes active, manually pinned, and branch-pinned deployments from retention, refreshing the protection queries before passes and the count cutoff.
src/Appwrite/Platform/Modules/Functions/Workers/Jobs.php Updates branch-pinned rules after a successful VCS build is committed as ready.
tests/unit/Deployment/RetentionTest.php Adds coverage that verifies refreshed protection excludes a deployment from the count cap.
✅ Fixed since the last review · 1
  • Cover the pre-count refresh path with a regression test · src/Appwrite/Deployment/Retention.php:65

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

@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

Worker retention protection stays covered by VCSGitea E2E; AGENTS.md
reserves unit tests for libraries, not Platform workers.

Co-authored-by: Chirag Aggarwal <[email protected]>

@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

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

This PR protects the newest ready branch build from retention cleanup and moves branch-rule activation inside a database transaction.

Key findings

  • 🟡 Retention kept-list races build worker rule repoint — Deletes.php:650
  • 🟡 Branch-rule repoint inside transaction can outlive rollback — Jobs.php:812

$kept[] = $rule->getAttribute('deploymentId');
}
);
$kept = $this->deploymentIdsProtectedFromRetention($dbForPlatform, $dbForProject, $project, $resource);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 bug · medium

Retention kept-list races build worker rule repoint

deleteOldDeployments computes the protected-id snapshot once and retires deployments in later passes (src/Appwrite/Platform/Workers/Deletes.php:650, 662-664). A build worker can finalize between the snapshot and the delete and repoint a branch rule at the new deployment (src/Appwrite/Platform/Modules/Functions/Workers/Jobs.php:917-921); that deploymentId was not in the kept list, so retention can delete the deployment the rule now serves. The new branch-newest lookup narrows but does not close the window, since a deployment still building at snapshot time matches neither status: ready nor any rule's deploymentId, and when two builds of the same branch finish out of order activateBranchRule repoints the rule to the just-finished build even though the kept lookup already captured a different newest-ready id. A domain pinned to a branch can briefly serve a deleted build after retention runs concurrently with a successful push.

📋 Prompt for AI Agents

In src/Appwrite/Platform/Workers/Deletes.php, deleteOldDeployments() around lines 650-664: the $kept id list from deploymentIdsProtectedFromRetention() is snapshotted once, but the build worker can repoint a manual/branch rule to a newer deployment between the snapshot and retireDeployments(), letting retention delete a deployment a rule now serves. Close the window by recomputing deploymentIdsProtectedFromRetention() inside the loop over $retention->passes(...) (or immediately before enqueueing each delete in retireDeployments(), re-fetching the resource's manual rules with the same filters and skipping deployments a rule's current deploymentId points at) so a rule repointed by the build worker during retention is still honored.

Comment on lines +812 to +813
} elseif ($applied > 0 && $success && $collection !== 'sites' && $deployment->getAttribute('activate') !== true && ! $resource->isEmpty()) {
$this->activateBranchRule($dbForPlatform, $project, $resource, $deployment, $bus);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 bug · medium

Branch-rule repoint inside transaction can outlive rollback

activateBranchRule moved inside the $dbForProject->withTransaction(...) closure (src/Appwrite/Platform/Modules/Functions/Workers/Jobs.php:812-813), but it writes rules through $dbForPlatform->updateDocument and dispatches RuleUpdated bus events that the transaction does not cover. If the transaction fails or rolls back after the closure body ran (deadlock, serialization failure on the status update), the deployment's status: ready transition is rolled back while the branch rules were already repointed to it — the router can serve a deployment that never became ready on a branch-pinned domain. Pre-patch, activateBranchRule ran strictly after the transaction returned, so a rollback could never leave repointed rules behind.

📋 Prompt for AI Agents

In src/Appwrite/Platform/Modules/Functions/Workers/Jobs.php, finalize() around lines 803-819: activateBranchRule was moved inside the $dbForProject->withTransaction closure, but it mutates platform-DB rules and dispatches RuleUpdated bus events that are outside the transaction's rollback scope. Restore the previous ordering: inside the transaction keep only the status update and activate() (which was already transactional pre-patch), and after the transaction returns with $applied > 0, run the branch-rule condition ($success && $collection !== 'sites' && $deployment->getAttribute('activate') !== true && !$resource->isEmpty()) before the activateBranchPreviewRule block, so a transaction rollback never leaves branch rules repointed to a deployment whose ready status was rolled back.

Recompute rule and branch-pinned keep list before every retention pass so
a build worker repoint during maintenance is honored. Move activateBranchRule
back outside the project transaction so platform rule writes cannot outlive
a rollback of the ready status.

Co-authored-by: Chirag Aggarwal <[email protected]>

@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

@github-actions

github-actions Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

6 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (3)
  • php.appwrite.secret-compare-timing (1)
  • 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.

Pass retention the same resource queries as before, including notEqual
filters for protected builds, while still recomputing that keep list
before each pass when enqueuing deletes.

Co-authored-by: Chirag Aggarwal <[email protected]>

@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

Retention passes now accept a callback that rebuilds resource queries
immediately before the count-cap lookup, after age passes may have run
concurrently with new branch builds.

Co-authored-by: Chirag Aggarwal <[email protected]>

@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 src/Appwrite/Deployment/Retention.php Resolved
Assert that refreshResourceBeforeCount shifts the count-cap cutoff when
a protected deployment must not consume a retention slot.

Co-authored-by: Chirag Aggarwal <[email protected]>

@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

✨ Benchmark results

Comparing main (before) → cursor/fix-vcs-retention-branch-rule-race-21e8 (after).

Metric Before After Change
🚀 Requests/sec 181.64 206.33 🟢 +13.6%
⏱️ Latency P50 93.58 ms 83.35 ms 🟢 -10.9%
⏱️ Latency P95 227.06 ms 199.19 ms 🟢 -12.3%
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 83.35 199.19 12,711 206.33 -27.87
Account 161.65 292.78 669 11.09 -54.4
TablesDB 79.08 147.05 6,913 113.85 -32.1
Storage 80.2 184.68 3,345 57.31 -16.49
Functions 122.63 238.85 1,784 31.4 -19.39

Top API waits (after)

API request Max wait (ms)
storage.buckets.create 442.67
account.name.update 412.4
functions.create 400.96
account.prefs.update 367.91
functions.variables.create 367.71

@ChiragAgg5k
ChiragAgg5k merged commit c5d0572 into main Oct 29, 2026
114 of 119 checks passed
@ChiragAgg5k
ChiragAgg5k deleted the cursor/fix-vcs-retention-branch-rule-race-21e8 branch October 29, 2026 10:32
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