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
- Variables
- func IsTerminalPhase(phase agentorcav1alpha1.AgentRunPhase) bool
- func Migrate(ctx context.Context, db *sql.DB) (int, error)
- type Approval
- type ApprovalQuery
- type CostQuery
- type CostRow
- type HistoryPage
- type HistoryQuery
- type HistoryResult
- type RunArchive
- type Store
- func (s *Store) ApplyMigration(ctx context.Context) error
- func (s *Store) ArchiveRun(ctx context.Context, run *agentorcav1alpha1.AgentRun, traceEventsJSON []byte) error
- func (s *Store) Close() error
- func (s *Store) DecideApproval(ctx context.Context, id, status, by, reason string) (Approval, error)
- func (s *Store) GetApproval(ctx context.Context, id string) (Approval, error)
- func (s *Store) GetRun(ctx context.Context, namespace, name string) (*RunArchive, error)
- func (s *Store) ListApprovals(ctx context.Context, q ApprovalQuery) ([]Approval, error)
- func (s *Store) MarkApprovalApplied(ctx context.Context, id string) error
- func (s *Store) Ping(ctx context.Context) error
- func (s *Store) QueryCostRows(ctx context.Context, q CostQuery) ([]CostRow, error)
- func (s *Store) QueryHistory(ctx context.Context, q HistoryQuery) (*HistoryPage, error)
- func (s *Store) RequestApproval(ctx context.Context, a Approval) (Approval, error)
- func (s *Store) WithdrawBySourcePrefix(ctx context.Context, kind, prefix, reason string) error
- func (s *Store) WithdrawRunApprovals(ctx context.Context, namespace, runName string) error
Constants ¶
const ( ApprovalPending = "pending" ApprovalApproved = "approved" ApprovalRejected = "rejected" ApprovalExpired = "expired" ApprovalWithdrawn = "withdrawn" )
Approval statuses.
const ApprovalKindBudget = "budget"
ApprovalKindBudget is a request to raise a paused run's spend cap.
const ApprovalKindEgress = "egress"
ApprovalKindEgress is a request to allow sandbox egress (an OpenShell policy draft chunk).
const ApprovalKindTool = "tool"
ApprovalKindTool is a request to run a tool whose side-effect class needs an approver (GuardrailPolicy.spec.toolApproval).
const ApprovalKindWorkflow = "workflow"
ApprovalKindWorkflow is an approval step of an AgentWorkflow waiting for a decision.
Variables ¶
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.
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 ¶
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 ¶
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) 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
GetApproval returns one approval, or sql.ErrNoRows.
func (*Store) ListApprovals ¶ added in v0.9.0
ListApprovals returns approvals, newest first.
func (*Store) MarkApprovalApplied ¶ added in v0.9.0
MarkApprovalApplied records that a decision reached its source.
func (*Store) QueryCostRows ¶ added in v0.8.0
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
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
WithdrawBySourcePrefix withdraws the pending approvals of one kind whose source key starts with prefix (a workflow's approval steps, when it ends).