indexbuild

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Overview

Package indexbuild contains the Experimental embeddable workflow engine for durable index builds.

The engine owns the v2 build pipeline over the internal journal/segment substrate: crawl with an injected provider, seal observation journals, compact sealed journals, publish immutable segments/manifests, write the completion marker, and advance the local latest pointer. Command packages remain adapters that parse operator input and construct typed Config values.

Providers are injected as pkg/provider handles. This package does not import concrete provider packages, command packages, cobra/viper, or SQLite-backed index-store packages. The package is Experimental; see docs/api-stability.md.

Index

Constants

View Source
const (
	EventTypeRunStart          = "run_start"
	EventTypeCrawlError        = "crawl_error"
	EventTypeSnapshotPublished = "snapshot_published"
)
View Source
const (
	// DefaultMaxJournalLanes is the resolved lane ceiling when Config
	// .MaxJournalLanes is zero.
	DefaultMaxJournalLanes = 4
	// MaxJournalLanesCeiling is the highest lane count this engine accepts. It
	// stays well below the streaming merge's journal-source budget, so a run can
	// never produce more sealed journals than publication is able to stage.
	MaxJournalLanesCeiling = 32
)

Variables

This section is empty.

Functions

func ReadLatest

func ReadLatest(latestPath string) (ManifestSummary, []ObjectState, error)

ReadLatest reads the latest published internal snapshot through the same digest and traversal guards used by the substrate.

Types

type Clock

type Clock func() time.Time

Clock returns the current time for run metadata. Supplying a deterministic clock makes retry identity and CLI/library parity byte-testable.

A Clock must be safe for concurrent use. Experimental: a build stamps an observation time per record, and a multi-lane build writes records from every lane at once, so an injected Clock is called concurrently. This is a contract on the implementation rather than a lock inside the engine deliberately — guarding every per-record call would put a global lock on the hot path this slice exists to widen, and a per-lane wrapper would break the determinism an injectable clock is for. A closure over an immutable value is already safe; a clock holding mutable state needs its own synchronization.

type Config

type Config struct {
	IndexSetID          string
	RunID               string
	GonimbusVersion     string
	GonimbusCommit      string
	GonimbusVCSModified *bool
	BaseURI             string
	Source              Source
	Match               MatchConfig
	Filter              *match.CompositeFilter
	Crawl               crawler.Config
	// MaxJournalLanes bounds how many journal-writing lanes a build may split its
	// crawl across. Experimental.
	//
	// A build funnels every observation through one journal writer, which becomes
	// the ceiling once listing is no longer the constraint. Lanes give each a
	// private crawl pipeline and journal, while one shared request budget keeps
	// listing concurrency and request rate at their configured run-global values.
	//
	// Zero selects the resolved default; one keeps the single-journal form. Values
	// above the engine ceiling are refused before any side effect rather than
	// clamped. The effective lane count is the smallest of this value, the crawl
	// concurrency, and the number of crawl-plan entries — so lanes require an
	// explicit CrawlPrefixes plan with more than one entry, since a plan entry is
	// the unit of coverage authority a lane attests.
	//
	// A multi-lane run seals several journals, each recording only the plan subset
	// it observed. Recovery from such a run must be handed the complete set: an
	// omitted journal narrows the derived plan and refuses whole-run coverage.
	MaxJournalLanes int
	// CrawlPrefixes, when supplied, is the exact provider-prefix observation
	// plan. It lets CLI adapters pass a manifest scope plan into the engine
	// without making the engine import manifest or command packages. Entries
	// must be canonical provider-key prefixes (no leading slash or surrounding
	// whitespace) so the plan compared against coverage is exactly what drives
	// LIST. Coverage must equal this plan exactly (per-prefix set equality, no
	// roll-up/extra/missing/duplicate/windowed and confirmed-complete only) or
	// Build refuses before any side effect. When empty the effective plan is the
	// full base prefix; either way the plan is sealed into the journal as
	// recovery provenance and prior rows outside the attested plan are retained.
	// Any durable build additionally rejects a reducing observation selector
	// (see Match) so the sealed plan is a truthful record of what was observed.
	CrawlPrefixes []string
	// ObservationSinks receive the same observed crawl stream as the durable
	// journal materializer. This is the library-owned fanout boundary used by
	// CLI adapters to materialize compatibility formats from one observation.
	ObservationSinks []output.Writer
	Paths            PathConfig
	Coverage         []CoverageAttestation
	// PriorRows is retained only for source compatibility and is NOT an accepted
	// input: public Build rejects any non-nil value (including an empty non-nil
	// slice) before side effects. Durable prior state is loaded from the verified
	// parent under the held lease at continuity activation, never from
	// caller-supplied rows.
	PriorRows []ObjectState
	// ExpectedParent, when set, enforces latest-pointer CAS at publish advance.
	// When nil, Build/Retry capture the current latest (or first-publish) under
	// the write lease. Malformed latest fails closed (not first-publish).
	// Stale provided tokens are validated immediately after lease acquisition
	// and before any crawl/observation mutation.
	ExpectedParent *ParentToken
	// LossAcknowledgment records an explicit pinned scope-loss acknowledgment
	// bound to the parent manifest SHA-256 and current plan digest. When present,
	// it is sealed into the run's journal headers so recovery re-publications
	// verify the exact recorded acknowledgment rather than ambient flags.
	LossAcknowledgment *durableindex.TransitionAcknowledgment
	// Authority optionally supplies caller-held whole-set exclusion. When nil,
	// Build acquires the same stable authority used by CLI and GC. A supplied
	// lease remains caller-owned and is never released by Build.
	Authority *indexcoord.Lease

	RunStartedAt         time.Time
	ManifestCreatedAt    time.Time
	Clock                Clock
	TargetRowsPerSegment int
	// Spill is host/operator capacity configuration for the durable streaming
	// merge's scratch workspace. Zero values select the substrate defaults.
	Spill  SpillConfig
	Events EventSink
	// OnSegmentProgress is optional observational progress during segment write
	// (counts only). Outside artifact bytes; never a publish failure vector.
	OnSegmentProgress OnSegmentProgressFunc
}

Config configures a full crawl-to-publish durable index build.

func (Config) GoString

func (c Config) GoString() string

GoString implements fmt %#v with the same redaction as String.

func (Config) String

func (c Config) String() string

String returns a redacted config summary. Provider handles, callbacks, and local paths are rendered by presence only.

type CoverageAttestation

type CoverageAttestation struct {
	Scope    *Scope        `json:"scope,omitempty"`
	Basis    CoverageBasis `json:"basis"`
	Complete bool          `json:"complete"`
	Gaps     []Scope       `json:"gaps,omitempty"`
}

CoverageAttestation is the public engine coverage contract.

type CoverageBasis

type CoverageBasis string

CoverageBasis states the trust level of coverage evidence.

const (
	CoverageBasisConfirmed CoverageBasis = "confirmed"
	CoverageBasisInferred  CoverageBasis = "inferred"
)

type Digest

type Digest struct {
	Algorithm string
	Hex       string
}

type Event

type Event struct {
	Type    string         `json:"type"`
	RunID   string         `json:"run_id"`
	Message string         `json:"message,omitempty"`
	Details map[string]any `json:"details,omitempty"`
}

Event is the sanitized event payload delivered by the engine.

type EventSink

type EventSink interface {
	OnEvent(ctx context.Context, event Event) error
}

EventSink receives sanitized engine events. A sink may log or persist Event values without re-scrubbing. A nil sink disables event delivery.

type ManifestSummary

type ManifestSummary struct {
	GonimbusVersion        string
	GonimbusCommit         string
	GonimbusVCSModified    *bool
	DotSegmentPolicy       string
	Rows                   int
	ActiveRows             int
	Tombstones             int
	DistinctETags          int
	RetainedUnobservedRows int
	DotSegmentRows         int
	PlanDigest             string
	Admission              string
	Segments               []SegmentSummary
}

type MatchConfig

type MatchConfig struct {
	Includes      []string
	Excludes      []string
	IncludeHidden bool
}

MatchConfig is the library form of the index build match settings. Patterns are relative to BaseURI unless they are already full provider keys.

type ObjectState

type ObjectState struct {
	IndexSetID       string
	RelKey           string
	SizeBytes        int64
	LastModified     *time.Time
	ETag             string
	StorageClass     *string
	ArchiveStatus    *string
	RestoreState     *string
	RestoreExpiry    *time.Time
	ContentType      *string
	HeadEnrichedAt   *time.Time
	FirstSeenRunID   string
	FirstSeenAt      time.Time
	LastChangedRunID string
	LastChangedAt    time.Time
	LastSeenRunID    string
	LastSeenAt       time.Time
	DeletedAt        *time.Time
}

ObjectState is the public current-row form used for retry or compaction from a prior snapshot. It mirrors the durable manifest row shape without exposing the internal substrate package.

type OnSegmentProgressFunc

type OnSegmentProgressFunc func(progress SegmentProgress)

OnSegmentProgressFunc is observational best-effort segment progress.

type ParentToken

type ParentToken struct {
	IndexSetID     string
	RunID          string
	ManifestSHA256 string
	// CoverageSHA256 binds inherited coverage for enrich-only publications.
	CoverageSHA256 string
}

ParentToken is the public expected-parent CAS token for durable latest advance. Callers capture this from a verified latest snapshot before a write transaction.

type PathConfig

type PathConfig struct {
	JournalDir   string
	SegmentDir   string
	ManifestPath string
	CompletePath string
	LatestPath   string
	IndexDBDir   string
}

PathConfig holds explicit engine storage locations.

JournalDir and SegmentDir should be resolved by the adapter through the app-data path classes. If IndexDBDir is supplied, the engine rejects journal and segment paths below it so callers cannot silently place v2 working state under the legacy SQLite index directory.

Continuity layout contract: multi-run continuity requires the canonical latest-owned set layout — CompletePath at <dir(LatestPath)>/runs/<run_id>/complete.json with ManifestPath and SegmentDir contained in that run directory. A standalone first publication (no published latest) may use any caller-owned layout, but it can only be extended — or serve as the state parent of a later run — when it sits at the canonical locus, because continuity edges are recorded pathlessly and the production ancestry lookup rediscovers parents only under the latest-owned runs/ root. Same-run recovery must target the run's exact recorded locus.

func (PathConfig) GoString

func (p PathConfig) GoString() string

GoString implements fmt %#v with the same redaction as String.

func (PathConfig) String

func (p PathConfig) String() string

String returns presence-only path state so local filesystem layouts are not accidentally logged by embedders.

type RetryConfig

type RetryConfig struct {
	IndexSetID          string
	RunID               string
	GonimbusVersion     string
	GonimbusCommit      string
	GonimbusVCSModified *bool
	BaseURI             string
	Paths               PathConfig
	JournalPaths        []string
	// Coverage is destructive authority over verified-parent rows: a
	// confirmed-complete scope tombstones unobserved parent keys under it. Public
	// Retry does not trust this field on its own — it derives the observation
	// plan from the recorded `crawl_prefixes` journal header and requires Coverage
	// to match that plan exactly. The footer `content_sha256` is an unkeyed
	// integrity checksum over header+records (verified at validation and at the
	// compaction reopen) that detects corruption, truncation, and partial
	// modification on read; Retry consumes JournalPaths as engine-produced
	// recovery artifacts in trusted working storage. It is not a cryptographic
	// authentication mechanism; stronger authentication for untrusted
	// recovery-artifact storage is a tracked follow-up. Journals without a
	// recorded plan or checksum, or whose recorded plan is non-canonical, fail
	// closed.
	Coverage []CoverageAttestation
	// PriorRows is retained only for source compatibility and is NOT an accepted
	// input: public Retry rejects any non-nil value (including an empty non-nil
	// slice) before side effects. Durable prior state is loaded from the verified
	// parent under the held lease at continuity activation, never from
	// caller-supplied rows.
	PriorRows []ObjectState
	// ExpectedParent enforces latest CAS when republishing over an existing set.
	ExpectedParent *ParentToken
	// LossAcknowledgment, when supplied on Retry, must match the acknowledgment
	// already sealed in the journal headers; Retry never accepts an unsealed
	// acknowledgment override.
	LossAcknowledgment *durableindex.TransitionAcknowledgment
	// Authority follows Config.Authority semantics for public Retry.
	Authority *indexcoord.Lease

	RunStartedAt         time.Time
	ManifestCreatedAt    time.Time
	Clock                Clock
	TargetRowsPerSegment int
	// Spill follows Config.Spill semantics for public Retry.
	Spill             SpillConfig
	Events            EventSink
	OnSegmentProgress OnSegmentProgressFunc
}

RetryConfig configures publication retry from already sealed journals.

func (RetryConfig) GoString

func (c RetryConfig) GoString() string

GoString implements fmt %#v with the same redaction as String.

func (RetryConfig) String

func (c RetryConfig) String() string

String returns a redacted retry config summary.

type Runner

type Runner struct {
	// contains filtered or unexported fields
}

Runner executes durable index build workflows.

func NewRunner

func NewRunner(config Config) *Runner

NewRunner returns a Runner for config.

func (*Runner) Build

func (r *Runner) Build(ctx context.Context) (summary Summary, buildErr error)

Build crawls the injected provider, seals journals, and publishes a snapshot through the durable publication gate.

The index-set write lease is acquired before any ObservationSink mutation (including SQLite dual-format sinks) and held through durable latest advance.

type Scope

type Scope struct {
	Prefix string  `json:"prefix,omitempty"`
	Window *Window `json:"window,omitempty"`
}

Scope identifies a covered key prefix. When BaseURI is set on Config or RetryConfig, provider-key coverage is normalized into journal rel_key space before publication. Windowed coverage is carried for schema parity; this slice publishes only explicit complete prefix coverage.

type SegmentProgress

type SegmentProgress struct {
	Segment  int
	Total    int
	Rows     int
	RowsDone int
}

SegmentProgress is a sanitized segment-write progress signal (counts only).

type SegmentSummary

type SegmentSummary struct {
	SegmentID  string
	Path       string
	Rows       int
	Tombstones int
	Digest     Digest
}

type Source

type Source struct {
	Provider     provider.Provider
	ProviderName string
}

Source is the provider input for an index build. Provider construction and credential resolution are caller responsibilities.

func (Source) GoString

func (s Source) GoString() string

GoString implements fmt %#v with the same redaction as String.

func (Source) String

func (s Source) String() string

String returns a redacted source summary that never formats the provider handle, which may carry credential material.

type SpillConfig

type SpillConfig struct {
	// WorkspaceBytes overrides the merge's live on-disk workspace ceiling
	// (MaxWorkspaceBytes). A successive build stages the full prior current-state
	// into this workspace before merging, so size it to the corpus. Zero uses the
	// substrate default; a negative or sub-1 explicit value is rejected at publish.
	WorkspaceBytes int64
	// Root overrides the scratch directory (resolved absolute, real, non-symlink,
	// operator-exclusive at publish). Empty co-locates beside the run journals.
	Root string
	// RecordBytes overrides the max single journal-record (line) size
	// (MaxRecordBytes). The journal header carries the crawl-prefix plan, which
	// grows with scope prefix count, so very wide/dense scopes need a larger
	// bound. Zero uses the substrate default; a sub-1 explicit value is rejected.
	RecordBytes int64
}

SpillConfig is host/operator capacity configuration for the durable streaming merge's scratch workspace. It is never index identity, lineage, or artifact content, and an absolute Root must not enter manifests, receipts, or digests. Zero values select the substrate defaults.

type Summary

type Summary struct {
	IndexSetID      string
	RunID           string
	JournalPaths    []string
	ObjectsObserved int64
	PrefixesCrawled []string
	// ManifestSHA256 is the digest written into the durable complete marker at
	// publish time. Prefer this over re-hashing the manifest path after commit.
	ManifestSHA256 string
	// SnapshotCompletedAt is sampled at the immutable local complete-marker
	// commit boundary and is independent of the run start.
	SnapshotCompletedAt time.Time
	Manifest            ManifestSummary
	// PeakWorkspaceBytes is the high-water live on-disk spill workspace observed
	// during the durable merge (0 when nothing spilled or on the SQLite path).
	// Observational capacity evidence for sizing successive builds.
	PeakWorkspaceBytes int64
}

func Retry

func Retry(ctx context.Context, cfg RetryConfig) (summary Summary, retryErr error)

Retry publishes a snapshot from already sealed journals. It is the library recovery entry point for compaction or publication interruptions after a crawl completed.

Public Retry always acquires the real OS write lease (callers cannot inject a no-op guard). Build reuses its held lease via unexported retryWithLease.

type Window

type Window struct {
	From string `json:"from,omitempty"`
	To   string `json:"to,omitempty"`
}

Window represents a bounded temporal scope.

Jump to

Keyboard shortcuts

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