Skip to content

s3-binary-cache-store: getFile streaming from S3 - #6824

Closed
mupdt wants to merge 1 commit into
NixOS:masterfrom
mupdt:s3-download-streaming
Closed

mupdt wants to merge 1 commit into
NixOS:masterfrom
mupdt:s3-download-streaming

Conversation

@mupdt

@mupdt mupdt commented Jul 20, 2022

Copy link
Copy Markdown
Contributor

Before this change nix copy --from s3://... would download the entire object into memory before passing it on to the destination store. For bigger derivations this can lead to high memory usage and out-of-memory (OOM) errors. We experienced these OOM failures frequently.

This change adds support to stream objects from S3 to nix copy. This keeps the memory usage at a constant low level. We measured resident memory usage of roughly 40MB for packages of any size. To verify this patch works, we created a derivation with 10 GB of random data and did a before and after test. Without the patch we observed memory usage climbing to 10 GB. With the patch memory usage would settle at 40 MB.

We are now running this code in production and are no longer seeing OOM errors.

cc @thufschmitt

Comment thread src/libstore/s3-binary-cache-store.cc Outdated
Aws::S3::Model::GetObjectRequest()
.WithBucket(bucketName)
.WithKey(key)
.WithResponseContentEncoding("identity");

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Since we are streaming, we would need to get the content encoding before the download starts. Unfortunately, we were not able to find a way to inject the content encoding into the streamtoSink object before the streaming starts.

This is why we explicitly set the encoding to "identity" and are not applying the decompress step (unlike the old getObject function in L174 above).

Note that this is separate from nix's own compression of nar archives. Nix will still decompress nar archives if they were compressed when it uploaded them to S3.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

My intuition is that it's a reasonable tradeoff since Nix already does its own compression most of the time, and most people will only use an s3:// binary cache from inside aws (binary caches hosted on s3 but used outside of aws's datacenters will generally get an http proxy on front of them), so on a fast-enough network connection. @edolstra do you think there's a significant drawback in not having any compression on the transport layer here?

res.size = streamToSink.totalSize;
} catch (S3Error & e) {
if ((e.err != Aws::S3::S3Errors::NO_SUCH_KEY) &&
(e.err != Aws::S3::S3Errors::RESOURCE_NOT_FOUND) &&

@mupdt mupdt Jul 20, 2022 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is another interesting difference from the old getObject function. AWS started to respond with RESOURCE_NOT_FOUND instead of NO_SUCH_KEY when the object does not exist in S3. We do not know why this started happening, but the only difference between our code and the old getObject function is the fact that we pin encoding to identity, perhaps internally somehow this causes AWS to change its response from NO_SUCH_KEY to RESOURCE_NOT_FOUND.

Comment thread src/libstore/s3.hh Resolved
Comment thread src/libstore/s3-binary-cache-store.cc Outdated
std::streamsize write(const char* data, std::streamsize dataSize)
{
auto strViewData = std::string_view(data, dataSize);
this->sink(strViewData);

@mupdt mupdt Jul 22, 2022 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

We discovered that sink() uses boost coroutines underneath (in sinkToSource). It turns out that the coroutine system can throw a forced_unwind exception. Surprisingly, this exception is caught and swallowed by std::ostream::write. However, this exception is supposed to be caught by the boost coroutine system, which will handle it and report any user-code exceptions properly. So, now we only get an obfuscated error log that looks like this:

nix: include/boost/context/detail/exception.hpp:37: boost::context::detail::forced_unwind::~forced_unwind(): Assertion `caught' failed.

We believe we have a fix for this, but we still have to run it through its paces. Stay tuned.

Update: the fix has withstood the test of time and a ton of our nix copy operations. We'll add the fix to this PR soon.

Comment thread src/libstore/s3-binary-cache-store.cc Outdated
SinkToBidirectionalDeviceAdapter streamToSink(sink);

request.SetResponseStreamFactory([&]() {
return Aws::New<boost::iostreams::stream<SinkToBidirectionalDeviceAdapter>>("StreamToSink", streamToSink);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

After quite a lot of nix copying we discovered a flake here. Sometimes S3 downloads fail with retriable errors. In such situations AWS SDK simply restarts downloading and starts copying from the beginning. Our streaming code does not handle that and to nix it will appear as if it gets corrupted data.

We came up with a fix now and will test it for a week or so (hammering nix copy from S3). We'll push the fix after those tests.

Apologies for the back-and-forth on this patch!

@mupdt

mupdt commented Sep 26, 2022

Copy link
Copy Markdown
Contributor Author

Quick update: First of all, apologies for the radio silence. We have since fixed the "corruption on retry" bug mentioned in the previous comment. We've been since using the patch in production.

Unfortunately, we have observed yet another a flake (rare, but persistent) which we believe to be a bug in our patch. We are in the process of tracking down the bug and will try to get a fix as soon as possible. Once we have the bugfix ready, we will use it internally until we are satisfied that there are no longer any bugs in the code. This might take a while, but we will comment on this PR when it happens and submit the final patch in this PR.

Apologies again and thank you for bearing with us!

@mupdt
mupdt force-pushed the s3-download-streaming branch from f4ba0df to d7175b9 Compare November 22, 2022 09:15
@mupdt

mupdt commented Nov 22, 2022 •

Copy link
Copy Markdown
Contributor Author

Alright, this took much longer than expected, many apologies about that!

We managed to identify the cause for the second set of occasional failures. It turns out that AWS C++ SDK uses the truncate feature in streams (see this issue in AWS C++ SDK). For example, if there's a retriable HTTP error response then the response's error body is written straight into the stream. AWS SDK code parses that error body, truncates the stream back to the end of the last successful body, and continues with the download streaming.

So, if we use a stream that doesn't support truncate (which we did) then we'd occasionally see retriable errors streaming garbage into our nar or narinfo streams. This would happen very rarely, hence the rare failures.

We fixed this bug internally back on the 15th of October, stress-tested it for a while, and have then been using it in production since 25th of October. We haven't detected any failures since and have downloaded in the order of ~100TiB (very rough estimate).

@mupdt
mupdt requested a review from thufschmitt November 22, 2022 09:41
@mupdt

mupdt commented Feb 23, 2023 •

Copy link
Copy Markdown
Contributor Author

@thufschmitt: Could I ask you for another look? 🙏

P.s.: We've been using this code in production for 3 months now without any hiccups.

@fricklerhandwerk fricklerhandwerk added performance store Issues and pull requests concerning the Nix store labels Mar 3, 2023
@roberth roberth mentioned this pull request Apr 19, 2023
@roberth

roberth commented Apr 19, 2023

Copy link
Copy Markdown
Member

This PR needs a rebase.

Would you be interested in writing a test with minio? (#8239) While your practical testing is very encouraging, this would increase our confidence and help us maintain the S3 related code.

@nixos-discourse

Copy link
Copy Markdown

This pull request has been mentioned on NixOS Discourse. There might be relevant details there:

https://discourse.nixos.org/t/2023-04-28-nix-team-meeting-minutes-50/27698/1

@mupdt

mupdt commented May 2, 2023

Copy link
Copy Markdown
Contributor Author

@roberth: Do we have an existing example of using an external service (like minio) in integration tests? That would help me a lot.

@osnyx

osnyx commented Aug 7, 2023

Copy link
Copy Markdown

@mupdt You might want to have a look at the Prometheus NixOS test, which integrates a separate node holding a minio S3 storage for the other test VM nodes to use.

@edolstra edolstra removed their assignment Apr 26, 2024
@tomberek tomberek added the idea approved The given proposal has been discussed and approved by the Nix team. An implementation is welcome. label Oct 9, 2024
S3Helper::StreamResult res;

try {
size_t size = getObjectSize(bucketName, key);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This adds a HEAD request for every GET request, which I imagine adds a substantial amount of latency, especially for .narinfo files (which are very small). Do we really need to get the size in advance? Maybe we can start fetching from offset 0 and the response header will tell us what the full size is.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I'll give it a try. Let's hope the S3 HTTP API supports this.

@tomberek

Copy link
Copy Markdown
Contributor

stale: re-open and re-base as needed

@tomberek tomberek closed this May 18, 2026
@github-project-automation github-project-automation Bot moved this from 🏁 Review to Done in Nix team May 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

idea approved The given proposal has been discussed and approved by the Nix team. An implementation is welcome. performance store Issues and pull requests concerning the Nix store

Projects

Archived in project

Development

Successfully merging this pull request may close these issues.

8 participants