Skip to content

JAMES-4231 Compaction core (6a): chunk format and addressing - #3461

Open
HesandaLiyanage wants to merge 5 commits into
apache:feature/s3-object-compactionfrom
HesandaLiyanage:JAMES-4231-chunk-format
Open

HesandaLiyanage wants to merge 5 commits into
apache:feature/s3-object-compactionfrom
HesandaLiyanage:JAMES-4231-chunk-format

Conversation

@HesandaLiyanage

@HesandaLiyanage HesandaLiyanage commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

JAMES-4231 — Compaction core, part 6a: chunk format and addressing

Why item 6 is split in two

Items 2–5 of the agreed plan are merged. Item 6, the self-contained compaction core, is the largest piece, so I split it into two PRs:

  • 6a — data model (this PR): the binary chunk format and slot addressing, with their fuzzing.
  • 6b — next: ChunkedBlobStoreDAO (moved out of this PR following review), then initial compaction and re-compaction as two distinct operations driven by the BlobIdUpdater snapshot and a Bloom filter of live references, with the 200-mail layout tests and the property-based suite.

Item 7 (Guice wiring, WebAdmin, end-to-end tests) and item 8 (documentation) follow, as agreed.

Scope

New module server/blob/blob-compaction, not wired into any server.

  • Chunk format (v1): header JCHK + version + random chunk identity, then slots, a footer (identity, slot offsets and lengths) and a fixed trailer locating the footer. Each slot stores the caller metadata, the payload and a CRC32C, so reading a slot needs neither header nor footer.
  • Slot addresses: <chunk blob id>~<offset>~<length>, e.g. 1_689_chunk_<uuid>~1024~300 or 1/689/chunk/<uuid>~1024~300, recognized by ChunkMarker.
  • Chunk ids: allocated in the family, generation and layout of a blob of the compacted generation.

Dependency

Targets feature/s3-object-compaction. Builds on ChunkMarker (#3245), merged.

Design notes

  • Canonical encoding: a parsed slot encodes back to its exact bytes, and slot bytes do not depend on their position, so 6b can copy slots verbatim and size chunks with encodedSlotSize. Unencodable values (unpaired surrogates) are refused by the writer; non-lowercase metadata names and a stored total-object-size are rejected by the parser.
  • Error classes: checksums are little-endian, making each slot a CRC-32C codeword, so any change within 32 consecutive bits raises CorruptedSlotException (which will trigger the whole-chunk read in 6b). A slot of the wrong length is a plain ChunkFormatException.
  • Footer integrity: the footer repeats the header identity and is checksummed; a damaged or truncated chunk, or the footer of another chunk, fails rather than yielding a different footer.
  • Untrusted parsing: lengths and offsets are validated against the bytes received before use; malformed input only raises ChunkFormatException.
  • Trusted addresses: a misaligned location can only be detected when its bytes fail to parse (a payload may embed a valid slot); addresses come from the metadata store.
  • Opaque chunk ids: family and generation stay inside the chunk blob id. Samples the blob id factory would rewrite (zero-padded generation, integer overflow) are refused. Addresses are at most 200 characters, to fit the PostgreSQL VARCHAR(200) column.

Deliberately excluded

  • ChunkedBlobStoreDAO, compaction algorithms, property-based tests (6b).
  • Guice wiring, task registration, WebAdmin (item 7). Documentation and ADR (item 8).

Tests

  • ChunkFormatTest, SlotAddressTest, ChunkIdsTest: deterministic round trips, sizes, canonicity, and rejection of every malformed field.
  • Jazzer targets (10), each fuzzed for 10 minutes (maxDuration = "600s", about 640 million inputs in total), with a seed corpus and a dictionary:
    • SlotFuzzTest: canonicity; normalized round trips with exact sizes and position independence; error classes.
    • ChunkFuzzTest: footer consistency; damaged chunks (byte changes, truncation, extension, footer of another chunk, misaligned locations); writer lifecycle; agreement with ReferenceChunkDecoder, a second decoder written from the specification.
    • ChunkIdsFuzzTest, SlotAddressFuzzTest: allocation invariants, round trips across factories and layouts, exclusive classification.
  • Findings of earlier runs (rewritten generations in ChunkIds) are committed as inputs that normal builds replay, and as unit tests.

78 tests pass; Checkstyle and POM ordering checks pass. Review changes are in the last commit.

mvn -pl server/blob/blob-compaction -am test

To fuzz one target:

JAZZER_FUZZ=1 mvn -pl server/blob/blob-compaction test -Dtest='SlotFuzzTest#parsedSlotsShouldBeCanonical'

Follow-up

6b — ChunkedBlobStoreDAO, compaction algorithms and property-based tests.

Versioned binary layout packing blobs into one object. Each slot keeps the
caller payload and metadata (except the response-only total object size)
and a CRC32C, so a slot is read with a single ranged read. A footer and a
fixed trailer list the slots for later maintenance.

The parser treats chunk bytes as untrusted: lengths are validated before
use and malformed input only raises ChunkFormatException. Checksum
mismatches raise CorruptedSlotException.
A slot address is <chunk blob id>~<offset>~<length>. The chunk blob id
stays opaque: family and generation remain the concern of the blob id
factory. Parsing only accepts canonical addresses, so that serializing a
parsed address restores its input.

New chunk ids reuse the family, generation and layout of a blob of the
compacted generation, and are recognized by ChunkMarker.
Decorator meant to sit right above the storage DAO. Slot addresses are
read with one ranged read and returned with their stored metadata, so
compression and encryption decorators above keep working per blob. On a
checksum mismatch the whole chunk is read, letting the object store
verify and repair it.

Ranged reads of slot addresses are refused, chunks cannot be saved and
deleting them is ignored: compaction owns their lifecycle. Other blobs
are delegated unchanged, as checked by the BlobStoreDAO contracts.
Normal builds replay the fuzz targets as regular tests. JAZZER_FUZZ=1
fuzzes one target, as documented in ChunkParserFuzzTest. JUnit comes from
the project rather than from jazzer-junit.
class ChunkParserFuzzTest {
private static final String NAME_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789-";

@FuzzTest(maxDuration = "60s")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@fuzztest(maxDuration = "600s") at least

@chibenwa chibenwa left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Looks good to me

* A slot is returned with the payload and metadata it was stored with. Chunks are written and deleted by compaction
* only: saving a chunk id is refused and deleting one is ignored, as its space is reclaimed by re-compaction.</p>
*/
public class ChunkedBlobStoreDAO implements BlobStoreDAO {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Let's focus just on the data model for this PR ?

import com.google.common.base.Preconditions;

/** Allocates chunk blob ids recognized by {@link ChunkMarker}. */
final class ChunkIds {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

No fuzzing?

import com.google.common.base.Preconditions;

/** Allocates chunk blob ids recognized by {@link ChunkMarker}. */
final class ChunkIds {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

No fuzzing?

@chibenwa

chibenwa commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Likely issues

  • BlobMetadataValue accepts lone surrogates, but ChunkWriter.writeField uses getBytes(UTF_8), which silently replaces them with ?. "\uD800" reads back as "?". A strict CharsetEncoder (REPORT) would reject it instead.
  • BlobMetadataName lowercases, so the parser accepts Content-Encoding and returns content-encoding: two byte sequences decode to the same blob (non-canonical encoding).
  • The writer drops total-object-size, but the parser accepts it in a slot.

More oracle ideas for fuzzing the data model:

Slot encoding

  1. Canonicity: if parseSlot(bytes) returns b, then encodeSlot(b) must equal bytes. This one oracle catches all three issues above.
  2. Wider generator for the round trip: names from the full [a-zA-Z0-9-], values from arbitrary chars (surrogates included), sometimes TOTAL_OBJECT_SIZE. Either the write fails with IllegalArgumentException, or the read gives back the normalized blob.
  3. encodedSlotSize(b) == addSlot(b).length(), offset(n+1) == end(n), and finish().length == 5 + Σ slots + 4 + 16·n + 21. 6b will size chunks with encodedSlotSize.
  4. Slot bytes do not depend on their position in the chunk, so 6b can copy slots verbatim.
  5. Error classes: any burst of at most 4 bytes changed inside a valid slot must raise CorruptedSlotException (CRC32C guarantees it, so the oracle is deterministic). A truncated or extended slot must raise a plain ChunkFormatException. This matters because only CorruptedSlotException triggers the whole-chunk fallback.

Whole chunk
6. Mutate a valid chunk: parsing either fails or yields the original footer, never a different valid one. This also covers truncation (every strict prefix is rejected) and splicing the footer of chunk A onto the slots of chunk B.
7. A misaligned SlotLocation inside a valid chunk either fails or points at a window that is itself a canonical slot. That case is possible: a mail payload can embed a valid slot. Worth documenting that addresses are trusted because they come from the database.
8. Strengthen parseTrailerAndFooter with the full invariant: first offset is HEADER_SIZE, slots are contiguous, they end at footerOffset, and footerOffset + footerLength + TRAILER_SIZE == chunk.length.
9. Fuzz ChunkWriter as a state machine (sequences of addSlot/finish). A rejected addSlot leaves the writer unchanged, and every call after finish raises IllegalStateException.
10. Differential test against a small reference decoder written from the format spec (DataInputStream).

ChunkIds
11. newChunk(x) either throws IllegalArgumentException or returns an id that:
- is a chunk id according to isChunkId;
- keeps the family, generation and separator of x, as the factory reads them;
- contains no ~;
- satisfies factory.parse(r.asString()).asString() == r.asString();
- is not parsed as a SlotAddress;
- is unique across calls.
12. Every address built on a new chunk parses back: SlotAddress.parse(new SlotAddress(newChunk(x), loc).asBlobId(f), f) is present for any valid loc, and stays at 200 characters or less with 19-digit offsets. Inputs worth adding to the dictionary:
- generations with leading zeros (1_007_x is normalized to 1_7_…);
- generations above Integer.MAX_VALUE (the NumberFormatException escapes newChunk);
- long families.

SlotAddress
13. The opposite round trip: start from a generated (chunk, location) and check parse(serialize(a)) == a.
14. Compare factories and layouts (Plain/GenerationAware × _//).
15. Classification is exclusive: a blob id is exactly one of slot address, chunk or plain blob. Add line terminators to the dictionary (\n, 
, \u0085): the .* in ChunkMarker does not match them.

Tooling: maxDuration = "600s", a seed corpus of valid chunks, and a dictionary (JCHK, \x01, chunk, ~, _, /, total-object-size) so that the fuzzer reaches the footer and metadata paths.

@HesandaLiyanage

Copy link
Copy Markdown
Contributor Author

Likely issues

Thanks alot for the review. Working on it, will push once the fuzzing is done.

… fuzzing

- Narrow this PR to the data model: ChunkedBlobStoreDAO moves to 6b.
- Canonical encoding: values UTF-8 cannot encode are refused rather than
  replaced, metadata names must be lowercase, and a stored total object
  size is rejected.
- Bind the footer to its chunk with an identity repeated in the header
  and the footer, and store checksums little-endian so that each slot is
  a CRC-32C codeword.
- Bound slot addresses to 200 characters, and refuse chunk ids the blob
  id factory would rewrite (zero-padded generation, integer overflow).
- Fuzz with the suggested oracles: 10 targets of 600s, a reference
  decoder, a seed corpus and a dictionary. Findings are kept as inputs
  replayed by normal builds.
@HesandaLiyanage HesandaLiyanage changed the title JAMES-4231 Compaction core (6a): chunk format and slot reads Nov 27, 2026
@HesandaLiyanage

Copy link
Copy Markdown
Contributor Author

@chibenwa ping

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

Labels

None yet

2 participants