runtimebundle

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: Apache-2.0 Imports: 158 Imported by: 0

Documentation

Overview

Package runtimebundle is the standard-distribution composition root: BuildHost, inspection, ValidateDistribution, and generation compile/publish wiring.

Index

Constants

View Source
const DefaultMaxRetainedGenerations = 8
View Source
const DefaultSnapshotRefreshTimeout = 5 * time.Second

DefaultSnapshotRefreshTimeout bounds injectable source reads during Refresh.

Variables

View Source
var (
	ErrPreflightUnsupported       = errors.New("runtimebundle: backend preflight capability unsupported")
	ErrBillablePreflightForbidden = errors.New("runtimebundle: billable backend preflight is forbidden")
)

Sentinel errors for backend instance lifecycle and preflight (req 8.9, 8.11).

View Source
var (
	ErrRemoteDeciderRequired               = errors.New("runtimebundle: effective auth policy requires RemoteDecider but BuildOptions.RemoteDecider is nil")
	ErrAuthEventSinkRequired               = errors.New("runtimebundle: auth.event_delivery is custom but BuildOptions.AuthEventSink is nil")
	ErrAuthEventSinkDisallowed             = errors.New("runtimebundle: BuildOptions.AuthEventSink is set but auth.event_delivery is not custom")
	ErrAuthoritativeBillingRequired        = errors.New("runtimebundle: authoritative billing requires one durable BillingStore, cheap credit screen, exposure admission, TerminalUsageSink, and immutable rating snapshots")
	ErrProviderCostCutoverRequired         = errors.New("runtimebundle: provider-cost revision processing requires a durable execution/cutover fence")
	ErrLocalOnlyBackendDisallowedMultiUser = errors.New("runtimebundle: local-only backend is not allowed when access.mode is multi_user")
	ErrOAuthUserDisallowedMultiUser        = errors.New("runtimebundle: oauth_user credentials are not allowed when access.mode is multi_user")
	ErrUnknownCredentialMultiUser          = errors.New("runtimebundle: unknown credential mode is not allowed when access.mode is multi_user")
	// ErrBackendNotApprovedForMultiUser fails closed when an enabled backend is
	// connector-compatible with multi-user use but the host-owned approval registry
	// (internal/standardplugins/multi_user_backend_policy.go) does not list it.
	// Absence is denial, so a new or misclassified factory cannot grant itself
	// shared-use eligibility.
	ErrBackendNotApprovedForMultiUser   = errors.New("runtimebundle: backend is not approved for multi_user by the host-owned approval policy")
	ErrUnsupportedBackendCredentialMode = errors.New("runtimebundle: unsupported backend credential mode")
	ErrUnsupportedBackendAccessScope    = errors.New("runtimebundle: unsupported backend access scope")
)

Sentinel errors for runtime bundle wiring and backend security validation. Use errors.Is in tests.

View Source
var ErrCandidateFaultInjected = errors.New("runtimebundle: candidate fault injected")

ErrCandidateFaultInjected is returned when TestingOptions injects a candidate fault.

View Source
var ErrComposeBillingIncomplete = errors.New("runtimebundle: billing composition is incomplete")
View Source
var ErrShadowV2CaptureIncomplete = errors.New("runtimebundle: shadow V2 capture is incomplete")

ErrShadowV2CaptureIncomplete identifies missing shadow capture ports.

View Source
var ErrUnsafeLifecycleOverlap = errors.New("runtimebundle: lifecycle change cannot overlap safely")

ErrUnsafeLifecycleOverlap is returned when a feature/plugin lifecycle cannot safely Start/Stop under candidate overlap (req 8.8, design lifecycle adapt).

Functions

func AdaptOverlapSafeLifecycles

func AdaptOverlapSafeLifecycles(ledger *ResourceLedger, lifes []lipplugin.Lifecycle) error

AdaptOverlapSafeLifecycles registers Start on prepare and Stop on close/rollback for lifecycles already classified as overlap-safe. Lifecycles implementing QuiescePhaseLifecycles with a true QuiescePhase additionally stop at generation retirement via the PhaseQuiesce ledger entry, preserving quiesce ordering for admission-independent workers.

func BackendStateIdentitiesFromConfig

func BackendStateIdentitiesFromConfig(cfg *config.Config) (map[string]BackendStateIdentity, error)

BackendStateIdentitiesFromConfig maps instance id → identity for enabled and disabled backend rows present in cfg (absent ids are simply omitted).

func BuildFeatureHooks

func BuildFeatureHooks(reg *pluginreg.Registry, registrations []lipsdk.Registration) (hooks.Config, []lipplugin.Lifecycle, error)

BuildFeatureHooks merges enabled feature plugins into hook bus configuration.

func ClassifyBackendOverlap

func ClassifyBackendOverlap(reg *pluginreg.Registry, cfg *config.Config, liveFactoryKinds map[string]int) error

ClassifyBackendOverlap rejects enabled candidate backends whose factory kinds disallow concurrent instance handles while a live generation still holds that kind. Returns the typed restart-required classification before any candidate resource acquisition (req 7.3, 8.8; task 4.2).

func ClassifyFeatureLifecycles

func ClassifyFeatureLifecycles(lifes []lipplugin.Lifecycle) error

ClassifyFeatureLifecycles rejects lifecycles that are not explicitly overlap-safe.

func CompileGenerationContribution

func CompileGenerationContribution(cfg *config.Config, prod ProductionOptions, now time.Time) runtimegen.GenerationContribution

CompileGenerationContribution maps static config + production registrations into the public GenerationContribution shape (requirement 11.6; design D15).

func InspectInventory

func InspectInventory(ctx context.Context, in InspectInput) (diag.InventorySnapshot, error)

InspectInventory loads one effective snapshot and projects an inventory-only read model.

func InstallDiscoveredExports

func InstallDiscoveredExports(
	reg *pluginreg.Registry,
	host *processhost.Host,
	exports []ValidatedExport,
	opt DiscoveredInstallOptions,
) error

InstallDiscoveredExports registers each validated export as a host-backed lifecycle factory. Duplicate kinds and collisions with already-registered builtins fail closed. There is no connector-specific switch.

func InventorySnapshotForOperator

func InventorySnapshotForOperator(ctx context.Context, cfg *config.Config, reg *pluginreg.Registry, registrations []lipsdk.Registration) (diag.InventorySnapshot, error)

func LoadBootstrapEffectiveWithSource

func LoadBootstrapEffectiveWithSource(ctx context.Context, path string, cliOverrides config.StreamRecoveryOverrides) (effective *config.EffectiveConfig, active *configsource.ActiveSourceVersion, ownerSlot *configsource.SourceOwnerSlot, fixed config.StreamRecoveryOverrides, err error)

LoadBootstrapEffectiveWithSource is the sole canonical startup effective-load owner (req: single config-load owner). It loads the fixed startup path through the shared strict effective-configuration pipeline used by BuildHost, ValidateDistribution, InspectRoutes/InspectInventory, and pkg/lipruntime.Build, plus the active source identity and the resolved CLI+environment stream-recovery override snapshot. The snapshot is captured exactly once for process composition and must be reused for every future effective reload (startup-fixed; no env reread).

Order: stable source read → strict decode → defaults → fixed CLI/env stream-recovery overrides → standard feature injection → core validation → alias/prefix validation → private/public identity.

func NewMemoryContinuityStore

func NewMemoryContinuityStore(cfg config.ContinuityConfig) (b2bua.Store, error)

func NewTestGenerationPresentResolver

func NewTestGenerationPresentResolver(lookup func(instanceID string, id int64) *runtimehost.Generation) terminalworkapp.GenerationBoundResolver

NewTestGenerationPresentResolver exposes generationPresentResolver for tests.

func OpenContinuityStore

func OpenContinuityStore(ctx context.Context, cfg *config.Config) (b2bua.Store, error)

OpenContinuityStore opens a store with a dedicated database handle.

func OverrideSetFromModelCatalog

func OverrideSetFromModelCatalog(mc config.ModelCatalogConfig) modelcatalog.OverrideSet

OverrideSetFromModelCatalog maps operator model_catalog YAML override rows to modelcatalog.OverrideSet. Backend+model rows take precedence at resolve time over model-only keys per modelcatalog.OverrideResolver.

func PublishExecutableFromProduction

func PublishExecutableFromProduction(pub *snapshotgen.Publisher, cfg *config.Config, prod ProductionOptions, now time.Time) (*snapshotgen.ExecutableGeneration, error)

PublishExecutableFromProduction compiles and publishes when contribution is non-empty. Failed compile/publish leaves the prior executable generation active.

func RegisterPluginBuildCleanup

func RegisterPluginBuildCleanup(closers []func() error, cleanup func() error) []func() error

RegisterPluginBuildCleanup appends an idempotent plugin BuildResult cleanup immediately during assembly so later inventory/accounting/server failures reverse-dispose process/pipe/staging resources (Phase 3 composition seam).

func UnionFactoryKinds

func UnionFactoryKinds(essential []string, discovered []ValidatedExport) []string

UnionFactoryKinds returns the sorted-stable union of essential and discovered kinds.

func ValidateDistribution

func ValidateDistribution(ctx context.Context, in ValidateDistributionInput) error

func ValidateStructural

func ValidateStructural(ctx context.Context, in ValidateStructuralInput) error

ValidateStructural validates effective configuration for operator check-config. Requirements 2.8 and 5.5: structural rules only; no plugin process activation, runtime tracing, model-registry refresh, or provider network calls.

func VerifyBillingAccountingRecovery

func VerifyBillingAccountingRecovery(ctx context.Context, store AccountingRecoveryStore, capability billing.AccountingBinaryCapability) (billing.AccountingRecoverySnapshot, error)

VerifyBillingAccountingRecovery loads the durable snapshot for store and enforces capability before the process admits or posts anything. Compatible binaries receive the snapshot; stale binaries receive billing.ErrAccountingStaleBinary. The check is read-only.

Types

type AccountingRecoveryStore

type AccountingRecoveryStore interface {
	GetAccountingRecoverySnapshot(context.Context) (billing.AccountingRecoverySnapshot, error)
}

AccountingRecoveryStore is the narrow startup-verification port. Every durable billing store in an internal store-backed monetary composition implements it; production doubles carry an explicit safe snapshot. A non-nil store that hides this port is rejected at startup (fail closed) instead of silently serving unverified financial state.

type AuthOptions

type AuthOptions struct {
	// HTTPAuthProviders runs in [internal/stdhttp] before frontend decode (R4).
	// When nil, empty, or every entry is nil, [Build] composes providers from
	// validated config instead of using the override (so an accidental
	// []Provider{nil} slice cannot disable authentication). When at least one
	// entry is non-nil, [Build] uses a clone of this slice only: no config-derived
	// auth is applied. Custom binaries must supply an equivalent policy chain;
	// [cmd/lipstd] does not set this field unless you intentionally replace
	// transport auth at the composition root.
	HTTPAuthProviders []httpauth.Provider
	// AuthEventSink implements [auth.EventSink] when auth.event_delivery is
	// "custom". If set for other delivery modes, [Build] returns
	// [ErrAuthEventSinkDisallowed]. For default/disabled delivery the dispatcher
	// uses an internal slog sink or nil per config.
	AuthEventSink auth.EventSink
	// RemoteDecider is required when the effective auth handler is remote or
	// required_level is api_key_sso. The OSS standard binary does not construct
	// remote transports; inject at the composition root.
	RemoteDecider auth.RemoteDecider
	// OSIdentity supplies OS principal material for local_noop. When nil, [Build]
	// uses the default infra
	// [github.com/matdev83/go-llm-interactive-proxy/internal/infra/osidentity]
	// provider.
	OSIdentity auth.OSIdentityProvider
	// AuthErrorRenderer is optional terminal HTTP mapping for auth failures; nil
	// uses stdhttp defaults.
	AuthErrorRenderer httpauth.AuthErrorRenderer
	// AuthErrorRenderersByFrontend optional per auth-wire-frontend-id renderers
	// (stdhttp/auth DefaultFrontendIDFromRequest vocabulary). Non-nil entries
	// override the same key from [PluginRegistry.AuthErrorRenderers] when [Build]
	// composes HTTP auth providers.
	AuthErrorRenderersByFrontend map[string]httpauth.AuthErrorRenderer
}

AuthOptions carries transport-auth composition-root injection points.

type BackendInstance

type BackendInstance struct {
	Backend execbackend.Backend
	// contains filtered or unexported fields
}

BackendInstance wraps an execbackend.Backend with idempotent close, optional lifecycle, idle-transport cleanup, and explicit non-billable preflight.

func WrapBackendInstance

func WrapBackendInstance(be execbackend.Backend, hooks OptionalBackendHooks) *BackendInstance

WrapBackendInstance returns a generation-owned backend wrapper.

func (*BackendInstance) AsBackend

func (b *BackendInstance) AsBackend() execbackend.Backend

AsBackend returns the underlying backend value for executor maps.

func (*BackendInstance) CleanupIdleTransports

func (b *BackendInstance) CleanupIdleTransports(ctx context.Context) error

CleanupIdleTransports runs the optional idle-transport cleanup hook.

func (*BackendInstance) Close

func (b *BackendInstance) Close() error

Close stops optional lifecycle then closes the backend exactly once (req 8.9). Idle-transport cleanup runs before Stop/backend Close so generation release ordering stays correct when BackendInstance.Close is the ledger callback.

func (*BackendInstance) PreflightCapability

func (b *BackendInstance) PreflightCapability(ctx context.Context) (BackendPreflightResult, error)

PreflightCapability runs an optional non-billable readiness probe. It never invents billable inference traffic (req 8.11).

func (*BackendInstance) Start

func (b *BackendInstance) Start(ctx context.Context) error

Start runs the optional start hook exactly once. Concurrent and repeated callers share the first result. A failed/partial start still allows Close cleanup (Stop + backend Close) to run.

type BackendPreflightResult

type BackendPreflightResult struct {
	Ready       bool
	Billable    bool
	Description string
}

BackendPreflightResult is an optional non-billable readiness probe outcome. Billable must be false; WrapBackendInstance rejects billable results (req 8.11).

type BackendStateIdentity

type BackendStateIdentity struct {
	InstanceID   string
	FactoryKind  string
	ConfigDigest string
}

BackendStateIdentity is the canonical key for affinity/health observation reuse across request-plane candidates (requirements 6.7–6.8).

func BackendStateIdentityFromPlugin

func BackendStateIdentityFromPlugin(p config.PluginConfig) (BackendStateIdentity, error)

BackendStateIdentityFromPlugin derives a process state identity from one backend row.

func (BackendStateIdentity) Compatible

func (k BackendStateIdentity) Compatible(other BackendStateIdentity) bool

Compatible reports whether two identities may safely share affinity/health state.

func (BackendStateIdentity) Namespace

func (k BackendStateIdentity) Namespace() string

Namespace returns a stable opaque prefix for keyed observation storage.

type BackgroundAuxScheduler

type BackgroundAuxScheduler = auxreq.BackgroundScheduler

type BootstrapApp

type BootstrapApp = coreruntime.App

BootstrapApp is the standard-distribution bootstrap application from NewBootstrapApp (coreruntime.App).

func NewBootstrapApp

func NewBootstrapApp(opts BootstrapOptions) (*BootstrapApp, error)

NewBootstrapApp delegates to coreruntime.New so cmd/lipstd can call bootstrap without a direct import of internal/core/runtime.

type BootstrapOptions

type BootstrapOptions = coreruntime.Options

BootstrapOptions is coreruntime.Options for explicit root wiring.

type BuildHostInput

type BuildHostInput struct {
	ConfigPath              string
	Mandatory               []lipsdk.Requirement
	LogWriter               io.Writer
	StreamRecoveryOverrides config.StreamRecoveryOverrides
	HandlerComposer         HandlerComposer
	Production              ProductionOptions
	EnforceMultiUserCLIGate bool
	MultiUser               *bool
	// RegistrySetup optionally configures plugins in reg before process services build.
	RegistrySetup func(reg *pluginreg.Registry) error
}

type BuildOptions

type BuildOptions struct {
	// PluginRegistry selects which bundled factories Build uses for backends.
	// Required; nil fails [Build]. Kept top-level because it is set by nearly
	// every call site.
	PluginRegistry *pluginreg.Registry
	// WireModel resolves default upstream model ids when computing the effective
	// default route selector. When nil, Build uses standardplugins.DefaultWireModel
	// (standard distribution).
	WireModel   config.WireModelForBackend
	Startup     StartupOptions
	Infra       InfraOptions
	Auth        AuthOptions
	Extensions  ExtensionsOptions
	Policy      PolicyOptions
	Diagnostics DiagnosticsOptions
	Testing     TestingOptions
	// Production holds first-class enterprise injection seams (requirement 12.4).
	// Unlike Testing, these are supported for closed modules via pkg/lipruntime.
	Production ProductionOptions
	// DiscoveredPlugins, when set, installs validated catalog exports onto
	// PluginRegistry before backend construction (Phase 4 discovery bridge).
	DiscoveredPlugins *DiscoveredPluginInstall
	// FeatureLifecycles are merged feature plugin lifecycles owned by the candidate
	// resource ledger in serve/compile paths (task 3.2). When non-empty, callers must
	// not also Start/Stop the same instances via runtime.App (singular ownership).
	// Inspect-only bootstrap may keep lifecycles on App instead.
	FeatureLifecycles []lipplugin.Lifecycle
	// FeaturePlanes carries the immutable frozen feature plane set compiled from
	// enabled feature bundles and host contributions.
	FeaturePlanes lipfeature.FrozenPlaneSet
	// ReplaceCandidateSurface, when true, replaces process FeatureLifecycles and
	// Extensions with this overlay's values even when nil/empty. Used by
	// [CompileGeneration] so a candidate that removes the last feature does not
	// reuse startup-merged lifecycles/extensions. Legacy [CompileCandidate]
	// callers leave this false (nil overlay fields mean "no override").
	// CorePorts carries minimal fixed consumer-owned core interfaces compiled by featurehost.
	CorePorts               featurehost.CorePorts
	ReplaceCandidateSurface bool
}

BuildOptions configures composition-root dependencies for [Build]. Fields are grouped by concern to keep the contract readable and prevent the bag from becoming a service locator (arch review F-06). PluginRegistry is required; all other fields are optional (see [Build] for nil defaults).

type CandidateFaultInject

type CandidateFaultInject struct {
	After string // model|prepare|activate|handler|composer-clone|ledger-transfer
	Hook  func()
}

CandidateFaultInject is a test-only CompileCandidate/CompileGeneration failure seam.

type CandidateHTTPCompile

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

func (*CandidateHTTPCompile) BillingReports

func (c *CandidateHTTPCompile) BillingReports() billing.ReportingStore

func (*CandidateHTTPCompile) Close

func (c *CandidateHTTPCompile) Close() error

func (*CandidateHTTPCompile) DecodeAdmission

func (c *CandidateHTTPCompile) DecodeAdmission() lipsdk.DecodeAdmission

func (*CandidateHTTPCompile) EffectiveDefaultRoute

func (c *CandidateHTTPCompile) EffectiveDefaultRoute() string

func (*CandidateHTTPCompile) Executor

func (c *CandidateHTTPCompile) Executor() *runtime.Executor

func (*CandidateHTTPCompile) Metrics

func (c *CandidateHTTPCompile) Metrics() *metrics.Bundle

func (*CandidateHTTPCompile) ModelRegistry

func (c *CandidateHTTPCompile) ModelRegistry() *modelregistry.Registry

func (*CandidateHTTPCompile) PluginRegistry

func (c *CandidateHTTPCompile) PluginRegistry() *pluginreg.Registry

func (*CandidateHTTPCompile) Quiesce

func (c *CandidateHTTPCompile) Quiesce(ctx context.Context) error

func (*CandidateHTTPCompile) RollbackUnpublished

func (c *CandidateHTTPCompile) RollbackUnpublished() error

func (*CandidateHTTPCompile) RoutePrefixes

func (c *CandidateHTTPCompile) RoutePrefixes() []string

func (*CandidateHTTPCompile) RuntimeSnapshot

func (*CandidateHTTPCompile) StandardHTTPInput

func (c *CandidateHTTPCompile) StandardHTTPInput(frozen *config.Config, regs []lipsdk.Registration, route string) httpcontract.StandardHTTPInput

func (*CandidateHTTPCompile) Store

func (c *CandidateHTTPCompile) Store() b2bua.Store

type CandidateOverlapSafe

type CandidateOverlapSafe interface {
	SafeUnderCandidateOverlap() bool
}

CandidateOverlapSafe marks a Lifecycle that may Start while another generation remains active. Unmarked Lifecycles are rejected before publication.

type ClosePhase

type ClosePhase uint8

ClosePhase classifies when a generation-owned cleanup runs (design Resource Ledger).

const (
	PhasePrepare  ClosePhase = iota + 1 // rollback after fallible prepare work
	PhaseActivate                       // rollback after commit-safe activate work
	PhaseQuiesce                        // stop admission-independent workers after retirement
	PhaseClose                          // release clients/backends/transports after drain
	PhasePublish                        // start admission-independent workers after host publication
)

type ComposeBillingInput

type ComposeBillingInput struct {
	Store                   billing.AuthoritativeBilling
	TerminalUsageSink       billing.TerminalUsageSink
	Catalog                 *billingcompose.SnapshotCatalog
	Identity                *runtimecore.BillingIdentity // nil => PrincipalSessionIdentity
	Currency                string
	ModelMaxOutput          billingadmission.ModelMaxOutput // required
	Strict                  bool
	ConservativeCeiling     *billing.Money
	ReportsPath             string
	MaintenanceAccounting   billing.ProviderMaintenanceUsageObserver
	PostTurnBatchSize       int
	MinPreRouteHeadroomNano int64
	// ObservationEconomicWorkBuilder optionally overrides the stock immutable
	// observation-to-work classifier. A nil value uses the catalog-bound stock
	// provider/customer builder.
	ObservationEconomicWorkBuilder billing.ObservationEconomicWorkBuilder
}

type DiagnosticsOptions

type DiagnosticsOptions struct {
	// SecureSessionStore is optional; when set on Built, stdhttp may mount
	// secure-session diagnostics.
	SecureSessionStore app.Store
}

DiagnosticsOptions carries operator-diagnostics overrides. Currently a single-field group; it can grow as diagnostics overrides accrue.

type DialSessionFunc

DialSessionFunc establishes a configured ExecuteSession after peer auth. Tests inject an in-process FakeService bridge; production uses adapter.DialConfiguredSession.

type DialSessionRequest

type DialSessionRequest struct {
	Conn        net.Conn
	Peer        processhost.PeerIdentity
	Generation  uint64
	Secrets     backendplugin.SecretBundle
	ConfigYAML  []byte
	InstanceID  string
	FactoryKind string
	Policy      backendplugin.RuntimePolicy
}

DialSessionRequest is the peer-authenticated configure input for a discovered factory.

type DiscoveredInstallOptions

type DiscoveredInstallOptions struct {
	DialSession   DialSessionFunc
	RuntimePolicy backendplugin.RuntimePolicy
}

DiscoveredInstallOptions configures InstallDiscoveredExports.

type DiscoveredPluginInstall

type DiscoveredPluginInstall struct {
	Host    *processhost.Host
	Exports []ValidatedExport
	Options DiscoveredInstallOptions
	// Trusted holds every verified artifact bound to the shared staging root.
	// Exports reference the same pointers; the ownership holder must close all
	// of them before removing staging (Windows locks staged executables).
	Trusted []*trust.VerifiedArtifact
}

DiscoveredPluginInstall is an optional BuildOptions payload that installs validated catalog exports before backend construction.

type ExecuteSession

type ExecuteSession = adapter.ExecuteSession

ExecuteSession is the host-facing configured plugin session (adapter seam).

type ExtensionsOptions

type ExtensionsOptions struct{}

ExtensionsOptions is the feature-bundle extension surface merged into the runtime snapshot. All concrete feature state travels via ordinary planes, lifecycles, and fixed consumer ports; the struct is intentionally empty and retained so BuildOptions keeps a stable shape.

type FrozenRoutingView

type FrozenRoutingView struct {
	DefaultRoute  string
	RoutePrefixes []string
}

FrozenRoutingView is an immutable routing projection for a generation.

type GenerationBundle

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

func (*GenerationBundle) BackendFactoryKindCounts

func (b *GenerationBundle) BackendFactoryKindCounts() map[string]int

func (*GenerationBundle) BackendIDs

func (b *GenerationBundle) BackendIDs() []string

func (*GenerationBundle) BindModelViews

func (b *GenerationBundle) BindModelViews(ctx context.Context) context.Context

func (*GenerationBundle) Close

func (b *GenerationBundle) Close() error

func (*GenerationBundle) ExecutorView

func (b *GenerationBundle) ExecutorView() lipsdk.ExecutorView

func (*GenerationBundle) FrozenFrontends

func (b *GenerationBundle) FrozenFrontends() []config.PluginConfig

func (*GenerationBundle) HTTPAuthProviders

func (b *GenerationBundle) HTTPAuthProviders() []httpauth.Provider

func (*GenerationBundle) Handler

func (b *GenerationBundle) Handler() http.Handler

func (*GenerationBundle) Quiesce

func (b *GenerationBundle) Quiesce(ctx context.Context) error

func (*GenerationBundle) ReadinessReport

func (*GenerationBundle) Registrations

func (b *GenerationBundle) Registrations() []lipsdk.Registration

func (*GenerationBundle) ResourceCount

func (b *GenerationBundle) ResourceCount() int

func (*GenerationBundle) RoutePrefixes

func (b *GenerationBundle) RoutePrefixes() []string

func (*GenerationBundle) Routing

func (b *GenerationBundle) Routing() FrozenRoutingView

func (*GenerationBundle) StartPublished

func (b *GenerationBundle) StartPublished(ctx context.Context) error

func (*GenerationBundle) TerminalDecisionProvider

func (b *GenerationBundle) TerminalDecisionProvider() terminaldecision.Provider

TerminalDecisionProvider returns the provider frozen into this generation. The returned instance is never rebound while the generation is published; request admission snapshots the same value for the request lifetime.

func (*GenerationBundle) TerminalProviders

func (b *GenerationBundle) TerminalProviders() terminalworkapp.TerminalProviderView

type GenerationCompileInput

type GenerationCompileInput struct {
	Process          *ProcessServices
	Bus              *hooks.Bus
	Candidate        *config.Config
	CandidateOpts    *BuildOptions
	Compose          HandlerComposer
	LiveFactoryKinds map[string]int
	FaultInject      CandidateFaultInject
	GenerationRunner *auxiliary.GenerationExecutorRunner
}

type GenerationCompiler

type GenerationCompiler struct {
	Process *ProcessServices
	Compose HandlerComposer
}

func (GenerationCompiler) Compile

func (c GenerationCompiler) Compile(ctx context.Context, candidate *config.Config, liveFactoryKinds map[string]int) (GenerationRuntime, error)

type HandlerComposer

type HandlerComposer func(ctx context.Context, cfg *config.Config, log *slog.Logger, in httpcontract.StandardHTTPInput) (http.Handler, error)

HandlerComposer builds a complete standard http.Handler from one focused, lifecycle-free StandardHTTPInput projection without binding a listener or owning process services. cfg/log are explicit parameters (not carried on the input) because prepareStandardHandler needs the frozen candidate config and process logger for middleware composition outside the mount groups. Implemented by stdhttp to avoid an import cycle with this package (design Generation Compiler; task 3.4–3.5).

type Host

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

func BuildHost

func BuildHost(ctx context.Context, in BuildHostInput) (*Host, error)

func (*Host) ActiveGenerationID

func (h *Host) ActiveGenerationID() int64

func (*Host) ActivePublicFingerprint

func (h *Host) ActivePublicFingerprint() string

func (*Host) BeginShutdown

func (h *Host) BeginShutdown()

func (*Host) CanAcquireActive

func (h *Host) CanAcquireActive() bool

func (*Host) Capabilities

func (h *Host) Capabilities() controlplane.HostCapabilities

func (*Host) Close

func (h *Host) Close(ctx context.Context) error

func (*Host) Config

func (h *Host) Config() *config.Config

func (*Host) Effective

func (h *Host) Effective() *config.EffectiveConfig

func (*Host) ExecutorView

func (h *Host) ExecutorView() lipsdk.ExecutorView

func (*Host) FixedSourcePath

func (h *Host) FixedSourcePath() string

func (*Host) HTTPHandler

func (h *Host) HTTPHandler() http.Handler

func (*Host) HasProductionBillingStore

func (h *Host) HasProductionBillingStore() bool

HasProductionBillingStore reports whether composition injected a Production billing journal. It does not return the journal itself.

func (*Host) LargePayloadDiagnostics

func (h *Host) LargePayloadDiagnostics() largebody.DiagnosticsObserver

LargePayloadDiagnostics returns the process-owned diagnostics observer.

func (*Host) Logger

func (h *Host) Logger() *slog.Logger

Logger, Config, and Effective expose process-bound configuration views.

func (*Host) MeteringQuerier

func (h *Host) MeteringQuerier() metering.Querier

func (*Host) ProcessClosed

func (h *Host) ProcessClosed() bool

func (*Host) ReadinessReport

func (h *Host) ReadinessReport() controlplane.ReadinessReportReader

func (*Host) Ready

func (h *Host) Ready() bool

Host query helpers expose generation, capability, and metering views.

func (*Host) RefreshSnapshots

func (h *Host) RefreshSnapshots(ctx context.Context) error

func (*Host) Reload

func (h *Host) Reload(ctx context.Context, trigger sdkreload.Trigger) sdkreload.Result

func (*Host) SpoolLedger

func (h *Host) SpoolLedger() *largebody.SpoolLedger

SpoolLedger returns the process-owned large-payload spool ledger, or nil if unconfigured.

func (*Host) StartALeg

func (h *Host) StartALeg(id string) *leglifecycle.ALeg

func (*Host) Status

func (h *Host) Status() sdkreload.Status

func (*Host) WaitForIdle

func (h *Host) WaitForIdle(ctx context.Context) error

type InfraOptions

type InfraOptions struct {
	// HTTPClient is the shared upstream HTTP client for backends that need
	// outbound HTTP (Bedrock, ACP). When nil, Build uses httpclient.Standard().
	HTTPClient *http.Client
	// OutboundTracing when true wraps the upstream transport with OpenTelemetry
	// HTTP propagation. When HTTPClient is non-nil, Build clones the client
	// before wrapping so caller-owned clients are not mutated.
	OutboundTracing bool
	// ProcessTracing carries an already-initialized process tracer shutdown handle
	// from BuildHost. ProcessServices retains it without owning Close (Host /
	// stdhttp remain the shutdown owners).
	ProcessTracing ProcessTracing
}

InfraOptions carries shared infrastructure (upstream HTTP, tracing).

type InspectInput

type InspectInput struct {
	ConfigPath              string
	Mandatory               []lipsdk.Requirement
	StreamRecoveryOverrides config.StreamRecoveryOverrides
}

InspectInput configures InspectRoutes / InspectInventory / PrepareInspect (no logger/tracing/runtime serve Host).

type InspectPrepared

type InspectPrepared struct {
	Config   *config.Config
	Registry *pluginreg.Registry
	// contains filtered or unexported fields
}

InspectPrepared is a one-shot inspect/doctor preparation: effective config, registry with optional discovered exports installed, and process-owned temporary host/staging that must be released via InspectPrepared.Close.

func PrepareInspect

func PrepareInspect(ctx context.Context, in InspectInput) (*InspectPrepared, error)

PrepareInspect loads one effective snapshot, installs the standard registry, and registers optional discovered backend exports for inspect/doctor. Callers must Close the result; it never constructs a serve Host or tracing.

func (*InspectPrepared) Close

func (p *InspectPrepared) Close() error

Close releases temporary discovery host/staging exactly once.

func (*InspectPrepared) PluginHost

func (p *InspectPrepared) PluginHost() *processhost.Host

PluginHost returns the process host used for discovered-export install, if any.

type OptionalBackendHooks

type OptionalBackendHooks struct {
	Start                 func(context.Context) error
	Stop                  func(context.Context) error
	CleanupIdleTransports func(context.Context) error
	PreflightCapability   func(context.Context) (BackendPreflightResult, error)
}

OptionalBackendHooks are generation-local optional backend lifecycle seams. Existing backends without hooks remain compatible.

type PluginCatalogResolution

type PluginCatalogResolution struct {
	Discovered  []discovery.Descriptor
	TrustBySafe map[string]trust.VerifyResult
	Snapshot    catalog.Snapshot
	CatalogErr  error
	Installable []ValidatedExport
}

PluginCatalogResolution is the serve/inspect shared catalog snapshot plus installable exports derived with the same conflict policy.

func ResolvePluginCatalog

func ResolvePluginCatalog(cfg *config.Config, reg *pluginreg.Registry, stagingDir string) (PluginCatalogResolution, error)

ResolvePluginCatalog runs the shared discover→trust→catalog path used by inspect and by standard serve bootstrap before factory install.

type PluginDoctorReport

type PluginDoctorReport = diagnostics.DoctorReport

PluginDoctorReport is the operator-facing doctor snapshot.

func DoctorBackendPlugin

func DoctorBackendPlugin(ctx context.Context, cfg *config.Config, reg *pluginreg.Registry, instanceID string, host *processhost.Host) (PluginDoctorReport, error)

DoctorBackendPlugin launches only the selected configured instance id.

type PluginInspectReport

type PluginInspectReport = diagnostics.Report

PluginInspectReport is the operator-facing inspect snapshot.

func InspectBackendPlugins

func InspectBackendPlugins(cfg *config.Config, reg *pluginreg.Registry) (PluginInspectReport, error)

InspectBackendPlugins runs non-executing discovery/catalog inspect for cfg. It uses the same ResolvePluginCatalog path as standard serve bootstrap.

func InspectBackendPluginsWithContext

func InspectBackendPluginsWithContext(ctx context.Context, cfg *config.Config, reg *pluginreg.Registry) (PluginInspectReport, error)

InspectBackendPluginsWithContext is like InspectBackendPlugins but accepts a context for live inventory projection.

type PolicyOptions

type PolicyOptions struct {
	// PolicyObservers, when non-empty, are chained as the policy decision
	// evidence observer for the runtime snapshot. When nil/empty, the snapshot
	// uses a no-op observer so deployments without policy evidence keep current
	// request outcomes (requirements 7.6, 10.5).
	PolicyObservers []policydecision.Observer
	// PolicyTimeoutBudgetSource, when set, supplies decision-provider evaluation
	// budgets per stage/provider. When nil, the snapshot uses the default
	// zero-budget source so legacy extension behavior is unchanged
	// (requirements 6.3, 10.5).
	PolicyTimeoutBudgetSource extensions.TimeoutBudgetSource
	// PolicyDiagnosticsEnabled controls whether privileged-visibility policy
	// decision records may leave the core through the evidence emitter. Default
	// false withholds privileged records (requirement 7.4).
	PolicyDiagnosticsEnabled bool
}

PolicyOptions carries policy-decision observer and budget configuration.

type ProcessServices

type ProcessServices struct {
	Logger         *slog.Logger
	FactoryCatalog *pluginreg.Registry
	Tracing        ProcessTracing
	Metrics        *metrics.Bundle
	GeoIP          *geoip.Service
	// IngressDefense is the single process-lifetime bounded adaptive state for
	// ingress self-defense. It is sized once from the startup-fixed
	// max_entries/state_ttl, survives policy-only generation reloads, and is
	// disposed only with this ProcessServices. A generation borrows it and can
	// never close or resize it.
	IngressDefense     *ingressdefense.State
	DatabasePools      *db.PoolRegistry
	Continuity         b2bua.Store
	RouteOverrideStore routeoverride.Store
	SecureSessions     ssessionapp.Store
	DecodeAdmission    lipsdk.DecodeAdmission
	SpoolLedger        *largebody.SpoolLedger
	ALegLifecycle      *leglifecycle.Coordinator
	AffinityStore      affinity.Store
	CandidateHealth    policy.CandidateHealth
	ExtensionState     lipstate.Store
	MeteringRecorder   metering.Recorder
	UsageAuthority     *authorityapp.Service
	Concurrency        *concurrencyapp.Service
	SnapshotGeneration *snapshotgen.Publisher
	SnapshotController *SnapshotController
	MeteringQuerier    metering.Querier

	TerminalWorkProcessor *terminalworkapp.Processor
	TerminalWorkRegistry  *terminalworkapp.Registry
	TerminalWorkQueries   *terminalworkapp.QueryService
	TerminalWorkMetrics   *terminalworkapp.MetricsObserver
	BackgroundAux         *BackgroundAuxScheduler

	// StandardFeatures owns the single standard-distribution feature host handle (Task 2.3).
	StandardFeatures *featurehost.Runtime
	// contains filtered or unexported fields
}

ProcessServices owns process-scoped resources constructed once per process. Generation compilation receives a non-owning reference and must not Close it.

func NewProcessServices

func NewProcessServices(ctx context.Context, in ProcessServicesInput) (*ProcessServices, error)

NewProcessServices constructs process-owned stores, pools, metrics, terminal-work, limiters, and related dependencies once. Closers are registered immediately; partial failures dispose acquired resources in reverse order.

func (*ProcessServices) Close

func (ps *ProcessServices) Close() error

Close disposes process-owned resources in reverse acquisition order. It is idempotent.

func (*ProcessServices) Closed

func (ps *ProcessServices) Closed() bool

Closed reports whether ProcessServices.Close has completed.

type ProcessServicesInput

type ProcessServicesInput struct {
	Cfg     *config.Config
	Log     *slog.Logger
	Opts    *BuildOptions
	Tracing ProcessTracing
	// HostEnv is a generic process-environment capability forwarded to the
	// standard feature host, which synthesizes the default env-derived host
	// binding from it when no explicit binding is registered. It names no
	// concrete feature and carries no feature semantics.
	HostEnv featurehost.HostEnvironment
	// PluginResourcePool, PluginHost, PluginArtifacts, and PluginStagingDir are
	// process-owned discovered-plugin resources. When set, NewProcessServices
	// takes sole ownership and disposes them once after generation retirement in
	// reverse acquisition order (pool → host → artifacts → staging), so pooled
	// physical cleanup can still use the live host and Windows releases staged
	// executable handles before staging removal.
	PluginResourcePool *backendResourcePool
	PluginHost         *processhost.Host
	PluginArtifacts    []*trust.VerifiedArtifact
	PluginStagingDir   string
	BackgroundAux      *BackgroundAuxScheduler // transferred and closed with process
}

ProcessServicesInput configures NewProcessServices.

type ProcessTracing

type ProcessTracing struct {
	Shutdown func(context.Context) error
	Active   bool
}

ProcessTracing holds process-owned tracing shutdown and outbound-propagation state.

type ProductionOptions

type ProductionOptions struct {
	BillingTerminalUsageSink billing.TerminalUsageSink
	// BillingStore is the authoritative durable billing boundary used by runtime
	// and read-side report composition. It is intentionally a domain port.
	BillingStore       billing.AuthoritativeBilling
	BillingReports     billing.ReportingStore
	BillingReportsPath string
	BillingIdentity    runtimecore.BillingIdentity
	// BillingCallRatingResolver resolves immutable call/exposure snapshots and never consults authorization holds.
	BillingCallRatingResolver   billing.CallRatingResolver
	BillingProviderCostResolver billing.ProviderCostResolver
	// BillingEconomicRevisionRater drives pure revision valuation from the
	// durable evidence queue. It is intentionally separate from settlement and
	// provider-cost stores; nil keeps the optional worker disabled.
	BillingEconomicRevisionRater billing.PostUsageRater
	// BillingObservationEconomicWorkBuilder converts durable metering
	// observations into immutable customer/provider queue markers. It performs
	// no rating or money mutation; the process-owned relay invokes it after the
	// observation transaction commits.
	BillingObservationEconomicWorkBuilder billing.ObservationEconomicWorkBuilder
	BillingEconomicRevisionReconciler     billing.EconomicRevisionReconciler
	BillingCostPassThroughSettlementStore billing.CostPassThroughSettlementStore
	BillingCustomerUnitLedger             billing.CustomerUnitLedger
	// MaintenanceAccounting receives provider-authoritative maintenance usage on
	// behalf of background maintenance operations (such as prompt cache keepwarm).
	MaintenanceAccounting    billing.ProviderMaintenanceUsageObserver
	BillingPostTurnBatchSize int
	// BillingCreditGate is the required pre-route settled-credit screen for
	// authoritative billing. It is intentionally separate from detailed post-route
	// exposure admission.
	BillingCreditGate runtimecore.BillingCreditGate
	// BillingExposureAdmission is the authoritative post-route operational
	// exposure seam, normally constructed by ComposeBilling from BillingStore.
	BillingExposureAdmission runtimecore.BillingExposureAdmission
	MeteringRecorder         metering.Recorder
	// MeteringAccountWindowStore is the optional nonfinancial gauge query port
	// used by an explicitly configured provider quota policy. It is separate
	// from all billing and customer-unit seams.
	MeteringAccountWindowStore coremetering.AccountWindowStore
	RequestRegistrations       []authority.RequestRegistration
	AttemptRegistrations       []authority.AttemptRegistration
	ConcurrencyRegistration    *authority.ConcurrencyRegistration
	UsageSnapshotSource        economics.RuleSnapshotSource
	ConcurrencySnapshotSource  economics.RuleSnapshotSource
	RatingSnapshotSource       economics.RatingSnapshotSource
	EvidenceSink               authority.EvidenceSink
	MeteringQuerier            metering.Querier
	TrafficObservers           []traffic.Observer
	UsageObservers             []usage.Observer
	PolicyObservers            []policydecision.Observer
	// Terminal-work processor ownership (tasks 4.4–4.5). When TerminalWorkStore is
	// set, Build constructs processor/registry/intents, starts the processor, and
	// injects IntentService into the executor.
	//
	// EffectProviders are composed as: RequestRegistrations -> AuthorityRequestEffectProvider
	// adapters (by descriptor ID), then TerminalWorkProviders merged by ProviderID with
	// explicit entries overriding derived adapters for the same ID.
	TerminalWorkStore          terminalworkapp.RecoveryStore
	TerminalWorkProviders      []terminalworkapp.EffectProvider
	TerminalWorkOwnerID        string
	TerminalWorkClaimTTL       time.Duration
	TerminalWorkClaimLimit     int
	TerminalWorkGlobalMax      int
	TerminalWorkPerProviderMax int
	TerminalWorkTickInterval   time.Duration
	TerminalWorkRenewInterval  time.Duration
	// FeatureHostRegistrations carries startup-only host-feature bindings
	// (Task 8.3/8.4, Requirements 9.3-9.6).
	FeatureHostRegistrations []featurehost.Registration
}

ProductionOptions carries enterprise/production injection seams (reqs 12.1, 12.3, 12.4). Canonical host construction accepts descriptor-bound registrations only.

func ComposeBilling

func ComposeBilling(in ComposeBillingInput) (ProductionOptions, error)

func (ProductionOptions) HasAuthorityOverrides

func (p ProductionOptions) HasAuthorityOverrides() bool

HasAuthorityOverrides reports whether production authority providers are set.

type QuiescePhaseLifecycles

type QuiescePhaseLifecycles interface {
	lipplugin.Lifecycle
	QuiescePhase() bool
}

QuiescePhaseLifecycles opt into PhaseQuiesce stop semantics: their Stop runs at generation retirement (Quiesce) instead of only at final close. Admission-independent workers such as keep-warm maintenance must implement it so a retired-but-not-closed generation stops background work at retirement (Requirement 6.5: quiesce ordering).

type QuiescedStrictAdmission

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

QuiescedStrictAdmission is the explicit quiesce alternative to failing startup: while the frozen durable snapshot requires strict quiesce for the frozen binary capability, Admit fails deterministically with billing.ErrAccountingStrictQuiesced before reaching the inner admission (zero new effects: no exposures, pins, journals, or balance moves). Otherwise it delegates to the inner admission unchanged. The verdict is frozen at construction from explicit inputs so admissions stay deterministic for the process lifetime; compatible recovery recomposes the process with a fresh snapshot.

func NewQuiescedStrictAdmission

NewQuiescedStrictAdmission composes the quiesce wrapper over inner. It fails closed on nil inner admission, invalid snapshots, or invalid capabilities.

func (*QuiescedStrictAdmission) Admit

Admit denies with billing.ErrAccountingStrictQuiesced while quiesced and delegates to the inner admission otherwise.

func (*QuiescedStrictAdmission) Quiesced

func (q *QuiescedStrictAdmission) Quiesced() bool

Quiesced reports whether strict monetary admissions are quiesced.

type ResourceLedger

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

ResourceLedger tracks candidate/generation-owned resources for reverse-order rollback, quiesce, and close. Sole generation-resource phase owner; never owns ProcessServices.

func NewResourceLedger

func NewResourceLedger() *ResourceLedger

func (*ResourceLedger) Activate

func (l *ResourceLedger) Activate(ctx context.Context) error

Activate runs PhaseActivate start hooks; commit-safe and bounded (req).

func (*ResourceLedger) Add

func (l *ResourceLedger) Add(name string, phase ClosePhase, closeFn func(context.Context) error)

func (*ResourceLedger) AddAction

func (l *ResourceLedger) AddAction(name string, phase ClosePhase, start, stop func(context.Context) error)

func (*ResourceLedger) AddClose

func (l *ResourceLedger) AddClose(name string, phase ClosePhase, closeFn func() error)

AddClose registers a no-arg closer; cleanup runs only via Rollback/Quiesce/Close.

func (*ResourceLedger) Close

func (l *ResourceLedger) Close(ctx context.Context) error

Close runs generation cleanup; retryable on failure. After Quiesce skips PhaseQuiesce.

func (*ResourceLedger) Len

func (l *ResourceLedger) Len() int

func (*ResourceLedger) Prepare

func (l *ResourceLedger) Prepare(ctx context.Context) error

Prepare runs PhasePrepare start hooks in acquisition order (req). Failure does not auto-rollback.

func (*ResourceLedger) Publish

func (l *ResourceLedger) Publish(ctx context.Context) error

Publish runs PhasePublish start hooks after the generation is the active published request plane. CompileCandidate/CompileGeneration must not call it.

func (*ResourceLedger) Quiesce

func (l *ResourceLedger) Quiesce(ctx context.Context) error

Quiesce runs PhaseQuiesce cleanups at most once in reverse order (req 10.5).

func (*ResourceLedger) Rollback

func (l *ResourceLedger) Rollback(ctx context.Context) error

Rollback closes all entries in reverse order; caches terminal result (req 3.4).

type RouteAlias

type RouteAlias struct {
	Pattern     string `json:"pattern"`
	Replacement string `json:"replacement"`
}

RouteAlias is one model alias rule from configuration.

type RouteBackend

type RouteBackend struct {
	ID      string `json:"id"`
	Kind    string `json:"kind"`
	Enabled bool   `json:"enabled"`
}

RouteBackend is one configured backend row for route inspection.

type RoutesSnapshot

type RoutesSnapshot struct {
	EffectiveDefaultRoute  string                      `json:"effective_default_route"`
	Backends               []RouteBackend              `json:"backends"`
	CompatibleBackends     []diag.CompatibleBackendRow `json:"compatible_backends,omitempty"`
	InstanceDiagnostics    []diag.InstanceDiagnostic   `json:"instance_diagnostics,omitempty"`
	OpenResponsesFrontends []diag.InstanceDiagnostic   `json:"openresponses_frontends,omitempty"`
	ModelAliases           []RouteAlias                `json:"model_aliases"`
	// CredentialPosture is derived from enabled backend factory ids only: all_local_stub when every
	// enabled backend uses factory kind local-stub; live_provider when any enabled backend is not
	// local-stub; no_enabled_backends when there are no enabled backend rows.
	CredentialPosture string `json:"credential_posture"`
}

RoutesSnapshot is a config-derived operator read model (no provider I/O).

func InspectRoutes

func InspectRoutes(ctx context.Context, in InspectInput) (RoutesSnapshot, error)

InspectRoutes loads one effective snapshot and projects a routes-only read model.

func RoutesSnapshotFrom

func RoutesSnapshotFrom(cfg *config.Config, reg *pluginreg.Registry) (RoutesSnapshot, error)

RoutesSnapshotFrom builds a deterministic route read model from config and the standard registry wire model (same default-route resolution as serving).

type ShadowV2CaptureInput

type ShadowV2CaptureInput struct {
	StoreID             string
	MaxObservations     int
	EvidenceSink        billing.ShadowEvidenceSink
	WorkAppender        billing.EconomicRevisionWorkAppender
	ResultStore         billing.EconomicRevisionResultStore
	ReconciliationStore billing.EconomicRevisionReconciliationStore
	Rater               billing.PostUsageRater
	V1Settlement        billing.CallSettlementStore
}

ShadowV2CaptureInput is the explicit typed shadow-mode wiring. Every pure port is required; V1Settlement proves the authoritative V1 writer remains bound while staying unreachable from the returned handle. Evidence capture requires the capture-only ShadowEvidenceSink: the ordinary terminal sink cannot satisfy this input, so shadow evidence can never become V1 posting or claim work through composition.

type ShadowV2Handle

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

ShadowV2Handle is the composed no-post shadow executor. It wraps only the pure billingstore runner; its static type exposes no monetary ledger.

func ComposeShadowV2Capture

func ComposeShadowV2Capture(in ShadowV2CaptureInput) (ShadowV2Handle, error)

ComposeShadowV2Capture validates explicit shadow wiring and returns a handle that can only persist immutable V2 evidence. Incomplete ports, unbounded work, missing store scope, or a missing V1 settlement fail closed before any capture runs.

func (ShadowV2Handle) AppendReconciliation

func (h ShadowV2Handle) AppendReconciliation(ctx context.Context, work billing.EconomicRevisionWork, reconciliation billing.EconomicReconciliation) error

AppendReconciliation persists one immutable reconciliation envelope.

func (ShadowV2Handle) AppendWork

AppendWork persists one immutable economic revision marker.

func (ShadowV2Handle) CaptureObservations

func (h ShadowV2Handle) CaptureObservations(ctx context.Context, observations []metering.Observation) error

CaptureObservations persists immutable V2 observations without monetary effects and without creating usage rows or claim state.

func (ShadowV2Handle) RateAndPersist

func (h ShadowV2Handle) RateAndPersist(ctx context.Context, work billing.EconomicRevisionWork) error

RateAndPersist rates one revision purely and persists the valuation.

type SnapshotController

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

SnapshotController retains injectable snapshot sources and publishes immutable generations through a Publisher (requirements 11.3, 11.6, 11.7).

Refresh is an explicit publication API: callers invoke it after Build and on enterprise source updates. No unmanaged background polling is started. Metadata planes remain additive compatibility/source-fetch views; enforcement objects are republished via PublishExecutableFromProduction (D10, task 5.5).

func (*SnapshotController) Publisher

func (c *SnapshotController) Publisher() *snapshotgen.Publisher

Publisher returns the atomic generation publisher used for admit-time binding.

func (*SnapshotController) Refresh

func (c *SnapshotController) Refresh(ctx context.Context) error

Refresh re-reads injectable sources (when present), composes an immutable generation from static config baselines plus source results, and publishes it atomically. Source failures preserve prior Value versions and expose degraded/unavailable posture without substituting an unrelated version.

A non-nil error means at least one injected source failed; a generation is still published so readiness/admission see the explicit posture.

type StartupOptions

type StartupOptions struct {
	// StartupContext, when non-nil, is the parent context for bounded startup I/O
	// (e.g. Postgres open and schema migrate for continuity and secure-session
	// stores). When nil, Build uses [context.Background] as the parent. It is not
	// stored or used for per-request paths.
	StartupContext context.Context
}

StartupOptions carries startup-context configuration.

type TerminalWorkReadiness

type TerminalWorkReadiness struct {
	Configured            bool
	Running               bool
	UnresolvedProviderIDs []string
	StoreReady            bool
	// StoreError is deprecated and always empty; use ErrorCode.
	StoreError string
	// BacklogKnown is true only when MetricsObserver.Snapshot succeeded.
	BacklogKnown bool
	// Backlog is outstanding terminal-work count from MetricsObserver.
	Backlog int
	// ReconcilerPending is unique WorkIDs owned by the ambiguous-append reconciler.
	ReconcilerPending int
	// ErrorCode is an operator-safe code (never raw store/snapshot error text).
	ErrorCode string
}

TerminalWorkReadiness is composition-root status for terminal-work recovery (task 4.4/4.5).

type TestingOptions

type TestingOptions struct {
	// Clock overrides time sources for the executor and routing-health circuit
	// breaker. Tests only.
	Clock func() time.Time
	// ControlPlaneStoreOverride, when non-nil, replaces the configured
	// control-plane store. When the override implements interface{ Close() error },
	// that Close is used as the closer and is disposed by Build on every error
	// path exactly like the production store closer. Tests only; production
	// leaves this nil so the store is built from config.
	ControlPlaneStoreOverride controlplane.Store
	// AuthorityStoreOverride, when non-nil, replaces the configured usage-
	// authority store. Tests only; production leaves this nil.
	AuthorityStoreOverride authorityapp.StateStore
	// ConcurrencyLeaseStoreOverride, when non-nil, replaces the configured
	// concurrency lease store. Tests only; production leaves this nil.
	ConcurrencyLeaseStoreOverride concurrencyapp.LeaseStore
	// PostgresPoolOpener, when non-nil, is used by Build's PoolRegistry instead
	// of the default Postgres opener. Tests only; production leaves this nil.
	PostgresPoolOpener db.PoolOpener
	// SnapshotPublisherOverride, when non-nil, replaces the Build-constructed
	// policy/rating generation publisher (Phase 9.3). Tests only.
	SnapshotPublisherOverride *snapshotgen.Publisher
	// FeatureHostRegistrations carries startup-only host-feature bindings for tests.
	FeatureHostRegistrations []sdkfeaturehost.Registration
}

TestingOptions carries test-only overrides. Production leaves these zero so Build constructs the real resources from config.

type ValidateDistributionInput

type ValidateDistributionInput struct {
	ConfigPath              string
	Mandatory               []lipsdk.Requirement
	StreamRecoveryOverrides config.StreamRecoveryOverrides
	Production              ProductionOptions
	HandlerComposer         HandlerComposer
}

type ValidateStructuralInput

type ValidateStructuralInput struct {
	ConfigPath              string
	Mandatory               []lipsdk.Requirement
	StreamRecoveryOverrides config.StreamRecoveryOverrides
}

ValidateStructuralInput configures structural check-config validation. It performs manifest-available ownership and compatible-backend structural checks without runtime tracing, process services, generation compile, plugin activation, or provider network I/O.

type ValidatedExport

type ValidatedExport struct {
	Kind        string
	Profile     pluginreg.BackendSecurityProfile
	ExecProfile lipsdk.BackendExecutionProfile
	Artifact    *trust.VerifiedArtifact
	Model       processhost.ProcessModel
	Sharing     processhost.SharingOptions
}

ValidatedExport is one catalog-approved factory export ready for generic registration.

func CollectInstallableExports

func CollectInstallableExports(
	snap catalog.Snapshot,
	trustBySafe map[string]trust.VerifyResult,
	discovered []discovery.Descriptor,
) ([]ValidatedExport, error)

CollectInstallableExports converts a catalog snapshot into ValidatedExport values for kinds in StateDiscovered with verified artifacts and declared process models.

Source Files

Jump to

Keyboard shortcuts

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