Skip to content

Stream S3 backend downloads without temporary-file spooling - #14607

Merged
loks0n merged 6 commits into
mainfrom
codex/s3-backend-streaming
Oct 16, 2026
Merged

loks0n merged 6 commits into
mainfrom
codex/s3-backend-streaming

Conversation

@loks0n

@loks0n loks0n commented Oct 16, 2026 •

Copy link
Copy Markdown
Member

S3 downloads wait for the whole backend object to spool into a temporary file. Forward one validated backend GET directly, preserving immutable-version overwrite consistency and bounding PHP memory. Queue obsolete-path cleanup so backend DELETE cannot block overwrite behind an active GET. Existing seekable read() and legacy-client fallbacks remain compatible.

The optional response-aware client capability exposes status before bytes. Error payloads and ignored ranges cannot become object data; canceled/truncated transfers never replay delivered bytes. Local handles are captured under the writer lock; backend reads use immutable paths, with one moved-path retry allowed only before delivery. Cleanup messages contain only the obsolete path and are idempotent.

Validation: Linux client 270 tests / 1,023 assertions; storage unit 139 / 458; native Swoole/cURL/MinIO streaming/cleanup/hash drills; selected full Cloud S3 gateway E2E 11 / 201. Buffering and capability regressions observed red then green. CE CI green after retrying an unrelated GitLab repository-cleanup HTTP 500. Cloud full CI green on measured runtime; final source PR CI is fully green.

Live NYC Spaces canary passed full 100 MiB and 15 MiB range hashes, HEAD, multipart and concurrent overwrite (write completed after 1,882,516 bytes; original GET intact, next GET replacement). Full before/after benchmarks: 1,006 measured samples each, zero failures/no exclusions; same Node 24.22.0/files-sdk 3.0.0/England→NYC route. Median 100 MiB throughput 22.34→32.79 MB/s; first chunk 1,641.08→177.63 ms. Rebuilt graph labels Appwrite as one route versus other providers’ supplied six-location medians.

Consumers must deploy before producers; rollback producers first, drain new files cleanup messages, then downgrade consumers. No database migration. NYC consumer/producer config PRs 625 and 626 merged. Cloud 1.51.6 is now live in all six production regions: https://github.com/appwrite-labs/cloud/releases/tag/1.51.6 . All 290 deployments and 12 ArgoCD applications verified healthy; source hashes match in every region. Temporary benchmark resources removed.

Cloud integration: https://github.com/appwrite-labs/cloud/pull/6616 . Full operational notes, benchmark provenance and artifact inventory: https://github.com/appwrite-labs/cloud/issues/6615 .

@loks0n loks0n self-assigned this Oct 16, 2026
@luxor-code-review

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

Copy link
Copy Markdown

Review complete. 🟠 1 high · 🟡 1 medium

💬 Inline comments (2)

  • 🟠 Redirect body fires onResponse with 3xx headers — Client.php:258
  • 🟡 Capability precondition burn inside retry loop — Retry.php:80

The change wires response-header-aware streaming through the client package: the curl adapter gains an onResponse callback so a sink receives body bytes only after headers are validated, and the retry decorator propagates that capability with replay-safe semantics. The storage package builds a range-aware S3::stream() on top, with Content-Range/ETag checks and a buffered fallback when the client lacks the new ResponseStreamingClientInterface. The platform S3 module then uses this for file GET/PUT, holding a smaller lock around metadata while the backend transfer happens outside, and replaces inline $deviceForFiles->delete() of the previous path with a DELETE_TYPE_FILES queue message consumed by the Deletes worker. Tests cover streaming behavior end-to-end via a local S3 stub server and unit-test the worker path.

Files Change
packages/client/src/*, packages/client/tests/* Add onResponse streaming hook to curl adapter, streaming interface, and retry decorator support with per-attempt notify semantics.
packages/storage/src/*, packages/storage/tests/* New S3::stream() range/ETag-validating streaming path plus streaming and S3 test updates with a local stream server fixture.
src/Appwrite/Platform/Modules/S3/* New S3 HTTP module: GET streams from the backend under a shortened lock; PUT enqueues prior-path deletion instead of deleting inline.
src/Appwrite/Platform/Workers/Deletes.php, tests/unit/*, app/init/constants.php Handles DELETE_TYPE_FILES cleanup messages from the queue, with constants and unit coverage.

Reviewed commit: 5bbf99a

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

This PR adds true streaming download support for S3-backed storage (curl onResponse streaming in the client package, a new S3::stream() device method, an S3 HTTP gateway with lock/retry semantics) and replaces synchronous prior-file deletion with an enqueued DELETE_TYPE_FILES cleanup message.

Key findings

  • 🟠 Redirect body fires onResponse with 3xx headers — Client.php:258
  • 🟡 Capability precondition burn inside retry loop — Retry.php:80

Comment on lines +258 to +261
$options = $this->options($request, $headers, $refused, static function (string $chunk) use ($sink, $notify): void {
$notify();
$sink($chunk);
}, $decompress);

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 · high

Redirect body fires onResponse with 3xx headers

When followRedirects is enabled and an intermediate 3xx response carries a body chunk, the write callback wrapper at packages/client/src/Adapter/Curl/Client.php:258-261 invokes notify() mid-redirect. notify() parses the last header block of the accumulated $headers — which is the redirect hop — builds a 3xx response, calls $onResponse, and sets $notified = true, so the final response is never notified. Callers relying on onResponse (auth refresh, content-type sniffing, cancellation) observe a stale 3xx while the returned response is the final one.

📋 Prompt for AI Agents

In packages/client/src/Adapter/Curl/Client.php, the notify closure (lines 241-257) and the wrapped write callback (lines 258-261) fire onResponse with the wrong response when CURLOPT_FOLLOWLOCATION follows a redirect whose intermediate 3xx response carries a body: the first body chunk triggers notify() while the last header block still belongs to the redirect hop, latching $notified so the final response is never notified. Fix: track redirect hop boundaries (e.g. count header blocks ending in the header callback, or consult CURLOPT_REDIRECT_COUNT inside the callbacks) and only invoke/latch notify() once the last header block's status is final; intermediate hop chunks must pass through to $sink without triggering notify. The empty-body path at line 298 must also notify with the final block.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This concern does not reproduce with native libcurl. Added testResponseNotificationOnlySeesTheFinalRedirectHop: an HTTP 302 response with a nonempty body followed by HTTP 200 notifies exactly once with 200 before final body bytes, and delivers only final. It passes without a transport change. libcurl documents that FOLLOWLOCATION skips intermediate redirect bodies rather than passing them to WRITEFUNCTION: https://curl.se/libcurl/c/CURLOPT_WRITEFUNCTION.html. Keeping the simpler implementation and retaining the regression.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The user's claim is that libcurl's CURLOPT_FOLLOWLOCATION never delivers intermediate redirect bodies to WRITEFUNCTION, making the bug non-reproducible in practice. This is a reasonable counter-argument worth examining carefully.

However, the curl documentation actually does NOT guarantee that redirect bodies are suppressed — it only says that WRITEFUNCTION receives the body of the final response. In practice, some servers send a body with a 3xx (e.g. a plain-text 'Redirecting...' message), and older libcurl versions or certain configurations may pass those bytes to WRITEFUNCTION. The fix claim relies entirely on libcurl behavior rather than making the PHP code correct by construction.

More importantly, the diff shown is unchanged from the original finding — the write callback wrapper still calls $notify() on the first chunk, which would still latch $notified = true with the 3xx header block if any body bytes arrive during a redirect hop. The regression test may pass today under the specific libcurl version in CI, but the code-level race condition described in the finding remains: nothing in the PHP code guards against $headers still pointing at a redirect block when the first WRITEFUNCTION call arrives.

The fix described in the original finding — tracking header block boundaries (e.g. counting complete header blocks in the header callback and only calling $notify() when the current block is known to be final) — is still not present. I cannot resolve this finding based on a behavioral assumption about libcurl.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The current official CURLOPT_WRITEFUNCTION documentation explicitly states: “When CURLOPT_FOLLOWLOCATION is enabled, libcurl automatically handles intermediate 3xx redirects, meaning their HTTP bodies are skipped and not passed to this callback.” Source: https://curl.se/libcurl/c/CURLOPT_WRITEFUNCTION.html . This is the documented adapter contract, not an assumption that redirect bodies happen to be empty. The native regression deliberately sends a nonempty 302 body and verifies only final 200 headers are notified before final payload bytes. The existing shared adapter contract additionally covers redirects with bodies. A header-block counter cannot know whether a response is final before libcurl decides to follow Location, so duplicating that state machine would add complexity without fixing a demonstrated defect. If there is a supported libcurl version/configuration that violates this documented behavior, please provide a reproducer; otherwise this finding is not actionable.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The user's argument hinges on the CURLOPT_WRITEFUNCTION documentation guaranteeing that intermediate redirect bodies are never passed to the write callback. However, the current diff shows no code change from the original finding — the write callback wrapper still calls $notify() on the first chunk unconditionally, and $notify() still parses whatever is currently in $headers (which could be a 3xx block). The code-level defect remains regardless of whether libcurl's current behavior happens to prevent it from triggering in practice. A documentation guarantee about libcurl behavior is not the same as the PHP code being correct by construction, and library behavior can vary across versions and configurations. Until the fix (e.g. tracking header block boundaries to ensure $notify() only fires when $headers reflects the final response) is visible in the diff, I cannot resolve this finding.

Comment thread packages/client/src/Decorator/Retry.php Resolved
@ghost

ghost commented Oct 16, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

No actionable issue is present in the incremental change or the reviewed pull request.

Adds an optional response-aware streaming capability to the HTTP client and uses it to stream validated S3 downloads without spooling whole objects, while retaining buffered behavior for legacy callers. S3 writes capture metadata under lock, serve immutable version paths, and queue idempotent cleanup of obsolete objects. The change includes client, storage, gateway, and worker tests for streaming behavior, failures, and cleanup.

Latest changes: The newest change adds a blank separator line in the retry decorator between its capability check and streaming setup; it does not alter behavior.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 19
File Change
app/init/constants.php Adds the queue type for obsolete S3 object-path cleanup.
packages/client/src/Adapter/Curl/Client.php Adds early response-header notification support to cURL streaming.
packages/client/src/Client.php Forwards streaming capability checks and early-response streaming to the adapter.
packages/client/src/Decorator/Retry.php Delegates streaming capability and avoids retrying requests that cannot expose headers early.
packages/client/src/Psr18/ResponseStreamingClientInterface.php Defines the optional response-aware streaming client capability.
packages/client/tests/Adapter/Curl/ClientTest.php Tests early-response notifications, including across redirects.
packages/client/tests/Decorator/RetryTest.php Tests retry behavior for unsupported early-response streaming.
packages/storage/src/Device.php Adds a chunked stream operation with a buffered-read default.
packages/storage/src/Device/S3.php Streams validated S3 GET responses when supported and retains buffered fallback behavior.
packages/storage/src/Device/Telemetry.php Adds telemetry around the stream operation.
packages/storage/tests/Device/S3StreamingTest.php Covers streaming success, response/range rejection, interruptions, cancellation, and telemetry.
packages/storage/tests/Device/S3Test.php Checks buffered streaming fallback with legacy clients.
packages/storage/tests/Device/s3-stream-server.php Provides controlled backend responses for S3 streaming tests.
packages/storage/tests/E2E/S3Test.php Tests concurrent object streaming and eventual obsolete-object deletion.
src/Appwrite/Platform/Modules/S3/Http/S3/Base.php Queues obsolete immutable object paths after replacements.
src/Appwrite/Platform/Modules/S3/Http/S3/Create.php Passes the cleanup queue publisher through regular and multipart writes.
src/Appwrite/Platform/Modules/S3/Http/S3/Get.php Captures metadata under lock and streams non-local objects with bounded buffering for small responses.
src/Appwrite/Platform/Workers/Deletes.php Processes obsolete S3 object-path cleanup messages idempotently.
tests/unit/Platform/Workers/DeletesTest.php Tests duplicate delivery of obsolete-path cleanup messages.

Reviewed the commits since 1adcb07 · 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 B · See the inline comments. Summary

Comment thread packages/storage/src/Device/S3.php Resolved
Comment thread packages/storage/src/Device/S3.php Resolved
@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → codex/s3-backend-streaming (after).

Metric Before After Change
🚀 Requests/sec 199.99 204.16 ⚪ +2.1%
⏱️ Latency P50 85.52 ms 85.04 ms ⚪ -0.6%
⏱️ Latency P95 211.67 ms 198.6 ms 🟢 -6.2%
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 85.04 198.6 12,654 204.16 -13.08
Account 154.86 311.41 666 11.01 -12.17
TablesDB 81.8 150.91 6,882 112.72 -18.82
Storage 78.89 179.5 3,330 56.76 +5.96
Functions 119.87 242.53 1,776 30.91 -4.42

Top API waits (after)

API request Max wait (ms)
functions.create 465.43
account.name.update 440.64
functions.variables.update 439.9
storage.files.create 403.76
account.prefs.update 367.57

@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

@loks0n
loks0n merged commit badc333 into main Oct 16, 2026
143 of 145 checks passed
eldadfux added a commit that referenced this pull request Oct 17, 2026
Port supportsResponseStreaming and the onResponse argument of
ResponseStreamingClientInterface::stream (utopia-php/client, #14607):
Adapter::supports_response_streaming and Adapter::stream_with_response,
on Http (told before the first body chunk, or once an empty response
checks out), Client and Retry (refused before any attempt when the
wrapped adapter cannot).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
eldadfux added a commit that referenced this pull request Oct 17, 2026
Port Device::stream, S3::stream and Telemetry::stream (utopia-php/storage,
#14607): a Sink trait, the read-then-pass-on default (storage::stream),
and on S3 one GET whose head is checked (status, Content-Range) before
any byte reaches the sink, delivered as it arrives and never replayed.
Clients say whether they hand the head over first
(Client::supports_response_streaming); one that does not keeps the
buffered fallback. Rust tests port S3StreamingTest against a local
backend.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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