gensqlc

package
v0.13.0 Latest Latest
Warning

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

Go to latest
Published: Jun 9, 2026 License: AGPL-3.0 Imports: 4 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AggregateSessionsByModelParams added in v0.8.0

type AggregateSessionsByModelParams struct {
	ProjectFilter  pgtype.Text
	AgentFilter    pgtype.Text
	ModelFilter    pgtype.Text
	ProviderFilter pgtype.Text
	SinceFilter    pgtype.Timestamptz
	UntilFilter    pgtype.Timestamptz
}

type AggregateSessionsByModelRow added in v0.8.0

type AggregateSessionsByModelRow struct {
	Model               pgtype.Text
	InputTokens         int64
	OutputTokens        int64
	CacheCreationTokens int64
	CacheReadTokens     int64
}

type AggregateSessionsParams added in v0.8.0

type AggregateSessionsParams struct {
	ProjectFilter  pgtype.Text
	AgentFilter    pgtype.Text
	ModelFilter    pgtype.Text
	ProviderFilter pgtype.Text
	SinceFilter    pgtype.Timestamptz
	UntilFilter    pgtype.Timestamptz
}

type AggregateSessionsRow added in v0.8.0

type AggregateSessionsRow struct {
	TurnCount           int64
	SessionCount        int64
	StemCount           int64
	RootCount           int64
	CompletedCount      int64
	InputTokens         int64
	OutputTokens        int64
	CacheCreationTokens int64
	CacheReadTokens     int64
	TotalDurationNs     int64
	ToolCalls           int64
}

type AncestryChainsParams

type AncestryChainsParams struct {
	Hashes   []string
	MaxDepth int32
}

type AncestryChainsRow

type AncestryChainsRow struct {
	StartHash                interface{}
	Hash                     interface{}
	ParentHash               interface{}
	Bucket                   interface{}
	Type                     interface{}
	Role                     interface{}
	Content                  interface{}
	Model                    interface{}
	Provider                 interface{}
	AgentName                interface{}
	StopReason               interface{}
	PromptTokens             interface{}
	CompletionTokens         interface{}
	TotalTokens              interface{}
	CacheCreationInputTokens interface{}
	CacheReadInputTokens     interface{}
	TotalDurationNs          interface{}
	PromptDurationNs         interface{}
	Project                  interface{}
	CreatedAt                pgtype.Timestamptz
	Depth                    int32
	HasUsage                 bool
}

type DBTX

type DBTX interface {
	Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error)
	Query(context.Context, string, ...interface{}) (pgx.Rows, error)
	QueryRow(context.Context, string, ...interface{}) pgx.Row
}

type GetSessionByNaturalKeyParams added in v0.10.0

type GetSessionByNaturalKeyParams struct {
	OrgID            pgtype.UUID
	HarnessID        string
	HarnessSessionID string
}

type GetSessionRecordParams added in v0.12.0

type GetSessionRecordParams struct {
	OrgID pgtype.UUID
	ID    pgtype.UUID
}

type InsertNodeParams

type InsertNodeParams struct {
	OrgID                    pgtype.UUID
	Hash                     string
	Bucket                   []byte
	Type                     pgtype.Text
	Role                     pgtype.Text
	Content                  []byte
	Model                    pgtype.Text
	Provider                 pgtype.Text
	AgentName                pgtype.Text
	StopReason               pgtype.Text
	PromptTokens             pgtype.Int4
	CompletionTokens         pgtype.Int4
	TotalTokens              pgtype.Int4
	CacheCreationInputTokens pgtype.Int4
	CacheReadInputTokens     pgtype.Int4
	TotalDurationNs          pgtype.Int8
	PromptDurationNs         pgtype.Int8
	Project                  pgtype.Text
	CreatedAt                pgtype.Timestamptz
	ParentHash               pgtype.Text
}

type InsertSessionPlaceholderParams added in v0.10.0

type InsertSessionPlaceholderParams struct {
	ID               pgtype.UUID
	OrgID            pgtype.UUID
	AuthSubject      string
	HarnessID        string
	HarnessSessionID string
	Now              pgtype.Timestamptz
}

type ListParentRefsRow

type ListParentRefsRow struct {
	Hash       string
	ParentHash pgtype.Text
}

type ListSessionRecordsParams added in v0.12.0

type ListSessionRecordsParams struct {
	OrgID    pgtype.UUID
	CursorTs pgtype.Timestamptz
	CursorID pgtype.UUID
	Lim      int32
}

type ListSessionsParams

type ListSessionsParams struct {
	ProjectFilter   pgtype.Text
	AgentFilter     pgtype.Text
	ModelFilter     pgtype.Text
	ProviderFilter  pgtype.Text
	SinceFilter     pgtype.Timestamptz
	UntilFilter     pgtype.Timestamptz
	CursorCreatedAt pgtype.Timestamptz
	CursorHash      pgtype.Text
	LimitCount      int32
}

type Node

type Node struct {
	Hash                     string
	Bucket                   []byte
	Type                     pgtype.Text
	Role                     pgtype.Text
	Content                  []byte
	Model                    pgtype.Text
	Provider                 pgtype.Text
	AgentName                pgtype.Text
	StopReason               pgtype.Text
	PromptTokens             pgtype.Int4
	CompletionTokens         pgtype.Int4
	TotalTokens              pgtype.Int4
	CacheCreationInputTokens pgtype.Int4
	CacheReadInputTokens     pgtype.Int4
	TotalDurationNs          pgtype.Int8
	PromptDurationNs         pgtype.Int8
	Project                  pgtype.Text
	CreatedAt                pgtype.Timestamptz
	ParentHash               pgtype.Text
	SessionID                pgtype.UUID
	OrgID                    pgtype.UUID
}

type Queries

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

func New

func New(db DBTX) *Queries

func (*Queries) AggregateSessions added in v0.8.0

func (q *Queries) AggregateSessions(ctx context.Context, arg AggregateSessionsParams) (AggregateSessionsRow, error)

Single-pass aggregate that powers /v1/stats. SUMs and turn/stem/root counts apply to the set of nodes matching the supplied per-node filters.

session_count and completed_count are session-grained, keyed on the first-class sessions table via nodes.session_id (PCC-565):

session_count   = distinct sessions touched by the matching nodes
completed_count = distinct sessions whose denormalized derived_status
                  is 'completed' (chain-aware, computed at ingest by
                  pkg/sessions.DetermineStatus — PCC-515)

Nodes with no session_id (legacy / non-session-tracked writers) are not counted as sessions; COUNT(DISTINCT session_id) ignores their NULLs.

stem_count is the leaf count (one per Merkle chain, matching /v1/stems) — the value session_count used to report before the sessions table existed.

total_duration_ns is wall-clock span MAX(created_at) - MIN(created_at) across the matching set, NOT SUM(nodes.total_duration_ns). The nodes.total_duration_ns column is currently never populated by the proxy (verified against jason@'s local store: 0 of 1460 rows have a non-zero value) — see PCC-514. Until that lands, SUMming the column would always return 0, which is misleading; wall-clock span is a meaningful "Agent Time" proxy that doesn't depend on the dead column.

The tool_calls subquery scans content JSONB per node to count tool_use blocks. This is acceptable at current corpus sizes; if it becomes a bottleneck the right next step is denormalizing tool_use_count onto the nodes table at write time.

func (*Queries) AggregateSessionsByModel added in v0.8.0

func (q *Queries) AggregateSessionsByModel(ctx context.Context, arg AggregateSessionsByModelParams) ([]AggregateSessionsByModelRow, error)

Per-model token rollup that powers the cost fold in /v1/stats. Filters apply per-node, matching aggregate_sessions.sql. Nodes with a NULL or empty model are excluded — they cannot be priced.

The API handler walks these rows, applies pkg/sessions.PricingForModel and pkg/sessions.CostForTokensWithCache to each, and sums into StatsResponse.TotalCost. Pricing intentionally lives in Go.

func (*Queries) AncestryChains

func (q *Queries) AncestryChains(ctx context.Context, arg AncestryChainsParams) ([]AncestryChainsRow, error)

func (*Queries) DuckdbForceExecution

func (q *Queries) DuckdbForceExecution(ctx context.Context) error

func (*Queries) GetNode

func (q *Queries) GetNode(ctx context.Context, hash string) (Node, error)

func (*Queries) GetNodesByParent

func (q *Queries) GetNodesByParent(ctx context.Context, parentHash pgtype.Text) ([]Node, error)

func (*Queries) GetRootNodes

func (q *Queries) GetRootNodes(ctx context.Context) ([]Node, error)

func (*Queries) GetSessionByNaturalKey added in v0.10.0

func (q *Queries) GetSessionByNaturalKey(ctx context.Context, arg GetSessionByNaturalKeyParams) (Session, error)

Lookup by the unique (org_id, harness_id, harness_session_id) index. Used by the parent-FK resolution path in ingest: when an inbound request carries a parent_harness_session_id hint, ingest reads the parent's sessions.id this way and FKs it onto the new row.

func (*Queries) GetSessionRecord added in v0.12.0

func (q *Queries) GetSessionRecord(ctx context.Context, arg GetSessionRecordParams) (Session, error)

func (*Queries) HasNode

func (q *Queries) HasNode(ctx context.Context, hash string) (bool, error)

func (*Queries) InsertNode

func (q *Queries) InsertNode(ctx context.Context, arg InsertNodeParams) (int64, error)

nodes is keyed by composite PK (org_id, hash) so the same content (e.g. a verbatim system prompt) can land for multiple orgs without the first writer permanently owning the row. Legacy non-session writers pass the nil-UUID (00000000-0000-0000-0000-000000000000) per the migration default; session-aware writers (IngestTurn) pass the validated cloud-trusted org_id.

func (*Queries) InsertSessionPlaceholder added in v0.10.0

func (q *Queries) InsertSessionPlaceholder(ctx context.Context, arg InsertSessionPlaceholderParams) (pgtype.UUID, error)

Insert the minimal-fields placeholder row used when the envelope names a fork-parent whose own first turn hasn't landed yet. The caller supplies the UUID; on natural-key conflict, the existing row's id is returned so the FK back-fills naturally when the parent's first real request lands.

Note: this uses `ON CONFLICT ... DO UPDATE SET last_seen_at = last_seen_at` (a no-op write) instead of DO NOTHING so the RETURNING clause still emits the existing row's id — sqlc/pgx treats DO NOTHING RETURNING as "no rows" on conflict.

func (*Queries) ListLeaves

func (q *Queries) ListLeaves(ctx context.Context) ([]Node, error)

func (*Queries) ListNodes

func (q *Queries) ListNodes(ctx context.Context) ([]Node, error)

func (*Queries) ListNodesBySession added in v0.12.0

func (q *Queries) ListNodesBySession(ctx context.Context, sessionID pgtype.UUID) ([]Node, error)

All nodes attributed to a session, ordered by capture time (chronological).

func (*Queries) ListParentRefs

func (q *Queries) ListParentRefs(ctx context.Context) ([]ListParentRefsRow, error)

func (*Queries) ListSessionRecords added in v0.12.0

func (q *Queries) ListSessionRecords(ctx context.Context, arg ListSessionRecordsParams) ([]Session, error)

Paginated list of sessions for an org ordered newest-first (last_seen_at DESC, id DESC). Pass NULL cursor values to start from the beginning.

func (*Queries) ListSessions

func (q *Queries) ListSessions(ctx context.Context, arg ListSessionsParams) ([]Node, error)

func (*Queries) SetNodeSessionID added in v0.10.0

func (q *Queries) SetNodeSessionID(ctx context.Context, arg SetNodeSessionIDParams) error

Stamp session_id onto an already-inserted nodes row. The existing InsertNode query is left intact (additive ALTER added the column with no NOT NULL constraint), so ingest can either use this safety hatch or extend InsertNode in a follow-up. Scoped to (org_id, hash) to match the composite PK introduced in this migration: a write that only matched on hash would clobber rows for unrelated orgs.

func (*Queries) UpdateSessionCounters added in v0.10.0

func (q *Queries) UpdateSessionCounters(ctx context.Context, arg UpdateSessionCountersParams) error

Roll the per-turn counters into the sessions row. Called by ingest after the nodes insert, inside the same Tx.

func (*Queries) UpdateSessionStatus added in v0.13.0

func (q *Queries) UpdateSessionStatus(ctx context.Context, arg UpdateSessionStatusParams) error

Persist the recomputed chain-aware status. has_git_activity is a sticky flag and tool_result_count / tool_error_count are cumulative totals, all accumulated across the session's turns and stems — the caller computes the new values in Go from the prior row state plus this turn's new nodes, so this query just writes them. derived_status mirrors pkg/sessions.DetermineStatus over those signals and the session's latest leaf. Called by ingest in the same Tx as UpdateSessionCounters.

func (*Queries) UpdateUsage

func (q *Queries) UpdateUsage(ctx context.Context, arg UpdateUsageParams) error

func (*Queries) UpsertSession added in v0.10.0

func (q *Queries) UpsertSession(ctx context.Context, arg UpsertSessionParams) (Session, error)

Insert-or-merge keyed by the natural identity (org_id, harness_id, harness_session_id). The caller supplies the UUID for `id` (Postgres 17 has no native UUIDv7, so ingest mints one app-side); on conflict the existing row's id is preserved via RETURNING.

On conflict, mutable fields are merged: last_seen_at is bumped to the caller-supplied `now`, harness_metadata is JSON-merged (last-write-wins per key), and name is updated only when the new value is non-null. auth_subject is overwritten with the caller-supplied value: when a child session's first turn arrived before the parent's, InsertSessionPlaceholder wrote the parent row carrying the *child's* auth_subject; the parent's real upsert here is authoritative and must reclaim attribution. Counters are NOT touched here — UpdateSessionCounters handles that after the nodes insert in the same Tx.

func (*Queries) WithTx

func (q *Queries) WithTx(tx pgx.Tx) *Queries

type Session added in v0.10.0

type Session struct {
	ID                pgtype.UUID
	OrgID             pgtype.UUID
	AuthSubject       string
	HarnessID         string
	HarnessSessionID  string
	Name              pgtype.Text
	Cwd               pgtype.Text
	HarnessVersion    pgtype.Text
	ParentSessionID   pgtype.UUID
	StartedAt         pgtype.Timestamptz
	LastSeenAt        pgtype.Timestamptz
	EndedAt           pgtype.Timestamptz
	HarnessMetadata   []byte
	TotalInputTokens  int64
	TotalOutputTokens int64
	TotalCostUsd      pgtype.Numeric
	TurnCount         int32
	DerivedStatus     string
	HasGitActivity    bool
	ToolResultCount   int32
	ToolErrorCount    int32
}

type SetNodeSessionIDParams added in v0.10.0

type SetNodeSessionIDParams struct {
	SessionID pgtype.UUID
	OrgID     pgtype.UUID
	Hash      string
}

type UpdateSessionCountersParams added in v0.10.0

type UpdateSessionCountersParams struct {
	Now               pgtype.Timestamptz
	TurnCountDelta    int32
	InputTokensDelta  int64
	OutputTokensDelta int64
	CostUsdDelta      pgtype.Numeric
	ID                pgtype.UUID
}

type UpdateSessionStatusParams added in v0.13.0

type UpdateSessionStatusParams struct {
	HasGitActivity  bool
	ToolResultCount int32
	ToolErrorCount  int32
	DerivedStatus   string
	ID              pgtype.UUID
}

type UpdateUsageParams

type UpdateUsageParams struct {
	Hash                     string
	PromptTokens             pgtype.Int4
	CompletionTokens         pgtype.Int4
	TotalTokens              pgtype.Int4
	CacheCreationInputTokens pgtype.Int4
	CacheReadInputTokens     pgtype.Int4
	TotalDurationNs          pgtype.Int8
	PromptDurationNs         pgtype.Int8
}

type UpsertSessionParams added in v0.10.0

type UpsertSessionParams struct {
	ID               pgtype.UUID
	OrgID            pgtype.UUID
	AuthSubject      string
	HarnessID        string
	HarnessSessionID string
	Name             pgtype.Text
	Cwd              pgtype.Text
	HarnessVersion   pgtype.Text
	ParentSessionID  pgtype.UUID
	Now              pgtype.Timestamptz
	HarnessMetadata  []byte
}

Jump to

Keyboard shortcuts

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