Help us shape the future of Go! Take the 2026 Go Developer Survey

postgresql

package
v0.9.0 Latest Latest
Warning

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

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

Documentation

Overview

Package postgresql provides a PostgreSQL-backed archival store for completed AgentRun resources. The operator's AgentRunReconciler snapshots terminal-phase runs here so the UI can display historical runs beyond the lifetime of the live Kubernetes CRDs (which may be garbage-collected by the controller's retention policy).

Index

Constants

View Source
const (
	ApprovalPending   = "pending"
	ApprovalApproved  = "approved"
	ApprovalRejected  = "rejected"
	ApprovalExpired   = "expired"
	ApprovalWithdrawn = "withdrawn"
)

Approval statuses.

View Source
const ApprovalKindBudget = "budget"

ApprovalKindBudget is a request to raise a paused run's spend cap.

View Source
const ApprovalKindEgress = "egress"

ApprovalKindEgress is a request to allow sandbox egress (an OpenShell policy draft chunk).

View Source
const ApprovalKindTool = "tool"

ApprovalKindTool is a request to run a tool whose side-effect class needs an approver (GuardrailPolicy.spec.toolApproval).

View Source
const ApprovalKindWorkflow = "workflow"

ApprovalKindWorkflow is an approval step of an AgentWorkflow waiting for a decision.

Variables

View Source
var ErrApprovalNotPending = errors.New("approval is no longer pending")

ErrApprovalNotPending is returned when deciding an approval that has already been decided, expired or withdrawn.

Functions

func IsTerminalPhase

func IsTerminalPhase(phase agentorcav1alpha1.AgentRunPhase) bool

IsTerminalPhase reports whether the given AgentRun phase is terminal.

func Migrate added in v0.9.0

func Migrate(ctx context.Context, db *sql.DB) (int, error)

Migrate applies the migrations db has not run yet and returns how many it applied. It holds an advisory lock for the duration, so replicas starting at once migrate one at a time.

Types

type Approval added in v0.9.0

type Approval struct {
	ID             string          `json:"id"`
	Tenant         string          `json:"tenant,omitempty"`
	Namespace      string          `json:"namespace"`
	RunName        string          `json:"runName"`
	Kind           string          `json:"kind"`
	SourceKey      string          `json:"sourceKey"`
	Summary        string          `json:"summary"`
	Details        json.RawMessage `json:"details,omitempty"`
	ApproverGroups []string        `json:"approverGroups"`
	Status         string          `json:"status"`
	RequestedAt    time.Time       `json:"requestedAt"`
	ExpiresAt      time.Time       `json:"expiresAt"`
	DecidedBy      string          `json:"decidedBy,omitempty"`
	DecidedAt      *time.Time      `json:"decidedAt,omitempty"`
	Reason         string          `json:"reason,omitempty"`
	AppliedAt      *time.Time      `json:"appliedAt,omitempty"`
	// Created is set by RequestApproval when the request is new rather than a
	// repeat of an existing one.
	Created bool `json:"-"`
}

Approval is a request for a decision (table approvals, migration 0002).

type ApprovalQuery added in v0.9.0

type ApprovalQuery struct {
	// Namespaces scopes the query to a tenant's namespaces.
	Namespaces []string
	Namespace  string
	RunName    string
	Status     string
	Limit      int
}

ApprovalQuery filters ListApprovals. Empty fields match everything.

type CostQuery added in v0.8.0

type CostQuery struct {
	// Namespaces restricts results to these namespaces. Empty = all.
	Namespaces []string
	// Deployment restricts to runs labelled agentorca.io/deployment=<name>.
	Deployment string
	// Run restricts to a single run name.
	Run string
	// Since drops runs that finished (or, if unfinished, started) before it.
	Since *time.Time
}

CostQuery filters the archived runs that feed the cost dashboard.

type CostRow added in v0.8.0

type CostRow struct {
	Name      string
	Namespace string
	AgentRef  string
	Phase     string
	SpendUSD  string
	// CostIncomplete is true when the run's spend could not be captured.
	CostIncomplete bool
	// Model is the model of the run's last routing decision ("" if none).
	Model string
	// When is the completion time, falling back to start then creation time.
	When time.Time
}

CostRow is the slice of an archived run that cost aggregation needs.

type HistoryPage

type HistoryPage struct {
	Runs   []HistoryResult `json:"runs"`
	Total  int             `json:"total"`
	Limit  int             `json:"limit"`
	Offset int             `json:"offset"`
}

HistoryPage is the paginated response for run history queries.

type HistoryQuery

type HistoryQuery struct {
	// Limit caps the number of results (default 50, clamped to [1, 200]).
	Limit int
	// Offset is the number of rows to skip (for pagination).
	Offset int
	// Phase filters by AgentRun phase (e.g. "Succeeded", "Failed"). Empty = all.
	Phase string
	// AgentRef filters by the agent name referenced by the run.
	AgentRef string
	// Namespaces restricts results to the given namespaces (typically a tenant's
	// authorized set). Empty = all namespaces (only meaningful when the caller has
	// cluster-wide access).
	Namespaces []string
	// Search matches against the run name case-insensitively.
	Search string
}

HistoryQuery holds filter/sort/pagination parameters for run history lookups.

type HistoryResult

type HistoryResult struct {
	Name           string     `json:"name"`
	Namespace      string     `json:"namespace"`
	AgentRef       string     `json:"agentRef"`
	Phase          string     `json:"phase"`
	SpendUSD       string     `json:"spendUSD"`
	StartTime      *time.Time `json:"startTime,omitempty"`
	CompletionTime *time.Time `json:"completionTime,omitempty"`
	Tenant         string     `json:"tenant,omitempty"`
	// ContextUsedTokens / MaxContextTokens are surfaced so the UI can show a
	// context-utilization preview without a full detail round-trip.
	ContextUsedTokens int `json:"contextUsedTokens,omitempty"`
	MaxContextTokens  int `json:"maxContextTokens,omitempty"`
}

HistoryResult is a single row in a history listing.

type RunArchive

type RunArchive struct {
	// ID is the composite primary key: "namespace/name".
	ID string `db:"id"`
	// Kubernetes metadata.
	Name      string            `db:"name"`
	Namespace string            `db:"namespace"`
	Labels    map[string]string `db:"labels"`
	// Spec-level fields.
	AgentRef     string        `db:"agent_ref"`
	Input        string        `db:"input"`
	ParentRunRef string        `db:"parent_run_ref"`
	PriorRunRef  string        `db:"prior_run_ref"`
	TimeoutSec   sql.NullInt64 `db:"timeout_sec"`
	// Status-level fields (captured at archival time).
	Phase    string `db:"phase"`
	PodName  string `db:"pod_name"`
	SpendUSD string `db:"spend_usd"`
	// CostCapture mirrors the run's CostCapture condition: "complete" when the
	// spend was read from the state store, "incomplete" when it could not be,
	// "" for rows archived before the column existed (spend unknown either way).
	CostCapture       string     `db:"cost_capture"`
	Output            string     `db:"output"`
	RawOutput         string     `db:"raw_output"`
	RestartCount      int        `db:"restart_count"`
	StartTime         *time.Time `db:"start_time"`
	CompletionTime    *time.Time `db:"completion_time"`
	ContextUsedTokens int        `db:"context_used_tokens"`
	MaxContextTokens  int        `db:"max_context_tokens"`
	// Tenant attribution (from agentorca.io/tenant label, empty if unattributed).
	Tenant string `db:"tenant"`
	// Routing decisions and child refs (JSON-serialised).
	RoutingDecisionsJSON []byte `db:"routing_decisions"`
	ChildRunRefsJSON     []byte `db:"child_run_refs"`
	// TraceEventsJSON is the archived execution trace — a JSON array of
	// {id, event, ts, childRunName} entries read from the Redis token stream
	// at archival time. NULL when no trace events were available (store
	// disabled, stream expired, or pre-feature run).
	TraceEventsJSON []byte `db:"trace_events"`
	// Timestamps.
	CreatedAt time.Time `db:"created_at"`
	UpdatedAt time.Time `db:"updated_at"`
}

RunArchive is the relational representation of an archived AgentRun. Fields are flattened from the CRD spec and status for SQL querying.

type Store

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

Store is the PostgreSQL archival store.

func NewStore

func NewStore(dsn string) (*Store, error)

NewStore creates a new PostgreSQL store from a connection DSN. The DSN format follows the pgx connection string syntax:

postgresql://user:password@host:5432/dbname?sslmode=require

func (*Store) ApplyMigration

func (s *Store) ApplyMigration(ctx context.Context) error

ApplyMigration brings the schema up to date (see migrate.go).

func (*Store) ArchiveRun

func (s *Store) ArchiveRun(ctx context.Context, run *agentorcav1alpha1.AgentRun, traceEventsJSON []byte) error

ArchiveRun upserts a completed AgentRun into the archival table. traceEventsJSON is a pre-marshalled JSON array of trace entries (or nil to leave the column untouched on conflict). It is passed in by the controller after reading the Redis token stream, so the full execution trace can be rendered in the history view.

func (*Store) Close

func (s *Store) Close() error

Close releases the connection pool.

func (*Store) DecideApproval added in v0.9.0

func (s *Store) DecideApproval(ctx context.Context, id, status, by, reason string) (Approval, error)

DecideApproval records a decision on a pending approval. It fails with ErrApprovalNotPending if the approval was decided, expired or withdrawn meanwhile, so two approvers cannot both decide.

func (*Store) GetApproval added in v0.9.0

func (s *Store) GetApproval(ctx context.Context, id string) (Approval, error)

GetApproval returns one approval, or sql.ErrNoRows.

func (*Store) GetRun

func (s *Store) GetRun(ctx context.Context, namespace, name string) (*RunArchive, error)

GetRun retrieves a single archived run by namespace/name.

func (*Store) ListApprovals added in v0.9.0

func (s *Store) ListApprovals(ctx context.Context, q ApprovalQuery) ([]Approval, error)

ListApprovals returns approvals, newest first.

func (*Store) MarkApprovalApplied added in v0.9.0

func (s *Store) MarkApprovalApplied(ctx context.Context, id string) error

MarkApprovalApplied records that a decision reached its source.

func (*Store) Ping

func (s *Store) Ping(ctx context.Context) error

Ping verifies connectivity.

func (*Store) QueryCostRows added in v0.8.0

func (s *Store) QueryCostRows(ctx context.Context, q CostQuery) ([]CostRow, error)

QueryCostRows returns the archived runs matching q, newest first, in the narrow shape cost aggregation needs (no output, input or trace payloads).

func (*Store) QueryHistory

func (s *Store) QueryHistory(ctx context.Context, q HistoryQuery) (*HistoryPage, error)

QueryHistory returns a paginated, filtered list of archived runs.

func (*Store) RequestApproval added in v0.9.0

func (s *Store) RequestApproval(ctx context.Context, a Approval) (Approval, error)

RequestApproval records a request, or refreshes the details of the existing request with the same kind and source key (whatever its status), and returns the stored row. A decided request is not reopened.

func (*Store) WithdrawBySourcePrefix added in v0.9.0

func (s *Store) WithdrawBySourcePrefix(ctx context.Context, kind, prefix, reason string) error

WithdrawBySourcePrefix withdraws the pending approvals of one kind whose source key starts with prefix (a workflow's approval steps, when it ends).

func (*Store) WithdrawRunApprovals added in v0.9.0

func (s *Store) WithdrawRunApprovals(ctx context.Context, namespace, runName string) error

WithdrawRunApprovals withdraws a run's pending approvals when it ends.

Jump to

Keyboard shortcuts

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