Skip to content

fix: clean up expired and failed CSV/JSON exports - #14758

Merged
ChiragAgg5k merged 15 commits into
mainfrom
fix/exports-cleanup
Oct 22, 2026
Merged

ChiragAgg5k merged 15 commits into
mainfrom
fix/exports-cleanup

Conversation

@ChiragAgg5k

@ChiragAgg5k ChiragAgg5k commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

What

Expired CSV/JSON exports were never deleted, and a failed export left its file in storage.

Problem Cause Fix
Expired exports never cleaned deleteOldCSVExports filtered endsWith('name', '.csv'), but export rows store the user's filename without an extension, so nothing matched; JSON was never covered Select by the platform default bucket (it only holds migration transfer files) + createdBefore(DATA_EXPORT_RETENTION)
Failed export leaves an orphan object CSV/JSON destination shutdown() uploads the file before the worker sees the errors; the worker then marks the migration failed and calls error(), which was a no-op error() deletes the file this run uploaded, plus the local working copy
Query::equal('bucketId', [$bucket->getId()]),
Query::createdBefore($expiry),

The default bucket also holds files the Console stages for imports; those are copied out when the import is created, so they now expire after the same week too.

Ownership

Case Behaviour
Failure after the file row is created The worker calls $destination->success() right after creating the row, so error() leaves the file in place
A run that never uploaded the file error() only deletes what its own shutdown() uploaded
Several workers with different storage devices sharing one platform database Cleanup drops a row only after this worker's device held the object and deleted it; a missing object (an S3 delete of a missing key still succeeds) or a failed delete keeps the row
A row whose object is gone everywhere Dropped once it is older than 2 × DATA_EXPORT_RETENTION, after every worker sharing the database has had a full cycle

Tests

CSVTest/JSONTest: test{CSV,JSON}ExportFailureLeavesNoFile (the uploader's error() removes the file) and test{CSV,JSON}ExportFailureKeepsAFileItDoesNotOwn (after success(), or from a run that never uploaded, the file survives). Each failed on CI before its fix (0a81ce9, 734a425) and passes with it.

The retention cleanup has no E2E: the retention is a fixed week, so an E2E cannot create an expired export.

The race between two retries of the same migration predates this PR and is left to a separate change.

Related: appwrite-labs/cloud#6628

shutdown() uploads the export before the worker checks for errors, so a
failed export keeps its object in storage with no file row pointing at it.
@github-actions

github-actions Bot commented Oct 22, 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.

Export file rows store the user's filename without an extension, so the
endsWith('name', '.csv') filter matched nothing and JSON exports were never
selected. The platform default bucket only holds migration transfer files,
so expire everything in it after the export retention.

A failed export already had its file uploaded by shutdown(); the worker
calls error() on failure, which now removes the uploaded file and the
local working copy.
@ChiragAgg5k ChiragAgg5k self-assigned this Oct 22, 2026
@github-actions

github-actions Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/exports-cleanup (after).

Metric Before After Change
🚀 Requests/sec 219.62 219.58 ⚪ 0%
⏱️ Latency P50 80.79 ms 76.98 ms ⚪ -4.7%
⏱️ Latency P95 177.98 ms 191.4 ms 🔴 +7.5%
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.98 191.4 13,680 219.58 +13.42
Account 153.67 298.48 720 12.31 +36.81
TablesDB 74.36 147.07 7,440 122.8 +5.8
Storage 70.42 166.64 3,600 60.64 -8.61
Functions 113.88 235.13 1,920 33.17 +36.75

Top API waits (after)

API request Max wait (ms)
account.name.update 565.23
tablesdb.rows.create 521.78
functions.variables.update 413.18
functions.create 386.52
functions.delete 384.58

…ites

The failed-export cases belong with the other destination tests rather
than in a file of their own.
…nation

The new imports in CSVTest shift the anonymous class from line 124 to 127,
and the baseline entry names the class by its line.
@ChiragAgg5k
ChiragAgg5k marked this pull request as ready for review October 22, 2026 09:33
@luxor-code-review

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

Copy link
Copy Markdown

Review complete. 🟡 1 medium

💬 Inline comments (1)

  • 🟡 Finalization failure deletes an already-published export file — CSV.php:238

The PR makes failed export runs clean up after themselves: CSV::error() and JSON::error() now delete the physical output file on deviceForFiles, and the Deletes worker's deleteOldExports() no longer filters by the .csv suffix since export rows are extension-less. The cleanup query targets the platform default bucket by $bucket->getId() and deletes files older than DATA_EXPORT_RETENTION in batches via deleteByGroup; tests are added for both destinations.

Files Change
packages/migration/src/Destinations/CSV.php, JSON.php Add error() handlers that delete the staged export file when finalization fails, plus bucketId wiring.
src/Appwrite/Platform/Workers/Deletes.php Widen deleteOldExports() from .csv-suffix to all files in the default bucket past retention.
packages/migration/tests/General/* Unit tests covering the new cleanup behavior for both destinations.

Reviewed commit: 21326ba

@ghost

ghost commented Oct 22, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

The PR adds ownership-aware cleanup for failed CSV/JSON exports and creates platform file records for completed exports, while expiring old files from the default bucket and removing stranded export rows. It also updates migration retry and stale-state handling, and adds destination ownership tests plus worker-test adjustments. The latest change narrows stale migration recovery to rows in processing status.

Latest changes: The newest commit renames the stale-migration recovery helper and limits its query to processing rows, removing the pending status from its recovery sweep.

Verdict New comments Fixed Still open
✅ Approved 0 0 0

Couldn't attach to a line

These findings could not be placed on a changed line, so they were not posted as inline comments.

📂 Walkthrough · 8
File Change
packages/migration/phpstan-baseline.neon Updates the static-analysis baseline for migration export tests.
packages/migration/src/Destinations/CSV.php Tracks the uploaded export file and deletes it on failure only while this destination owns it.
packages/migration/src/Destinations/JSON.php Applies the same ownership-aware failure cleanup to JSON exports.
packages/migration/tests/General/CSVTest.php Tests failed-export cleanup and preservation of files not owned by the current run.
packages/migration/tests/General/JSONTest.php Tests failed-export cleanup and preservation of files not owned by the current run.
src/Appwrite/Platform/Workers/Deletes.php Cleans expired and stranded export files and recovers stale processing migrations.
src/Appwrite/Platform/Workers/Migrations.php Creates platform file records for completed exports and transfers destination ownership to those records.
tests/unit/Migration/MigrationsWorkerExportTest.php Adjusts the worker export test for destination ownership handling.

Reviewed the commits since d30c490 · 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 · See the inline comments. 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.

Adds error() cleanup to CSV/JSON migration destinations so failed data-export workers delete staged output files, and widens the weekly Deletes worker cleanup to all expired files in the default bucket instead of .csv files only.

Key findings

  • 🟡 Finalization failure deletes an already-published export file — CSV.php:238

A run that never uploaded the file, or already handed it to its caller,
must not delete it: a retry of the same migration writes to the same path,
and the worker keeps going after the file row is created.
error() deleted the export path unconditionally, so a failure after the
file row was created removed the object from under the row, and a retry
that failed early could delete the file another run had published.

The destination now marks the file as its own when shutdown() starts the
upload and gives it up in success(); the worker calls success() right
after it creates the file row.
Workers with different storage devices can share one platform database.
An S3 delete of a missing key still succeeds, so a worker that does not
hold the object would drop the row and the worker that does would never
clean the object. Skip rows whose object is not on this device, and keep
the row when the delete fails so the next run retries it.

@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 B · See the inline comments. Summary

…bles

handleDataExportComplete() now takes the destination so it can hand the
file over once the file row exists; the worker test asserts it does so for
every export it finalizes.

@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

Only an export destination waits for its file row before succeeding;
every other destination still succeeds before its source, as before.
…eing

The retry endpoint checked for `failed` but never stored the new status, so
a second retry could enqueue another attempt of the same migration, and both
attempts write to the same export path. Re-read and persist `pending` under
a per-migration lock so a concurrent or repeated retry is refused.
A row whose object is already gone (deleted before its row, for instance)
was skipped on every run. Past twice the retention every worker sharing the
database has had a full cycle to clean its own object, so such a row is
stranded and is removed.
Worker behaviour is covered by the package tests and E2E; the worker unit
test only needs the destination argument to compile.

@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

The retry now stores `pending` before publishing. If publishing returns
false or throws, nothing will pick the migration up, so it stayed pending
and every later retry was refused as in progress. Put it back to `failed`
(only while it is still pending) and report the error.

@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

A publish exception does not prove the queue rejected the message, so
restoring `failed` could let a second retry run alongside the first. Only a
`false` from enqueue() restores `failed` now; on an exception the migration
stays `pending`, and the stuck-migration sweep, which already fails
`processing` migrations untouched for three days, fails `pending` ones too.

@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

The race between two retries of the same migration predates the export
cleanup, and each fix to the retry path surfaced a new queue edge case.
Restore the retry endpoint and the stuck-migration sweep to their previous
behaviour so this change stays about export files.

@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

@ChiragAgg5k
ChiragAgg5k merged commit dcc02c9 into main Oct 22, 2026
249 checks passed
Tapraj-Pathak pushed a commit to Tapraj-Pathak/appwrite that referenced this pull request Oct 24, 2026
fix: clean up expired and failed CSV/JSON exports
(cherry picked from commit dcc02c9)
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