Skip to content

fix(deletes): clear build output of deployments deleted mid-build - #14927

Merged
ChiragAgg5k merged 3 commits into
mainfrom
fix/deletes-cancel-build-orphans
Oct 25, 2026
Merged

ChiragAgg5k merged 3 commits into
mainfrom
fix/deletes-cancel-build-orphans

Conversation

@ChiragAgg5k

@ChiragAgg5k ChiragAgg5k commented Oct 24, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Deleting a deployment while it builds leaves the build artifact in storage with no row owning it.

DELETE deployment        -> row gone, build keeps running
deletes worker           -> deletes buildPath (not written yet, "success")
build finishes           -> writes {deploymentId}/code.* to the builds device
jobs worker              -> deployment empty, return    => orphan

Three fixes:

// Functions + Sites Http/Deployments/Delete.php: stop an unfinished build
if (!\in_array($deployment->getAttribute('status'), ['ready', 'failed', 'canceled'], true)) {
    $deployments->cancel($deployment->getId());   // best-effort, same as Status/Update
}

// Workers/Jobs.php: after the deduplicated handler, so every delivery of a callback for a deleted deployment retries the cleanup
if (CallbackEvent::tryFrom($event->event) !== CallbackEvent::Log
    && $dbForProject->getDocument('deployments', $deploymentId)->isEmpty()
    && !Deployments::deleteBuildDirectory($deviceForBuilds, $deploymentId)) {
    throw new \RuntimeException(...);
}

// Workers/Deletes.php deleteBuildFiles(): the whole {deploymentId}/ directory, not just buildPath
Deployments::deleteBuildDirectory($device, $deploymentId);

deleteBuildDirectory() uses deletePath($deploymentId) (the per-deployment directory, not dirname(buildPath), so a buildPath in another layout never widens the delete). Builds can write into that directory on the local device, so Local::delete(..., true) and Local::deletePath() now unlink symbolic links instead of recursing into their targets.

Jobs.php only appends to the end of action() and leaves the dedupe block alone, so it does not overlap #14914.

Test Plan

  • FunctionsCustomServerTest::testDeleteDeploymentDuringBuild: delete a deployment mid-build (commands: sleep 10), wait past the build, assert listFiles({deploymentId}) is [].
  • DeploymentsTest::testDeleteBuildDirectoryReportsWhetherAnythingIsLeft: deletes the whole directory, reports success when nothing is left (so a retry succeeds), and refuses a symlinked directory.
  • LocalTest::testRecursiveDeleteDoesNotFollowSymlinks: delete()/deletePath() on a directory holding a symlink leave the link target intact.

The retry after a failed cleanup lives in the worker and has no E2E: a storage failure cannot be forced from an E2E test.

Related: appwrite-labs/cloud#6628

Deleting a deployment while it builds let the build keep running and write
its artifact after the deletes worker had already run, with no row left to
own it. The delete endpoints now cancel an unfinished build, the jobs worker
removes the build directory when a callback arrives for a deleted deployment,
and deletes remove the whole per-deployment build directory rather than only
buildPath.

Local recursive deletes no longer follow symbolic links, since builds can
write into the directory being removed.
@luxor-code-review

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

Copy link
Copy Markdown

Review complete. 🟠 1 high · 🟡 1 medium

📍 Findings outside the diff (2) — 🟠 1 high · 🟡 1 medium — defects on lines GitHub can't attach comments to

🟠 High — TOCTOU: symlink swap can still escape deletePath · Local.php:517–523 · unchanged line

// packages/storage/src/Device/Local.php
517	        $path = realpath($this->getRoot() . DIRECTORY_SEPARATOR . $path);
518	
519	        if ($path === false || ! is_dir($path)) {
520	            return false;
521	        }
522	
523	        $files = $this->scanDirectory($path);

Deployments::deleteBuildDirectory guards the local device with realpath($directory) !== $directory (src/Appwrite/Deployment/Deployments.php:756-758), but Local::deletePath then independently calls realpath() on the composed path (packages/storage/src/Device/Local.php:517) and recursively deletes every entry it resolves. If a symlink replaces the deployment directory between the guard and the scan, deletePath walks the link target and unlinks its contents outside the builds tree. The new per-entry is_link checks protect child entries only, not the top-level path, which is canonicalized before listing rather than checked with is_link.


🟡 Medium — Cancel skipped on storage-delete failure and violates contract · Delete.php:132–144 · unchanged line

// src/Appwrite/Platform/Modules/Sites/Http/Deployments/Delete.php
132	        if (!empty($deployment->getAttribute('sourcePath', ''))) {
133	            if (!($deviceForSites->delete($deployment->getAttribute('sourcePath', '')))) {
134	                throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to remove deployment from storage');
135	            }
136	        }
137	
138	        // A build still running would write its output after the deletes worker has cleared it.
139	        if (!\in_array($deployment->getAttribute('status'), ['ready', 'failed', 'canceled'], true)) {
140	            try {
141	                $deployments->cancel($deployment->getId());
142	            } catch (\Throwable) {
143	            }

The delete actions call $deployments->cancel() after the storage deletion that throws GENERAL_SERVER_ERROR on failure (src/Appwrite/Platform/Modules/Sites/Http/Deployments/Delete.php:132-144); if that delete fails, cancel never runs while the deployment row is already gone, leaving the in-flight build writing to the builds volume with no deletes-worker cleanup enqueued. The same ordering exists in src/Appwrite/Platform/Modules/Functions/Http/Deployments/Delete.php:114-126. Separately, Deployments::cancel()'s contract requires the deployment to already be marked canceled so racing callbacks stop finalizing (src/Appwrite/Deployment/Deployments.php:413-417), but neither action marks the status before deleting the document, so a Jobs-worker callback in that window can read a live 'building' deployment and run its full finalize path for a deployment the user just deleted.

🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 Symlinked builds root permanently disables cleanup (Deployments.php:756) — deleteBuildDirectory returns false whenever realpath($directory) differs from the unresolved $directory (src/Appwrite/Deployment/Deployments.php:756-758).

This PR hardens deletion of deployment build directories: Local::deletePath now validates paths and skips symlinks, Deployments::deleteBuildDirectory guards against paths escaping the builds root, and the Functions/Sites deployment delete actions cancel in-flight builds while the build worker learns to skip deleted deployments.
+

Files Change
packages/storage/src/Device/Local.php, packages/storage/tests/Device/LocalTest.php Adds symlink-aware recursive deletePath with per-entry is_link checks and unit tests
src/Appwrite/Deployment/Deployments.php Adds deleteBuildDirectory with a realpath containment guard and cancel for in-flight builds
src/Appwrite/Platform/Modules/Functions/Http/Deployments/Delete.php, src/Appwrite/Platform/Modules/Sites/Http/Deployments/Delete.php Delete actions now remove build directories and cancel active builds
src/Appwrite/Platform/Modules/Functions/Workers/Jobs.php, src/Appwrite/Platform/Workers/Deletes.php Build worker skips deployments deleted mid-build; deletes worker cleans build directories
tests/e2e/Services/Functions/FunctionsCustomServerTest.php E2E coverage for deleting a deployment mid-build

Reviewed commit: 40b585f

@ghost

ghost commented Oct 24, 2026 •

Copy link
Copy Markdown

🔵 Tier A · Mergeable after minor fixes

Limited by an open minor finding: Keep worker retry coverage out of the unit suite

The PR cancels unfinished deployments on deletion and removes the deployment-scoped build directory both during deletion and when a late build callback arrives. Local recursive deletion unlinks symlinks without traversing their targets, with E2E and storage/deployment regression coverage. The latest changes move late-callback cleanup outside event deduplication and add coverage for idempotent cleanup and symlink refusal.

Latest changes: The newest commits move deleted-deployment cleanup after the callback lock so redeliveries retry it even when the dedupe marker remains, and add a deployment-directory cleanup regression test.

Verdict New comments Fixed Still open
✅ Approved 0 1 1
Fix with agent prompt
### Issue 1
tests/unit/Platform/Modules/Functions/Workers/ActivateRulesTest.php:177
**Keep worker retry coverage out of the unit suite**

This directly invokes `Jobs::action()` with stubbed dependencies, adding a unit test for worker behavior. The repository guidance says not to unit-test workers and to cover their behavior through E2E, so this retry scenario belongs in the worker's E2E coverage instead.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
📂 Walkthrough · 10
File Change
packages/storage/src/Device/Local.php Unlinks symlinks during recursive deletion instead of following their targets.
packages/storage/tests/Device/LocalTest.php Covers symlink-safe recursive deletion and deletePath behavior.
src/Appwrite/Deployment/Deployments.php Adds deployment-scoped build-directory cleanup with local symlink protection.
src/Appwrite/Platform/Modules/Functions/Http/Deployments/Delete.php Cancels unfinished function builds when their deployment is deleted.
src/Appwrite/Platform/Modules/Functions/Workers/Jobs.php Cleans build output when callbacks arrive after the deployment has been deleted, outside callback deduplication.
src/Appwrite/Platform/Modules/Sites/Http/Deployments/Delete.php Cancels unfinished site builds when their deployment is deleted.
src/Appwrite/Platform/Workers/Deletes.php Removes the entire deployment build directory during deployment deletion.
tests/e2e/Services/Functions/FunctionsCustomServerTest.php Covers deleting a deployment during a build and checking its output is removed.
tests/unit/Platform/Modules/Functions/Workers/ActivateRulesTest.php Covers retries of late cleanup after a cleanup failure.
tests/unit/Deployment/DeploymentsTest.php Covers successful and repeat build-directory cleanup and refuses to follow a symlink.
⏳ Still open from earlier reviews · 1
✅ Fixed since the last review · 1
  • Keep cleanup retryable if marker purge fails · src/Appwrite/Platform/Modules/Functions/Workers/Jobs.php:185

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

@ChiragAgg5k ChiragAgg5k self-assigned this Oct 24, 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 A · See the inline comments. Summary

@github-actions

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.

@github-actions

github-actions Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/deletes-cancel-build-orphans (after).

Metric Before After Change
🚀 Requests/sec 221.34 227.41 ⚪ +2.7%
⏱️ Latency P50 76.55 ms 76.22 ms ⚪ -0.4%
⏱️ Latency P95 184.71 ms 173.13 ms 🟢 -6.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 76.22 173.13 14,193 227.41 -11.58
Account 143.52 256.42 747 12.39 -29.92
TablesDB 75.04 137.42 7,719 126.24 -3.59
Storage 68.1 160.59 3,735 62.72 -9.55
Functions 105.48 196.54 1,992 34.18 -49.24

Top API waits (after)

API request Max wait (ms)
functions.create 419.58
account.name.update 364.1
account.prefs.update 342.73
functions.variables.update 302.54
functions.delete 292.22

The callback's dedupe key is saved before the cleanup runs, so a cleanup
that failed was skipped as already processed on redelivery and its output
stayed orphaned. Release the key and fail the callback instead.

@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

Purging the dedupe marker on a failed cleanup still lost the retry when the
cache itself was down. The cleanup now runs after the deduplicated handler,
so every delivery of a callback for a deleted deployment retries it whatever
the marker says, and Jobs.php no longer touches the dedupe block. Coverage
moves from a worker unit test to the Deployments library, per the test
guidance.

@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

@ChiragAgg5k
ChiragAgg5k merged commit d748a81 into main Oct 25, 2026
76 checks passed
@ChiragAgg5k
ChiragAgg5k deleted the fix/deletes-cancel-build-orphans branch October 25, 2026 07:00
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