indexer

package
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2026 License: Apache-2.0 Imports: 37 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 indexer contains the language-specific invalidation plans that sit between file changes and canonical fact deltas.

Index

Constants

View Source
const DefaultRepublishRatio = 0.5

DefaultRepublishRatio is the share of the indexed files a delta may restate before a full republish becomes the better route. Above it the delta stops being cheaper than a clean bulk load, and the republish also buys an atomic swap and a fresh graph.backup instead of mutating the generation queries are being served from.

View Source
const ProviderDefinitionNotIndexed = "PROVIDER_DEFINITION_NOT_INDEXED"

ProviderDefinitionNotIndexed is the reason of a use whose provider is in the graph and does not publish the declaration the use resolves to. The standard library reaches this through macros: `impl Add for u32` is generated by `add_impl!`, so it exists in no source range and no index defines it.

Variables

View Source
var ErrCacheDiverged = errors.New("fact cache diverged from the analysis")

ErrCacheDiverged reports that a cached entry did not match the facts the analysis produced for the same unit. It aborts the pass on purpose: a cache that answers with facts nobody can reproduce is worse than no cache, because the graph it publishes looks exactly like a correct one.

View Source
var ErrUpdateFailed = errors.New("incremental update failed")

ErrUpdateFailed reports that an incremental update did not reach a usable graph. The wrapped detail names what stopped it.

Functions

func DecodeFactsJSON

func DecodeFactsJSON(data []byte) (facts.Set, error)

DecodeFactsJSON is kept small and explicit for callers that persist a facts set between indexing and rebuilding.

func ValidCacheMode

func ValidCacheMode(mode CacheMode) bool

ValidCacheMode reports whether mode is one this package implements.

Types

type CacheMode

type CacheMode string

CacheMode selects what the fact cache does during a pass.

const (
	// CacheOff analyses every unit. No entry is read and none is written.
	CacheOff CacheMode = "off"
	// CacheOn serves a unit from its entry when every input it recorded
	// still has the same fingerprint.
	CacheOn CacheMode = "on"
	// CacheVerify analyses every unit and, when an entry would have been
	// served, compares it against what the analysis just produced. The
	// fresh facts are always the ones published: verification costs the
	// whole pass and buys the proof that the cache does not lie.
	CacheVerify CacheMode = "verify"
)

type CacheReport

type CacheReport struct {
	Mode     CacheMode
	Hits     int
	Misses   int
	Verified int
}

CacheReport counts what the cache did, for the pass to report.

type ChangeKind

type ChangeKind string

ChangeKind is a conservative classification of the observable impact of a changed file. It is never a semantic relationship and never creates a graph edge by itself.

const (
	ChangeBodyOnly           ChangeKind = "BODY_ONLY"
	ChangeSignatureChanged   ChangeKind = "SIGNATURE_CHANGED"
	ChangeImportsChanged     ChangeKind = "IMPORTS_CHANGED"
	ChangeExportsChanged     ChangeKind = "EXPORTS_CHANGED"
	ChangeDeclarationAdded   ChangeKind = "DECLARATION_ADDED"
	ChangeDeclarationRemoved ChangeKind = "DECLARATION_REMOVED"
	ChangeManifestChanged    ChangeKind = "MANIFEST_CHANGED"
	ChangeProjectConfig      ChangeKind = "PROJECT_CONFIG_CHANGED"
	ChangeFileDeleted        ChangeKind = "FILE_DELETED"
	ChangeGoModChanged       ChangeKind = "GO_MOD_CHANGED"
	ChangeReplaceChanged     ChangeKind = "REPLACE_CHANGED"
	ChangePackageDeleted     ChangeKind = "PACKAGE_DELETED"
	ChangeUnknown            ChangeKind = "UNKNOWN"
)

type Decision

type Decision struct {
	Route  Route  `json:"route"`
	Reason string `json:"reason"`
	// ChangedFiles are the durable file keys the delta withdraws and,
	// except for removals, restates.
	ChangedFiles []string `json:"changed_files,omitempty"`
	// TotalFiles is the size of the indexed state the ratio is measured
	// against.
	TotalFiles int64 `json:"total_files"`
	// ForcedBy names the actions that made a republish mandatory.
	ForcedBy []InvalidationAction `json:"forced_by,omitempty"`
}

Decision explains which route an update takes and why.

func Decide

func Decide(plans []InvalidationPlan, delta facts.Delta, hasActive bool, totalFiles int64, republishRatio float64) Decision

Decide chooses the route for the plans and the computed delta. It never touches the store: the caller supplies the layout facts it needs.

hasActive reports whether a generation is currently published; totalFiles is the file count of the state the delta would be applied to.

type FullOptions

type FullOptions struct {
	Repositories      []workspace.Repository
	SyntheticWorkFile string
	IncludeTests      bool
	// GoBuildTags are the build constraints the Go loads satisfy. A package
	// guarded by a tag that is absent here declares no file to read and is
	// reported as unresolved instead of indexed.
	GoBuildTags []string
	// GoAllowNetwork lets the Go loads reach a module proxy. Indexing is
	// hermetic by default.
	GoAllowNetwork bool
	// GoMaximumLoads bounds concurrent Go loads. Zero uses the processor
	// count, capped, because every load holds a complete type universe.
	GoMaximumLoads int
	// TypeScriptMaximumWorkers bounds concurrent TypeScript workers. Zero
	// uses the documented default.
	TypeScriptMaximumWorkers int
	TypeScriptWorker         string
	// RustAnalyzer is the command line of the external Rust indexer.
	RustAnalyzer string
	// RustTargetDirectory is where cargo writes the artifacts of the Rust
	// analysis. It lives outside every indexed repository, because
	// rust-analyzer always runs build scripts.
	RustTargetDirectory string
	// RustMaximumWorkspaces bounds concurrent analyzer processes. Zero uses
	// the documented default: each one holds a whole workspace in memory.
	RustMaximumWorkspaces int
	RustFeatures          []string
	RustAllFeatures       bool
	RustNoDefaultFeatures bool
	RustCfgs              []string
	RustBuildScripts      bool
	RustProcMacros        bool
	// RustIncludeTests sets `cfg(test)` for the crates of a workspace.
	RustIncludeTests bool
	// RustAllowNetwork lets cargo reach a registry while a workspace loads.
	RustAllowNetwork bool
	RustSysroot      string
	// RustIndexSysroot puts the standard library of the toolchain in the
	// graph as a synthetic provider. It is off by default: it multiplies the
	// symbol count by an order of magnitude, and its absence leaves the
	// graph exactly as it was, declaring what it lost.
	RustIndexSysroot bool
	WorkingDirectory string
	// CacheMode selects whether a unit may be served from its stored
	// facts. Empty is CacheOff.
	CacheMode CacheMode
	// CacheDirectory holds one entry per analysis unit. It lives outside
	// every indexed repository, like the rest of the state.
	CacheDirectory string

	// Progress, when set, is called synchronously as each unit of work
	// starts and finishes. It must not block: a slow callback slows the
	// index down.
	Progress func(ProgressEvent)
}

FullOptions configures one clean semantic indexing pass. The pass never writes inside a registered repository: Go's synthetic workspace and the temporary TypeScript facts payloads live outside the sources.

type FullReport

type FullReport struct {
	// Cache reports what the fact cache did, so a pass says how much of
	// itself it skipped and on whose authority.
	Cache CacheReport
	// TypeScriptWithoutPackages names the repositories registered as
	// TypeScript that declare no package. They contribute nothing, and a
	// registry entry that contributes nothing looks like coverage.
	TypeScriptWithoutPackages []string
	// GoDiagnostics carries what the Go loader reported without blocking
	// the pass. The count alone said something happened and nothing said
	// what, and a diagnostic nobody can read is a diagnostic nobody has.
	GoDiagnostics []string

	GoRepositories int
	GoModules      int
	GoLoads        int
	GoLoadErrors   int
	// GoLoadDiagnostics counts the diagnostics that did not block the pass:
	// a directory with no file to select, and the advisory the loader
	// attaches to it.
	GoLoadDiagnostics int
	// GoModulesNotLoaded counts the modules the loader could not read. Their
	// facts are absent and declared; the pass still publishes the rest.
	GoModulesNotLoaded int
	// GoWorkspaces counts the synthetic go.work files this pass installed.
	// A module that reaches no other registered module loads without one.
	GoWorkspaces           int
	GoDefinitions          int
	GoReferences           int
	GoUnresolved           int
	TypeScriptRepositories int
	TypeScriptSymbols      int
	TypeScriptReferences   int
	TypeScriptUnresolved   int
	// TypeScriptAmbiguous counts the package names several manifests of one
	// repository declare. No manifest provides them.
	TypeScriptAmbiguous int
	RustRepositories    int
	RustWorkspaces      int
	RustCrates          int
	RustSymbols         int
	RustReferences      int
	RustUnresolved      int
	// RustWorkspacesNotLoaded counts the workspaces the analyzer could not
	// read. Their facts are absent and declared; the pass publishes the rest.
	RustWorkspacesNotLoaded int
	// RustDiagnostics carries what the analyzer reported without blocking
	// the pass, which is where a degraded load says so.
	RustDiagnostics []string
	// RustWithoutWorkspaces names the repositories registered as Rust that
	// declare no Cargo manifest. They contribute nothing, and a registry
	// entry that contributes nothing looks like coverage.
	RustWithoutWorkspaces []string
	// EdgesWithoutProvider counts the edges the merge dropped because the
	// repository that provides the target does not publish its declaration.
	// Each one is declared as an unresolved reference with the position that
	// was observed.
	EdgesWithoutProvider int
	// RustSysroot names the synthetic repository the standard library was
	// published under, empty when it is not in this graph.
	RustSysroot string
	// RustSysrootReason says why the standard library is absent. It is set
	// whenever RustSysroot is empty, because a reader cannot tell a machine
	// without a toolchain from a configuration that asked for nothing.
	RustSysrootReason string
	SyntheticWorkFile string
}

FullReport records the work performed before the caller publishes the resulting facts. Counts are informational; an error is never hidden in a successful report.

func Full

func Full(ctx context.Context, options FullOptions) (facts.Set, FullReport, error)

Full loads every configured repository and normalises the authoritative Go and TypeScript facts into one validated set. A loader diagnostic aborts the pass instead of publishing a graph that is known to be incomplete.

type GoChange

type GoChange struct {
	RepositoryKey string
	PackageKey    string
	FileKey       string
	Path          string

	BodyChanged      bool
	SignatureChanged bool
	ImportsChanged   bool
	GoModChanged     bool
	ReplaceChanged   bool
	FileDeleted      bool
	PackageDeleted   bool
}

GoChange contains the signals produced by Go loading and package/module discovery for one transition. The signals are intentionally explicit: this package does not infer semantic identity from names or text matches.

type GoSourceChange

type GoSourceChange struct {
	GoChange
	Previous []byte
	Current  []byte
}

GoSourceChange supplies the bytes needed to classify a Go source transition when the loader has not already emitted explicit change signals.

type InvalidationAction

type InvalidationAction string

InvalidationAction is an instruction for the later index/delta coordinator. Actions describe scope, not facts: executing one must still obtain facts from the authoritative language engine.

const (
	ActionReindexFile                InvalidationAction = "REINDEX_FILE"
	ActionReindexProvider            InvalidationAction = "REINDEX_PROVIDER"
	ActionReindexPackage             InvalidationAction = "REINDEX_PACKAGE"
	ActionInvalidateConsumers        InvalidationAction = "INVALIDATE_CONSUMERS"
	ActionResolveReferences          InvalidationAction = "RESOLVE_REFERENCES"
	ActionRebuildRegistry            InvalidationAction = "REBUILD_REGISTRY"
	ActionInvalidateModuleResolution InvalidationAction = "INVALIDATE_MODULE_RESOLUTION"
	ActionReindexProject             InvalidationAction = "REINDEX_PROJECT"
	ActionRemoveFile                 InvalidationAction = "REMOVE_FILE"
	ActionRemovePackage              InvalidationAction = "REMOVE_PACKAGE"
)

type InvalidationPlan

type InvalidationPlan struct {
	Language      facts.Language       `json:"language"`
	RepositoryKey string               `json:"repository_key,omitempty"`
	PackageKey    string               `json:"package_key,omitempty"`
	FileKey       string               `json:"file_key,omitempty"`
	Path          string               `json:"path,omitempty"`
	Class         ChangeKind           `json:"class"`
	ChangedRanges []syntax.SyntaxRange `json:"changed_ranges,omitempty"`
	Actions       []InvalidationAction `json:"actions"`
}

InvalidationPlan identifies the affected source and the conservative work required before a canonical delta can be produced.

func ClassifyGoChange

func ClassifyGoChange(change GoChange) InvalidationPlan

ClassifyGoChange maps authoritative Go loader signals to invalidation scope. More disruptive signals take precedence over narrower source changes.

func ClassifyGoModChange

func ClassifyGoModChange(change GoChange, previous, current []byte) (InvalidationPlan, error)

ClassifyGoModChange classifies a go.mod transition and distinguishes a replace change from ordinary module metadata changes.

func ClassifyGoSourceChange

func ClassifyGoSourceChange(change GoSourceChange) (InvalidationPlan, error)

ClassifyGoSourceChange compares imports and declaration signatures using the Go parser. A parse failure is returned rather than silently downgraded to a body change; the returned plan is conservative and requests a project scan.

func ClassifyRustChange

func ClassifyRustChange(change RustChange) InvalidationPlan

ClassifyRustChange converts syntax evidence into a conservative invalidation plan.

The unit the analyzer can rerun is the whole Cargo workspace: `rust-analyzer scip` has no per file mode. A body-only edit still reindexes just the file's facts, but anything that can change a signature, a manifest or the build script reindexes the project, because that is the smallest thing the engine can actually recompute.

func ClassifyTypeScriptChange

func ClassifyTypeScriptChange(change TypeScriptChange) InvalidationPlan

ClassifyTypeScriptChange converts syntax evidence into a conservative invalidation plan. Syntax candidates remain evidence only; no symbol or relationship is inferred here.

func (InvalidationPlan) Has

func (plan InvalidationPlan) Has(action InvalidationAction) bool

Has reports whether the plan contains action.

type ProgressEvent

type ProgressEvent struct {
	Phase      ProgressPhase
	Repository string
	Detail     string
	Started    bool
	Completed  int
	Total      int
}

ProgressEvent reports that one unit of indexing work started or finished. Completed counts finished units of the phase and is 0 on a start event; Total is 0 when the phase has no countable units.

type ProgressPhase

type ProgressPhase string

ProgressPhase names the unit of work a progress event belongs to.

const (
	// PhaseGo is one Go module of one repository.
	PhaseGo ProgressPhase = "go"
	// PhaseTypeScript is one TypeScript repository.
	PhaseTypeScript ProgressPhase = "typescript"
	// PhaseRust is one Cargo workspace.
	PhaseRust ProgressPhase = "rust"
	// PhaseMerge is the final sort and validation of the merged fact set.
	PhaseMerge ProgressPhase = "merge"
)

type Route

type Route string

Route is the publication strategy chosen for one incremental update.

const (
	// RouteNoop means the delta would change nothing.
	RouteNoop Route = "NOOP"
	// RouteDelta applies the change transactionally to graph.active.
	RouteDelta Route = "DELTA"
	// RouteRepublish rebuilds into graph.next and swaps it in atomically.
	RouteRepublish Route = "REPUBLISH"
)

type RustChange

type RustChange struct {
	RepositoryKey string
	PackageKey    string
	FileKey       string
	Path          string

	Previous      syntax.SyntaxInventory
	Current       syntax.SyntaxInventory
	ChangedRanges []syntax.SyntaxRange

	Deleted  bool
	Manifest bool
	// BuildScript marks `build.rs`, whose output decides what the analyzer
	// sees of the crate that owns it.
	BuildScript bool
}

RustChange carries the syntax evidence and the workspace metadata for one Rust file transition. A manifest or lockfile change is supplied by discovery because it decides which crates exist at all.

type SnapshotBuild

type SnapshotBuild struct {
	Report rebuild.SnapshotReport
}

SnapshotBuild is the in-memory publication report produced after a delta. It is present only when UpdateOptions.SnapshotStore is configured.

type TypeScriptChange

type TypeScriptChange struct {
	RepositoryKey string
	PackageKey    string
	FileKey       string
	Path          string

	Previous      syntax.SyntaxInventory
	Current       syntax.SyntaxInventory
	ChangedRanges []syntax.SyntaxRange

	Deleted       bool
	Manifest      bool
	ProjectConfig bool
}

TypeScriptChange carries the syntax evidence and the workspace metadata for one TypeScript or JavaScript file transition. Manifest and project-config changes are supplied by discovery because their filenames may be configured.

type UpdateOptions

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

	// Plans are the invalidation plans that motivated this update.
	Plans []InvalidationPlan
	// Previous is the indexed state the active generation holds; Next is
	// the state the language engines just produced for it.
	Previous facts.Set
	Next     facts.Set

	// RepublishRatio overrides DefaultRepublishRatio.
	RepublishRatio float64

	GenerationID    string
	ResolverVersion string
	SnapshotID      int64

	// SnapshotStore is optional for callers that do not serve in-memory
	// queries. When set, the delta route rebuilds a complete immutable
	// HotSnapshot from the mutated database before publishing it atomically.
	SnapshotStore *hotsnapshot.SnapshotStore
	BuildSnapshot func(context.Context, rebuild.BuildSnapshotOptions) (*hotsnapshot.GraphSnapshot, rebuild.SnapshotReport, error)

	// Layout, ApplyDelta, Counts and Republish default to the real
	// implementations; tests substitute them so the orchestration runs
	// without cgo, exactly as rebuild.Options already allows.
	Layout     func(context.Context, rebuild.LayoutOptions) (rebuild.Layout, error)
	ApplyDelta func(context.Context, string, facts.Delta, ladybug.CanonicalLoadOptions) (ladybug.CanonicalMutationResult, error)
	Counts     func(context.Context, string) (map[string]int64, error)
	Republish  func(context.Context, rebuild.Options) (rebuild.Report, error)
}

UpdateOptions configures one incremental update.

type UpdateResult

type UpdateResult struct {
	Decision Decision
	Delta    facts.Delta
	// Generation is the generation serving queries once the update is done:
	// the mutated active generation, or the newly published one.
	Generation generation.Generation
	// Mutation is populated on the delta route.
	Mutation ladybug.CanonicalMutationResult
	// SnapshotDigest is the refreshed digest recorded for the mutated
	// generation on the delta route.
	SnapshotDigest string
	// Snapshot is populated after a successful full HotSnapshot rebuild and
	// atomic publication on the delta route.
	Snapshot SnapshotBuild
	// Rebuild is populated on the republish route.
	Rebuild rebuild.Report
	Passed  bool
}

UpdateResult accounts for one incremental update.

func Update

func Update(ctx context.Context, options UpdateOptions) (UpdateResult, error)

Update computes the delta between the previous and the next indexed state, decides how to publish it, and carries it out.

On the delta route the change is applied transactionally to graph.active and that generation's snapshot.sha256 is rewritten from the row counts the mutation left behind: rollback revalidates a destination by recomputing that digest, so a generation mutated in place without refreshing it could never be rolled back to again.

When SnapshotStore is configured, the mutated database is then scanned and rebuilt into a complete immutable HotSnapshot. Only after that build passes validation does SnapshotStore.Publish atomically replace the pointer seen by readers. A failed build leaves the previous in-memory snapshot serving.

On the republish route nothing touches graph.active: rebuild.Run builds graph.next, verifies it and swaps it in, leaving the previous generation as graph.backup.

Jump to

Keyboard shortcuts

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