~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/stream

jetstream v2 in zig · mirror of https://tangled.org/zat.dev/stream

0
0
227 lines · 12.7 KB Raw History

jss v1 sealing + gloom construction (from upstream @ 0c45f29 + gloom v0.1.0)

what the writer's seal path must produce, bit-exact. complements jss-format-v1.md, which describes the format at rest; this file describes how to write it.

Upstream right-sized per-block blooms after this spec was pinned

This file is pinned to upstream 0c45f29 (2026-07-08). Upstream f02919c (2026-07-10) changed per-block DID bloom sizing, and Stream has not picked it up. Measured on experiment 6, 2026-07-30, and it is the memory ceiling:

sealed segments4,767
total blocks5,041,001
archived events16,728,092,842
per-block bloom at capacity 40968,409 bytes each
resident bloom bytes39.5 GiB
process RSS44.3 GB (41.3 GiB) — so ~96% is blooms

segment_writer.zig passes max_events_per_block (4096) as the footer bloom_capacity, so every per-block bloom marshals to 8,409 bytes no matter how few DIDs it holds. Upstream's commit message reports the median unique-DID count per block as 1–3 on real archives, making the sizing roughly three orders of magnitude larger than needed, and measured the same symptom we have: ">90% of server heap (44.3 GiB full-network)".

Upstream's fix sizes every per-block bloom for the segment's actual maximum per-block unique-DID cardinality (clamped to ≥ 1), computed from the seal walk's existing per-block DID sets. Using the segment-wide maximum keeps every bloom in the region the same size, so the region stays indexable by multiplication with no offset table — upstream states explicitly that this is not a format change, which is why it can be adopted without breaking the byte-exactness contract described below. 04cae8c applies the same sizing in compaction Rewrite, and upstream keeps a segment/testdata/legacy_fixed4096_blooms.jss fixture, so readers still accept old fixed-capacity segments.

Adopting it is not urgent for correctness: an oversized bloom still has no false negatives. It is the reason the workload needs a 61 GB machine and the likely reason it was OOM-killed once at 62.9 GB anon-rss.

The cost recurs on every startup. manifest.zig holds resident sealed-segment metadata, so those 39.5 GiB have to be loaded before backfill can begin. Measured latency from process start to starting repository backfill across experiment 6's restarts:

early in the run (median)2.0 min
by hour 54 (median of last 10)4.5 min

It doubled as the archive grew, consistent with the cost tracking resident bloom bytes. With the process restarting roughly every 45 minutes at the batch boundary, that is ~10% of wall-clock time spent in startup, and rising. Right-sizing the blooms shrinks both the resident footprint and this recurring startup cost.

The rest of the process fits in 1.75 GiB — and there is no leak

Subtracting modelled bloom bytes from RSS at two points 1.7 h apart isolates everything that is not blooms:

segmentsblocksbloomsRSSnon-bloom
12:47Z4,7675,041,00139.5 GiB41.3 GiB1.78 GiB
14:30Z4,8655,130,41140.2 GiB41.9 GiB1.73 GiB

The non-bloom working set is flat (−0.05 GiB), while total RSS rose by exactly the 89,410 new blocks × 8,409 bytes the model predicts. Two conclusions:

  • There is no leak. Every gigabyte of growth is accounted for by blooms, and the model predicting RSS growth from block count corroborates the 8,409-byte figure.
  • The floor for this workload is around 2 GiB plus right-sized blooms. Everything else — RocksDB, the segment writer, 100 backfill workers, the live pipeline, the repair pool — costs under 1.8 GiB combined at full-network scale.

Verified: the fix does not invalidate the existing archive

Upstream states the change is not a format change; verified against this codebase as follows.

segment_footer.zig writes an 8-byte region header before the per-block blooms holding block count and per-bloom size, and segment.zig blockBloomBlobs reads both back and indexes by multiplication:

const count = readInt(u32, self.bytes, start);
const size  = readInt(u32, self.bytes, start + 4);
const at    = start + 8 + i * @as(u64, size);

Nothing assumes 8,409 or the 4096 capacity. A segment sealed with fixed-size blooms records size = 8409 and still reads; a right-sized one records its own smaller size and reads the same way. Old and new segments coexist in one archive — the equal-size-region invariant upstream describes.

A rebuilt binary therefore resumes on the current archive (1.37 TB and 3.8M repositories at hour 60).

What adopting it would take

Upstream's f02919c changes buildFooter to drop its maxEventsPerBlock parameter and instead compute, from the seal walk's existing per-block DID sets, the segment-wide maximum per-block unique-DID count clamped to ≥ 1 — then passes that to gloom.New instead of the fixed capacity. Their comment states the reasoning: sizing every filter for the max rather than each block's own count is what preserves the equal-size region invariant, so the false-positive target is realized exactly on the largest block and beaten on all the rest. The clamp exists so a segment of DID-less events (identity/account markers) still yields a valid minimal filter.

Stream already has the data in hand. segment_footer.zig iterates self.block_dids.items at the exact point it calls gloom.Filter.init(scratch, self.bloom_capacity, 0.001), so the change is a max-scan over that list immediately before the loop, using it in place of self.bloom_capacity. Both callers currently supply the fixed value — segment_writer.zig passes max_events_per_block, and segment_rewrite.zig takes it as a parameter, which is the path upstream's 04cae8c covers.

Scope note: upstream changed only the per-block blooms. The segment-wide DID bloom is sized separately and is not part of this.

Measured on this archive, 2026-07-30. stream inspect-segment --blocks=summary reports the numbers directly. Sampling six sealed segments across the run:

segmentblocksunique DIDs in the whole segment
seg_0000000000858287
seg_00000000p01187358
seg_00000001e01097357
seg_0000000230986333
seg_00000002s0878627
seg_00000003h09222360

Within a single file: seg_0000000000 holds 3,506,746 events over 858 blocks with 287 unique DIDs total. Its segment-wide bloom, covering all 287, is 601 bytes. Each of its 858 per-block blooms, sized for 4096, is 8,409 bytes — fourteen times larger than the segment-wide filter.

What this bounds. These counts are segment-wide, and the fix sizes by the per-block maximum, which cannot exceed the segment total — so segment-wide counts give an upper bound on the new capacity, and therefore a conservative lower bound on the saving. Even at that pessimistic bound the filter shrinks from 8,409 bytes to roughly 601 bytes (287 DIDs) up to ~4.3 KB (2,360 DIDs). Actual per-block cardinality is far lower — a backfill block of 4,096 events is mostly one repository — which is why upstream measures >90%. Measuring true per-block counts needs block decoding and was not done.

Note the trend: later segments hold more unique DIDs (287 → 2,360) because the crawl reaches smaller repositories, so more of them fit per segment. The saving per segment therefore shrinks as the archive grows, though it stays large.

if you are reading this cold

  • jss is Stream's segment file format — the on-disk columnar container the archive is made of. A sealed segment is one that is finished and immutable; see invariants.md.
  • gloom is a blocked-bloom-filter library (jcalabro/gloom, pinned at v0.1.0). Its serialized filters are embedded in sealed jss footers, one per segment and one per block, so a reader can ask "might this segment contain this DID?" without opening the segment body.
  • upstream throughout this file means Bluesky's Jetstream V2 (bluesky-social/jetstream), pinned at the commit in the title.

Why bit-exact and not merely compatible. A bloom filter's contract is no false negatives: if it says a DID is absent, the reader skips the segment without looking. A single bit placed differently from the Go implementation breaks that promise silently — a reader skips a segment that does hold the DID, and nothing in the format detects it. The constants below are therefore copied verbatim from the Go implementation, and the parameter maths is pinned by golden vectors generated from the Go library: the float arithmetic is sensitive enough that an independent implementation can land on different block counts.

gloom filter construction (bit-exact or their reader rejects / false-negatives)

  • OptimalParams(n, p): clamp n==0→1, p≤0→0.0001, p≥1→0.99. bitsPerItem = -ln(p)/0.4804530139182014; totalBits = n·bitsPerItem; baseBlocks = ceil(totalBits/512); maxBlocks = ceil(baseBlocks·4). numBlocks = baseBlocks; k = bestK; while EstimateFPR(numBlocks,k,n) > p and numBlocks < maxBlocks: numBlocks = min(numBlocks + numBlocks/8 + 1, maxBlocks) (integer div), re-pick k.
  • bestK: scan k=3..17, pick k minimizing EstimateFPR (strict < → lowest k wins).
  • EstimateFPR: lambda = n/numBlocks; if lambda>10000 → partitionedBlockFP(primes, lambda); else Poisson sum j=0..(lambda+10√lambda+20), logProb = -λ + j·ln λ − Σln(j), break when prob<1e-15 and j>int(λ); Σ prob·partitionedBlockFP(primes,j). partitionedBlockFP(primes,j) = ∏(1−(1−1/pᵢ)^j). FLOAT-SENSITIVE: golden-test (n=4096,p=0.001) + a sweep vs Go output.
  • prime partitions per k (sum 512 each) — copy tables verbatim from gloom params.go:40-56. offsets[i] = prefix sum of primes.
  • Add: h = xxh3_128(did); blockIdx = mulhi64(h.hi, numBlocks) (Lemire, HIGH word); intra: u32 = trunc(h.lo) ^ trunc(h.lo>>32); for i in 0..k: bit = offsets[i] + intra % primes[i]; set bit (bitPos/64 word, bitPos%64) in blocks[blockIdx·8..]. count += 1 per Add.
  • MarshalBinary (LE): version u8=1 | k u32 | numBlocks u64 | count u64 | numBlocks×64B words | crc32c(Castagnoli) u32 over all preceding bytes. count = unique DIDs added (dedup'd!).
  • constructors coerce numBlocks 0→1; unsupported k → 7; reader rejects version≠1, k∉3..17, numBlocks 0 or >1<<50, length mismatch, crc mismatch.

seal sizing + sequence

  • segment bloom: gloom.New(n = unique non-empty DIDs in segment, p=0.001); one AddString per unique DID. zero DIDs → still written (n coerced to 1, count=0).
  • per-block blooms: gloom.New(n = configured MaxEventsPerBlock (4096 default), p=0.001) — all identical size (region indexable by multiplication); populated with the block's unique non-empty DIDs. zero blocks → 8-byte region header only (0,0).
  • empty-string DIDs excluded from blooms and unique_did_count.
  • collection ids: FIRST-SEEN order during the frame walk. real collections intern with count++ per event; kinds account/identity/sync ALSO intern sentinels "$account"/"$identity"/"$sync" inline (taking the next first-seen id, interleaved not appended) with count NOT incremented.
  • walk: frames from 256 to footer_offset; block decoding to 0 events terminates the walk.
  • footer order: block index (at footer_offset == block_index_offset) | segment bloom | per-block bloom region (8B header + n×size) | collection index (16B header + zstd body: table in id order [len u8][count u32][nsid], then per-block bitmasks).
  • header: min/max seq + witnessed_at all 0 when event_count==0. checksum = xxh3_64 of header[12..256] (checksum field zeroed) ++ file[footer_offset..EOF] — covers to EOF, no slack bytes allowed anywhere.
  • io order: pwrite footer, fsync, pwrite header, fsync, close.

reader validations ours must survive

  • offsets monotone: 256 ≤ footer ≤ size; block_index==footer ≤ did_bloom ≤ block_blooms ≤ collection_index ≤ size; bloom region size must equal collection_index_offset − block_blooms_offset exactly (8 + n×size).
  • blocks: within [256, footer), non-overlapping, offset-monotonic, MaxSeq≥MinSeq, and non-empty blocks strictly increasing seq ranges (min > previous max).
  • VerifySealedMetadata re-derives EVERYTHING from rows: exact counts, envelopes, collection table (no dups, exact counts, sentinel presence both directions), bitmask sets exactly equal row-derived, and NO false negatives in either bloom for any row DID.