Skip to content

s3: CargoShip's 64 MiB upload buffer is allocated per GC cycle, and 4 KiB PUTs pay for all of it #362

Closed

Description

@scttfrdmn

Found while working #193. That issue asks for a per-iteration allocation budget on the difftest fuzz target, on the premise that the harness allocates hard. It does — 1.9 MiB per fuzz iteration — but 82% of that is one allocation site in production code, reachable from every PutObject on the shipped default configuration. So the memory #193 is about is not the harness's, and a budget asserted on the harness would have pinned this in place as expected behavior.

The allocation

internal/storage/s3/client.go:233 builds CargoShip's transporter, and cargoship/pkg/aws/s3/transporter.go:63 configures the AWS SDK uploader with:

u.BufferProvider = manager.NewBufferedReadSeekerWriteToPool(64 * 1024 * 1024)

That provider holds its buffers in a sync.Pool. The Go runtime clears every sync.Pool at the start of each GC cycle, so the buffer is not amortized across uploads the way the comment above it assumes ("Pool size automatically managed by AWS SDK") — it is re-allocated on the first PUT after every GC.

Measured, internal/storage/s3 against the substrate endpoint, compression off so the transporter is actually reached (a compressed object bypasses it — backend.go:945), 4 KiB objects:

20 PUTs, no GC between 20 PUTs, GC after each
CargoShip on (default) 3.4 MiB total 837.2 MiB total — 41.9 MiB/PUT
CargoShip off 2.4 MiB 3.8 MiB — 0.2 MiB/PUT

The GC-between column is the pathological case stated plainly; the real cost sits between the two and depends on GC frequency, which is the problem — see below.

Per-PUT allocation across object sizes, warmed, 100 PUTs each:

object size CargoShip on off ratio on, as a multiple of the object
4 KiB 825.3 KiB 115.3 KiB 7.2× 206×
64 KiB 1724.2 KiB 355.8 KiB 4.8× 27×
1 MiB 4069.9 KiB 3357.3 KiB 1.2× 4×

The default MultipartThreshold is 32 MiB (config.go:443), so every object below the multipart threshold pays a 64 MiB buffer's allocation for a single-part upload. That is the wrong direction: the buffer exists to make large multipart uploads efficient, and the objects that don't need it are the ones it costs the most, relatively.

Why it makes memory pressure worse, not better

GOMEMLIMIT and this interact badly. Lowering the limit makes the GC run more often, and every GC drops the pooled buffer, so a tighter limit increases total allocation. Measured over 300 difftest iterations:

cargo=on   GOMEMLIMIT=768MiB   totalAlloc=751MiB   numGC=4    heapSys=531MiB
cargo=on   GOMEMLIMIT=384MiB   totalAlloc=3570MiB  numGC=28   heapSys=499MiB
cargo=off  GOMEMLIMIT=768MiB   totalAlloc=285MiB   numGC=12   heapSys=67MiB
cargo=off  GOMEMLIMIT=384MiB   totalAlloc=285MiB   numGC=12   heapSys=67MiB

Halving the limit multiplied allocation by 4.75× with CargoShip on and changed nothing with it off. With CargoShip off the workload is insensitive to the limit, as an ordinary one should be.

And the retained footprint is 8.5× larger over the same work: 649.9 MiB vs 76.3 MiB of runtime.Sys after 500 difftest iterations. HeapAlloc is flat at 30.2 MiB in both, and 604 MiB of the difference is HeapIdle — so this is not a leak, it is garbage the collector has released to no one, held as heap the runtime keeps mapped. That is exactly the shape #193's GOMEMLIMIT=768MiB fix works on, and it explains why capping memory raised fuzz throughput 17×: the cap was fighting this allocation, not the harness's.

What to do

Options, roughly in order of how much they change:

  1. Size the buffer against the configured chunk size rather than a constant 64 MiB, and don't install a BufferProvider at all when the upload is single-part. Both belong in CargoShip (transporter.go:63) — file there, since ObjectFS only passes MultipartChunkSize in.
  2. Don't route sub-threshold objects through the transporter. backend.go already bypasses it for three other reasons — compressed objects, encryption modes it can't express, per-object storage classes — so a fourth bypass for len(data) < MultipartThreshold is a one-line change in a place that already reads as a list of the transporter's limits. This is the cheap fix and it is entirely within ObjectFS.
  3. Leave it and document the cost, which is the least defensible: the default configuration enables CargoShip (config.go:442), and a FUSE filesystem's PUT size distribution is dominated by small objects.

(2) is the one I'd land first — it removes the cost where it is worst without touching CargoShip's behavior for the uploads the buffer was designed for. (1) is the real fix and belongs upstream.

How this was found

Not by reading. runtime/pprof alloc profile over 500 difftest iterations, top node:

2240MB 81.95%  cargoship/pkg/aws/s3.NewTransporter.func1.NewBufferedReadSeekerWriteToPool.1
                 ← sync.Pool.Get

2240 MiB / 64 MiB = 35 buffer allocations across 500 iterations, against numGC in the same range. Then confirmed on the production PutObject path with a flag flip, rather than assumed from the harness measurement.

Activity

  1. added
    type: bug
    priority: medium
    area: s3
    area: buffer
    effort: small
    cargoship: integration
    on Aug 5, 2026
  2. scttfrdmn commented on Aug 5, 2026

    @scttfrdmn
    OwnerAuthor

    Went to implement fix (2) — bypass the transporter for sub-threshold objects — and measurement inverted it. The transporter is only ever reached below the threshold, so fix (2) would bypass it always, i.e. delete the integration. That may still be the right answer, but for a different and stronger reason than allocation.

    The transporter never performs a multipart upload

    backend.go:905 returns into putObjectMultipart before the transporter is consulted:

    if dataSize >= b.config.MultipartThreshold {
        return b.putObjectMultipart(ctx, key, uploadData, ...)   // hand-rolled; zero transporter references
    }
    ...
    transporter := b.clientManager.GetTransporter()              // only reachable below the threshold

    putObjectMultipart contains no reference to the transporter — it drives CreateMultipartUpload/UploadPart/CompleteMultipartUpload itself. Confirmed by probing the stored metadata, which distinguishes the paths (objectfs-upload: true is stamped only by the CargoShip branch), with the threshold at 8 MiB:

    size=     4096  via CARGOSHIP
    size=  1048576  via CARGOSHIP
    size=  7340032  via CARGOSHIP
    size=  9437184  via direct      ← threshold
    size= 20971520  via direct
    

    So the 64 MiB BufferProvider is a multipart-upload buffer installed on a code path that, in ObjectFS, only ever handles single-part uploads. The allocation isn't merely disproportionate — nothing it exists for can ever happen here.

    And it costs correctness, not just memory

    Two things the transporter loses on the objects it does handle:

    Content-Type is dropped. The direct path sets input.ContentType from detectContentType(key) (backend.go:931). The CargoShip branch passes it as user metadata ("content-type" in cargoMeta), and cargoships3.Archive has no ContentType field, so the HTTP header is never set. Measured on file.txt:

    cargo=true   ContentType="application/octet-stream"
    cargo=false  ContentType="text/plain"
    

    This is the same shape as the Content-Encoding bug already documented at backend.go:934 — a value computed correctly and turned into metadata nobody reads. That one caused silent corruption; this one is milder, but every object under 32 MiB written on the default config has the wrong Content-Type.

    Four metadata keys per object, for nothing. buildMetadata adds cargoship-original-size (always 0 — ObjectFS never sets Archive.OriginalSize), cargoship-compression-type (always empty), cargoship-created-by, and cargoship-upload-time. So a timestamp goes into user metadata on every small PUT, which also makes otherwise-identical objects non-identical.

    There is no throughput to trade away

    The reason to keep it would be the BBR/CUBIC optimization the comments cite. Against the substrate endpoint, 30 PUTs each, warmed:

    size CargoShip on off
    4 KiB 327 µs/put, 11.9 MiB/s 243 µs/put, 16.1 MiB/s
    1 MiB 2.851 ms/put, 350.8 MiB/s 2.624 ms/put, 381.2 MiB/s
    8 MiB 20.531 ms/put, 389.7 MiB/s 20.786 ms/put, 384.9 MiB/s

    CargoShip is slower at every size that reaches it, by 8% at 1 MiB and 35% at 4 KiB. A local endpoint isn't the network where BBR would help, so this is not evidence that CargoShip is slower over the internet — but it does mean the measurable trade here is all cost. And the sizes where its transport optimization could matter are exactly the ones that never reach it.

    Revised recommendation

    Stop routing PutObject through the transporter, and delete the branch rather than adding a fourth bypass condition. The branch already carries three bypasses with long comments explaining what the transporter cannot express (Content-Encoding, encryption headers, per-object storage class); Content-Type is a fourth, the 64 MiB buffer serves an upload shape that cannot occur, and the throughput case is unmeasurable-to-negative. Four documented limitations and no demonstrated benefit is a subtraction, not a tuning problem.

    That leaves EnableCargoShipOptimization as a config field nothing reads, which needs its own decision — either remove it (a breaking config change, so it wants deprecation) or keep it inert with a note. ObjectFS would still depend on CargoShip for the pieces it actually uses; this is only about the PutObject transporter path.

    Worth noting the ordering hazard already recorded in the plan: EnableCargoShipOptimization: true lives in NewDefaultConfig and buildS3Config maps it from UseCargoShip, so this path is live on a real mount, not latent.

    I'd like a call on this one before deleting an integration, since it's more than the allocation fix this issue was filed for. The narrow version — keep the branch, add dataSize to the bypass list, which given the above disables it in practice — is available if you'd rather leave the code in place.

  3. scttfrdmn commented on Aug 5, 2026

    @scttfrdmn
    OwnerAuthor

    Implemented in #363 as the deletion version, per the recommendation above.

    Two things worth recording that came out of doing it.

    The Content-Type test nearly shipped passing for the wrong reason. The first draft set MultipartChunkSize to 1 MiB. That is below the AWS SDK uploader's 5 MiB part minimum, so every CargoShip upload failed with part size must be at least 5242880 bytes, fell back to the direct path, and the direct path sets the header correctly — a green test against the broken code, in the one file written specifically to prove the header was dropped. It surfaced only because the run was supposed to fail and the CargoShip optimization failed, falling back to standard S3 warning was sitting in the output of the tests that did.

    Raising the chunk size to 5 MiB and the threshold to 8 MiB produced the split the earlier probe predicted: three single-part cases fail (text/plain, application/json, image/png all stored as application/octet-stream), multipart cases pass, and the unmapped case passes on both sides — which is why it was included, since application/octet-stream is also what the bug produced and a suite of only-mapped suffixes could not tell "correctly defaulted" from "silently lost".

    The removal reached further than the branch. EnableCargoShipOptimization had no remaining reader, so it went too, and with it storage.s3.use_cargoship, GetTransporter, IsCargoShipEnabled, and cargoShipCanEncrypt. The config key is removed rather than deprecated — the loader decodes strictly, so a file still setting it now fails at startup naming the key, matching what this repo did with the security.encryption booleans and the cost_optimization block. Ten test files referenced the flag; two encryption tests (TestCargoShipIsBypassedWhenItCannotSendTheHeaders, TestCargoShipCarriesTheKeyForTheModeItSupports) lost their subject entirely and were deleted, and storage_tier_seam_test.go collapsed from a two-path table to one. ConvertTierToCargoShipStorageClass stays; CargoShip is still a dependency for the awsconfig tier types.

    go mod tidy dropped six transitive dependencies afterwards, including aws-sdk-go-v2/feature/s3/manager and service/cloudwatch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: bufferarea: s3cargoship: integrationeffort: smallpriority: mediumtype: bug

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions