state

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: Apache-2.0 Imports: 9 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 state defines the StateStore interface for persistent storage of agents, threads, runs, and store items. Implemented today by SQLite, Postgres, MySQL (internal/state/sqlite, postgres, mysql), and MongoDB (internal/state/mongo, the non-SQL exemplar). Any backend that satisfies this interface and passes internal/state/conformance's shared test suite is a valid implementation -- DynamoDB remains a possible future driver.

Index

Constants

View Source
const (
	ActionDeliveryPending         = "pending"
	ActionDeliveryDelivered       = "delivered"
	ActionDeliveryDeadLetter      = "dead_letter"
	MaxActionDeliveryPayloadBytes = 64 * 1024
)
View Source
const (
	AttemptGenerationKey    = "_runkite_attempt_generation"
	CompletionGenerationKey = "_runkite_completion_generation"
)

These reserved metadata fields are maintained only by the dispatch/completion store transactions. Run creation removes client-supplied copies.

View Source
const OpaqueCreateOnly int64 = 0

ErrConflict is returned for any conflicting write a caller should see as OpaqueCreateOnly is the ifMatch sentinel for INSERT-only puts (HTTP If-None-Match: *). Real opaque versions always start at 1, so 0 cannot collide with a CAS If-Match value.

View Source
const SQLExcludeSimulationMySQL = ` AND COALESCE(JSON_UNQUOTE(JSON_EXTRACT(metadata,'$.simulation')),'') <> 'true'`
View Source
const SQLExcludeSimulationPostgres = ` AND COALESCE(metadata->>'simulation','') <> 'true'`
View Source
const SQLExcludeSimulationSQLite = `` /* 130-byte string literal not displayed */
View Source
const WorkloadOwnerKey = "_runkite_workload_owner"

Variables

This section is empty.

Functions

func BindAttemptWorkload added in v0.8.0

func BindAttemptWorkload(ctx context.Context, metadata map[string]interface{}, generation int64) error

BindAttemptWorkload may transfer ownership only when a new generation is installed. Missing identity never turns an owned run back into a fleet run.

func CheckOpaqueCheckpointIdentity added in v0.10.0

func CheckOpaqueCheckpointIdentity(run *models.Run, binding RunCheckpointBinding) error

CheckOpaqueCheckpointIdentity requires the original stored run record in addition to its attempt generation. Blob CAS never grants run authority.

func CheckRunCheckpointBinding

func CheckRunCheckpointBinding(run *models.Run, binding RunCheckpointBinding) error

func CheckRunCompletionOwner added in v0.8.0

func CheckRunCompletionOwner(ctx context.Context, metadata map[string]interface{}, completion *RunCompletion) error

func CheckWorkloadOwner added in v0.8.0

func CheckWorkloadOwner(ctx context.Context, metadata map[string]interface{}) error

func EvaluateRunAdmission

func EvaluateRunAdmission(
	caps *RunAdmissionCaps,
	agentID string,
	countActive func(agentID string) (int, error),
	countSince func(since time.Time, agentID string) (int, error),
) error

EvaluateRunAdmission runs COUNT checks against already-locked scope. countActive/countSince must observe the same transactional snapshot as the subsequent INSERT (same connection/tx).

func IsBootstrapAgentSchema added in v0.10.0

func IsBootstrapAgentSchema(schema *models.AgentSchema) bool

IsBootstrapAgentSchema recognizes only the exact four-field bootstrap stub. A partial report, omitted field or annotation is not a bootstrap schema.

func MetadataGeneration

func MetadataGeneration(metadata map[string]interface{}, key string) int64

func NewCompletionCheckpointID added in v0.7.0

func NewCompletionCheckpointID() string

NewCompletionCheckpointID separates retained conversation history from a run identifier that may be deleted and reused. Completion metadata in the same transaction provides idempotence; the checkpoint identifier does not.

func RunIdentity added in v0.10.0

func RunIdentity(run *models.Run) string

RunIdentity identifies the original stored run for internal mutation fences. It does not grant the backend SQL-only public observation capabilities.

func StoredWorkloadOwner added in v0.8.0

func StoredWorkloadOwner(metadata map[string]interface{}) (*transport.WorkloadIdentity, error)

func TerminalRunStatus

func TerminalRunStatus(status models.RunStatus) bool

func WithTrustedAttemptRecovery added in v0.8.0

func WithTrustedAttemptRecovery(ctx context.Context) context.Context

WithTrustedAttemptRecovery is only for a control-plane reaper which already verified the exact retained queue generation. It never grants runner access.

Types

type ActionDelivery added in v0.7.0

type ActionDelivery struct {
	ID             string          `json:"id"`
	SinkID         string          `json:"sink_id"`
	TenantID       string          `json:"tenant_id"`
	ActionID       string          `json:"action_id"`
	Sequence       int64           `json:"sequence"`
	PayloadRaw     json.RawMessage `json:"payload"`
	Attempts       int             `json:"attempts"`
	Status         string          `json:"status"`
	AvailableAt    time.Time       `json:"available_at"`
	ClaimToken     string          `json:"-"`
	ClaimUntil     *time.Time      `json:"claim_until,omitempty"`
	LastReasonCode string          `json:"last_reason_code,omitempty"`
	CreatedAt      time.Time       `json:"created_at"`
	UpdatedAt      time.Time       `json:"updated_at"`
}

type ActionDeliveryPayload added in v0.7.0

type ActionDeliveryPayload struct {
	Schema     string                       `json:"schema"`
	DeliveryID string                       `json:"delivery_id"`
	SinkID     string                       `json:"sink_id"`
	Action     *models.ConnectorAction      `json:"action"`
	Event      *models.ConnectorActionEvent `json:"event"`
}

ActionDeliveryPayload is metadata for an existing action event. Receiving or retrying it never authorizes dispatching the associated tool operation.

type ActionDeliverySearchRequest added in v0.7.0

type ActionDeliverySearchRequest struct {
	TenantID string
	SinkID   string
	Status   string
	Limit    int
	Offset   int
}

type ActionDeliveryStore added in v0.7.0

type ActionDeliveryStore interface {
	ClaimActionDeliveries(context.Context, string, time.Time, time.Time, int) ([]*ActionDelivery, error)
	AckActionDelivery(context.Context, string, string) error
	FailActionDelivery(context.Context, string, string, time.Time, string, bool) error
	SearchActionDeliveries(context.Context, *ActionDeliverySearchRequest) ([]*ActionDelivery, error)
	RetryActionDelivery(context.Context, string, string) error
}

ActionDeliveryStore exports evidence at least once. Workers require a system context; reads and explicit dead-letter retries retain tenant scoping.

type AgentSchemaRecoveryStore added in v0.10.0

type AgentSchemaRecoveryStore interface {
	// RecoverAgentSchema atomically replaces an existing row only when all four
	// stored fields are exactly {"type":"object"}. The write is scoped to
	// tenant.FromContext(ctx), including for system contexts. Missing rows,
	// existing reports and an incoming all-stub schema return false, nil.
	// Storage and encoding failures return an error. No row is inserted and
	// neither schema nor its maps may be mutated.
	RecoverAgentSchema(ctx context.Context, schema *models.AgentSchema) (bool, error)
}

AgentSchemaRecoveryStore is an optional extension for recovering an existing bootstrap schema without replacing any report already published by a runner. Stores that do not implement it retain the ordinary schema publication API.

type CachedRunCreator

type CachedRunCreator interface {
	CreateCachedRun(context.Context, *models.Run, *RunAdmissionCaps) error
}

CachedRunCreator is an optional synchronous creation boundary. A cache hit inserts its admitted run, final output, merged thread state and completion checkpoint in one transaction. The transaction must reject a busy or foreign thread. A rolled-back transaction leaves neither a run nor a changed thread. A lost commit acknowledgement can leave the complete result durable; a retry with the same run ID must reconcile it rather than assume the commit failed. Stores without this boundary use ordinary dispatch instead of cache hits.

type CompletionResult

type CompletionResult struct {
	Accepted bool
	Applied  bool
}

func CheckCompletion

func CheckCompletion(metadata map[string]interface{}, status models.RunStatus, c *RunCompletion) CompletionResult

CheckCompletion must execute under the same transaction lock as its writes.

type ConnectorActionDispatch added in v0.7.0

type ConnectorActionDispatch struct {
	ActionID   string
	TenantID   string
	DispatchID string
	Version    int64
	// Applied is true only for this transaction's new dispatch claim. A
	// persistence replay returns the receipt with Applied false and must not
	// cause another downstream request.
	Applied bool
}

ConnectorActionDispatch is an internal persistence receipt, never a token for executing or re-executing a downstream operation.

type ErrAdmissionLimitExceeded

type ErrAdmissionLimitExceeded struct {
	Scope   string // "tenant" | "agent"
	Kind    string // "concurrent" | "daily"
	Limit   int
	Current int
}

ErrAdmissionLimitExceeded is returned by CreateRunAdmitted when a concurrent or daily ceiling would be exceeded. Mapped to HTTP 429.

func (*ErrAdmissionLimitExceeded) Error

func (e *ErrAdmissionLimitExceeded) Error() string

type ErrConflict

type ErrConflict struct {
	Resource string
	ID       string
	// Reason overrides the default "already exists" wording when set.
	// Empty (the common case) keeps the original message unchanged for
	// every existing caller.
	Reason string
}

ErrConflict is returned for optimistic-concurrency failures and "already exists" collisions (e.g. duplicate thread_id, or create-only put when the opaque checkpoint row is already present). Mapped to HTTP 409 or 412 depending on the route.

func (*ErrConflict) Error

func (e *ErrConflict) Error() string

type ErrNotFound

type ErrNotFound struct {
	Resource string
	ID       string
}

ErrNotFound is returned when a requested resource does not exist.

func (*ErrNotFound) Error

func (e *ErrNotFound) Error() string

type ErrRunCheckpointFence

type ErrRunCheckpointFence struct{ ReasonCode string }

ErrRunCheckpointFence is a rejected attempt, not a blob-version conflict. The HTTP proxy preserves the existing run-binding denial reason codes.

func (*ErrRunCheckpointFence) Error

func (e *ErrRunCheckpointFence) Error() string

type ProtectedActionStore added in v0.7.0

type ProtectedActionStore interface {
	// Creation captures the actual stored run incarnation, version and identity.
	CreateConnectorAction(context.Context, *models.ConnectorAction, string) (*models.ConnectorAction, error)
	RecordConnectorActionDecision(context.Context, string, int64, models.ConnectorActionDecision, string) (*models.ConnectorAction, error)
	// Peek never consumes approval. Prepare locks and validates it again.
	PeekApprovedConnectorAction(context.Context, string) (*models.PendingAction, error)
	// Approval consumption, dispatch intent and its event commit atomically.
	PrepareConnectorActionDispatch(context.Context, string, int64, string, string, time.Time, string) (*ConnectorActionDispatch, error)
	// Empty dispatch ID permits only a proven not_dispatched observation.
	// An original receipt remains usable for evidence after run cancellation or
	// reclaim, including refining outcome_unknown with its late response.
	FinishConnectorAction(context.Context, string, int64, string, models.ConnectorActionObservation, string) (*models.ConnectorAction, error)
	GetConnectorAction(context.Context, string) (*models.ConnectorAction, error)
	SearchConnectorActions(context.Context, *models.ConnectorActionSearchRequest) ([]*models.ConnectorAction, error)
	ListConnectorActionEvents(context.Context, string, int64, int) ([]*models.ConnectorActionEvent, error)
	MarkExpiredConnectorActionsUnknown(context.Context, time.Time, int) (int, error)
	// Only resolved observations may be explicitly pruned. Unknown outcomes,
	// active intents and unresolved approvals survive ordinary run retention.
	PruneConnectorActions(context.Context, time.Time, int) (int, error)
}

ProtectedActionStore is optional. SQL backends implement it; unsupported deployments must reject enabled action recording instead of dropping evidence.

type RunAdmissionCaps

type RunAdmissionCaps struct {
	TenantConcurrent int
	TenantDaily      int
	AgentConcurrent  int
	AgentDaily       int
	// Now is used for the UTC day boundary of max_daily. Zero means time.Now.
	Now time.Time
}

RunAdmissionCaps are occupancy/quota ceilings enforced atomically with CreateRunAdmitted (lock + COUNT + INSERT on one connection/tx). Values <= 0 mean unlimited for that dimension.

func (*RunAdmissionCaps) DayStart

func (c *RunAdmissionCaps) DayStart() time.Time

DayStart returns the UTC midnight for Now (or time.Now if zero).

func (*RunAdmissionCaps) Enabled

func (c *RunAdmissionCaps) Enabled() bool

Enabled reports whether any ceiling is set.

type RunCheckpointBinding

type RunCheckpointBinding struct {
	RunID      string
	Generation int64
	ThreadID   string
	// RecordIdentity is mandatory for opaque mutations, captured from the
	// stored run at dispatch. Other users of the shared attempt fields retain
	// their own existing incarnation checks.
	RecordIdentity string
}

RunCheckpointBinding identifies the durable attempt allowed to mutate a thread's opaque state. Stores check it under the same transaction as the mutation, serialized with BeginRunAttempt and terminal completion.

type RunCheckpointStore

type RunCheckpointStore interface {
	PutBoundOpaqueCheckpoint(context.Context, RunCheckpointBinding, string, []byte, string, *int64) (int64, error)
	DeleteBoundOpaqueCheckpoint(context.Context, RunCheckpointBinding, string) error
}

type RunCompletion

type RunCompletion struct {
	// ExpectedIncarnationID fences trusted observation against run ID reuse.
	ExpectedIncarnationID string `json:"-"`
	// TrustedSystem is set only by internal cancellation, timeout, retained
	// event recovery and reaper paths. Missing worker proof is never a bypass.
	TrustedSystem bool `json:"-"`
	// FailUnstarted settles an enqueue failure only while the original run is
	// still pending and no worker attempt has begun. Publication errors can
	// follow acceptance, so a started assignment must keep its thread claim.
	FailUnstarted bool `json:"-"`
	// RunnerKind is the authenticated bridge identity; ReplayOnly permits only
	// acknowledgement of an already committed result after the lease is gone.
	// CancelCurrentAttempt is for trusted control-plane cancellation/timeout only.
	// It is resolved under the store transaction lock. Only CancelUsage from
	// the captured Generation may survive; arbitrary values are discarded.
	CancelCurrentAttempt bool
	CancelUsage          map[string]interface{}
	RunnerKind           string
	ReplayOnly           bool
	RunID                string
	Generation           int64
	Status               models.RunStatus
	Error                string
	Values               map[string]interface{}
}

func PrepareCachedRun

func PrepareCachedRun(run *models.Run) (*models.Run, *RunCompletion, error)

PrepareCachedRun reuses the ordinary generation-zero completion invariant inside cached creation's transaction. It leaves the caller's result and metadata untouched; the prepared nonterminal row is never visible outside a committed transaction containing its matching terminal writes.

func ResolveCompletion

func ResolveCompletion(metadata map[string]interface{}, c *RunCompletion) *RunCompletion

ResolveCompletion binds trusted cancellation/timeout to the current attempt. External completions must always present their own dispatch generation.

func WithoutDurableUsage added in v0.8.0

func WithoutDurableUsage(completion *RunCompletion) *RunCompletion

WithoutDurableUsage demotes reserved report provenance when no private SQL snapshot backs it. Native SDK counters retain their established convention.

type RunCompletionStore

type RunCompletionStore interface {
	BeginRunAttempt(context.Context, string, string, int64) (bool, error)
	CompleteRun(context.Context, *RunCompletion) (CompletionResult, error)
}

RunCompletionStore advances attempts monotonically before dispatch and commits output, checkpoint, run status and thread release in one durable transaction. Retrying a committed completion is accepted without applying its writes twice.

type RunTerminalHookStore added in v0.10.0

type RunTerminalHookStore interface {
	// TryClaimRunTerminalHook verifies the tenant-scoped current run is terminal
	// and has the supplied nonempty original identity in the same transaction
	// that claims delivery. A matching previous claim returns false, nil.
	// Missing, replaced, nonterminal or legacy-ambiguous records fail closed.
	// A legacy bare run-ID claim cannot establish which record was finalized;
	// callers must reconcile it and use fresh operation IDs, never backfill it.
	TryClaimRunTerminalHook(ctx context.Context, runID, incarnation string) (bool, error)
}

RunTerminalHookStore claims terminal hook delivery for an exact stored run. It is optional so custom stores do not silently inherit an unfenced fallback.

type RunUsageBinding added in v0.8.0

type RunUsageBinding struct {
	RunCheckpointBinding
	RunIncarnationID string
	TenantID         string
}

type RunUsageEventStore added in v0.10.0

type RunUsageEventStore interface {
	WriteRunUsageEvent(context.Context, string, *models.UsageEvent) error
}

RunUsageEventStore atomically binds terminal accounting to the original durable run record. Unbound legacy usage is never inferred from public IDs.

type RunUsageHoldStore added in v0.10.0

type RunUsageHoldStore interface {
	UpsertRunUsageHold(context.Context, string, *models.UsageHold) error
	ReleaseRunUsageHold(context.Context, string, string) error
}

RunUsageHoldStore serializes reservation mutations with run replacement. The final argument to ReleaseRunUsageHold is the original record identity.

type RunUsageStore added in v0.8.0

RunUsageStore is optional and SQL-only. Reports and terminal completion use the same run lock. Acknowledged cumulative reports survive process loss and settle through the existing terminal usage ledger exactly once per run.

type Store

type Store interface {
	RunCompletionStore
	RunCheckpointStore

	// --- Agents ---
	GetAgent(ctx context.Context, agentID string) (*models.Agent, error)
	SearchAgents(ctx context.Context, req *models.AgentSearchRequest) ([]*models.Agent, error)
	// CountAgents returns the number of agents visible under ctx
	// (tenant-scoped, or every tenant when ctx is SystemContext). Used
	// by the Admin overview so totals are real COUNT aggregates, not
	// len(SearchAgents) capped by a list page size.
	CountAgents(ctx context.Context) (int, error)
	UpsertAgent(ctx context.Context, agent *models.Agent) error
	GetAgentSchema(ctx context.Context, agentID string) (*models.AgentSchema, error)
	UpsertAgentSchema(ctx context.Context, schema *models.AgentSchema) error
	// ListAgentVersions returns every historical snapshot for agentID,
	// newest first, supporting full version history browsing. Written
	// by UpsertAgent itself, once per actual version bump -- see
	// models.AgentVersion's doc comment.
	ListAgentVersions(ctx context.Context, agentID string) ([]*models.AgentVersion, error)
	// GetAgentVersion returns one specific historical snapshot, or
	// ErrNotFound if that version never existed for this agent.
	GetAgentVersion(ctx context.Context, agentID string, version int) (*models.AgentVersion, error)

	// --- Threads ---
	CreateThread(ctx context.Context, thread *models.Thread) error
	GetThread(ctx context.Context, threadID string) (*models.Thread, error)
	UpdateThread(ctx context.Context, threadID string, patch *models.ThreadPatch) (*models.Thread, error)
	DeleteThread(ctx context.Context, threadID string) error
	SearchThreads(ctx context.Context, req *models.ThreadSearchRequest) ([]*models.Thread, error)
	// CountThreadsByStatus returns per-status counts for threads
	// visible under ctx (system = all tenants). Empty statuses are
	// omitted; total threads is the sum of the map values.
	CountThreadsByStatus(ctx context.Context) (map[string]int, error)
	SetThreadStatus(ctx context.Context, threadID string, status models.ThreadStatus) error

	// TryClaimThread atomically transitions a thread from any non-busy status
	// to busy in a single conditional statement, so two concurrent requests can
	// never both observe "not busy" and both proceed (TOCTOU-safe). Returns
	// false, without error, if the thread was already busy.
	TryClaimThread(ctx context.Context, threadID string) (bool, error)

	// ReleaseThreadIfNoOtherActive atomically sets the thread's status
	// (typically idle or interrupted) only when the thread is currently
	// busy AND no pending/running run exists on it other than
	// excludeRunID. Closes the check-then-act race where SearchRuns +
	// SetThreadStatus could idle a thread a newer run had already
	// claimed. Returns (true, nil) if the UPDATE applied; (false, nil)
	// if skipped (another active run, or thread not busy). Does not
	// bump Thread.Version (same as SetThreadStatus/TryClaimThread).
	ReleaseThreadIfNoOtherActive(ctx context.Context, threadID, excludeRunID string, status models.ThreadStatus) (bool, error)

	// --- Checkpoints (Agent Protocol thread history / time-travel view) ---
	// Child writes must verify the current parent belongs to the context tenant
	// in the same transaction as the mutation. A prior API lookup cannot fence
	// parent deletion and cross-tenant reuse of a custom thread ID.
	SaveCheckpoint(ctx context.Context, threadID string, state *models.ThreadState) error
	GetLatestCheckpoint(ctx context.Context, threadID string) (*models.ThreadState, error)
	ListCheckpoints(ctx context.Context, threadID string, limit int, before string) ([]*models.ThreadState, error)

	// --- Opaque runner checkpoints (proxy-mode BaseCheckpointSaver blobs) ---
	// Distinct from ThreadState history above: these are framework-owned
	// bytes the control plane never parses (LangGraph ProxyCheckpointSaver,
	// future CrewAI adapters, etc.). See runner-protocol §6.2.
	//
	// PutOpaqueCheckpoint upserts the blob and returns the new version
	// (ETag). When ifMatch is non-nil:
	//   - *ifMatch >= 1: UPDATE-only CAS (version must equal *ifMatch)
	//   - *ifMatch == OpaqueCreateOnly (0): INSERT-only (If-None-Match: *);
	//     returns *ErrConflict if the row already exists
	// nil ifMatch = unconditional upsert (bumps version when the row
	// already existed).
	PutOpaqueCheckpoint(ctx context.Context, threadID, checkpointID string, data []byte, framework string, ifMatch *int64) (int64, error)
	GetOpaqueCheckpoint(ctx context.Context, threadID, checkpointID string) (*models.OpaqueCheckpoint, error)
	// GetLatestOpaqueCheckpoint returns the newest blob for threadID,
	// ordered by checkpoint_id DESC (LangGraph time-sortable UUIDs —
	// same as AsyncPostgresSaver). Not by created_at: parent blobs often
	// receive late aput_writes that bump write time, and Mongo Date is
	// only ms-precise so concurrent tip/parent writes routinely tie.
	// namespace "" matches root keys (checkpoint_id with no "\x1f");
	// a non-empty namespace matches keys prefixed with namespace+"\x1f".
	GetLatestOpaqueCheckpoint(ctx context.Context, threadID, namespace string) (*models.OpaqueCheckpoint, error)
	ListOpaqueCheckpoints(ctx context.Context, threadID string, limit int) ([]models.OpaqueCheckpointMeta, error)
	DeleteOpaqueCheckpoint(ctx context.Context, threadID, checkpointID string) error
	// PruneOpaqueCheckpoints keeps only keepLast most recent opaque
	// checkpoints per thread (by created_at), deleting older ones.
	// Same retention knob as PruneCheckpoints (checkpoints_keep_last).
	PruneOpaqueCheckpoints(ctx context.Context, keepLast int) (int64, error)

	// --- Runs ---
	// CreateRun and CreateRunAdmitted atomically bind the run to a parent owned
	// by the context tenant. Missing or foreign parents return ErrNotFound.
	CreateRun(ctx context.Context, run *models.Run) error
	// CreateRunAdmitted inserts a run only if caps allow. When caps is
	// nil or disabled, identical to CreateRun. Otherwise serializes
	// per-tenant / per-agent scope (DB advisory lock or equivalent),
	// COUNTs, then INSERTs on the same connection/transaction so a
	// burst of concurrent creates cannot all pass a stale COUNT.
	// Returns *ErrAdmissionLimitExceeded when over ceiling.
	CreateRunAdmitted(ctx context.Context, run *models.Run, caps *RunAdmissionCaps) error
	GetRun(ctx context.Context, runID string) (*models.Run, error)
	UpdateRunStatus(ctx context.Context, runID string, status models.RunStatus, output []byte, errMsg string) error
	DeleteRun(ctx context.Context, runID string) error
	SearchRuns(ctx context.Context, req *models.RunSearchRequest) ([]*models.Run, error)
	// CountRunsByStatus returns per-status counts for runs visible
	// under ctx (system = all tenants). Empty statuses are omitted;
	// total runs is the sum of the map values.
	CountRunsByStatus(ctx context.Context) (map[string]int, error)
	// CountActiveRuns returns pending+running runs visible under ctx.
	// When agentID is non-empty, only that agent is counted. Used by
	// admission_limits.max_concurrent.
	CountActiveRuns(ctx context.Context, agentID string) (int, error)
	// CountRunsCreatedSince returns runs with created_at >= since
	// (inclusive), tenant-scoped like CountActiveRuns. Used by
	// admission_limits.max_daily (UTC day start).
	CountRunsCreatedSince(ctx context.Context, since time.Time, agentID string) (int, error)
	// TryClaimTerminalHook atomically claims the right to dispatch the
	// terminal webhook (run_complete/error/interrupt) for runID so
	// exactly one control-plane replica fires it when cancel and
	// ReportStatus race across an LB. Returns false, without error, if
	// another replica (or an earlier call) already claimed it. run_id is
	// globally unique (UUID); no tenant scoping. Failures from the
	// underlying store are returned to the caller -- api.finishRun
	// fail-opens (still dispatches) on error so a blip cannot silence
	// every terminal webhook. api.finishRun only calls this when
	// hooks.HasSinks() is true so unconfigured deployments pay nothing.
	TryClaimTerminalHook(ctx context.Context, runID string) (bool, error)

	// PruneTerminalHookClaims deletes terminal_hook_claims rows whose
	// claimed_at is older than olderThan. Not tenant-scoped (the table
	// keys only on run_id). Opt-in via retention.terminal_hook_claims_max_age.
	PruneTerminalHookClaims(ctx context.Context, olderThan time.Time) (int64, error)

	// ListActiveRunsCreatedBefore returns pending/running runs whose
	// created_at is strictly before `before`, oldest first, capped at
	// limit. Backs the opt-in run-timeout sweep (cmd/run_timeout.go): a
	// genuinely hung agent (alive but stuck -- not crashed, so the
	// heartbeat/reclaim path never fires) has no other automatic
	// terminal transition. Scoped to the caller's tenant unless ctx is
	// a system context. limit <= 0 defaults to 100. Returns a non-nil
	// empty slice when nothing matches.
	ListActiveRunsCreatedBefore(ctx context.Context, before time.Time, limit int) ([]*models.Run, error)

	// TryMarkRunTimeout atomically transitions a run from pending or
	// running to timeout. Returns true if THIS call won the transition
	// (so the caller should cancel the queue lease, signal the runner,
	// release the thread, and finish bookkeeping); false if the run was
	// already terminal or another replica timed it out first. Multi-
	// instance safe: N replicas' timeout tickers racing the same overdue
	// run_id produce exactly one winner.
	TryMarkRunTimeout(ctx context.Context, runID string, errMsg string) (bool, error)

	// --- Store (key-value) ---
	// TTL (gap found when a live agent called store.aput(..., ttl=...),
	// a documented LangGraph BaseStore feature RunkiteStore never
	// implemented, so it hard-failed with "TTL is not supported by
	// RunkiteStore"). Matches LangGraph's own semantics: item.TTLMinutes
	// nil on PutItem means no expiration;
	// an expired item (now >= its stored expiry) is treated as absent by
	// GetItem/SearchItems, deleted opportunistically by a background
	// sweep (see PruneExpiredStoreItems) rather than synchronously here.
	PutItem(ctx context.Context, item *models.StoreItem) error
	// GetItem returns ErrNotFound for a missing OR expired item (the
	// HTTP layer maps that to 404; Python RunkiteStore maps 404 to
	// None). If refreshTTL is true and the item has a TTL, its expiry
	// is extended to now+ttl -- matching LangGraph's "expiration timer
	// refreshes on read operations" default (Python callers resolve
	// their own TTLConfig.refresh_on_read default before passing this
	// through).
	GetItem(ctx context.Context, namespace []string, key string, refreshTTL bool) (*models.StoreItem, error)
	DeleteItem(ctx context.Context, namespace []string, key string) error
	// SearchItems excludes expired items and, per req.RefreshTTL, refreshes
	// the TTL of every item it returns -- same semantics as GetItem.
	SearchItems(ctx context.Context, req *models.StoreSearchRequest) ([]*models.StoreItem, error)
	ListNamespaces(ctx context.Context, req *models.StoreListNamespacesRequest) ([][]string, error)

	// --- Webhook dead-letter (event hooks / webhook delivery) ---
	SaveWebhookDeadLetter(ctx context.Context, dl *models.WebhookDeadLetter) error
	// ListWebhookDeadLetters returns newest-first dead letters, scoped
	// to the caller's tenant unless ctx is a system context
	// (tenant.SystemContext), in which case it lists across every tenant.
	ListWebhookDeadLetters(ctx context.Context, limit int) ([]*models.WebhookDeadLetter, error)
	// PruneWebhookDeadLetters deletes dead letters whose failed_at is
	// older than olderThan. Same tenant-scoping rule as ListWebhookDeadLetters.
	PruneWebhookDeadLetters(ctx context.Context, olderThan time.Time) (int64, error)

	// --- Run cache (LLM response caching) ---
	// GetCachedRunResult returns ErrNotFound for a missing OR expired
	// entry -- callers never need to separately check ExpiresAt.
	GetCachedRunResult(ctx context.Context, cacheKey string) (*models.CachedRunResult, error)
	SaveCachedRunResult(ctx context.Context, result *models.CachedRunResult) error

	// --- Cron scheduler ---
	UpsertCronSchedule(ctx context.Context, sched *models.CronSchedule) error
	ListCronSchedules(ctx context.Context) ([]*models.CronSchedule, error)
	DeleteCronSchedule(ctx context.Context, name string) error
	// TryClaimCronFire atomically claims a specific (schedule, fire time)
	// pair so exactly one control-plane instance dispatches the run for
	// it, even with multiple replicas of the scheduler loop running
	// concurrently against the same database. Returns false, without
	// error, if another instance already claimed it first.
	TryClaimCronFire(ctx context.Context, scheduleName string, fireTime time.Time) (bool, error)
	// ReleaseCronClaim undoes a successful TryClaimCronFire so a later
	// tick (or peer) can retry the same fire after a transient dispatch
	// failure. No-op if the claim row is already gone.
	ReleaseCronClaim(ctx context.Context, scheduleName string, fireTime time.Time) error
	// GetLastCronFireTime returns the most recent fire_time ever claimed
	// for a schedule, and false if none exists yet. Lets the scheduler
	// distinguish "restarting a schedule that has fired before" (catch up
	// to the latest fire missed since then) from "a schedule that has
	// never fired" (start counting from now -- no surprise immediate
	// fire just because its expression's most recent occurrence already
	// passed before it was ever registered).
	GetLastCronFireTime(ctx context.Context, scheduleName string) (fireTime time.Time, found bool, err error)

	// PruneRuns deletes TERMINAL runs (success/error/interrupted/timeout
	// -- matching api.isTerminalStatus; never pending/running, which
	// must never be pruned regardless of age) whose updated_at is older
	// than olderThan. Scoped to the caller's
	// tenant unless ctx is a system context (tenant.SystemContext), in
	// which case it prunes across every tenant. Returns rows deleted.
	// Cascades to that run's own data via the runs table's own FK
	// constraints where applicable; does not touch the parent thread.
	PruneRuns(ctx context.Context, olderThan time.Time) (int64, error)

	// PruneCheckpoints keeps only the keepLast most recent checkpoints
	// per thread (ordered by created_at), deleting older ones. keepLast
	// <= 0 is a no-op (prunes nothing) -- there is no "prune everything"
	// footgun via a zero/negative value. Same tenant-scoping rule as
	// PruneRuns. Never deletes a thread's own values_json (the "current
	// state" snapshot lives on the threads row itself, not here).
	PruneCheckpoints(ctx context.Context, keepLast int) (int64, error)

	// PruneCronClaims deletes cron_claims rows (the multi-instance-safe
	// fire dedup table) with fire_time older than olderThan -- README's
	// "Cron's claim table has no retention sweep" gap, closed alongside
	// the others since it's the same class of unbounded-growth problem.
	// Same tenant-scoping rule as PruneRuns.
	PruneCronClaims(ctx context.Context, olderThan time.Time) (int64, error)

	// PruneExpiredStoreItems deletes store_items rows past their TTL
	// expiry (see the Store section's TTL doc comment above). Unlike
	// PruneRuns/PruneCheckpoints/PruneCronClaims this is NOT opt-in --
	// always run by cmd/serve.go on a fixed interval regardless of
	// "retention" config, since it's deleting data that is already
	// unconditionally excluded from every read (GetItem/SearchItems),
	// not a configurable data-retention policy choice. Same
	// tenant-scoping rule as PruneRuns.
	PruneExpiredStoreItems(ctx context.Context) (int64, error)

	// --- Registry: an agent marketplace for publishing, discovering,
	// and deploying agent definitions ---
	// PublishRegistryEntry creates a new entry or republishes an
	// existing one, same increment-on-actual-change version semantics
	// as UpsertAgent (see models.RegistryEntry's doc comment).
	PublishRegistryEntry(ctx context.Context, entry *models.RegistryEntry) error
	GetRegistryEntry(ctx context.Context, name string) (*models.RegistryEntry, error)
	SearchRegistryEntries(ctx context.Context, req *models.RegistrySearchRequest) ([]*models.RegistryEntry, error)
	DeleteRegistryEntry(ctx context.Context, name string) error
	// ListRegistryEntryVersions / GetRegistryEntryVersion mirror
	// ListAgentVersions / GetAgentVersion exactly -- same append-only
	// history contract.
	ListRegistryEntryVersions(ctx context.Context, name string) ([]*models.RegistryEntryVersion, error)
	GetRegistryEntryVersion(ctx context.Context, name string, version int) (*models.RegistryEntryVersion, error)

	// --- Lifecycle ---
	Init(ctx context.Context) error      // Apply pending numbered schema migrations
	Downgrade(ctx context.Context) error // Roll back the most recently applied migration
	Close() error

	// Ping verifies the store can actually reach its backing database
	// right now -- a real round trip, not just "was the connection pool
	// constructed successfully at startup." Backs GET /readyz: a
	// replica whose Postgres/MySQL/Mongo has since become unreachable
	// (network partition, DB restart, credentials rotated out from
	// under it) should stop receiving new traffic from a load balancer
	// even though its own process is still very much alive -- which is
	// exactly the distinction a liveness check alone can't make.
	Ping(ctx context.Context) error
}

Store is the persistence interface for all control plane metadata.

type WebhookDeadLetterLookup

type WebhookDeadLetterLookup interface {
	GetWebhookDeadLetter(ctx context.Context, id string) (*models.WebhookDeadLetter, error)
}

WebhookDeadLetterLookup is an optional indexed lookup for a known dead-letter ID. Built-in stores implement it so redelivery does not depend on list limits. The caller's tenant is enforced unless ctx carries SystemContext.

type WorkloadIdentityStore added in v0.8.0

type WorkloadIdentityStore interface {
	SupportsWorkloadIdentity() bool
}

Directories

Path Synopsis
Package conformance provides backend-agnostic test suites for the state.Store interface.
Package conformance provides backend-agnostic test suites for the state.Store interface.
Package migrate is a small numbered up/down schema migration runner for control-plane state stores and (separately) the pgvector vector store.
Package migrate is a small numbered up/down schema migration runner for control-plane state stores and (separately) the pgvector vector store.
Package mongo implements the state.Store interface using MongoDB.
Package mongo implements the state.Store interface using MongoDB.
Package mysql implements the state.Store interface using MySQL -- the second SQL exemplar alongside Postgres/SQLite, using the same conformance suite (internal/state/conformance) as every other backend.
Package mysql implements the state.Store interface using MySQL -- the second SQL exemplar alongside Postgres/SQLite, using the same conformance suite (internal/state/conformance) as every other backend.
Package postgres implements the state.Store interface using PostgreSQL via pgx.
Package postgres implements the state.Store interface using PostgreSQL via pgx.
Package sqlcompletion shares the transactional completion invariant between SQL backends.
Package sqlcompletion shares the transactional completion invariant between SQL backends.
Package sqlite implements the state.Store interface using embedded SQLite.
Package sqlite implements the state.Store interface using embedded SQLite.

Jump to

Keyboard shortcuts

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