Skip to content

fix(storage): prevent concurrent chunk finalization - #13505

Merged
ChiragAgg5k merged 3 commits into
mainfrom
fix/storage-parallel-upload-finalization
Sep 6, 2026
Merged

ChiragAgg5k merged 3 commits into
mainfrom
fix/storage-parallel-upload-finalization

Conversation

@ChiragAgg5k

Copy link
Copy Markdown
Member

What does this PR do?

Fixes the upload race behind StorageCustomServerTest::testCreateBucketFileParallelChunksLargeFile in the linked CI job. This is a server bug, not a test timeout.

Utopia\Storage\Device::upload() can finalize an upload itself. Previously Appwrite locked preparation and document completion separately but called upload() outside either lock. Concurrent Local uploads could both enter joinChunks(), then unlink parts another request was still reading. CI reported Failed to open chunk ...part.3 and HTTP 500; cleanup also failed afterward.

  • Hold the existing per-file lock across preparation, transfer, and document completion, including the adapter's implicit finalization.
  • Keep completed-upload replays, event suppression, and the existing contention timeout/429 response.
  • Extend the E2E regression with concurrent duplicate chunks, distinct content blocks, response-count checks, and a completed-upload replay followed by download/hash verification. HTTP 500s are not retried or accepted.

Transfers to the storage device for the same file now serialize. Different files retain independent locks. This avoids an upstream storage API change; it can increase same-file contention. The existing 600-second lock lease is unchanged and is not automatically renewed.

Test Plan

Validated in an isolated Local-storage/PostgreSQL dedicated stack with the repository's locked Composer dependencies, PHP 8.5.9, and Swoole:

  • Mounted unchanged main's Create.php into the same stack and ran the enhanced regression: the duplicate-chunk dataset failed with HTTP 500 and Failed to open chunk ...part.2, reproducing the CI failure mechanism.
  • Restored the fix and ran both concurrency datasets 20 times: 40 tests, 1,320 assertions, all passed.
  • Full Storage PHPUnit suite: 93 tests, 1,508 assertions, one antivirus-only skip.
  • CI-style ParaTest: vendor/bin/paratest --processes 4 --functional tests/e2e/Services/Storage --exclude-group abuseEnabled --exclude-group screenshots --exclude-group antivirus: 92 tests, 1,600 assertions, all passed.
  • composer lint for both changed files, php -l for both files, and git diff --check: passed.
  • Independent read-only review: no blockers.

S3, shared-table mode, and antivirus integration were not exercised locally.

Related PRs and Issues

Checklist

  • Read the Contributing Guidelines and AGENTS.md.
  • No API metadata/spec/example changes are needed.

@greptile-apps

greptile-apps Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR serializes preparation, transfer, implicit storage finalization, and document completion under the existing per-file lock.

  • Exposes the active distributed lock to lock callbacks.
  • Refreshes the upload lease immediately before transfer and checks ownership before document completion.
  • Expands the storage regression test to cover concurrent duplicate chunks, response counts, replay behavior, and downloaded-content integrity.

Confidence Score: 5/5

The PR appears safe to merge, with no outstanding actionable findings.

The upload lifecycle is serialized under one per-file lock, lease ownership is checked around the transfer, completed-upload replays remain handled, and the expanded regression test validates duplicate concurrency and final content integrity.

Important Files Changed

Filename Overview
app/init/resources.php Passes the active distributed lock to callbacks so long-running operations can refresh and inspect their lease.
src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Create.php Holds one per-file lock across upload preparation, transfer, and completion while preserving contention and replay behavior.
tests/e2e/Services/Storage/StorageBase.php Extends the parallel-upload regression coverage with duplicate chunks, distinct data, replay checks, and hash verification.

Reviews (4): Last reviewed commit: "Merge branch 'main' into fix/storage-par..." | Re-trigger Greptile

@ChiragAgg5k

Copy link
Copy Markdown
Member Author

Full local before/after verification

Ran the complete CI-style Storage suite against both baseline and fix in the same isolated PostgreSQL dedicated / Local-storage environment (PHP 8.5.9, locked dependencies). Both runs used the same enhanced tests from this PR; only the HTTP upload action was swapped. SHA-256 checks verified the mounted action matched baseline 7800bfadbe and PR head 7edb7619b4 respectively.

vendor/bin/paratest --processes 4 --functional tests/e2e/Services/Storage \
  --exclude-group abuseEnabled --exclude-group screenshots --exclude-group antivirus
Version Result
Before: unchanged main upload action 92 tests, 1,537 assertions, 4 failures (exit 1)
After: this PR's upload action 92 tests, 1,599 assertions, 0 failures (exit 0)

All four baseline failures were testCreateBucketFileParallelChunksLargeFile HTTP 500s: distinct chunks in CustomClient, ConsoleClient, and CustomServer, plus duplicate chunks in CustomServer. Server logs confirmed Utopia\Storage\Exception\StorageException: Failed to open chunk ...part.2/3/4.

This supplements the earlier targeted before/after reproduction, 20 repeated fixed regression runs, and passing full-suite checks. S3, shared-table mode, and antivirus integration remain untested locally.

@ChiragAgg5k

Copy link
Copy Markdown
Member Author

@greptile review

@github-actions

github-actions Bot commented Sep 6, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/storage-parallel-upload-finalization (after).

Metric Before After Change
🚀 Requests/sec 236.95 236.79 ⚪ -0.1%
⏱️ Latency P50 76.43 ms 76.61 ms ⚪ +0.2%
⏱️ Latency P95 162.04 ms 163.15 ms ⚪ +0.7%
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.61 163.15 14,820 236.79 +1.11
Account 140.59 231.89 780 13.26 -15.19
TablesDB 76.85 134.5 8,060 132.03 -1.89
Storage 64.63 143.42 3,900 65.52 +1.69
Functions 102.52 191.96 2,080 35.54 +5.75

Top API waits (after)

API request Max wait (ms)
storage.files.preview 412.99
functions.create 386.6
account.name.update 382.67
functions.variables.update 320.39
storage.buckets.create 307.97

The per-file lock used a fixed 600 second lease measured from acquisition.
A slow transfer could outlive it and let a second request finalize the same
file concurrently. The lock resource now hands the Distributed lock to its
callback so the upload refreshes the lease before the transfer and verifies
it still holds the lock before recording completion, failing with the existing
429 instead of finalizing under a lapsed lease.
@ChiragAgg5k
ChiragAgg5k merged commit c0e04f1 into main Sep 6, 2026
46 checks passed
@ChiragAgg5k
ChiragAgg5k deleted the fix/storage-parallel-upload-finalization branch September 6, 2026 18:30
abnegate added a commit that referenced this pull request Sep 7, 2026
Storage learned this in #13505 and the two deployment endpoints were left
behind. Both took the per-deployment lock to prepare, dropped it to transfer,
and took it again to finalize. upload() finalizes by itself once it sees the
last chunk, and Local::joinChunks() renames the assembled file and then unlinks
the parts, so a concurrent chunk that passed the file_exists check a moment
earlier finds its part gone and 500s out of joinChunks.

CI showed it as `"parts":{"2":true,"5":true,"3":true},"chunks":5` — three of
five parts left — on Functions and on Sites, across PostgreSQL and MongoDB. The
sibling assertion, testUpdateSiteDeploymentRequiresOwnership, saw the same race
as an empty deployment id.

Prepare, transfer and finalize now run in one lock, shaped like the Storage fix:
the lease is refreshed before the transfer so it gets a full window, and checked
after it so nothing is recorded under a lapsed lease. This serialises the chunks
of a single deployment, which is what Storage already accepted, and it depends
on the lock pool having room for the waiters.

Covered by testCreateDeploymentParallelChunksLargeFile in both suites, which is
what caught it.

Co-Authored-By: Claude Opus 5 <[email protected]>
@ChiragAgg5k ChiragAgg5k mentioned this pull request Sep 10, 2026
2 of 4 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.

2 participants