indexing

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: 25 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

Index

Constants

View Source
const FollowInterval = 2 * time.Second

FollowInterval is how often a follower asks the generation store which generation is published. The question costs one read of the CURRENT pointer, and the answer only changes when something else publishes, so the interval trades a negligible cost for a bounded staleness a person will not notice.

View Source
const ResyncDebounce = 3 * time.Second

ResyncDebounce is how long HEAD must hold still before a move is acted on. A checkout is not atomic seen from outside: HEAD moves, then thousands of files are rewritten, and a rebase moves HEAD once per replayed commit.

View Source
const ResyncInterval = 2 * time.Second

ResyncInterval is how often the resynchroniser asks each registered repository where its HEAD is.

The question is two small file reads per repository and no subprocess, and its answer only changes when somebody checks out, so polling costs nothing worth measuring and avoids what watching would cost: git rewrites HEAD and refs with an atomic rename, so a descriptor held on either goes on pointing at the old inode, and under kqueue every watched path is a descriptor the source-tree watcher already needs.

Variables

View Source
var ErrIndexProcess = errors.New("index process failed")

ErrIndexProcess reports that the child index did not produce a graph.

Functions

func Follow

func Follow(ctx context.Context, store *hotsnapshot.SnapshotStore, options FollowOptions) error

Follow keeps a snapshot store on the generation the store root publishes.

A server loads the published HotSnapshot once, at startup. Anything that publishes afterwards -- `kivgraph index --full` in another terminal, or another process entirely -- leaves that server answering from a graph that no longer exists on disk, with no way to tell. Follow closes that gap by reading the CURRENT pointer and rebuilding only when the identifier moves.

It never coordinates with other publishers: SnapshotStore.Publish only accepts a strictly newer generation, so a follower that loses the race to an in-process index simply observes the newer identifier on its next tick.

Follow blocks until ctx is done.

func Resync

func Resync(ctx context.Context, options ResyncOptions) error

Resync keeps the published graph on the code that is actually checked out.

It observes one thing -- HEAD moving -- because that one thing covers every way a tree changes wholesale: checkout, pull, merge, rebase, reset, and commit. A push is not among them: it moves no local ref and rewrites no file, so the code the graph describes is identical before and after.

Debouncing is per workspace and not per repository on purpose. A pull across thirty-three repositories must produce one rebuild: a rebuild costs the whole corpus, so paying it once per repository would cost minutes to reflect one afternoon's fetch.

Resync blocks until ctx is done.

Types

type Counts

type Counts struct {
	Repositories int `json:"repositories"`
	Packages     int `json:"packages"`
	Files        int `json:"files"`
	Symbols      int `json:"symbols"`
	Evidence     int `json:"evidence"`
	Edges        int `json:"edges"`
	Unresolved   int `json:"unresolved"`
}

Counts is the number of authoritative facts produced by one full pass.

type DetachedOptions

type DetachedOptions struct {
	// Executable is the binary to run, and defaults to this one. The child
	// must be this build: it carries the same storage library, the same
	// resolver and the same schema, and a graph published by anything else is
	// not the graph this process knows how to serve.
	Executable string

	ConfigPath       string
	RepositoriesPath string
	ResolverVersion  string
	// WorkingDirectory is where the child resolves a relative repository path,
	// so it must be the directory the request was made from.
	WorkingDirectory string

	// Progress receives every step the child reports. A nil sink is not an
	// absence of progress: the child still reports, and the lines are dropped
	// here rather than costing the child a channel it cannot see.
	Progress func(ProjectProgress)

	// Log receives the child's own stderr as it is written. The child logs the
	// diagnostics a loader produced without failing the pass, and a diagnostic
	// nobody can read is a diagnostic nobody has; a server passes the stream it
	// already logs to. The tail is kept to explain a failure either way.
	Log io.Writer
}

DetachedOptions configures one full index run in a child process.

type FollowOptions

type FollowOptions struct {
	// Root is the directory that holds the generation store.
	Root string
	// Store selects the generation layout; the zero value is the default.
	Store generation.Config
	// Interval overrides FollowInterval.
	Interval time.Duration
	// OnPublish, when set, is called with each generation this follower
	// installs. It must not block.
	OnPublish func(uint64)
	// OnError, when set, receives a failure the follower absorbed. A
	// follower never stops on a failed generation: the published one keeps
	// answering queries, and the next tick tries again.
	OnError func(error)
}

FollowOptions configures Follow.

type FullDocument

type FullDocument struct {
	Passed       bool         `json:"passed"`
	GenerationID string       `json:"generation_id"`
	Counts       Counts       `json:"counts"`
	Index        IndexSummary `json:"index"`
	// Error is why the pass did not pass. It is the child's own message,
	// preserved so the caller reports the reason rather than an exit code.
	Error string `json:"error,omitempty"`
}

FullDocument is what one full index pass concluded, in the form that survives a process boundary.

It carries what a caller reports and nothing else: the generation that was published, the fact counts, and the per-language summary. The diagnostics and stage details stay in the child's own report, which it prints for whoever ran it; a server forwards its progress and reads this.

func DocumentFromResult

func DocumentFromResult(result FullResult) FullDocument

DocumentFromResult projects one in-process result onto the wire form.

func RunDetached

func RunDetached(ctx context.Context, options DetachedOptions) (FullDocument, error)

RunDetached indexes the registered repositories in a child process and returns what that pass concluded.

A full pass holds the type universe of every Go module, the reply of every TypeScript worker and the SCIP index of every Cargo workspace at once. Its peak is measured in gigabytes, and a Go heap that has once grown to it keeps the arena: a server that indexed in its own process parks at that peak for as long as it runs, whether or not anybody queries it again. Running the pass in a child makes the peak die with the child, and the server pays only for the snapshot it then loads. See ADR 0042.

type FullEvent

type FullEvent struct {
	Event    FullEventKind    `json:"event"`
	Progress *ProjectProgress `json:"progress,omitempty"`
	Result   *FullDocument    `json:"result,omitempty"`
}

FullEvent is one line of that stream.

The stream is the protocol between a server and the index it runs in a child process, so it is a declared shape and not the log the command writes for a person. A reader ignores a kind it does not know: adding one must not break a server built before it existed.

type FullEventKind

type FullEventKind string

FullEventKind names one line of the stream `index --full --json` writes to stdout.

const (
	// FullEventProgress is one unit of work starting or finishing.
	FullEventProgress FullEventKind = "progress"
	// FullEventResult is what the pass concluded. Exactly one is written, and
	// it is the last line.
	FullEventResult FullEventKind = "result"
)

type FullOptions

type FullOptions struct {
	Repositories      []workspace.Repository
	SyntheticWorkFile string
	IncludeTests      bool
	// GoBuildTags are the build constraints every Go load satisfies.
	GoBuildTags []string
	// GoAllowNetwork lets the Go loads reach a module proxy.
	GoAllowNetwork bool
	// GoMaximumLoads bounds concurrent Go loads.
	GoMaximumLoads int
	// TypeScriptMaximumWorkers bounds concurrent TypeScript workers.
	TypeScriptMaximumWorkers int
	TypeScriptWorker         string
	// Rust* configure the external analyzer: the command, where its build
	// artifacts land, and the build configuration it is given.
	RustAnalyzer          string
	RustTargetDirectory   string
	RustMaximumWorkspaces int
	RustFeatures          []string
	RustAllFeatures       bool
	RustNoDefaultFeatures bool
	RustCfgs              []string
	RustBuildScripts      bool
	RustProcMacros        bool
	RustIncludeTests      bool
	RustAllowNetwork      bool
	RustSysroot           string
	// RustIndexSysroot asks for the standard library in the graph.
	RustIndexSysroot bool
	WorkingDirectory string
	// CacheMode and CacheDirectory configure the fact cache: whether a
	// unit may be served from the facts a previous pass stored, and where
	// those entries live.
	CacheMode       indexer.CacheMode
	CacheDirectory  string
	Root            string
	ResolverVersion string
	Store           generation.Config
	Metrics         *metrics.Registry

	Progress        func(indexer.ProgressEvent)
	RebuildProgress func(rebuild.StageName)
}

FullOptions configures a complete index and canonical graph publication. The operation reads every configured repository and publishes a new generation only after the rebuild gates pass.

func OptionsFromConfig

func OptionsFromConfig(configuration config.Config) FullOptions

OptionsFromConfig maps a loaded configuration onto a full index request.

Every caller that indexes -- the CLI and the MCP tool -- asks for the same pass over the same configuration, and the only difference between them is who reports progress and where the work runs. Building the request twice is how one of them came to index no Rust at all: a field added to the configuration reached one call site and not the other. The caller fills in Repositories, WorkingDirectory, ResolverVersion and the progress sinks, which are the only things the configuration does not decide.

type FullResult

type FullResult struct {
	Counts        Counts
	IndexReport   indexer.FullReport
	RebuildReport rebuild.Report
}

FullResult contains the reports needed by CLI and MCP callers without exposing the temporary facts set after the rebuild has completed.

func RunFull

func RunFull(ctx context.Context, options FullOptions) (FullResult, error)

RunFull indexes all repositories, validates the facts, and publishes one canonical generation. It does not modify the repository registry; callers that manage a candidate registry commit it separately.

type IndexSummary

type IndexSummary struct {
	GoRepositories         int `json:"go_repositories"`
	GoModules              int `json:"go_modules"`
	GoDefinitions          int `json:"go_definitions"`
	GoReferences           int `json:"go_references"`
	GoUnresolved           int `json:"go_unresolved"`
	TypeScriptRepositories int `json:"typescript_repositories"`
	TypeScriptSymbols      int `json:"typescript_symbols"`
	TypeScriptReferences   int `json:"typescript_references"`
	TypeScriptUnresolved   int `json:"typescript_unresolved"`
	RustRepositories       int `json:"rust_repositories"`
	RustWorkspaces         int `json:"rust_workspaces"`
	RustSymbols            int `json:"rust_symbols"`
	RustReferences         int `json:"rust_references"`
	RustUnresolved         int `json:"rust_unresolved"`
	// RustWorkspacesNotLoaded counts the Cargo workspaces the analyzer
	// could not read. Their facts are absent and declared, so a caller that
	// only saw the symbol count would read silence as coverage.
	RustWorkspacesNotLoaded int `json:"rust_workspaces_not_loaded"`
}

IndexSummary retains the useful phase counts from the full index pass.

func SummaryFromReport

func SummaryFromReport(report indexer.FullReport) IndexSummary

SummaryFromReport keeps the phase counts a caller reports and drops the detail that belongs to the command that produced them.

Every language is named whether or not it contributed. A language missing from the report reads as a language with no code, so the summary must be able to say zero.

type Project

type Project struct {
	Name      string   `json:"name"`
	Path      string   `json:"path"`
	Languages []string `json:"languages"`
}

Project identifies a repository that a caller wants to add to the registry and index. Paths are resolved relative to WorkingDirectory when they are not absolute; the source repository itself is never modified by this service.

type ProjectIndexer

type ProjectIndexer interface {
	IndexProjects(context.Context, []Project, func(ProjectProgress)) (ProjectResult, error)
}

ProjectIndexer is the mutation boundary used by the MCP tool. The caller must obtain explicit consent before invoking this method.

The whole batch is registered before anything is built. Every project costs one full rebuild of the canonical graph -- cross-repository edges are resolved over the complete fact set, so there is no cheaper unit -- and rebuilding once per project throws away all but the last result. Eleven projects registered one call at a time cost eleven rebuilds for one useful graph; registered together they cost one.

type ProjectProgress

type ProjectProgress struct {
	Phase      string `json:"phase,omitempty"`
	Repository string `json:"repository,omitempty"`
	Detail     string `json:"detail,omitempty"`
	Completed  int    `json:"completed,omitempty"`
	Total      int    `json:"total,omitempty"`
}

ProjectProgress is one step of a project index.

A full rebuild takes minutes on a large registry, and an MCP client applies its own timeout to a request. Without a sign of life it cancels a call that is working, so every unit of work reports one.

func ProgressFromEvent

func ProgressFromEvent(event indexer.ProgressEvent) ProjectProgress

ProgressFromEvent projects one indexer event onto the project-level step a caller reports.

type ProjectResult

type ProjectResult struct {
	// Project is the first project of the batch, kept so a single-project
	// caller reads its own request back.
	Project      Project      `json:"project"`
	Projects     []Project    `json:"projects"`
	GenerationID string       `json:"generation_id"`
	SnapshotID   uint64       `json:"snapshot_id"`
	Counts       Counts       `json:"counts"`
	Index        IndexSummary `json:"index"`
}

ProjectResult reports the generation published after a batch was indexed.

type RepositoryMovement

type RepositoryMovement struct {
	Repository workspace.Repository
	From       string
	To         string
	Branch     string
}

RepositoryMovement is one repository whose working tree left the commit the graph was built from.

type ResyncOptions

type ResyncOptions struct {
	// Repositories are the registered repositories to follow. A repository
	// whose HEAD cannot be read is reported once and skipped, never guessed.
	Repositories []workspace.Repository
	// LockPath is the file that elects the single writer. Several servers
	// may follow the same repositories; only one may rebuild them.
	LockPath string
	// Resync performs the rebuild for the repositories whose HEAD moved. It
	// is injected because the loop decides *when*, never *how*: the route
	// belongs to the indexer.
	Resync func(context.Context, []workspace.Repository) error
	// Interval and Debounce override the constants above.
	Interval time.Duration
	Debounce time.Duration

	// ContentUnchanged, when set, is asked whether the bytes the graph
	// describes are still the ones on disk for the repositories that moved.
	//
	// HEAD moving is cheap to observe but says nothing about content: a
	// commit moves it and rewrites no file. Without this the loop would
	// rebuild the whole corpus after every commit to produce a graph
	// identical to the one it already had.
	ContentUnchanged func(context.Context, []RepositoryMovement) (bool, error)
	// OnMoved reports the repositories a tick observed moving, before the
	// debounce. It must not block.
	OnMoved func([]RepositoryMovement)
	// OnResynced reports a completed rebuild.
	OnResynced func([]RepositoryMovement)
	// OnError receives a failure the loop absorbed. A resynchroniser never
	// stops on one: the published graph keeps answering and the next tick
	// tries again.
	OnError func(error)
	// OnSkipped reports a movement that needed no rebuild: the content is
	// what the graph already describes, or another process is rebuilding it.
	OnSkipped func([]RepositoryMovement)

	// Now overrides the clock, for tests.
	Now func() time.Time
}

ResyncOptions configures Resync.

type Service

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

Service serializes registry mutations and full rebuilds while preserving the immutable snapshot publication contract used by MCP query tools.

func NewService

func NewService(
	loaded config.Loaded,
	snapshotStore *hotsnapshot.SnapshotStore,
	resolverVersion string,
	workingDirectory string,
) *Service

NewService creates a project indexer over the configured registry and snapshot store. A nil snapshot store is accepted so construction remains cheap, but IndexProject will reject it before changing the registry.

func (*Service) IndexProjects

func (service *Service) IndexProjects(
	ctx context.Context,
	projects []Project,
	progress func(ProjectProgress),
) (ProjectResult, error)

IndexProjects adds every project to a candidate registry, persists that candidate, rebuilds the complete canonical graph once, and publishes the resulting HotSnapshot. A failed index or rebuild restores the prior registry and leaves the prior generation active. If publication of the already-validated active graph fails, the candidate registry is retained and the error is returned so the caller can retry publication without reindexing.

The batch is the unit on purpose. A rebuild resolves cross-repository edges over the complete fact set, so it costs the whole corpus whatever was added; doing it once per project throws away every result but the last.

func (*Service) Reindex

func (service *Service) Reindex(ctx context.Context) error

Reindex rebuilds the graph of the repositories already registered and publishes it. It never touches the registry: keeping the graph on the code that is checked out is not the same act as registering a project, and the consent for it was given when the repository was registered.

It shares the gate with IndexProjects, so a resynchronisation and an index_project cannot run at once inside one process.

Jump to

Keyboard shortcuts

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