Skip to content

Seekable zstd framing so a ranged read fetches only the frames it covers #185

Closed

Description

@scttfrdmn

Summary

A compressed object cannot be read partially. zstd's default single-frame output must be decoded from the start, so any ranged read of a compressed object requires fetching and decoding the whole object. Framing the stream as a sequence of independently-decodable frames plus a skippable-frame index makes ranged reads fetch only the frames covering the requested bytes.

Why this is worth doing

The read path currently handles compressed objects by re-fetching whole (internal/storage/s3/backend.go:416-427 and the encoded re-fetch above it). That is correct — v0.10.1 fixed the version that dispatched on the write config and silently returned raw zstd frames with exit status 0 — but it means a compressed object is a whole-object-read object.

The v0.10.0 audit measured what that costs when it was applied bucket-wide (fixed 4 KiB read against real S3, us-west-2):

object size penalty
16 MiB 15.6×
64 MiB 43.0×
256 MiB 216.5×

Those figures were for the C4 defect, where the config flag forced whole-object reads for every object in the bucket including uncompressed ones. That is fixed — the decision is now per-object, from the object's own Content-Encoding. But for an object that genuinely is compressed, the amplification is unchanged, and it scales with object size: a 4 KiB read of a compressed 10 GiB object transfers 10 GiB.

This is the structural reason compression defaults to off. Seekable framing is what would let it default to on for large objects without making random reads pathological.

What it takes

klauspost/[email protected] (already a dependency) has every primitive needed. No new dependency.

Format. Compress in fixed-size uncompressed blocks — each block becomes its own zstd frame, independently decodable. Append a skippable frame (magic 0x184D2A5x) holding the index: for each frame, compressed size and uncompressed size. A reader fetches the trailing index, computes which frames cover [offset, offset+size), issues one ranged GET spanning them, decodes only those, and slices.

Block size is the tradeoff: smaller means finer granularity and worse ratio; larger means better ratio and more waste per small read. Somewhere in 1–4 MiB is the usual answer, and it should be configurable but with a default that is not a guess — pick it from a measurement on a representative object.

Compatibility. A seekable stream is still a valid zstd stream — zstd -d and any standard decoder read it correctly, ignoring the skippable frame. So this does not make objects less portable than they already are.

What makes this a format change, not an optimization

This changes the bytes stored. That brings requirements the current compression path does not have:

  1. A format-version metadata key. Something like objectfs-compression-format: seekable-v1. Without it, a reader cannot tell a seekable object from a single-frame one except by parsing, and the two need different read strategies.

  2. Old objects must stay readable. Every object written before this exists is single-frame. The read path needs both strategies, chosen from the metadata key, indefinitely — not behind a migration deadline. A migration tool is fine; a migration requirement is not.

  3. The SHA-256 contract. objectfs-sha256 is recorded over the whole uncompressed content and verifyChecksum only runs when the buffer holds all of it (backend.go:459-466). A ranged read of a seekable object holds some frames, never the whole file — so it cannot verify against the whole-object hash. This is the important design question in the issue: either

    • store a per-frame hash in the index, so a partial read verifies exactly what it fetched, or
    • accept that ranged reads of compressed objects are unverified, which weakens the integrity contract that v0.10.1 established and would have to be stated in the documentation.

    Per-frame hashes are the right answer. Integrity is priority ci(deps): Bump actions/setup-go from 4 to 5 #1 for this project and the whole point of seekable framing is to make partial reads of compressed objects normal — so making them the one read that is not verified would be backwards. The index already exists as a place to put them; the cost is 32 bytes per frame.

  4. Interaction with the range-aware cache. The cache is keyed on (key, chunkIndex, etag). Frame boundaries and cache chunk boundaries will not align. Worth deciding whether the cache stores decoded bytes (simple, aligns with the existing key) or frames (avoids re-decode on a repeat read). Decoded is probably right; noting it so it is a decision rather than an accident.

  5. Multipart uploads. A part boundary must not split a frame if a reader is to fetch frames by range without stitching across parts. Frame size and part size need to be compatible, or the index needs to record part offsets too.

Sequencing and prerequisites

Testing

  • Round-trip fuzz: arbitrary bytes → seekable compress → PUT → ranged GET at fuzzed (offset, size) → assert byte-identity against the same range of the original. Extend the existing round-trip fuzzer rather than adding a parallel one.
  • Assert bytes transferred, not latency: a 4 KiB read of a compressed 64 MiB object must issue a ranged GET covering one or two frames. Latency alone would pass on a fast link with a whole-object fetch, which is the trap the C4 tests were written to avoid.
  • Read a seekable object with zstd -d to confirm the skippable frame is ignored and the output is identical.
  • Read a pre-existing single-frame object after the change, to confirm the format-version fallback works.

Activity

  1. added this to the Future Work milestone on Aug 2, 2026
  2. added
    type: performance
    priority: medium
    area: compression
    on Aug 2, 2026
  3. added
    effort: large
    on Aug 3, 2026
  4. scttfrdmn commented on Sep 15, 2026

    @scttfrdmn
    OwnerAuthor

    Both prerequisites this issue names are now met, and the substrate one is measured rather than read off a closed issue.

    #184 is closed, so the content analyzer is wired. The issue notes that may shrink this one's payoff — whichever formats the analyzer skips are the large files where seekable framing would matter most — so that measurement is still owed before committing to the full format change.

    Substrate honours Range GET as of v0.111.0 (substrate#396, closed). Probed in-process against internal/testaws rather than inferred from the issue state, because all three primitives this design needs are separable and only one of them is what "supports Range" usually means:

    PROBE len=100 ContentRange="bytes 1000-1099/4096" ContentLength=100   # mid-object range
    PROBE suffix len=64 ContentRange="bytes 4032-4095/4096" equal=true     # bytes=-64
    PROBE 416: status=416                                                  # unsatisfiable, refused not clamped
    

    The middle one is the one worth calling out. Reading the skippable index frame is a suffix range — bytes=-N — because the index sits at the end and its length is not known before it is read. A backend that implements bytes=a-b and not bytes=-N would pass a naive range test and still make the index unreadable. It works, and Content-Range reports the resolved absolute offsets.

    The third matters for the fallback path: backend.go's case ranged && isInvalidRange(err) arm depends on a range past the end being refused, not silently clamped. A backend that clamped would turn an EOF read into a short read of real bytes.

    So this is testable in-process now, which the "assert bytes transferred, not latency" requirement above depends on — that assertion needs a request recorder, and testaws counts every request through its proxy.

  5. scttfrdmn commented on Sep 15, 2026

    @scttfrdmn
    OwnerAuthor

    Answering the open sequencing question above — "#184 may shrink this issue's payoff considerably … worth measuring after #184 lands before committing to this."

    It does not shrink it. Measured by running Analyze/AlreadyCompressed over each format's leading bytes rather than by reading classifyByMagic:

    format AlreadyCompressed
    gzip, zstd true
    BAM true
    Parquet, ORC, HDF5, CRAM, NetCDF-classic false
    FASTQ, SAM, VCF, CSV, TIFF false

    BAM coming back true is the one result worth knowing and it was not obvious: BAM is bgzf, which is a gzip container, so it carries gzip magic and #184's gate skips it without anyone having added BAM to the list. It is skipped correctly and for free.

    Everything #184 skips is a format that was never a candidate for seekable framing — an object stored raw is already served by range, so it has no amplification to remove. So the set #184 removed from this issue's scope is empty, and the two sets it leaves behind are different problems:

    1. Internally-compressed containers — Parquet, ORC, chunk-compressed HDF5, CRAM. Compress runs a full codec pass, the output is no smaller, and the len(compressed) >= len(data) fallback stores the original. They are never stored compressed, so seekable framing never applies to them either. That wasted pass is Compression: settle the entropy gate with a measurement, and decide whether the three selectors have a caller #410, not this issue.
    2. Genuinely compressible large scientific data — FASTQ, SAM, VCF, CSV/TSV, uncompressed NetCDF and TIFF. These are stored compressed, and they are large. This is exactly the population that pays the whole-object read penalty, and it is the population seekable framing is for.

    So the payoff stands and lands where the issue said it would. It is worth stating that this establishes which objects reach the compressed path, not what ratio they achieve — a ratio measurement still needs a real corpus, because the padding in this probe was synthetic. (For the same reason, ignore the ContentClass values it reported: ASCII padding made classifyByContent answer text for the binary formats. That is an artifact of the probe's own input, not a classifier defect.)

    Prerequisites are therefore both settled: #184 closed without narrowing this, and substrate's Range GET is verified in-process (previous comment).

  6. scttfrdmn commented on Sep 15, 2026

    @scttfrdmn
    OwnerAuthor

    CargoShip already shipped this format, and it changes four of the decisions above

    This issue was written without knowing that scttfrdmn/cargoship has an identical mechanism in
    production as "Random-access frame index (format 2.1)" — cargoship#436 (frame table and per-file
    offsets), #439 (per-frame checksums), #492 (offsets recorded for unframed chunks too), and #502
    (cutting frames inside a large file), all closed. docs/reference/format/compression.md in that repo
    is the specification. The consequence is not "adopt it wholesale" — the container is different in a
    way that matters — but three questions this issue leaves open are already answered upstream, and one
    of the answers is a correctness refinement this issue got wrong.

    What transfers, what does not, and what is now measured rather than guessed:

    Question Status here before After reading cargoship
    Per-frame hash: over which bytes? "per-frame hash", side unspecified compressed side, verified before decode — cargoship#439
    Index record layout undesigned adopt cargoship's field set verbatim
    Where the index lives trailing skippable frame still in-object, but leading, and the reason is a code fact — see below
    Frame-size default "somewhere in 1–4 MiB" neither 1–4 MiB nor cargoship's 16 MiB; it is a function of object size, derived below

    The per-frame hash is over the compressed bytes, and it is checked before the decoder runs

    Item 3 above says "store a per-frame hash in the index, so a partial read verifies exactly what it
    fetched" without saying which bytes it covers. That ambiguity is the whole design. cargoship#439
    resolved it: chunks[].frames[].checksum is the SHA-256 of the frame's compressed bytes — exactly
    what a ranged GET of [compressed_offset, compressed_size) returns
    — and the documented read
    procedure is fetch → verify → decode, in that order.

    Hashing the compressed side is strictly better than hashing the decoded side, for three reasons that
    are not about convenience:

    1. A corrupt or hostile frame never reaches the decoder. A decompressor is an attack surface fed
      attacker-controlled length fields; the uncompressed-side hash can only be checked after that code
      has already run on unverified input.
    2. It verifies the bytes the transport actually delivered, so it catches every S3-compatible range
      quirk as a hard error rather than as silent corruption. A store that clamps an unsatisfiable range
      instead of refusing it, that serves bytes=a-b off by a byte, or that serves a range from a
      different generation of an overwritten object, all fail the frame hash. This is the property that
      makes the whole design safe to attempt optimistically on any endpoint — see the capability section.
    3. It is free. It is computed at write time from bytes already in hand, and checked at read time
      over bytes already in the buffer.

    Adopt cargoship's field set unchanged: compressed_offset, compressed_size, uncompressed_offset,
    uncompressed_size, checksum. Frames tile the object contiguously and each begins with the zstd
    magic 0x28 0xB5 0x2F 0xFD, so the two offsets are derivable by prefix sum and are stored anyway
    because a corrupted index that disagrees with itself is then detectable.

    Verified locally against klauspost/[email protected] and zstd(1) 1.5.7 rather than assumed: a
    concatenation of EncodeAll outputs plus a skippable frame decodes byte-identically through
    Decoder.DecodeAll and through zstd -d; one frame lifted out of the middle by its
    [compressed_offset, compressed_size) decodes in isolation to exactly its uncompressed_size bytes;
    and sha256.Sum256 of those extracted bytes equals the recorded frame checksum. zstd -l reports
    Frames 18 Skips 1, i.e. the index frame is seen and skipped.

    One correction to "no new dependency" above. klauspost/[email protected] exports no
    skippable-frame writer — skippableFrame and calcSkippableFrame in zstd/frameenc.go are
    unexported and reachable only through WithEncoderPadding. So ObjectFS emits the 8-byte header itself
    (4-byte little-endian magic 0x184D2A50 | id, 4-byte little-endian payload length), which is trivial
    but is code we own rather than a library call. The reader side is exported and sufficient:
    zstd.Header.Decode fills Skippable, SkippableID, SkippableSize, and HeaderSize from the first
    8 bytes. Still no new dependency; the claim just needed narrowing.


    The index crux: cargoship's answer does not transfer, and neither does this issue's

    cargoship puts the index in the manifest — a sidecar object it already owns and already fetches
    once per archive. ObjectFS has no sidecar. An ObjectFS object is a standalone S3 object, and the only
    out-of-band space is S3 user metadata. Three candidate locations, with the arithmetic that decides
    between them:

    User metadata alone is arithmetically impossible. internal/vfs/xattr.go puts the real numbers on
    this: s3UserMetadataLimit = 2048 (S3 rejects an over-budget PUT rather than truncating),
    reservedMetadataBytes = 290 for objectfs-mode/uid/gid/mtime/sha256/original-size at their
    widest, leaving XattrBudget = 1758 bytes for extended attributes — and xattr_test.go re-derives
    that rather than hardcoding it. A minimal index record is compressed_size (4) + uncompressed_size
    (4) + SHA-256 (32) = 40 bytes, which is 56 bytes base64'd. 1758 bytes therefore holds 31
    frames
    — a 31 MiB object at 1 MiB frames — and only by spending the entire extended-attribute budget,
    so compressed files would have no xattrs at all. Metadata cannot hold the index. It is a fine place for
    a fixed-size descriptor.

    A trailing skippable frame scales but is the wrong end of the object. This issue's plan. It costs
    one extra suffix-range GET, which is verified to work (see my earlier comment: substrate v0.111.0
    honours bytes=-N and reports resolved absolute offsets in Content-Range).

    A leading skippable frame is better here, and the reason is a property of ObjectFS's write path
    that cargoship does not share.
    cargoship streams a tar pipeline through the encoder, so it cannot
    know the index until the stream is finished and the index must therefore trail. ObjectFS does not
    stream: Compressor.Compress(src []byte) ([]byte, error) takes the whole buffer, and
    prepareUpload (internal/storage/s3/backend.go:964) compresses before the multipart dispatch at
    backend.go:883, so the entire compressed object is in memory at write time regardless of size. The
    index can be written first. That matters because most reads of a file start at offset 0, so a single
    prefix GET bytes=0-K can carry the index and the first data frames — one request where a trailing
    index needs two. Verified: a leading skippable frame is skipped correctly by both
    Decoder.DecodeAll and zstd -d, and zstd.Header.Decode(obj[:8]) reads the index length out of the
    first 8 bytes, so K can be over-fetched and corrected in one hop.

    The resolution is both, with the object as the authority. The index lives in a leading skippable
    frame. A fixed-size descriptor — format version, frame size, frame count, index length, index
    SHA-256 — lives in one user-metadata key (objectfs-seekable, ~28 bytes base64-packed, ~56 bytes
    against the 2 KB limit including the x-amz-meta- prefix). The descriptor is an accelerator, never the
    authority, and the reason is a bug class this repo has already been bitten by twice: SetObjectMetadata
    is a CopyObject with MetadataDirective=REPLACE, which discards everything not restated — the same
    mechanism that made a chmod capable of dropping Content-Encoding and rendering a compressed object
    permanently unreadable (see the comment at backend.go:1014). A tier transition does the same. If the
    descriptor is authoritative, a chmod silently turns a seekable object into a whole-object-read object;
    if the object carries the index, losing the descriptor costs one round trip. The implementation must
    still restate objectfs-seekable in SetObjectMetadata alongside Content-Encoding — but the
    consequence of forgetting is then performance, not correctness.

    Adding a reserved key changes reservedMetadataBytes, so XattrBudget drops from 1758 to roughly
    1700. That is a user-visible number: xattr_test.go asserts the arithmetic and README.md states 1758
    in prose. Both must move in the same commit.


    A reader learns the object is seekable from a response it was already getting

    The read dispatch at backend.go:400–480 already establishes seekability without a wasted round trip,
    and this is worth spelling out because it is the part that looks like it needs a HEAD and does not.
    getObjectRange records metadata = result.Metadata from the GetObject response
    (backend.go:701) — and S3 returns x-amz-meta-* and Content-Encoding on a 206 exactly as on a
    200.
    Probed, not read from documentation, against real AWS S3 in us-west-2:

    mid-object  bytes=1000-1099  ContentRange="bytes 1000-1099/8192"  ContentEncoding="zstd"  Metadata={objectfs-seekable, objectfs-sha256, objectfs-original-size}
    suffix      bytes=-64        ContentRange="bytes 8128-8191/8192"  ContentEncoding="zstd"  all 3 metadata keys present
    prefix      bytes=0-7        ContentRange="bytes 0-7/8192"        ContentEncoding="zstd"  all 3 metadata keys present
    If-Match with a stale ETag on a ranged GET → 412 PreconditionFailed
    

    Same four probes against substrate v0.111.0 through internal/testaws give identical answers, so this
    is testable in-process.

    So the existing dispatch keeps its shape, and both of its arms already have the descriptor in hand:

    • case ranged && err == nil && read.contentEncoding != "" — the speculative ranged GET landed inside
      a compressed body. Today it re-fetches whole. It becomes: if read.metadata carries
      objectfs-seekable, fetch the index (one prefix GET) and then the covering frames, instead of
      re-fetching whole. The wasted bytes are the misaligned size bytes of compressed body the
      speculative request already returned — bounded by the kernel's read buffer, 131072 bytes by default
      (internal/fuse/read_path_test.go:164), against the whole stored object today.
    • case ranged && isInvalidRange(err) — the range fell past the end of a short compressed body. It
      already calls HeadObject, and info.Metadata already carries the descriptor. No new request.

    Keep the speculative-range-first order. Making the first request a prefix or suffix range would
    penalise the overwhelmingly common uncompressed object to benefit the rare compressed one, which is
    audit finding C4's mistake in the opposite direction.

    One requirement this issue does not have and needs. A framed read is two requests — index, then
    frames — so an overwrite landing between them yields an index describing generation 1 and frames from
    generation 2: every request succeeds, the lengths add up, and the assembled buffer never existed. This
    is exactly the race objectRead.etag was introduced for on the parallel-read path
    (backend.go:637–644). Pass the index fetch's ETag as If-Match on the frame fetch. And note that
    the per-frame compressed-side hash catches this even where If-Match is unhonoured — generation
    2's frame bytes will not match generation 1's recorded hash — so the conditional-GET support recorded
    in docs/design/conditional-write-compatibility.md (Wasabi ignores If-Match; Ceph RGW rejects the
    quoted ETag it just returned) is a performance nicety here rather than the guarantee. The guarantee is
    the hash.


    Frame size: not 16 MiB, not 1–4 MiB, and probably not a constant

    This issue guessed 1–4 MiB. cargoship chose 16 MiB. Both are right for their own cost model and
    neither transfers
    , because the index cost is amortised in cargoship and paid per object here.
    cargoship fetches one manifest per archive and gets the frame index for every chunk in it; ObjectFS
    pays for an index on the cold read of each object, so index size is a first-order term for us and a
    rounding error for them.

    The ratio arm of the tradeoff is much flatter than this issue assumed, and two independent measurements
    agree:

    corpus 256 KiB 512 KiB 1 MiB 4 MiB 16 MiB
    synthetic FASTQ, 144 MB, zstd SpeedDefault (ratio 3.67) +1.78% +0.89% +0.31% −0.02% −0.06%
    this repo's .go + .md, 16.5 MB (ratio 4.61) +29.6% +24.6% +20.9% +15.2% +1.8%

    (Percentages are stored size against a single-frame encode of the same bytes. The FASTQ corpus is
    synthetic — random ACGT with locally-repetitive headers and position-degrading quality strings — and is
    a model of read locality, not a real corpus; label it as such. The repo-text row is real data and is
    the pessimistic end, because concatenated Go and CHANGELOG text is self-similar across megabytes and a
    frame boundary throws that window away. Negative values at 4 MiB and above are real and reproducible:
    frame boundaries occasionally help.)

    scttfrdmn/lith's bench/results/framesize-curve.csv corroborates the flat end, on real AWS,
    cold, with bytes counted through the CloudTrail ledger — 1985 small files packed by cargoship at 16/8/4/1
    MiB frames gives archive_MB of 13.1, 13.1, 13.1, 13.2. Under 1% of ratio across a 16× range of frame
    size, while the single-file cold read falls from 3.30 MB to 0.90 MB.

    So frame size is decided by bytes transferred and index size, not by ratio. For an object of
    uncompressed size S, ratio r, frame size F, and a 40-byte index record, the cold read of one
    frame costs 40·S/F (index) + F/r (frame) bytes. That is U-shaped, minimised at
    F = √(40·S·r):

    object size F minimising cold-read bytes cold-read bytes at that F
    64 MiB 97 KiB 53 KiB
    1 GiB 388 KiB 211 KiB
    10 GiB 1.20 MiB 668 KiB
    100 GiB 3.79 MiB 2.06 MiB
    1 TiB 12.1 MiB 6.60 MiB

    cargoship's 16 MiB is the optimum for a ~2 TiB single object under ObjectFS's per-object index cost.
    For the 10 GiB object this issue's opening table is about, the fixed-F curve (128 KiB kernel read,
    worst case straddling two frames) is:

    F frames index 2 frames cold total vs. 128 KiB read warm (index cached)
    256 KiB 40960 1600 KiB 139 KiB 1739 KiB 13.6× 1.1×
    512 KiB 20480 800 KiB 279 KiB 1079 KiB 8.4× 2.2×
    1 MiB 10240 400 KiB 558 KiB 958 KiB 7.5× 4.4×
    4 MiB 2560 100 KiB 2230 KiB 2330 KiB 18.2× 17.4×
    16 MiB 640 25 KiB 8921 KiB 8946 KiB 69.9× 69.7×

    Today the same read transfers the whole 2.72 GiB stored body: 22,303×. So any point on this curve
    is three to four orders of magnitude better than the status quo, which is the honest framing — the
    default is worth ~2× against a neighbouring choice, not 200×.

    Two consequences. First, frame at fixed uncompressed-size boundaries, because an ObjectFS object
    is one file and there are no file boundaries inside it to cut at; cargoship#502 arrived at the same
    place from the other direction, adding maybeCutMidFile so a large file inside an archive is not one
    unseekable multi-GB frame. Second, derive F from the object's uncompressed size at write time
    rather than shipping one constant, recording the chosen F in the descriptor and index so the reader
    never needs to know the rule. Rounded to a power of two, F = clamp(2^round(log2 √(40·S·r)), 256 KiB, 16 MiB) with r taken from the compression already performed reproduces the table above.

    The measurement that settles this is not a ratio benchmark. It is: replay a real read trace against
    framed objects at F ∈ {256 KiB … 16 MiB} on a real corpus of the population my earlier comment
    identified (FASTQ, SAM, VCF, CSV/TSV, uncompressed NetCDF and TIFF), counting bytes transferred
    and requests through testaws's recording proxy, with a cold and a warm index. The open input is
    the read-size distribution: the amplification denominator is the kernel's MaxRead, and the whole
    curve shifts if real workloads read 128 KiB or 1 MiB at a time. Nobody has measured that here.


    Which kind of capability this is

    Per CLAUDE.md, the classification is not uniform across this feature, and saying so precisely is the
    point:

    • Framing, and range-based frame fetching, is a performance capability. It degrades silently. An
      endpoint that ignores Range and returns 200 with the whole body loses nothing that framing was
      going to give it — it already sent every byte — so the reader decodes whole and verifies against
      objectfs-sha256, which is today's behaviour and is correct.
    • Per-frame verification is a correctness capability. It fails closed. A frame whose bytes do not
      match its recorded hash, an index whose bytes do not match the descriptor's hash, or an index that
      disagrees with itself, is ErrCodeDataCorruption — never a quiet fall back to a whole-object fetch
      that happens to work. No path may return bytes from a compressed object that were verified by
      neither the frame hash nor the whole-object hash.

    The probe is per-response, not per-endpoint, and it needs no request of its own. A store that
    ignores Range reports itself: wholeObjectResponse (backend.go:763) already reads the total after
    the slash in Content-Range and returns whole = true for a sub-range request answered with the whole
    body. That is the probe. This differs from conditional write deliberately, and the difference is worth
    recording next to docs/design/conditional-write-compatibility.md: there, "accepted and ignored" is
    indistinguishable from "honoured" until a race is lost, which is why it needs BackendCapabilities
    and a fail-closed default. Here the response itself carries the evidence, and anything it does not
    carry — a clamped range, an off-by-one range, bytes from another generation — is caught by the frame
    hash. So no BackendCapabilities field is required for this, and no compatibility matrix gates it.
    That is the design property to protect in review: if a change makes the frame hash optional, the
    capability becomes probed-and-fail-closed like conditional write, and the matrix comes back.

    One thing that must not be silent. Falling back to a whole-object fetch is safe for integrity — the
    whole-object hash is the stronger attestation — and catastrophic for performance, since it restores the
    216× amplification in the table above. A silent safe-but-slow fallback is precisely audit finding C4's
    sibling in the parallel-read gate: "it fails quietly … nothing failed and nothing was logged"
    (backend.go:377). Every fallback needs a counter and a Warn, and a test that asserts the counter.


    What the implementation touches

    internal/compression/zstd.go (87 lines today, Compress/Decompress over whole buffers). Add a
    framing encoder and a frame-index type. Compress stays as it is for the non-framed path; the framed
    path is for each F-byte window: EncodeAll accumulating (compressed_size, uncompressed_size, sha256(frame)), plus the 8-byte skippable header emitted by hand. Add DecompressFrame for the
    single-frame decode, which is DecodeAll over one frame's bytes with the invariant that the result is
    exactly uncompressed_size — DecodeAll over a concatenation would silently decode a neighbour. The
    frame index belongs in internal/compression, not in internal/storage/s3: it is a property of the
    format, and internal/vfs will want it for the cache.

    internal/storage/s3/backend.go. prepareUpload (line 964) chooses F, frames, and writes the
    leading index frame plus objectfs-seekable; it already computes the uncompressed SHA-256 first
    (line 969), which is the ordering the contract below depends on. SetObjectMetadata (line 1014)
    restates objectfs-seekable alongside Content-Encoding. GetObject's two encoded arms (lines
    ~440–480) gain the index-then-frames path. sliceRange's call site (line 580) needs the frame-relative
    offset offset − frame.uncompressed_offset rather than the current whole-object offset — this is where
    a double-applied offset will be introduced if it is introduced anywhere, and FuzzSliceRange is the
    right place to catch it. checkFullyDecoded (line 2358) computes wholeObject := offset == 0 && (size <= 0 || size >= want) and compares len(data) against objectfs-original-size; a framed partial read
    holds one frame's bytes, so this must compare against the frame's uncompressed_size on that path or
    it will report a correct read as "still encoded".

    The objectfs-sha256 contract. objectfs-sha256 keeps its exact current meaning: SHA-256 over the
    whole uncompressed content, computed before any encoding. Do not redefine it. What changes is the
    coverage statement, and it changes in one direction only:

    • Today: verifyChecksum runs iff read.whole (backend.go:568), i.e. a partial read of a
      compressed object is unverified — and cannot occur, because such a read re-fetches whole. The
      contract holds by construction.
    • After: a partial read of a seekable object can occur, and is verified frame-by-frame against the
      index before decode. verifyChecksum still runs on whole reads, unchanged. The invariant "no
      compressed bytes are returned unverified" must now be enforced explicitly instead of falling out of
      the design, so it needs a test that fails when the frame verification is deleted — verified by
      mutation, not by inspection.
    • The strength of the guarantee is unchanged and must not be overstated: per-frame hashes are user- or
      object-writable, so like objectfs-sha256 they detect corruption, truncation, and misdelivery, not
      tampering by someone holding s3:PutObject. SECURITY.md already anticipates this work — "A read
      that covers less than the whole object is not verified
      … Per-chunk checksums belong with the
      seekable-framing work, which changes the stored layout" — and that bullet is rewritten by this
      issue, while the "not a defence against a bucket an attacker can write to" paragraph below it stands
      verbatim.

    internal/cache. Item 4 above stands and the answer stays "decoded bytes": the cache key is
    (key, chunkIndex, etag) and decoded bytes align with it, while caching frames would need a second
    key space. The addition is that the index wants its own cache entry keyed on (key, etag) — the
    warm column in the table above is the whole payoff, and the ETag in the key is what makes an overwrite
    invalidate it.

    Item 5 above (multipart part boundaries) is wrong and should be struck. A ranged GET is served
    over the assembled object; part boundaries are not visible to it and a frame may straddle one freely.
    What is true is the narrower thing already recorded elsewhere in this repo and in cargoship's own
    reader guidance: a multipart ETag is not a content hash, so it is usable as a generation token for
    If-Match and never as an integrity check.


    Requirements from this issue that stand unchanged

    • Assert bytes transferred, not latency. testaws counts every request through its recording
      proxy, so a 128 KiB read of a framed 64 MiB object must be asserted to transfer one or two frames'
      worth of compressed bytes plus at most one index. Latency would pass on a fast link with a
      whole-object fetch, which is the trap the C4 tests exist to avoid.
    • Round-trip fuzz over (offset, size) against the same range of the original bytes, extending the
      existing round-trip fuzzer. Add the degenerate cases the arithmetic above will get wrong: a range
      entirely inside one frame, a range straddling exactly two, a range ending on a frame boundary, a
      read at S-1, and a zero-length read.
    • zstd -d must still read the object. Verified above for both a leading and a trailing skippable
      frame with zstd 1.5.7; it needs to be a test, run against the CLI where available and against
      klauspost always.
    • A pre-existing single-frame object must still be readable, with no migration requirement. An
      object with no objectfs-seekable and no leading skippable frame takes the existing whole-object
      path forever. A migration tool is fine; a migration deadline is not.
    • A format-version key, which is now the objectfs-seekable descriptor rather than a separate
      objectfs-compression-format. Version lives in both the descriptor and the index frame, because the
      descriptor can be lost by a CopyObject.

    Genuinely open

    1. The read-size distribution, which sets the amplification denominator and therefore the frame
      size. Closed by instrumenting a real mount, not by reasoning about MaxRead.
    2. The ratio penalty on the real target corpus. Both rows in my table are proxies. The FASTQ row is
      synthetic; the repo-text row is real but is not scientific data. Closed by running the sweep over
      actual FASTQ/SAM/VCF/CSV files.
    3. Whether F should be derived per object or fixed. The closed form argues derived; the
      counter-argument is that a derived F makes stored bytes depend on a formula that will change, and
      the descriptor records F so a change is readable but not retroactive. Closed by deciding how much
      the ~2× at the curve's edges is worth against one fewer moving part.
    4. Whether the whole-object objectfs-sha256 should also be recorded in the index frame, so that
      an object surviving a CopyObject that dropped its metadata is still fully verifiable. Costs 32
      bytes. Leaning yes; it makes the object self-verifying, which is the same argument that put the index
      in the object rather than in metadata.

    Interoperability with cargoship and lith: one direction, and only if cargoship changes

    ObjectFS should not read cargoship-written objects. A cargoship chunk is a tar stream inside a
    .tar.zst, its uncompressed_offset is a position in that tar stream, and its index is in a manifest
    at a different key. Reading one would mean implementing tar-in-object presentation and manifest
    discovery — a different feature, not a format decision. An ObjectFS object is one file, and its
    uncompressed_offset is a position in that file's own content. The coordinate spaces are not the same
    space.

    lith could read ObjectFS-written objects, and that is the direction worth enabling, because the
    per-frame record layout would be byte-identical. What differs is only the locator: cargoship's index
    is in a manifest, ObjectFS's is in a leading skippable frame. A reader that implements one index parser
    and two locators serves both. Documenting the record layout as a shared thing — rather than each
    project inventing its own field names — is the cheap part, and it is worth doing in the same change.

  7. scttfrdmn commented on Sep 16, 2026

    @scttfrdmn
    OwnerAuthor

    Two corrections to the design comment above, both found by checking the library rather than reasoning about it, plus one open interop question. Stage 1 is up as #509.

    zstd.Header.AppendTo is exported. The design comment says klauspost/compress exports no skippable-frame writer and that objectfs therefore has to emit the 8-byte header itself. That is wrong at the version this repo is actually on. Header.AppendTo is exported as of v1.20.0 and is the exact inverse of Header.Decode, which is what the reader side uses — so the writer and reader now go through the same library's understanding of the header instead of a hand-rolled encoder on one side and a parser on the other. skippableFrame and calcSkippableFrame do remain unexported, which is probably what the original note was looking at.

    The version in the comment is wrong too: go.mod is on klauspost/compress v1.20.0, not v1.18.0.

    Open: skippable ID 0xE and the Zstandard Seekable Format. #509 uses ID 0xD, not 0xE, and the reason is worth recording as a decision rather than leaving as a detail. 0x184D2A5E is claimed by convention for the Zstandard Seekable Format's seek table, and that format is not what this is: its per-frame checksum is a 32-bit XXH64 truncation over each frame's decompressed bytes, which is both weaker than SHA-256 and on the wrong side of the decoder to protect it — the frame has already been decompressed by the time the checksum can be evaluated. objectfs hashes the compressed bytes precisely so a hostile frame never reaches the decompressor. Claiming 0xE would mean two incompatible layouts answering to one ID, and a reader that guessed wrong would misparse rather than cleanly decline, so 0xD plus an in-payload "OFSI" magic it is.

    The open question is whether objectfs should additionally emit a real 0xE seek table for third-party interop (zstdseek, and anything else that speaks that convention). It would be strictly additive — a second skippable frame — but it duplicates the frame table in a weaker form, and a reader trusting the 0xE table would be doing unverified ranged reads over the same object. Not doing it in this milestone; filing it separately if a concrete consumer turns up.

  8. scttfrdmn commented on Sep 16, 2026

    @scttfrdmn
    OwnerAuthor

    Stages 1 and 2 are in main.

    No read is faster yet. Framing changes what gets stored; the reader is still whole-object. What the
    two merged stages buy is that objects written from now on are seekable when the reader lands, rather
    than needing a rewrite. A framed object is an ordinary zstd stream — the index is a skippable frame —
    so the existing whole-object path, aws s3 cp and zstd -d all decode one byte for byte, which is what
    made it safe to ship the halves separately.

    Stage 3 — the read path, remaining

    • GetObject's two encoded arms take an index-then-frames path: read the descriptor from the response
      metadata it already has, GET bytes=0-(IndexLength-1) for the index, then only the frames
      FramesCovering names.
    • sliceRange's call site needs the frame-relative offset, offset - frame.UncompressedOffset
      (FramesCovering's second return). This is the off-by-one that would make every ranged read on a
      framed object return shifted bytes.
    • checkFullyDecoded must compare against the frame's UncompressedSize on the framed-partial path.
      Against the object's size it reports a correct partial read as still-encoded.
    • The index fetch's ETag goes on the frame fetch as If-Match, so a concurrent overwrite cannot splice
      frames from two generations.
    • Every whole-object fallback — no descriptor, a descriptor that does not parse, an index whose hash
      disagrees — needs a counter and a Warn. A silent fallback is the failure mode of the whole feature:
      it stays correct and quietly stops being fast. A test asserts the counter, not the log.

    The win is asserted in bytes transferred, via ts.BytesRead(key) (internal/testaws/recorder.go:679),
    not in latency. TestFramedObjectServesRangedReads already logs today's amplification as the baseline to
    measure against.

    Recorded as deliberate, not forgotten

    No real 0xE Zstandard Seekable Format seek table for third-party interop this milestone. The index is
    ObjectFS's own format; a reader outside this project sees a valid zstd stream and nothing more.

  9. scttfrdmn commented on Sep 17, 2026

    @scttfrdmn
    OwnerAuthor

    Stage 3 is up as #516 — the read path, which is the stage that makes stages 1 and 2 pay
    for themselves.

    Where the three stages stand

    stage what status
    1 frame-index format (internal/compression) merged, #509
    2 upload path frames and stores a descriptor merged, #513
    3 ranged read serves from covering frames #516, open

    A ranged read of a compressed object no longer fetches the whole object. It resolves the
    span to the frames covering it, issues one ranged GET for exactly those frames, decodes
    them and slices frame-relative. Objects without a usable descriptor take the old path,
    and SeekableLastFallbackReason records why — so an expensive read is diagnosable rather
    than just slow.

    Two design points settled in stage 3

    The decoder is chosen by the object, not by the configuration. An earlier draft looked
    up the decoder from Settings.Algorithm, which meant flipping algorithm in the config
    made every already-written compressed object unreadable. Decoders are now built for every
    supported algorithm regardless of what is enabled, and the lookup key is the object's
    own stored encoding. A read must not depend on how the writer is configured today.

    A frame that disagrees with its index is an error, not a fallback. Falling back to the
    whole object on a checksum mismatch would convert a detected integrity failure into a slow
    success. Per this project's stated order — integrity first — the read fails closed and
    names the frames and the span. DecodeFrames also checks the body length against the index
    before decoding, so a damaged or hostile index cannot drive the output allocation.

    That second one is also a lesson about the test suite: deleting the body-length check
    produced a build the entire S3 suite still passed, because the backend computes its Range
    from the same index it then validates against, so the guard is unreachable through that
    path. It had to be tested against the function directly, which is what
    internal/compression/decode_frames_test.go is for. A 19-mutation run over the read path
    and the frame decoder now catches all 19; five survived the first pass and are the reason
    that file and four S3 tests exist.

    Deliberately not in this milestone

    Emitting a real 0xE Zstandard Seekable Format skippable frame so third-party zstd tools
    can seek these objects. The index here is ObjectFS's own and is read only by ObjectFS.
    Interop is worth doing, but it is additive to a format that now works end to end, so it
    belongs to its own issue rather than holding up the stage that removes the read
    amplification. Happy to file it if you want it tracked separately.

    Related, found on the way

  10. scttfrdmn commented on Sep 17, 2026

    @scttfrdmn
    OwnerAuthor

    All three stages are merged. Seekable framing is complete end to end.

    stage what PR
    1 frame-index format #509
    2 upload path frames and stores a descriptor #513
    3 ranged read serves from the covering frames #516

    The measured result, on a 1 MiB ~50%-compressible object: a 4 KiB read went from transferring
    the whole 1,074,071-byte stored body to 134,554 bytes — the frame index plus the one frame
    covering the offset. The saving scales with the object rather than the read, so at the 256 KiB
    frame-size floor a small read of a 10 GiB compressed object costs the index plus one frame no
    matter how large the object is. That is the read amplification this issue was opened about.

    What was settled along the way, and is worth not relitigating

    • A framed object is an ordinary zstd stream. The index rides in a skippable frame, which
      every conformant decoder must ignore, so zstd -d, aws s3 cp, and the pre-existing
      whole-object read path all return the file byte for byte. Objects written by earlier versions
      are untouched.
    • No configuration flag. Framing is chosen per object and declined in five ordinary cases;
      frame size is derived as sqrt(40 * size * ratio) clamped to [256 KiB, 16 MiB] rather than
      fixed. Neither Seekable zstd framing so a ranged read fetches only the frames it covers #185's original 1–4 MiB guess nor CargoShip's 16 MiB was adopted, because each
      is right for a different cost model.
    • The decoder answers for the object, not the configured codec. An earlier draft keyed the
      read on Settings.Algorithm, which made every already-written compressed object unreadable
      the moment algorithm changed. A read must not depend on how the writer is configured today.
    • Corruption fails closed. A frame that disagrees with the index stored with it is reported
      as non-retryable DATA_CORRUPTION, not worked around by re-fetching the whole object — the
      whole-object path is not a second opinion, since the same damaged bytes are in that stream too.
      A read covering every frame is deliberately routed to the whole-object path, which restores
      the whole-content objectfs-sha256 check for whole-file reads and is also the cheaper request.
    • Every other decline is counted with its reason. A declined framed read still returns
      correct bytes, so the failure mode is not an error anyone sees but a silent return to
      whole-object transfer. Hence seekable_reads, seekable_read_bytes,
      seekable_whole_fallbacks, and seekable_last_fallback_reason, all at warn rather than debug.

    Follow-ups, both filed

    I would close this as complete, with #518 and #514 carrying the remainder. Leaving that to you
    since #514 in particular is the same cost centre and you may prefer this stay open until it is
    dealt with.

  11. scttfrdmn commented on Sep 17, 2026

    @scttfrdmn
    OwnerAuthor

    Closed as complete: all three stages are merged (#509 frame-index format, #513 upload path, #516 ranged read) and the measured result is in the issue above — a 4 KiB read of a 1 MiB ~50%-compressible object went from 1,074,071 bytes transferred to 134,554.

    Shipping in 0.15.0 (#523), not the 0.16.0 this milestone was originally titled. The milestone has been renamed: the four changelog lines that made 0.16.0 look like the next number were describing the #362 upload-path removal, which actually shipped in 0.12.0.

    Two follow-ons were filed off this work and are deliberately out of scope here: #514 (an abandoned parallel-read fan-out still transfers most of the body framing exists to avoid) and #518 (emit a standard Zstandard Seekable Format table — its own recommendation is not to build it until a consumer is named).

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: compressioneffort: largepriority: mediumtype: performance

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions