store

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2026 License: MIT Imports: 38 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 store persists execution state independently of the Parsar product.

Index

Constants

This section is empty.

Variables

View Source
var ErrExecutionAuthority = errors.New("operation requires the execution writer")

ErrExecutionAuthority rejects an execution-only operation on a pooled Store.

View Source
var ErrSandboxResetSessionBusy = errors.New("the hosted Session is busy")

Functions

func UnstorableText

func UnstorableText(err error) bool

UnstorableText reports PostgreSQL rejecting text it cannot store; see pgunit.IsUnstorableText. Store returns database errors untranslated, so api checks them with this until store is deleted.

Types

type AdminAssetCounts

type AdminAssetCounts struct {
	Agents               int64 `json:"agents"`
	Skills               int64 `json:"skills"`
	EnvironmentTemplates int64 `json:"environment_templates"`
	Files                int64 `json:"files"`
	Vaults               int64 `json:"vaults"`
	Credentials          int64 `json:"credentials"`
}

type AdminRuntimeTarget

type AdminRuntimeTarget struct{ SessionID, TenantID string }

type AdminRuntimeTargetPage

type AdminRuntimeTargetPage struct {
	Data    []AdminRuntimeTarget
	HasMore bool
}

type AdminSummaryFilter

type AdminSummaryFilter struct{ CreatedAfter, CreatedBefore *time.Time }

type CoreExecutionHistory

type CoreExecutionHistory struct {
	Interrupted int64
	QueueWaitMS CoreQueueWait
	Buckets     []CoreQueueWaitBucket
}

type CoreExecutionSnapshot

type CoreExecutionSnapshot struct {
	QueuedTurns, WaitingForDaemon, InProgressTurns int64
	OldestQueuedSeconds                            *float64
}

type CoreQueueWait

type CoreQueueWait struct{ P50, P95 *float64 }

type CoreQueueWaitBucket

type CoreQueueWaitBucket struct {
	Start time.Time
	P95MS *float64
}

type Store

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

func New

func New(pool *pgxpool.Pool) *Store

func NewExecution

func NewExecution(s *Store, lease *pgunit.Lease) *Store

NewExecution returns the execution writer built on lease, which the caller acquired and closes. The writer's Session and execution-only transactions run on the leased connection; reads keep the pool. Keep public admission on the pooled Store. Losing or closing the lease never falls back to a pooled writer.

func NewWithCredentialCipher

func NewWithCredentialCipher(pool *pgxpool.Pool, cipher *credentialcrypto.Cipher) *Store

NewWithCredentialCipher configures immutable credential encryption before the Store is published. A nil cipher leaves non-secret resource operations available.

func (*Store) ArchiveManagedSession

func (s *Store) ArchiveManagedSession(ctx context.Context, tenantID, sessionID string, expectedGeneration uint64) (sessions.ManagedArchive, error)

ArchiveManagedSession ends a managed Environment's lifetime while keeping its public Session, history and persisted files. The lifecycle owner performs the external cleanup; only its existing confirmation can release an allocation.

func (*Store) ArchiveSandboxResetSession

func (s *Store) ArchiveSandboxResetSession(ctx context.Context, tenantID, sessionID string, generation uint64, requestedAt time.Time) (sessions.ManagedArchive, error)

A reset instance is identified by its persisted request time as well as its generation, preventing a cancelled clear's candidates from affecting its successor.

func (*Store) ArchivedCancellationReceipt

func (s *Store) ArchivedCancellationReceipt(ctx context.Context, deviceID, credentialHash string, runIDs []string) (runtimedevice.ArchivedCancellationReceipt, error)

ArchivedCancellationReceipt is a read-only exception for the exact already authenticated delivery. The ordinary credential view remains revoked; this cannot authorize bootstrap, reconnect, dispatch, workspace access or renewal. A marker records that archive caused the first revocation; timestamps alone cannot distinguish an earlier ordinary cancel/revoke followed by archive.

func (*Store) AuditSessionOperation

func (s *Store) AuditSessionOperation(ctx context.Context, tenantID, sessionID, action string) error

AuditSessionOperation records an authorized public no-op or creation replay. It cannot create ownership or admit execution work.

func (*Store) BeginTurnArtifactCapture

func (s *Store) BeginTurnArtifactCapture(ctx context.Context, tenantID, sessionID, turnID string, appliedThrough int64) error

BeginTurnArtifactCapture separates native completion from bounded output publication. Later messages use the existing reservation path instead of the finished executor.

func (*Store) CancelEnvironmentInput

func (s *Store) CancelEnvironmentInput(ctx context.Context, tenantID, sessionID, reservationID string) (sessions.EnvironmentInputReservation, error)

func (*Store) CompleteExecution

func (s *Store) CompleteExecution(ctx context.Context, tenantID, sessionID, turnID, status string, outcome json.RawMessage, nativeID string, appliedThrough int64) (sessions.Turn, error)

CompleteExecution commits the outcome and native continuity under the admission lock.

func (*Store) CreateSession

func (s *Store) CreateSession(ctx context.Context, tenantID string, input sessions.CreateSession) (sessions.Session, error)

CreateSession uses a project-scoped key to make retries safe, including concurrent submissions. Different input or creator with the same key conflicts.

func (*Store) CreateSessionStream

func (s *Store) CreateSessionStream(ctx context.Context, tenant string, input sessions.CreateSession) (sessions.Creation, error)

CreateSessionStream shares admission and retry identity with ordinary creation. The upsert returns its event cursor while holding the Session write lock, before initial inputs commit. No post-commit cursor lookup may skip those inputs.

func (*Store) DeleteSession

func (s *Store) DeleteSession(ctx context.Context, tenantID, sessionID string) error

DeleteSession removes public access to a durably idle or failed Session while retaining state needed to settle execution. The decision is taken under the Session lock that also orders Turn and input admission, so a concurrent admission either commits first and is rejected here, or observes the deletion. The owner's repeated deletion succeeds without another resource write; foreign and missing Sessions remain not found.

func (*Store) ExpireEnvironmentInput

func (s *Store) ExpireEnvironmentInput(ctx context.Context, tenantID, sessionID, reservationID string) (sessions.EnvironmentInputReservation, error)

func (*Store) ExpireEnvironmentInputs

func (s *Store) ExpireEnvironmentInputs(ctx context.Context) (int64, error)

ExpireEnvironmentInputs settles one bounded batch without creating Turn history. Only the current execution writer may run this cross-Session maintenance.

func (*Store) FailEnvironmentInput

func (s *Store) FailEnvironmentInput(ctx context.Context, tenantID, sessionID, reservationID, code string) error

FailEnvironmentInput settles a confirmed pre-admission failure. The Session lock and pending-state predicate preserve cancellation and newer input.

func (*Store) FindSessionCreation

func (s *Store) FindSessionCreation(ctx context.Context, tenantID, key string, request json.RawMessage, creator identity.Subject) (sessions.Creation, error)

FindSessionCreation recovers recorded caller intent without resolving a mutable source.

func (*Store) GetEnvironmentInputReservation

func (s *Store) GetEnvironmentInputReservation(ctx context.Context, tenantID, sessionID, reservationID string) (sessions.EnvironmentInputReservation, error)

func (*Store) GetManagedSessionArchive

func (s *Store) GetManagedSessionArchive(ctx context.Context, tenantID, sessionID string) (sessions.ManagedArchive, error)

GetManagedSessionArchive reads one database snapshot and never contacts compute.

func (*Store) GetSession

func (s *Store) GetSession(ctx context.Context, tenantID, sessionID string) (sessions.Session, error)

GetSession always scopes lookup to the authenticated caller's tenant.

func (*Store) GetSessionDiagnosticsSnapshot

func (s *Store) GetSessionDiagnosticsSnapshot(ctx context.Context, tenantID, sessionID string) (sessions.Session, error)

GetSessionDiagnosticsSnapshot keeps all existing Session projections in one read-only snapshot, including the failure precedence used by the public API.

func (*Store) GetSessionExecutionBinding

func (s *Store) GetSessionExecutionBinding(ctx context.Context, tenantID, sessionID string) (sessions.ExecutionBinding, error)

func (*Store) GetSessionExecutionConfiguration

func (s *Store) GetSessionExecutionConfiguration(ctx context.Context, tenantID, sessionID string) (v1.SessionExecutionConfiguration, error)

GetSessionExecutionConfiguration reads only safe committed configuration. It never loads provider ciphertext, current defaults or runtime health.

func (*Store) GetTurn

func (s *Store) GetTurn(ctx context.Context, tenantID, sessionID, turnID string) (sessions.Turn, error)

GetTurn reads a root Turn. A Subagent Turn ID is not found here, exactly like a missing one; GetSubagentTurn reads child Turns.

func (*Store) GetTurnDiagnosticsSnapshot

func (s *Store) GetTurnDiagnosticsSnapshot(ctx context.Context, tenantID, sessionID, turnID string) (sessions.TurnDiagnosticsSnapshot, error)

GetTurnDiagnosticsSnapshot reads only root Turns and their root Items. Its bounded query and public projection share the same committed snapshot.

func (*Store) InsertRuntimeHistorySample

func (s *Store) InsertRuntimeHistorySample(ctx context.Context, record runtimeobs.ExportRecord) error

InsertRuntimeHistorySample copies a sanitized periodic observation. Public Session/Turn Usage remains the accounting authority; these measured counters are only sampled chart values. Deleted or mismatched owners cannot create orphan rows.

func (*Store) ListAdminRuntimeTargets

func (s *Store) ListAdminRuntimeTargets(ctx context.Context, tenantIDs []string, after string, limit int, ascending bool) (AdminRuntimeTargetPage, error)

func (*Store) ListEnvironmentInputWork

func (s *Store) ListEnvironmentInputWork(ctx context.Context, after string, connectedDevices []string) ([]sessions.EnvironmentInputWork, error)

func (*Store) ListExecutionDevices

func (s *Store) ListExecutionDevices(ctx context.Context, tenantID string) ([]sessions.ExecutionDevice, error)

func (*Store) ListExecutionWork

func (s *Store) ListExecutionWork(ctx context.Context, after string, statuses []string, connectedDevices []string) ([]sessions.ExecutionWork, error)

func (*Store) ListRuntimeHistorySamples

func (s *Store) ListRuntimeHistorySamples(ctx context.Context, tenantID, sessionID, environmentID string, startNS, endNS int64, limit int32) ([]runtimeobs.ExportRecord, error)

func (*Store) ListSessionEvents

func (s *Store) ListSessionEvents(ctx context.Context, tenantID, sessionID string, after int64) ([]sessions.SessionChange, error)

func (*Store) ListSessions

func (s *Store) ListSessions(ctx context.Context, tenantID, cursor string, limit int, ascending bool, agentID *string) (sessions.Page, error)

ListSessions orders by creation time and ID. The cursor is the last returned session ID and must belong to the same tenant; it grants no additional access.

func (*Store) ListTurnInputs

func (s *Store) ListTurnInputs(ctx context.Context, tenantID, sessionID, turnID string, after int64, limit int) ([]sessions.TurnInput, error)

ListTurnInputs is an internal ordered recovery query, not the public SSE stream.

func (*Store) ListTurns

func (s *Store) ListTurns(ctx context.Context, tenantID, sessionID, cursor string, limit int, ascending bool) (sessions.TurnPage, error)

ListTurns pages a Session's root Turns. Subagent Turns are not Session Turns; sessionpg.Store.ListSubagentTurns reads them.

func (*Store) MeasuredSessionUsage

func (s *Store) MeasuredSessionUsage(ctx context.Context, tenantID, sessionID string) (json.RawMessage, error)

MeasuredSessionUsage returns Core-internal measured usage for Runtime telemetry: the sum of every recorded root Turn snapshot, active Turns included, and null only when nothing is recorded. Public Session usage keeps the official rule of SessionTokenUsage. A missing Session reads as null, so callers resolve the Session first.

func (*Store) PromoteEnvironmentInput

func (s *Store) PromoteEnvironmentInput(ctx context.Context, tenantID, sessionID, reservationID string) (sessions.EnvironmentInputReservation, error)

PromoteEnvironmentInput admits and claims work for the retained native preparation.

func (*Store) PruneRuntimeHistorySamples

func (s *Store) PruneRuntimeHistorySamples(ctx context.Context, beforeNS int64) (int64, error)

func (*Store) ReadAdminSummary

func (s *Store) ReadAdminSummary(ctx context.Context, tenantID string, filter AdminSummaryFilter, visit func(sessions.Session, *string) error) (AdminAssetCounts, error)

ReadAdminSummary visits one space's Sessions from one read-only snapshot. The visitor reuses the API's Session projection instead of creating another status or usage model. Paging keeps the stored configurations out of an unbounded slice.

func (*Store) ReadCoreDatabaseSize

func (s *Store) ReadCoreDatabaseSize(ctx context.Context) (int64, error)

ReadCoreDatabaseSize measures the current PostgreSQL database in bytes.

func (*Store) ReadCoreExecutionHistory

func (s *Store) ReadCoreExecutionHistory(ctx context.Context, start, end time.Time, resolution time.Duration) (CoreExecutionHistory, error)

ReadCoreExecutionHistory reads a bounded, repeatable read-only snapshot of root Turn history. The interval is [start,end), with complete epoch-aligned buckets. Interruptions use failed Turns' completed_at and execution_interrupted error code. Queue waits use started_at-created_at in milliseconds, grouped by started_at, including retained history of deleted Sessions. Counts of an empty interval are zero; percentile values without observations are nil. Read errors invalidate the entire result and must not be presented as measured zeros.

func (*Store) ReadCoreExecutionSnapshot

func (s *Store) ReadCoreExecutionSnapshot(ctx context.Context, now time.Time, connectedDeviceIDs []string) (CoreExecutionSnapshot, error)

ReadCoreExecutionSnapshot counts persisted root Turns across the deployment. WaitingForDaemon is the queued subset whose Session binding is absent from the supplied live registry IDs; callers must distinguish an unavailable registry from an observed empty one before using this method. Age is in seconds, and is nil when the queue is empty. No Session deletion filter hides operational state.

func (*Store) RequestCancel

func (s *Store) RequestCancel(ctx context.Context, tenantID, sessionID, key string) (sessions.InputReceipt, error)

func (*Store) ReserveEnvironmentInput

func (s *Store) ReserveEnvironmentInput(ctx context.Context, tenantID, sessionID, key string, inputs []sessions.Input) (sessions.EnvironmentInputReservation, error)

ReserveEnvironmentInput appends to active work or reserves an idle message batch. The Session lock decides both paths; only promotion can create a new Turn.

func (*Store) SessionEventCursor

func (s *Store) SessionEventCursor(ctx context.Context, tenantID, sessionID string) (int64, error)

func (*Store) SessionModelExecution

func (s *Store) SessionModelExecution(ctx context.Context, tenant, session string) (*v1.ModelProviderInput, error)

func (*Store) SessionStreamSnapshot

func (s *Store) SessionStreamSnapshot(ctx context.Context, tenantID, sessionID string) (sessions.Session, int64, error)

SessionStreamSnapshot reads the projection that GetSession returns and the committed Session event cursor from one database snapshot.

func (*Store) SetPlacement

func (s *Store) SetPlacement(rules *placement.Rules)

SetPlacement records the installation's placement rules, built once in the composition root. Call it once, before serving requests.

func (*Store) SubmitInputs

func (s *Store) SubmitInputs(ctx context.Context, tenantID, sessionID, key string, inputs []sessions.Input) ([]sessions.InputReceipt, error)

SubmitInputs commits a request in order under one Session lock. The entire batch is the retry identity; replay never re-evaluates a cancellation target. Internal receipts are not the response body of the public events endpoint.

func (*Store) SubmitMessage

func (s *Store) SubmitMessage(ctx context.Context, tenantID, sessionID, key string, payload json.RawMessage) (sessions.InputReceipt, error)

SubmitMessage and RequestCancel use the same request-level admission as batches.

func (*Store) TransitionTurn

func (s *Store) TransitionTurn(ctx context.Context, tenantID, sessionID, turnID string, input sessions.TurnTransition) (sessions.Turn, error)

TransitionTurn is a compare-and-set for execution callbacks. Once terminal, a Turn cannot be reopened or have its outcome overwritten, including by retries. A dispatcher must claim queued -> in_progress before sending work to a daemon.

func (*Store) UpdateSessionMetadata

func (s *Store) UpdateSessionMetadata(ctx context.Context, tenantID, sessionID string, values map[string]string) (sessions.Session, error)

Jump to

Keyboard shortcuts

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