Reclamation

Reclamation

How the auditor rewrites live records into new objects and deletes objects nobody references.

Reclamation is how the auditor rewrites records and frees storage without breaking a reader. It rests on two rules. A rewrite never changes the bytes at an existing key: it publishes a new object and moves references to it with a compare-and-set. And an object is deleted only after every reference to it is gone and a full read grace has passed since that was first observed.

Where it lives

PackageWhat it holds
internal/storage/rewriteThe mover: denorm (streamdenorm.go), gc and tail-extension revisions (denorm.go), and the era walk (era.go)
internal/storage/reclaimThe probe (prober.go), the reap spool (reapspool.go), the ref walker for retention and teardown (walker.go), the orphan judge (orphan.go), and star reclaim (star.go)
internal/metadataCatalog rows and their compare-and-set (catalog.go), write intents (commit.go), reap and trim-check markers
internal/storage/objectstore/s3Assembly of an output from source ranges (assemble.go, plan.go)

Shared rewrite process

A rewrite reads ranges of existing objects, publishes a new object, and moves references to it. Three jobs use the same mover:

JobSourcesOutputReference change
DenormA stream's chunks in transit bundlesA stream object, revision 0Replace the first span ref with a catalog row
Tail extension, inside denormThe stream's small last object plus new chunksThe last object's next revisionReplace the row's last entry
Garbage collectionThe live chunks of one stream objectIts next revisionReplace the exact (epoch, first, revision) entry

An object's footer lists its chunks with their sequence and byte ranges. A chunk is live while a ref at or below its first sequence number names this object.

Publishing a rewrite

Write the intent for the output key Is an object already at the key? Read each source footer by range Assemble the output, if no object exists Write catalog rows, swap the first span ref by CAS Delete the covered span refs Resolve the intent Arm the trim-check, resolve the marker Denorm job Metadata store Object storage
A denorm publish. Every step can be repeated, and a loser adopts the winner's object.

Record the intended output

The job writes a write intent under due/orphan/, holding the output's class and its own birth time, before anything is uploaded. The output key comes from the bucket, stream, epoch, and first sequence number, with ~{revision} for a revision. A retry of the same work derives the same key.

Select live records

The job reads each source footer with one ranged read. Denorm takes the stream's chunks in its transit window. Garbage collection takes the stream's chunks of the object, skipping a chunk only when it lies wholly below the trim watermark.

Assemble the output

Source ranges that touch are merged into runs. A run of at least 5 MiB in the same bucket, or on the same endpoint and region, is copied by the storage service inside a multipart upload. Smaller runs are read by range, through the auditor's fetch cache for denorm's WAL reads when it has one, and uploaded as parts.

An output with no server-side copy, up to --s3-single-put-max (64 MiB), goes up as one conditional write instead. Each attempt of that write gets at least the object's time at 4 MiB/s, and a failed attempt sends the whole object again. Chunk bytes and checksums are kept, and the footer is rebuilt. The rewrite budget is charged after the publish lands.

Publish once

The upload completes only if no object exists at the key, so the first publisher wins. Denorm first checks whether an object already stands, and adopts it without uploading. A denorm or tail extension that loses the race reads the winner's footer and commits refs to those bytes, trimmed to a whole row. Coverage that would end inside a row fails the commit. Denorm refuses an output another incarnation of the stream published, and leaves its marker to wait one read grace.

internal/storage/rewrite/streamdenorm.go
	if standing {
		return rw.adoptStanding(ctx, dst, newKey, size, id, epoch, window[0].First, relocs)
	}

	desc, stats, err := rw.relocateWithRetry(ctx, src, dst, newKey, relocs)
	if errors.Is(err, objectstore.ErrAlreadyExists) {
		// Another run's publish landed between the check and the commit.
		return rw.describeStanding(ctx, dst, newKey, id, epoch, window[0].First, relocs)
	}

Garbage collection does not adopt: a key already taken fails the job. See the crash points.

Update references

Denorm writes the catalog rows that follow first, then swaps the row at the window's first key with a compare-and-set on the version it read. That swap is the moment readers see the stream objects. It then deletes the covered span refs in ascending runs.

internal/metadata/catalog.go
	if isCatalog(&row) {
		return nil // a completed put: the re-run has nothing to swap
	}

	cat.s.tail.dropRefAt(id, page.FirstID)

	if _, err := loc.PutIndexed(ctx, key, value, rec.Version, tsEntry); err != nil {
		return fmt.Errorf("metadata: catalog %v/%d: %w", id, page.FirstID, err)
	}

	return nil

Garbage collection replaces the exact (epoch, first, revision) entry it read, by compare-and-set on the row's version. Tail extension replaces the row's last entry when its first sequence and epoch match and its revision is lower. A mismatch leaves the output under its intent.

Schedule source cleanup

Before the job resolves its marker, it arms each source's next check: a trim-check one read grace out for a WAL slot, a reap-check for a stream object. Tail extension arms the old tail's reap-check before it moves any reference, because it could not find that object again afterwards.

Remove the write intent

Denorm and tail extension resolve the output's intent once a ref names the object. Garbage collection leaves its intent for the orphan duty, which finds the ref after the grace and resolves it. Last, the job resolves its own marker.

Revisions

A rewrite of a stream object keeps its epoch and often its first sequence number, so the revision tells the keys apart. A denorm output is revision 0, with no suffix. A revision is its source entry's revision plus one, ~{revision}. A gc output's first sequence number is its first live chunk, which can be above the source's.

Writing new bytes at the old key would leave existing refs pointing into a different layout if a crash stopped the metadata change. A new key keeps both objects readable until the references move.

Storage class

Every rewrite output is in the standard bucket, including those of Express streams. Express storage holds only WAL slots, each due for denorm within the Express age cap. A source's class comes from its ledger, ref, intent, or marker.

Checking whether an object is still used

A probe reads one stream object's footer by range and checks the ref of each chunk, 128 lookups at once. It reads each stream's descriptor once: the chunks of a deleted stream are dead without a ref read. It totals live and dead bytes:

VerdictCondition
GoneThe footer read finds no object
ReapableNo live bytes
Gc-worthyLive bytes remain, and dead bytes are at least 64 MiB and more than half the object
StandAnything else

Reap-check acts on the verdict.

Deletion in two stages

A reap-check marker records whether it is confirmed. An unconfirmed check that finds every chunk dead does not delete. It arms a confirmed check one read grace out, rounded up to 30 seconds, and resolves. Only a confirmed check that still finds every chunk dead deletes the object.

internal/storage/reclaim/prober.go
	case probeReapable:
		if !check.Confirmed {
			confirmed := check
			confirmed.Confirmed = true

			if err := p.due.ArmReapCheck(ctx, objectKey, confirmed, p.now().Add(p.readGrace), streams); err != nil {
				return err
			}

			return p.due.ResolveDue(ctx, record)
		}

		if batch := p.spool.add(check.Class, objectKey, record); batch != nil {
			return p.flushBatch(ctx, check.Class, batch)
		}

This guarantees a full read grace after the first observation that the object is dead, even when the first marker was armed early. It needs no stored deletion time and tolerates merged markers and clock differences. The cost is one extra probe per deleted object.

Confirmed deletes are spooled by class and sent as batch deletes of up to 1,000 keys, split to the delete budget's burst. A batch leaves when a class fills, or when a pass ends. Markers resolve only after their batch succeeds.

The read grace, 10 minutes by default, is twice the life of a read plan and of a cached footer: both are derived as half of it. So a reader holding either finishes before the object goes.

Deleting WAL slots

WAL slots are deleted by position, without a probe. Each ledger keeps a rewritten cursor, bounded by its first standing denorm marker or by its checkpoint, and a trimmed cursor. Trim-check deletes the slots between them in batches, from every bucket of the class, and moves trimmed after each batch:

internal/auditor/trimcheck.go
	for from < to {
		end := min(from+uint64(budget.batchKeys()), to) //nolint:gosec // a batch is at most MaxDeleteBatch

		lo, hi := from, end
		trim := func(ctx context.Context) error { return loglet.Trim(ctx, cfg, lo, hi) }

		if err := budget.spend(ctx, int(end-from), trim); err != nil { //nolint:gosec // a batch is at most MaxDeleteBatch
			return fmt.Errorf("auditor: trim-check %v/%d: %w", cfg.Star, cfg.Epoch, err)
		}

		if err := d.ledgers.AdvanceTrimmed(ctx, cfg.Star, cfg.Epoch, from, end); err != nil {
			return err
		}

		from = end
	}

Deletes ignore missing objects, and the cursors only move forward. The indexer never deletes slots. The one exception is a slot above a fenced ledger's cut that was never acknowledged, which the ledger recovery that finds it deletes.

Checking abandoned writes

After --auditor-orphan-grace (1 hour), the orphan duty reads the object behind an intent with a head request, then its footer from the tail:

FindingJudgment
No objectNothing to reclaim
Shorter than a trailer, or a footer that does not decodeThe upload never finished: delete it now
A ref names a chunk, and the stream is liveVisible: resolve the intent
A whole object that no live ref namesArm a confirmed reap-check one read grace out
internal/storage/reclaim/orphan.go
	case orphanUnreferenced:
		check.Class = class
		check.Confirmed = true

		if err := p.due.ArmReapCheck(ctx, objKey, check, p.now().Add(p.readGrace), streams); err != nil {
			return err
		}

		p.log.Info("reclaim: orphan handed to the reap", "object", objKey)

		return nil

A whole object goes through the reap, so it is deleted only if it is still unreferenced a read grace later. A failed read leaves the intent for a later pass.

Crash points

Crash afterState left behindWhat the re-run doesTest
The intent, before the uploadAn intent, no objectUploads again at the same key; or the orphan judge finds nothingTestCrashEnumerationStreamObjectRewriteConverges
A denorm upload, before its commitAn intent and an unreferenced objectFinds the object standing, adopts it, and commitsTestCrashedDenormConvergesOnTheStandingOutput, TestACutBetweenPublishAndCommitConverges
A gc upload, before its catalog swapAn intent and an unreferenced objectDerives the same key and fails. The marker stays, and each retry renews the intent's birth.None. This window is not yet handled.
Another publisher winsA standing object that covers less than this walkCommits refs to the standing object. The rest stays in transit, rescheduled for its age cap or a linger from now.TestConvergedShortDenormHoldsTheRemainder
The catalog swap, before the intent resolvesA referenced object under an intentThe orphan judge finds the ref and resolves the intentTestOrphanGenuineCommitResolvesIntentOnly
The commit, before the source's checkThe duty's marker standingFinds the source replaced and arms its checkTestCrashEnumerationStreamObjectRewriteConverges
A reap-check armed, before the ref removalAn early reap-checkThe probe finds a live ref and standsTestReapCheckStandsWhileAnySpanLives, TestReclaimKillsNoRefBeforeItsArmsAreDurable
The unconfirmed dead probeA confirmed marker one grace outThe confirmed probe checks again before it deletesTestReapCheckObservesThenConfirmsThenDeletes
A batch delete, before its markers resolveMarkers over deleted objectsThe probe judges gone and resolvesTestCrashEnumerationOrphanToReapConverges
A trim batch's delete, before its cursor movesDeleted slots behind an old trimmedDeletes them again, finds nothing, moves the cursorTestTrimCheckCutBetweenDeleteAndCursorConverges
A teardown walk mid-removalSome refs gone, reap-checks armedWalks the remaining refsTestTeardownWalkMutationsConverge
A denorm, at any catalog changeSome members committedSkips the committed members and finishes the restTestADenormFaultedAtAnyCatalogMutationConverges

Concurrency

Two auditors may run the same rewrite during a ring change, and a reader may hold an old footer while its object is replaced. The create-once upload, the catalog compare-and-set on the version read, and the read grace before any delete cover all three. A stale gc that loses its compare-and-set leaves an output that the orphan duty reclaims.

Bounds and signals

BoundDefaultSet by
Server-side copyRuns of at least 5 MiBFixed
Single conditional uploadOutputs up to 64 MiB with no copy--s3-single-put-max
Probe lookups at once128Fixed
Batch delete1,000 keysFixed
Gc threshold64 MiB and half the objectFixed
Read grace10 minutes--auditor-read-grace
Orphan grace1 hour--auditor-orphan-grace
Upload attempts3, 200 ms apartFixed

Metrics:

  • nova.auditor.probe.verdicts, by verdict
  • nova.auditor.denorm.spans and nova.auditor.denorm.bytes, by outcome
  • nova.auditor.member.phase and nova.auditor.denorm.adoptions_refused
  • nova.auditor.slots.trimmed
  • nova.auditor.delete_budget.keys and nova.auditor.delete_budget.throttles

Log lines:

  • reclaim: probe armed gc
  • reclaim: objects reaped by probe
  • reclaim: orphan reclaimed
  • reclaim: orphan handed to the reap
  • rewrite: denorm converged short of the walk
  • rewrite: tail-fill abandoned

Deletes and the object cache

A single-object delete goes through the object cache when one is configured, which drops the cached copy. Batch deletes, which carry every confirmed reap and every WAL trim, go to object storage directly. Their cached copies, and copies in other zones, expire under the cache's own TTL: one hour in the cache the Kubernetes operator deploys and in the Compose stack (get_ttl: 1h).

Go deeper

Why deletes wait a read grace: Background work.

On this page