rebuild

package
v0.9.9-dev.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 4, 2026 License: Apache-2.0 Imports: 20 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package rebuild orchestrates the full rebuild: facts become the canonical LadybugDB graph and that graph replaces CURRENT, or nothing changes.

The pipeline is eight checkpoints — facts, staging, graph.next, bulk load, integrity, snapshot, golden probes, publish — and every one of them is recorded on the returned Report, in that order, whether or not it passed. The integrity checkpoint itself has two gates: canonical table row counts must match what the fact set implies, and the semantic invariants of LUQUE-0904 (no dangling exact edges, no missing evidence, no duplicate stable keys, no unknown confidence or provenance, no invalid repository ownership) must hold over the graph that was just loaded. The snapshot checkpoint also has two gates: it writes the deterministic digest of the candidate's per-table counts (snapshot.sha256, next to the candidate database), and it builds the real in-memory HotSnapshot from the candidate's definitive graph (BuildSnapshot) — a graph the latter cannot convert is never published, however clean its integrity gate looked. The package never talks to LadybugDB itself: staging, loading, counting, scanning, probing and invariant checking are hooks the caller supplies (Options.Load/Counts/Scan/Probes/Integrity), which default to the real ladybug implementations. That is what lets the orchestration be exercised without cgo.

Index

Constants

View Source
const PublishedSnapshotDigestFileName = "snapshot.content.sha256"

PublishedSnapshotDigestFileName records the digest of the graph the published snapshot contains. It is what proves the file belongs to this generation.

It is deliberately not snapshot.sha256. That one digests the canonical table counts, and counts cannot tell two graphs of the same shape apart: measured on `workspace`, two indexings whose graphs differed in 288 rows produced a byte-identical snapshot.sha256. A file proven only against counts is a file that can be accepted for a graph it does not contain. The counts digest keeps its own job, which is Rollback's cheap check that a destination database still holds what it recorded. See ADR 0061.

A generation published before this file existed carries none, which is not a defect: the reader cannot prove the snapshot and derives the graph from the canonical store exactly as it always did.

View Source
const PublishedSnapshotFileName = "snapshot.kvsnap"

PublishedSnapshotFileName is the HotSnapshot a generation carries, next to its database and its digest.

Before this existed, a generation carried only the canonical graph and every server derived the snapshot from it: 1.003 MB allocated and ~1,05 GB of peak per install, once per published generation, in every process. See ADR 0045.

View Source
const SnapshotRowFormatVersion uint32 = 3

SnapshotRowFormatVersion versions the mapping this file implements from ladybug.CanonicalGraph to hotsnapshot.LadybugSnapshotRows. It is distinct from both ladybug.CanonicalSchemaVersion (the database layout) and facts.CodeFormatVersion (the kind/confidence/provenance numbering): this constant changes only when this adapter's own row shaping rules change in a way that would produce a different snapshot for the same canonical graph.

Variables

View Source
var ErrNoPublishedSnapshot = errors.New("the generation carries no published snapshot")

ErrNoPublishedSnapshot says a generation carries no snapshot, which is not a defect: one published before the file existed carries none, and a reader derives the graph exactly as it always did. A file that is there and cannot be used is a different answer, and gets a different error.

View Source
var ErrNoRecordedGraphDigest = errors.New("the generation records no digest for its published snapshot")

ErrNoRecordedGraphDigest says a generation carries a snapshot but not the digest of the graph it should hold, which is what every generation published before ADR 0061 looks like.

It is the same class of answer as absence, and for the same reason: nothing is wrong, the definitive graph is there, and a reader that cannot prove the file derives the snapshot instead. Counting it as a failure would mark doctor red on every install the moment it upgrades, which is exactly how a real failure stops being noticed.

View Source
var ErrRebuildFailed = errors.New("full rebuild failed")

ErrRebuildFailed reports that a full rebuild did not reach a published generation. The wrapped detail names the stage that stopped it, so a caller can report exactly what failed without parsing the Report.

View Source
var ErrRollbackFailed = errors.New("rollback failed")

ErrRollbackFailed reports that a rollback did not reach a switched generation. Like ErrRebuildFailed, the wrapped detail names exactly what stopped it — no destination, a digest mismatch, a broken invariant — so a caller can report the cause without re-deriving it from the report.

View Source
var ErrSnapshotBuildFailed = errors.New("snapshot build failed")

ErrSnapshotBuildFailed reports that the definitive graph read from a database could not become a HotSnapshot: an edge table outside the canonical vocabulary, an unknown confidence or provenance code, a source line that overflows uint32, or a dangling symbol or evidence reference. LUQUE-0904's invariants (no dangling exact edges, no missing evidence, no unknown confidence or provenance) already guarantee a valid canonical graph never trips any of these — every case here is a coherence assertion, not a value this package expects to actually see, so a broken graph fails loudly instead of silently producing a wrong snapshot.

Functions

func RefreshSnapshotDigest

func RefreshSnapshotDigest(generationPath string, tables map[string]int64) (string, error)

RefreshSnapshotDigest recomputes snapshot.sha256 for an already published generation whose graph was mutated in place by an incremental delta.

Rollback revalidates a destination by recomputing this digest from the live row counts and comparing it against the recorded file, so a generation mutated after publication must have its digest rewritten or it can never be rolled back to again. Both paths share writeSnapshotDigest, so an in-place update and a fresh publish can never disagree about what a generation's digest means.

func ReturnBuildMemory

func ReturnBuildMemory()

ReturnBuildMemory hands what a snapshot build borrowed back to the operating system.

BuildSnapshot materialises the graph three times before it can publish it once: the rows the canonical scan decodes, the snapshot's own row set, and the snapshot. Measured on a 189 MB graph -- 102 385 symbols, 259 556 edges -- the Go heap peaks near 500 MB to produce 173 MB of live snapshot, and the runtime then keeps that arena: the heap goal alone is twice the live heap at the default GOGC, and a process that only answers queries never allocates enough afterwards to reuse the rest. Left alone, a server parks at three times what it holds, for as long as it runs.

This is the one moment the transient is provably dead: the snapshot has been published, or was dropped because another publisher won, and either way nothing can reach its inputs. A server has nothing else to do until the next request, so the collection and scavenge cost it nothing a caller can observe.

It is deliberately not a memory limit, and the reason is now narrower than it was. Since ADR 0042 the pass runs as a child process, so what a limit set here still reaches is only what the child inherits -- the environment, since `subprocess.go` never sets `command.Env` -- and `GOMEMLIMIT` there would bound the indexer, whose peak is the work itself.

It would also buy almost nothing, which is the part measurement had to settle. On a 189 MB graph the Go heap parks 2.4-4 MB above the live snapshot after every single build: there is no Go-side gap for a ceiling to close. What made a long-lived server park at three times what it holds was the allocator underneath the engine, and that is what the second call below returns. See ADR 0044.

Types

type BuildSnapshotOptions

type BuildSnapshotOptions struct {
	DatabasePath string
	SnapshotID   uint64
	Metrics      *metrics.Registry

	// Scan defaults to ladybug.ScanCanonical, exactly like Options.Load,
	// Options.Counts, Options.Probes and Options.Integrity already default
	// for Run: tests substitute it so this is exercised without cgo.
	Scan func(context.Context, string) (ladybug.CanonicalGraph, error)
}

BuildSnapshotOptions configures one snapshot build.

type GenerationSnapshotOptions

type GenerationSnapshotOptions struct {
	Root    string
	Store   generation.Config
	Metrics *metrics.Registry

	// GenerationID selects which published generation to snapshot; empty
	// means graph.active — the generation actually serving right now,
	// unlike RollbackOptions.GenerationID, whose empty value means the
	// registered graph.backup.
	GenerationID string
	SnapshotID   uint64
	Scan         func(context.Context, string) (ladybug.CanonicalGraph, error)
}

GenerationSnapshotOptions resolves a generation inside a generation store and builds its HotSnapshot in one call — the same root+generation resolution RollbackOptions already does for Rollback, applied here to BuildSnapshot instead of generation.Store.Restore.

type IntegrityCheck

type IntegrityCheck struct {
	Table    string
	Expected int64
	Observed int64
	Passed   bool
}

IntegrityCheck compares the row count LadybugDB reports for one canonical table against the count the fact set implies.

type Layout

type Layout struct {
	Active    generation.Generation
	Backup    generation.Generation
	HasBackup bool
	NextID    string
	Retained  []string
}

Layout reports the three roles the plan requires.

func Roles

func Roles(ctx context.Context, options LayoutOptions) (Layout, error)

Roles resolves graph.active, graph.next and graph.backup for the generation store rooted at options.Root. A store that has never published a generation is not an error: Layout.Active is the zero Generation and Layout.HasBackup is false, so a caller renders an empty layout instead of failing — the same stance generation.Store.Current already takes for CURRENT alone.

type LayoutOptions

type LayoutOptions struct {
	Root  string
	Store generation.Config
}

LayoutOptions locates a generation store.

type Options

type Options struct {
	Root            string
	GenerationID    string
	Facts           facts.Set
	ResolverVersion string
	SnapshotID      int64
	Store           generation.Config
	Metrics         *metrics.Registry

	// Progress, when set, is called with the name of each stage as it
	// starts. A rebuild reports nothing else while it runs: the bulk load
	// and the snapshot are the long stages, and this is how a caller can
	// show which one is in flight.
	Progress func(StageName)

	// Load, Counts, Probes, Integrity and Scan default to the ladybug
	// implementations; tests substitute them so the orchestration is
	// exercised without cgo.
	Load      func(context.Context, string, facts.Set, ladybug.CanonicalLoadOptions) (ladybug.LoadReport, error)
	Counts    func(context.Context, string) (map[string]int64, error)
	Probes    func(context.Context, string, []ladybug.CanonicalProbe) ([]ladybug.CanonicalProbeResult, error)
	Integrity func(context.Context, string) (ladybug.CanonicalIntegrityReport, error)
	Scan      func(context.Context, string) (ladybug.CanonicalGraph, error)
}

Options configures one full rebuild run.

type PublishedSnapshotInfo added in v0.2.1

type PublishedSnapshotInfo struct {
	Path    string
	Bytes   int64
	ID      uint64
	Symbols int
}

PublishedSnapshotInfo describes the snapshot a generation carries.

func InspectPublishedSnapshot added in v0.2.1

func InspectPublishedSnapshot(directory string) (PublishedSnapshotInfo, error)

InspectPublishedSnapshot answers what a generation's published snapshot is, or why a server would have to derive the graph instead of reading it.

It exists so a tool can say which of the two is happening. Nothing did, and the cost of that silence is measured: twice while this was being built, a server derived the whole graph -- 1003 MB and 1.7 s per generation -- and every suite stayed green, because both routes produce the same snapshot and only memory tells them apart.

type Report

type Report struct {
	GenerationID   string
	Stages         []Stage
	Load           ladybug.LoadReport
	Integrity      []IntegrityCheck
	Invariants     ladybug.CanonicalIntegrityReport
	Probes         []ladybug.CanonicalProbeResult
	SnapshotDigest string
	Snapshot       SnapshotReport
	Publication    generation.Publication
	Pruned         []string
	Passed         bool
}

Report is the full account of one rebuild run, successful or not.

func Run

func Run(ctx context.Context, options Options) (Report, error)

Run drives one full rebuild: it stages and bulk loads the fact set into a fresh candidate database, verifies it, snapshots it, and publishes it through the generation store's atomic swap. A failure at any stage aborts the publish, so the previous CURRENT generation is left untouched.

type Role

type Role string

Role names one of the three pointers LUQUE-0905 requires the generation store to expose. None of the three renames anything on disk: generations/<id> and CURRENT are the load bearing, already exhaustively tested layout, and stay exactly as they are. graph.active is the generation CURRENT names, graph.next is the <id>.tmp candidate generation.Store.Publish builds and swaps in, and graph.backup is the generation a rollback would restore — the generation that was active a moment ago, retained on purpose instead of being pruned.

const (
	RoleActive Role = "graph.active"
	RoleNext   Role = "graph.next"
	RoleBackup Role = "graph.backup"
)

type RollbackOptions

type RollbackOptions struct {
	Root         string
	Store        generation.Config
	GenerationID string

	// Counts and Integrity default to the ladybug implementations, exactly
	// like Options.Counts and Options.Integrity already do for Run; tests
	// substitute them so rollback validation is exercised without cgo.
	Counts    func(context.Context, string) (map[string]int64, error)
	Integrity func(context.Context, string) (ladybug.CanonicalIntegrityReport, error)
}

RollbackOptions configures one rollback.

type RollbackReport

type RollbackReport struct {
	From       generation.Generation
	To         generation.Generation
	Digest     string
	Expected   string
	Invariants ladybug.CanonicalIntegrityReport
	Passed     bool
}

RollbackReport accounts for one rollback.

func Rollback

func Rollback(ctx context.Context, options RollbackOptions) (RollbackReport, error)

Rollback switches CURRENT back to a previously published generation. The destination is options.GenerationID when given, otherwise the registered graph.backup; with neither, there is nowhere defined to roll back to and Rollback fails without touching the store.

Before switching anything, the destination is revalidated exactly like a fresh publish would be: its snapshot digest is recomputed from Counts and compared against the snapshot.sha256 the original rebuild's snapshot stage wrote for it, using the very same canonicalSnapshotDigest calculation — so rollback and rebuild can never disagree about what a generation's digest means — and Integrity must report all six LUQUE-0904 invariants passing. Both checks run inside the generation.ValidateFunc generation.Store.Restore calls before it ever rewrites CURRENT, so a failing check leaves the active generation untouched by the store's own construction: Rollback does not need, and does not attempt, its own undo path. A successful Restore also makes the generation that was active a moment ago the new graph.backup, so a rollback can always be rolled forward again.

type SnapshotReport

type SnapshotReport struct {
	SnapshotID  uint64
	Version     uint32
	Digest      string
	Stats       SnapshotStats
	Passed      bool
	Loaded      bool
	LoadRefused string
}

SnapshotReport is the account of one snapshot build.

Loaded and LoadRefused describe where the snapshot came from, which a server has to be able to say out loud: one that derives the graph on every published generation looks exactly like one that never had a published snapshot to read, and the difference is a gigabyte of peak per install. Digest is empty for a loaded snapshot -- it is computed from the canonical rows a build reads, and a load never reads them.

func BuildSnapshot

BuildSnapshot builds the in-memory HotSnapshot from the definitive graph stored at options.DatabasePath — never from a facts.Set. That is the point of LUQUE-0906: the snapshot is derived from what is actually stored in LadybugDB, the same definitive graph doctor graph and rollback already verify, not from the input the loader was handed. A graph that cannot become a snapshot is reported as an error wrapping ErrSnapshotBuildFailed; a *hotsnapshot.GraphSnapshot is only ever returned once hotsnapshot.BuildGraphSnapshot has itself validated it.

func LoadOrBuildSnapshot added in v0.1.2

func LoadOrBuildSnapshot(ctx context.Context, options BuildSnapshotOptions) (*hotsnapshot.GraphSnapshot, SnapshotReport, error)

LoadOrBuildSnapshot answers with the generation's published snapshot when it can be trusted, and derives it from the canonical graph when it cannot.

The fallback is the whole point: a generation always carries the definitive graph, so a missing, foreign, stale or corrupt snapshot file costs a rebuild and never an answer. The report says which happened, because a server that silently derives every time would look exactly like one that never had to.

func SnapshotGeneration

SnapshotGeneration resolves options.GenerationID (or, when empty, the active generation) inside the generation store rooted at options.Root, then builds its HotSnapshot exactly like BuildSnapshot does. It is the entry point the snapshot CLI command uses.

type SnapshotStats

type SnapshotStats struct {
	Repositories int
	Packages     int
	Files        int
	Symbols      int
	Evidence     int
	Edges        int
	PackageEdges int
	Unresolved   int
	SkippedEdges int
}

SnapshotStats accounts for what a built snapshot contains.

type Stage

type Stage struct {
	Name       StageName
	Passed     bool
	Detail     string
	DurationMS float64
}

Stage is one recorded checkpoint of a rebuild run.

type StageName

type StageName string

StageName identifies one checkpoint of the rebuild pipeline.

const (
	StageFacts     StageName = "facts"
	StageStaging   StageName = "staging"
	StageGraphNext StageName = "graph.next"
	StageBulkLoad  StageName = "bulk load"
	StageIntegrity StageName = "integrity"
	StageSnapshot  StageName = "snapshot"
	StageProbes    StageName = "golden probes"
	StagePublish   StageName = "publish"
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL