WAL, slots and ledgers

WAL, slots and ledgers

How a node commits flights to object storage as numbered slots and acknowledges them in order.

A node's WAL is its write-ahead log in object storage, one per storage class. The WAL acknowledges a flight only when its slot holds W copies and every earlier slot of the same ledger has been acknowledged. Each slot is written at most once in each bucket, so the acknowledged slots of a ledger run from slot 0 with no gaps.

A flight is a group of batches from many streams, written as one object. A slot is one flight's numbered position in the WAL. A ledger is a run of slots written by one writer under one number, its epoch. A WAL is a sequence of ledgers. Each slot is written to the K buckets of its class's bucket set: one standard bucket, or one express bucket per availability zone. The slot is committed once W of them, the copy quorum, hold the flight. W is 1 on Standard and 2 by default on Express. The glossary has every term.

par [one create per bucket] Publish(flight) backlog token Next(payload) slot seq PutIfAbsent(slot) W confirms done (slot order) acknowledged wake RetireThrough span rows, then checkpoint CAS, in the metadata store Flusher WAL Sequencer K buckets Indexer

Where it lives

PackageWhat it owns
internal/storage/durabilityThe write core of one class: the pool, the flusher that cuts flights, the flight index, and the live indexer loop
internal/storage/walWAL: the mint, Publish, the backlog budget, the in-place roll, the open gate, and the release flush
internal/storage/logletSequencer (slot numbers, the fan-out to K buckets, in-order release) and the static half: Fence, Walk, Trim, ProbeGarbage. It never touches the metadata store.
internal/storage/indexerAbsorber, which turns committed slots into span rows, and ledger recovery
internal/metadata (ledgers.go)Ledgers: the mint counter and the ledger records, all changed by CAS
internal/objectkeyWALSlot, which derives a slot's key

The write core builds one WAL per class. Standard and Express run the same code over a different bucket set. See Storage classes inside.

The data

Slot keys

Every slot key is derived from the ledger record, so no reader lists a bucket to find a slot. The ledger records its slot layout when it is minted, and every reader derives keys from that record:

LayoutKeyUsed by
hashedwal/<h>/<star>/<epoch>/<seq>New Standard ledgers (the default of --wal-key-layout)
starwal/<star>/<epoch>/<seq>Express ledgers, and Standard with --wal-key-layout=star

<seq> is zero-padded to 20 digits, so key order is slot order. <h> is four hex characters folded from an FNV-1a hash of the star and epoch. It gives each ledger its own place in the key space, so S3 can split partitions between ledgers. Storage layout has the whole key scheme.

The slot envelope

Every slot starts with a 60-byte envelope. One small read at offset 0 tells a reader what the slot holds, proves that it sits at the key it claims, and locates the bundle's footer:

internal/storage/loglet/envelope.go
func (e envelope) encode() []byte {
	buf := make([]byte, envelopeLen)

	binary.BigEndian.PutUint32(buf[0:], envelopeMagic) // "CHNE"
	buf[4] = envelopeVersion
	buf[5] = byte(e.kind) // 1 flight, 2 poison
	binary.BigEndian.PutUint64(buf[8:], uint64(e.epoch))
	binary.BigEndian.PutUint64(buf[16:], e.seq)
	binary.BigEndian.PutUint64(buf[24:], e.nonce)
	binary.BigEndian.PutUint64(buf[32:], uint64(e.size))
	binary.BigEndian.PutUint64(buf[40:], uint64(e.footerOff))
	binary.BigEndian.PutUint64(buf[48:], uint64(e.footerLen))
	binary.BigEndian.PutUint32(buf[56:], crc32.Checksum(buf[:56], crcTable))

	return buf
}

Bytes 6 and 7 are reserved. The checksum is CRC-32C over the first 56 bytes. A flight's bundle starts at byte 60, and every offset a reference stores counts from the start of the object. A poison slot is the envelope alone: the marker a fencer writes so that a slot can never commit. The nonce identifies the writer. A Sequencer draws a random one when it opens, and a fencer draws its own.

Slot lifetime

Every write to a slot is a create that fails when the key exists, so a slot is written at most once in each bucket. A slot ends in one of two states, and neither can change:

StateHolds in its K bucketsThen
CommittedW or more flight copiesKept until the indexer has absorbed it and denorm has copied every stream out of it. The auditor's trim-check then deletes it from every bucket and moves the ledger's trimmed cursor past it.
DeadK−W+1 or more poison envelopesKept until the star is decommissioned

The two states cannot overlap: W flight copies and K−W+1 poison envelopes do not fit in K buckets. Epochs and fencing shows how a fence drives a slot to one of them.

The ledger record

A ledger has one record at ledgers/<star>/<epoch> in the streams keyspace. Its constants are fixed when the ledger is minted. A WAL that needs other settings rolls to a new ledger instead of changing one.

proto/nova/v1/metadata.proto
message Ledger {
  LedgerState state = 1;        // OPEN, FENCED, INDEXED
  uint64 checkpoint = 2;        // first slot the indexer has not absorbed
  uint64 trimmed = 5;           // slots below it are deleted
  uint64 rewritten = 8;         // slots below it hold no live refs
  uint32 storage_class = 9;
  uint32 quorum = 10;           // W
  repeated string bucket_zones = 11; // the bucket set, in fixed order; K = len
  uint32 window = 13;           // the pipeline bound
  optional uint64 cut = 14;     // present once fenced
  uint64 absorbed_bytes = 15;
  uint32 slot_layout = 16;
}

The three cursors only move forward, each by CAS. Neither rewritten nor trimmed may pass the checkpoint, and the trim-check deletes slots only below rewritten. The star's mint counter sits at ledgers/<star>. It holds the last epoch, the head epoch of each class, and a writer record per class. Epochs and fencing explains the mint.

Committing a flight

  1. The first use mints. WAL.init mints the ledger by CAS on the mint counter, then fences every unindexed ledger of the same class that an earlier process left. The daemon calls it through Prime before the node registers, so a crashed ledger is already superseded when the node first looks alive.
  2. The flusher cuts a flight from the pool once 8 MiB has gathered (--s3-bundle-size-mib), or once the oldest byte has waited 200 ms on Standard (--s3-bundle-batch-interval) or 25 ms on Express. One flusher per class hands flights to Publish one at a time, so slot order is the order of arrival.
  3. Publish takes a backlog token. The token is held until the indexer absorbs the flight. When none is free, Publish counts a stall and waits until the flight's deadline.
  4. Sequencer.Next assigns the slot. It takes a window permit (128 by default, --s3-parallel-uploads), gives the flight the next sequence number, and starts its upload with a 30-second budget.
  5. The slot fans out. The upload sends one PutIfAbsent per bucket, in parallel, each body a fresh reader over the same bytes.
  6. The quorum decides. W confirms commit the slot. Once more than K−W buckets have refused, the slot fails and the ledger halts.
  7. Acknowledgements release in slot order. A finished slot waits until every earlier slot has released.
  8. The indexer absorbs. It writes metadata for the acknowledged flights and moves the checkpoint, which frees their backlog tokens. See Indexing.

The quorum loop counts each bucket's answer as it arrives:

internal/storage/loglet/slot.go
for range k {
	out := <-results

	switch out.kind {
	case attemptConfirmed:
		confirms++
		if confirms >= a.cfg.Quorum {
			return nil
		}
	case attemptForeign:
		denied++
		foreign = out.err
	case attemptFailed:
		denied++
		failure = out.err
	}

	if denied > k-a.cfg.Quorum { /* the quorum is out of reach */ }
}

The release is a cursor that only moves over finished slots:

internal/storage/loglet/sequencer.go
func (a *Sequencer) advanceLocked() {
	for {
		if a.halted && a.released >= a.haltSeq {
			return
		}

		next, ok := a.pending[a.released]
		if !ok || !next.finished {
			return
		}

		next.done <- next.result
		<-a.window
		delete(a.pending, a.released)
		a.released++
	}
}

When a create's answer is lost

An answer can go missing after the object has landed. On any failed create, send reads the slot's envelope back and decides what happened:

What the envelope read findsVerdict
A flight with this writer's nonceConfirmed: the create landed and only the answer was lost
Any other envelopeForeign: a fencer or another writer holds the slot, and the ledger halts
Nothing, and the create was not a conflictFailed: nothing landed in this bucket
Anything elseUnresolved: counts against the quorum

A throttled create is sent again when the bucket's throttle gate admits it, until the slot's 30-second budget runs out. A slow partition costs latency and leaves the ledger open. A bucket whose upload permits are all in use is skipped for this slot and counted as failed. Only real confirms count toward W, so skipping a slow minority is safe.

When a ledger halts

A slot that cannot reach its quorum halts its ledger. The first failure latches the halt: that slot and every later one resolve with ErrEpochHalted, and no acknowledgement at or after it is ever released. Slots below it can still finish. A halted ledger never resumes. The WAL rolls to a new ledger in place:

Abort, Close wait for every publish to park Fence(epoch, from checkpoint) cut PublishCut (CAS) take a roll pacer token MintNext (CAS, refused if deposed) republish into the new ledger open the gate below the cut, acknowledge late; at or above it, republish WAL roll Halted sequencer Bucket set Metadata store

The roll runs in three phases:

  1. Quiesce. It aborts and closes the halted sequencer, then waits until every in-flight publish has resolved or parked. The set of parked flights is then final.
  2. Settle. It fences its own ledger from the checkpoint and publishes the cut by CAS. A parked flight below the cut is committed, and its acknowledgement is only late. A flight at or above the cut was never committed in this ledger, so it is republished.
  3. Turn over. It takes a token from the roll pacer, mints the next ledger with MintNext, installs a new sequencer, and republishes the parked flights in order.
internal/storage/wal/roll.go
for _, pf := range *remaining {
	if pf.epoch == from && pf.seq < cut {
		pf.resolve(t.resolutionAt(nil, from, pf))

		continue
	}

	republish = append(republish, pf)
}

Fencing before minting keeps the roll free of duplicates. Each flight lands in exactly one ledger's coverage, so no sequence number is committed twice. Producers usually see a pause and no error. A parked flight whose deadline passes before the new ledger is minted fails with ErrPublishDeadline, and so does every flight parked after it. None of them was published, so sending them again cannot duplicate a record. While the roll runs, Publish waits at the WAL's gate, and the stall is counted as rolling, or as roll_pacer while the roll waits for a token.

MintNext refuses the roll when its class's head epoch has moved, or when recovery has revoked the head. Either means a successor owns this star's writing, so the WAL is deposed: it becomes terminal and fails its parked flights. Any other failure retries the phase. Each attempt has 60 seconds, and attempts are spaced 0.5 to 1.5 seconds apart, so stars that roll through one outage do not retry their fences together.

The halt's cause labels the roll: foreign_occupant, throttled, probe_unresolved, put_failed, or unknown when the halt recorded no cause.

Indexing acknowledged records

The indexer turns committed slots into per-stream metadata. Its one operation, absorb, takes a dense run of a ledger's slots that starts at the checkpoint. For each stream in the run, it writes one span ref: a row keyed by the stream's first sequence number in the run. The row lists, for each slot, the slot number, the first sequence number, the footer range, and the bytes. It also holds the epoch, the slot layout, the time bounds, and the stream's running byte total. Absorb then advances the checkpoint by CAS. It writes metadata only and never reads object storage.

internal/storage/indexer/absorb.go
spanCommits, objects := buildSpans(slots, dead, b, c.cfg.Class, status)

outcomes, err := c.commitBatch(ctx, b.Epoch, spanCommits, objects)
if err != nil {
	return 0, fmt.Errorf("indexer: ledger %d: %w", b.Epoch, err)
}

adv := metadata.CheckpointAdvance{From: checkpoint, To: slots[len(slots)-1].Seq + 1, Bytes: slotsBytes(slots)}

if err := c.advance(ctx, b, adv); err != nil {
	return 0, fmt.Errorf("indexer: ledger %d: %w", b.Epoch, err)
}

commitBatch writes each stream's row with a create-only put, up to --absorb-fanout streams at a time (4,096 by default). The aftermath then arms one denorm batch marker for the run and the streams' retention checks. A span for a stream that was deleted meanwhile is dropped, and the batch goes on. See Stream objects and denorm for the marker.

The live indexer runs on the leader. The release path wakes it each time a flight joins the flight index. One round takes at most 512 slots, and one pass has 60 seconds. --absorb-pass-interval sets a minimum gap between passes, so more slots share each row. A publish that finds the backlog full skips that gap. Ledger recovery runs the same Absorber over a stopped ledger, 32 slots at a time.

Crash afterState left behindWhat the re-run does
Some span rows commitRows for part of the run; checkpoint unmovedCommits the run again; each existing row is found and counted as covered
All span rows commitEvery row; no marker; checkpoint unmovedThe same, then arms the marker it finds missing
The aftermathRows and the marker; checkpoint unmovedCommits again and re-arms the marker, which converges on the same key
The checkpoint advancesNothing left to dodenseFrom drops every slot below the checkpoint and returns

Crash points

A WAL lives in one process. When the process stops, the next start of the same node, or another node's recovery, finishes the work:

Crash afterState left behindWhat the next start does
The mint counter CASA head epoch with its record reserved in the counter, not yet createdAny reader of the counter creates the reserved record (materializeHeads) before it mints or recovers
Some slots commit, before their acknowledgementCommitted slots past the checkpointThe new process fences the old ledger, so those slots stay below its cut and are absorbed. The producer's retry may append them twice.
A roll's fence, before PublishCutPoison at the cut; no cut recordedAny fencer reaches the same cut, and the first publish wins
A roll's PublishCut, before MintNextA fenced ledger, still the class headThe restart mints past it and recovers it like any fenced prior
MintNext, before republishingAn empty new ledgerThe restart fences it at cut 0; a prior whose cut equals its checkpoint is reaped and marked Indexed at once

A restart fences its own priors in init. A prior with nothing left to absorb, where the cut equals the checkpoint, has its garbage window deleted and is marked Indexed on the spot. Any other prior waits for ledger recovery.

Concurrency

  • One writer per ledger. Only the process that minted a ledger writes its flights. The sequencer's mutex guards the slot counter, the pending set, and the halt latch.
  • Slot order comes from one flusher. Each class has one flusher, and it calls Publish in arrival order. Uploads run in parallel, and the release cursor puts them back in order.
  • Per-bucket upload permits. Each bucket allows Window uploads at once, quorum stragglers included, so a slow bucket cannot build up readers.
  • Stale writers. A writer that only seems dead keeps writing until it meets a poison marker. Its next create in that slot fails, it reads a foreign envelope, and its ledger halts. Recovery revoked its head before fencing, so its roll is deposed. See Epochs and fencing.
  • The roll gate. While a roll runs, new publishes wait at the gate, and the parked set is settled before any slot is judged.

Bounds and signals

BoundDefaultAt the bound
Pool256 MiB per class (--s3-memory-buffer-mib)Producers wait
Slots uploading at once128 per class (--s3-parallel-uploads)Sequencer.Next waits
Backlog: flights acknowledged but not absorbed1,024 flights (--s3-wal-backlog-flights) and 4 GiB (fixed)Publish waits; the stall is counted by cause
One slot's upload30 sThe slot fails and the ledger halts
One roll attempt60 sRetried after 0.5 to 1.5 s
RollsA burst of 3, then 1 every 200 sThe roll waits for a token; publishes wait at the gate

The Express WAL uses the same values, fixed in code. The --s3-express-parallel-uploads, --s3-express-memory-buffer-mib, and --s3-express-publish-deadline flags configure only the Express fan-out store; the Express WAL ignores them.

The backlog reports itself as pressed at three quarters of either bound. The metrics are in the metrics catalogue:

SignalWhat it shows
nova.wal.backlog.ageAge of the oldest flight awaiting absorb. Alert on this.
nova.wal.backlog.stallPublishes that waited, by cause: absorb_lag, metastore_slow, rolling, roll_pacer
nova.wal.slot.duration, nova.wal.boarding.durationOne slot's upload, and the wait between token and slot
nova.wal.roll.count, nova.wal.roll.waitingRolls by outcome and reason; a roll waiting for a token
nova.indexer.pass.duration, nova.indexer.phase.durationOne absorb pass, and its liveness, commit, aftermath, and checkpoint phases

The log lines are wal: ledger minted (with priors_fenced), wal: epoch halted; rolling (with reason and cause), wal: ledger rolled in place, wal: roll attempt failed; retrying, and wal: roll failed; the WAL is terminal. A slot or a backlog wait longer than 5 seconds logs wal: slot resolved slow or wal: publish waited on the backlog budget. The stall cause metastore_slow means the last ref commit took longer than one second.

Tests

  • internal/storage/loglet: TestAppendAssignsDenseSeqsAndReleasesInOrder, TestReleaseOrderSurvivesOutOfOrderCompletion, TestQuorumAckSurvivesOneBucketDown, TestQuorumMinorityPoisonLosesTheRace, TestGhostPutResolvesByOwnNonce, TestForeignOccupancyHaltsTheEpochPermanently, TestThrottledSlotGivesUpAtItsBudget, TestEnvelopeEncodesTheGoldenLayout.
  • internal/storage/wal: TestFirstPublishMintsAndCommitsInOrder, TestBacklogBlocksUntilRetired, TestRollAcknowledgesLateBelowTheCut, TestRollDeposedShedsTerminally, TestRollPacerBoundsCascades, TestRestartFencesPriors, TestRestartConvergesAcrossAHalfRolledPair, TestClosedS3PartitionCostsAppendsLatencyNotEpochs.
  • internal/storage/indexer: TestAbsorbConvergesFromAnyMidBatchCrash, TestAbsorbRefusesGaps, TestAbsorbCommitsOneSpanPerStream.
  • tlaplus/Ledger.tla models the slot quorum, the fence, and acknowledgement order.

See also

On this page