feat(postgres): State Store schema and sqlc queries, with the claim path proven on PG 18

goose migration 0001 lands the twelve State Store tables on Postgres, and sqlc generates the task queries from it. Two behaviours that genuinely differ from SQLite are pinned by tests against a real PG 18: claiming takes the oldest queued row with FOR UPDATE SKIP LOCKED (without the clause a second claimer blocks, which the test shows by timing out), and every column behind a Go int is bigint -- SQLite's INTEGER is 64-bit, and the chat issue-number allocator seeds at 10^15, which does not fit an int4.

task db:generate writes the committed postgresdb package; task db:check regenerates it in the gate, as proto:check and ui:check do.

The remaining store methods (events, resources, identities, the status tables) still run on SQLite: porting them is the rest of archie-core-7r0x.2.
This commit is contained in:
sam committed 2026-09-24 01:18:19 +10:00
1 parent c6df4b4a54
commit a69f9c81c2
11 files changed
+1408

No files matched your search

@@ -0,0 +1,191 @@
-- State Store schema: tasks, transitions, events, resources, the control-plane
-- resource documents, channel/apply status, config snapshots and identities.
--
-- Translations from the SQLite schema this replaces, and why:
-- * AUTOINCREMENT becomes GENERATED BY DEFAULT AS IDENTITY. BY DEFAULT
-- rather than ALWAYS so the one-time import can insert historical ids and
-- then advance the sequence.
-- * Times become timestamptz. SQLite stored them as fixed-width text and
-- ordered them lexicographically; Postgres orders them natively, so the
-- layout normalisation that step needed does not exist here.
-- * Blobs become bytea; the 0/1 flag columns become boolean.
-- * `events.data` stays text even though it holds JSON: nothing queries into
-- it, and jsonb would reorder keys and reject what the writer accepted.
-- * identity_aliases is unique on lower(alias) rather than using citext, so
-- a deployment needs no extension.
-- * Every column behind a Go int is bigint. SQLite's INTEGER is 64-bit, so
-- a 32-bit column here would narrow silently: the chat issue-number
-- allocator seeds at 10^15, which does not fit an int4.
-- +goose Up
CREATE TABLE tasks (
id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
owner text NOT NULL,
repo text NOT NULL,
issue_number bigint NOT NULL,
title text NOT NULL DEFAULT '',
body text NOT NULL DEFAULT '',
labels text NOT NULL DEFAULT '',
status text NOT NULL DEFAULT 'queued',
workflow text NOT NULL DEFAULT '',
stage text NOT NULL DEFAULT '',
branch text NOT NULL DEFAULT '',
plan text NOT NULL DEFAULT '',
notes text NOT NULL DEFAULT '',
pr_number bigint NOT NULL DEFAULT 0,
tokens_used bigint NOT NULL DEFAULT 0,
iterations bigint NOT NULL DEFAULT 0,
attempt bigint NOT NULL DEFAULT 0,
park_reason text NOT NULL DEFAULT '',
watch_comment_id bigint NOT NULL DEFAULT 0,
park_class text NOT NULL DEFAULT 'needs_human',
remediation_rounds bigint NOT NULL DEFAULT 0,
retry_count bigint NOT NULL DEFAULT 0,
source text NOT NULL DEFAULT 'forge',
identity text NOT NULL DEFAULT '',
binding_id text NOT NULL DEFAULT '',
binding_version bigint NOT NULL DEFAULT 0,
review_payload text NOT NULL DEFAULT '',
workflow_definition_version bigint NOT NULL DEFAULT 0,
workflow_definition_digest text NOT NULL DEFAULT '',
workflow_definition_yaml text NOT NULL DEFAULT '',
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (owner, repo, issue_number)
);
CREATE INDEX idx_tasks_pr ON tasks (owner, repo, pr_number);
CREATE INDEX idx_tasks_status ON tasks (status);
CREATE TABLE transitions (
id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
task_id bigint NOT NULL,
at timestamptz NOT NULL DEFAULT now(),
from_status text NOT NULL,
to_status text NOT NULL,
detail text NOT NULL DEFAULT ''
);
CREATE INDEX idx_transitions_task ON transitions (task_id, id);
CREATE TABLE events (
id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
at timestamptz NOT NULL,
kind text NOT NULL,
task_id bigint NOT NULL DEFAULT 0,
repo text NOT NULL DEFAULT '',
issue bigint NOT NULL DEFAULT 0,
workflow text NOT NULL DEFAULT '',
stage text NOT NULL DEFAULT '',
attempt bigint NOT NULL DEFAULT 0,
actor_id text NOT NULL DEFAULT '',
actor_kind text NOT NULL DEFAULT '',
principal_id text NOT NULL DEFAULT '',
detail text NOT NULL DEFAULT '',
data text NOT NULL DEFAULT '{}'
);
CREATE INDEX idx_events_task ON events (task_id, id);
CREATE INDEX idx_events_kind ON events (kind, id);
CREATE INDEX idx_events_at ON events (at, id);
CREATE TABLE resources (
kind text PRIMARY KEY,
value bytea NOT NULL,
version bigint NOT NULL,
updated_at timestamptz NOT NULL
);
CREATE TABLE resource_history (
id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
kind text NOT NULL,
value bytea NOT NULL,
version bigint NOT NULL,
actor text NOT NULL,
source text NOT NULL,
request_id text NOT NULL,
expected_version bigint NOT NULL,
current_version bigint NOT NULL,
at timestamptz NOT NULL
);
CREATE INDEX idx_resource_history_kind_version ON resource_history (kind, version);
-- The request-ID idempotency key is per kind, not global: a resource write
-- replays only the same kind's prior write (resourceByRequest).
CREATE UNIQUE INDEX idx_resource_history_kind_request ON resource_history (kind, request_id);
CREATE TABLE channel_status (
id text PRIMARY KEY,
name text NOT NULL DEFAULT '',
state text NOT NULL DEFAULT '',
detail text NOT NULL DEFAULT '',
configured boolean NOT NULL DEFAULT false,
reload_supported boolean NOT NULL DEFAULT false,
observed_at timestamptz NOT NULL
);
CREATE TABLE apply_status (
process text NOT NULL,
kind text NOT NULL,
applied_version bigint NOT NULL DEFAULT 0,
error text NOT NULL DEFAULT '',
reported_at timestamptz NOT NULL,
PRIMARY KEY (process, kind)
);
CREATE TABLE config_snapshot (
id bigint PRIMARY KEY CHECK (id = 1),
schema text NOT NULL DEFAULT '',
document text NOT NULL DEFAULT '',
published_at timestamptz NOT NULL
);
CREATE TABLE identities (
id text PRIMARY KEY,
kind text NOT NULL,
display_name text NOT NULL,
lifecycle text NOT NULL,
version bigint NOT NULL,
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL
);
CREATE TABLE identity_aliases (
alias text PRIMARY KEY,
identity_id text NOT NULL REFERENCES identities (id)
);
CREATE UNIQUE INDEX idx_identity_aliases_alias ON identity_aliases (lower(alias));
CREATE TABLE identity_events (
id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
identity_id text NOT NULL,
event_type text NOT NULL,
from_lifecycle text NOT NULL,
to_lifecycle text NOT NULL,
display_name text NOT NULL,
actor_id text NOT NULL,
source text NOT NULL,
request_id text NOT NULL UNIQUE,
at timestamptz NOT NULL
);
CREATE INDEX idx_identity_events_identity ON identity_events (identity_id, id);
CREATE TABLE identity_subjects (
issuer text NOT NULL,
subject text NOT NULL,
identity_id text NOT NULL REFERENCES identities (id),
bound_at timestamptz NOT NULL,
PRIMARY KEY (issuer, subject)
);
-- +goose Down
DROP TABLE identity_subjects;
DROP TABLE identity_events;
DROP TABLE identity_aliases;
DROP TABLE identities;
DROP TABLE config_snapshot;
DROP TABLE apply_status;
DROP TABLE channel_status;
DROP TABLE resource_history;
DROP TABLE resources;
DROP TABLE events;
DROP TABLE transitions;
DROP TABLE tasks;
@@ -4,6 +4,7 @@ package postgres
import (
"context"
"embed"
"errors"
"fmt"
"io/fs"
@@ -17,6 +18,19 @@ import (
// minServerVersion is PostgreSQL 18 in server_version_num form.
const minServerVersion = 180000
//go:embed migrations/*.sql
var migrations embed.FS
// Migrations is the State Store schema, rooted at the migration files.
func Migrations() fs.FS {
sub, err := fs.Sub(migrations, "migrations")
if err != nil {
// Unreachable: the pattern above embeds the directory.
panic(err)
}
return sub
}
// ErrServerTooOld is returned for a server older than PostgreSQL 18.
var ErrServerTooOld = errors.New("postgres: server is older than PostgreSQL 18")
@@ -0,0 +1,32 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
package postgresdb
import (
"context"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
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
}
func New(db DBTX) *Queries {
return &Queries{db: db}
}
type Queries struct {
db DBTX
}
func (q *Queries) WithTx(tx pgx.Tx) *Queries {
return &Queries{
db: tx,
}
}
@@ -0,0 +1,150 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
package postgresdb
import (
"time"
)
type ApplyStatus struct {
Process string
Kind string
AppliedVersion int64
Error string
ReportedAt time.Time
}
type ChannelStatus struct {
ID string
Name string
State string
Detail string
Configured bool
ReloadSupported bool
ObservedAt time.Time
}
type ConfigSnapshot struct {
ID int64
Schema string
Document string
PublishedAt time.Time
}
type Event struct {
ID int64
At time.Time
Kind string
TaskID int64
Repo string
Issue int64
Workflow string
Stage string
Attempt int64
ActorID string
ActorKind string
PrincipalID string
Detail string
Data string
}
type Identity struct {
ID string
Kind string
DisplayName string
Lifecycle string
Version int64
CreatedAt time.Time
UpdatedAt time.Time
}
type IdentityAlias struct {
Alias string
IdentityID string
}
type IdentityEvent struct {
ID int64
IdentityID string
EventType string
FromLifecycle string
ToLifecycle string
DisplayName string
ActorID string
Source string
RequestID string
At time.Time
}
type IdentitySubject struct {
Issuer string
Subject string
IdentityID string
BoundAt time.Time
}
type Resource struct {
Kind string
Value []byte
Version int64
UpdatedAt time.Time
}
type ResourceHistory struct {
ID int64
Kind string
Value []byte
Version int64
Actor string
Source string
RequestID string
ExpectedVersion int64
CurrentVersion int64
At time.Time
}
type Task struct {
ID int64
Owner string
Repo string
IssueNumber int64
Title string
Body string
Labels string
Status string
Workflow string
Stage string
Branch string
Plan string
Notes string
PrNumber int64
TokensUsed int64
Iterations int64
Attempt int64
ParkReason string
WatchCommentID int64
ParkClass string
RemediationRounds int64
RetryCount int64
Source string
Identity string
BindingID string
BindingVersion int64
ReviewPayload string
WorkflowDefinitionVersion int64
WorkflowDefinitionDigest string
WorkflowDefinitionYaml string
CreatedAt time.Time
UpdatedAt time.Time
}
type Transition struct {
ID int64
TaskID int64
At time.Time
FromStatus string
ToStatus string
Detail string
}
@@ -0,0 +1,567 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: tasks.sql
package postgresdb
import (
"context"
"time"
)
const claimNextTask = `-- name: ClaimNextTask :one
UPDATE tasks
SET status = 'running', attempt = attempt + 1, updated_at = now()
WHERE id = (
SELECT id FROM tasks
WHERE status = 'queued'
ORDER BY id
FOR UPDATE SKIP LOCKED
LIMIT 1
)
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, stage, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at
`
// FOR UPDATE SKIP LOCKED replaces the SQLite single-writer assumption: two
// claimers running at once take different rows instead of blocking, so the
// daemon no longer depends on holding the only connection to the file.
func (q *Queries) ClaimNextTask(ctx context.Context) (Task, error) {
row := q.db.QueryRow(ctx, claimNextTask)
var i Task
err := row.Scan(
&i.ID,
&i.Owner,
&i.Repo,
&i.IssueNumber,
&i.Title,
&i.Body,
&i.Labels,
&i.Status,
&i.Workflow,
&i.Stage,
&i.Branch,
&i.Plan,
&i.Notes,
&i.PrNumber,
&i.TokensUsed,
&i.Iterations,
&i.Attempt,
&i.ParkReason,
&i.WatchCommentID,
&i.ParkClass,
&i.RemediationRounds,
&i.RetryCount,
&i.Source,
&i.Identity,
&i.BindingID,
&i.BindingVersion,
&i.ReviewPayload,
&i.WorkflowDefinitionVersion,
&i.WorkflowDefinitionDigest,
&i.WorkflowDefinitionYaml,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const clearTerminalTasks = `-- name: ClearTerminalTasks :execrows
DELETE FROM tasks
WHERE status IN ('merged', 'rejected', 'dead', 'closed_wont_do')
`
func (q *Queries) ClearTerminalTasks(ctx context.Context) (int64, error) {
result, err := q.db.Exec(ctx, clearTerminalTasks)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const countTasksByStatus = `-- name: CountTasksByStatus :many
SELECT status, count(*)::int AS count FROM tasks GROUP BY status
`
type CountTasksByStatusRow struct {
Status string
Count int32
}
func (q *Queries) CountTasksByStatus(ctx context.Context) ([]CountTasksByStatusRow, error) {
rows, err := q.db.Query(ctx, countTasksByStatus)
if err != nil {
return nil, err
}
defer rows.Close()
var items []CountTasksByStatusRow
for rows.Next() {
var i CountTasksByStatusRow
if err := rows.Scan(&i.Status, &i.Count); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const insertChatTask = `-- name: InsertChatTask :one
INSERT INTO tasks (owner, repo, issue_number, title, body, labels, workflow, source, identity)
VALUES (
$1, $2,
COALESCE((
SELECT MAX(existing.issue_number) FROM tasks existing
WHERE existing.owner = $1
AND existing.repo = $2
AND existing.source = 'chat'
), $3) + 1,
$4, $5, 'chat', $6, 'chat', $7
)
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, stage, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at
`
type InsertChatTaskParams struct {
Owner string
Repo string
FallbackIssueNumber int64
Title string
Body string
Workflow string
Identity string
}
// The synthetic issue number keeps chat-sourced tasks off the forge's real
// issue numbers; this allocator is the single source of truth for it.
// fallback_issue_number is only the seed for a repo's first chat task -- the
// passed value is not the issue number that lands.
func (q *Queries) InsertChatTask(ctx context.Context, arg InsertChatTaskParams) (Task, error) {
row := q.db.QueryRow(ctx, insertChatTask,
arg.Owner,
arg.Repo,
arg.FallbackIssueNumber,
arg.Title,
arg.Body,
arg.Workflow,
arg.Identity,
)
var i Task
err := row.Scan(
&i.ID,
&i.Owner,
&i.Repo,
&i.IssueNumber,
&i.Title,
&i.Body,
&i.Labels,
&i.Status,
&i.Workflow,
&i.Stage,
&i.Branch,
&i.Plan,
&i.Notes,
&i.PrNumber,
&i.TokensUsed,
&i.Iterations,
&i.Attempt,
&i.ParkReason,
&i.WatchCommentID,
&i.ParkClass,
&i.RemediationRounds,
&i.RetryCount,
&i.Source,
&i.Identity,
&i.BindingID,
&i.BindingVersion,
&i.ReviewPayload,
&i.WorkflowDefinitionVersion,
&i.WorkflowDefinitionDigest,
&i.WorkflowDefinitionYaml,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const insertTransition = `-- name: InsertTransition :exec
INSERT INTO transitions (task_id, from_status, to_status, detail)
VALUES ($1, $2, $3, $4)
`
type InsertTransitionParams struct {
TaskID int64
FromStatus string
ToStatus string
Detail string
}
func (q *Queries) InsertTransition(ctx context.Context, arg InsertTransitionParams) error {
_, err := q.db.Exec(ctx, insertTransition,
arg.TaskID,
arg.FromStatus,
arg.ToStatus,
arg.Detail,
)
return err
}
const listTaskSummaries = `-- name: ListTaskSummaries :many
SELECT id, owner, repo, issue_number, title, status, workflow, stage,
pr_number, tokens_used, iterations, attempt, park_reason, retry_count,
created_at, updated_at, plan, source, identity, binding_id, binding_version
FROM tasks ORDER BY updated_at DESC LIMIT $1
`
type ListTaskSummariesRow struct {
ID int64
Owner string
Repo string
IssueNumber int64
Title string
Status string
Workflow string
Stage string
PrNumber int64
TokensUsed int64
Iterations int64
Attempt int64
ParkReason string
RetryCount int64
CreatedAt time.Time
UpdatedAt time.Time
Plan string
Source string
Identity string
BindingID string
BindingVersion int64
}
// The dashboard's list. This projection is deliberately narrow: Plan gates
// the "Decision required" panel and Source labels the row, and widening it
// back would send rows without them.
func (q *Queries) ListTaskSummaries(ctx context.Context, limit int32) ([]ListTaskSummariesRow, error) {
rows, err := q.db.Query(ctx, listTaskSummaries, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListTaskSummariesRow
for rows.Next() {
var i ListTaskSummariesRow
if err := rows.Scan(
&i.ID,
&i.Owner,
&i.Repo,
&i.IssueNumber,
&i.Title,
&i.Status,
&i.Workflow,
&i.Stage,
&i.PrNumber,
&i.TokensUsed,
&i.Iterations,
&i.Attempt,
&i.ParkReason,
&i.RetryCount,
&i.CreatedAt,
&i.UpdatedAt,
&i.Plan,
&i.Source,
&i.Identity,
&i.BindingID,
&i.BindingVersion,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const parkTask = `-- name: ParkTask :execrows
UPDATE tasks
SET status = 'parked', park_reason = $2, park_class = $3, updated_at = now()
WHERE id = $1 AND status = $4
`
type ParkTaskParams struct {
ID int64
ParkReason string
ParkClass string
Status string
}
func (q *Queries) ParkTask(ctx context.Context, arg ParkTaskParams) (int64, error) {
result, err := q.db.Exec(ctx, parkTask,
arg.ID,
arg.ParkReason,
arg.ParkClass,
arg.Status,
)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const recoverStaleTasks = `-- name: RecoverStaleTasks :execrows
UPDATE tasks SET status = 'queued', updated_at = now() WHERE status = 'running'
`
func (q *Queries) RecoverStaleTasks(ctx context.Context) (int64, error) {
result, err := q.db.Exec(ctx, recoverStaleTasks)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const stampTaskBinding = `-- name: StampTaskBinding :exec
UPDATE tasks SET binding_id = $2, binding_version = $3 WHERE id = $1
`
type StampTaskBindingParams struct {
ID int64
BindingID string
BindingVersion int64
}
func (q *Queries) StampTaskBinding(ctx context.Context, arg StampTaskBindingParams) error {
_, err := q.db.Exec(ctx, stampTaskBinding, arg.ID, arg.BindingID, arg.BindingVersion)
return err
}
const taskByID = `-- name: TaskByID :one
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, stage, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at FROM tasks WHERE id = $1
`
func (q *Queries) TaskByID(ctx context.Context, id int64) (Task, error) {
row := q.db.QueryRow(ctx, taskByID, id)
var i Task
err := row.Scan(
&i.ID,
&i.Owner,
&i.Repo,
&i.IssueNumber,
&i.Title,
&i.Body,
&i.Labels,
&i.Status,
&i.Workflow,
&i.Stage,
&i.Branch,
&i.Plan,
&i.Notes,
&i.PrNumber,
&i.TokensUsed,
&i.Iterations,
&i.Attempt,
&i.ParkReason,
&i.WatchCommentID,
&i.ParkClass,
&i.RemediationRounds,
&i.RetryCount,
&i.Source,
&i.Identity,
&i.BindingID,
&i.BindingVersion,
&i.ReviewPayload,
&i.WorkflowDefinitionVersion,
&i.WorkflowDefinitionDigest,
&i.WorkflowDefinitionYaml,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const taskByIssue = `-- name: TaskByIssue :one
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, stage, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at FROM tasks WHERE owner = $1 AND repo = $2 AND issue_number = $3
`
type TaskByIssueParams struct {
Owner string
Repo string
IssueNumber int64
}
func (q *Queries) TaskByIssue(ctx context.Context, arg TaskByIssueParams) (Task, error) {
row := q.db.QueryRow(ctx, taskByIssue, arg.Owner, arg.Repo, arg.IssueNumber)
var i Task
err := row.Scan(
&i.ID,
&i.Owner,
&i.Repo,
&i.IssueNumber,
&i.Title,
&i.Body,
&i.Labels,
&i.Status,
&i.Workflow,
&i.Stage,
&i.Branch,
&i.Plan,
&i.Notes,
&i.PrNumber,
&i.TokensUsed,
&i.Iterations,
&i.Attempt,
&i.ParkReason,
&i.WatchCommentID,
&i.ParkClass,
&i.RemediationRounds,
&i.RetryCount,
&i.Source,
&i.Identity,
&i.BindingID,
&i.BindingVersion,
&i.ReviewPayload,
&i.WorkflowDefinitionVersion,
&i.WorkflowDefinitionDigest,
&i.WorkflowDefinitionYaml,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const taskByPR = `-- name: TaskByPR :one
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, stage, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at FROM tasks WHERE owner = $1 AND repo = $2 AND pr_number = $3
`
type TaskByPRParams struct {
Owner string
Repo string
PrNumber int64
}
func (q *Queries) TaskByPR(ctx context.Context, arg TaskByPRParams) (Task, error) {
row := q.db.QueryRow(ctx, taskByPR, arg.Owner, arg.Repo, arg.PrNumber)
var i Task
err := row.Scan(
&i.ID,
&i.Owner,
&i.Repo,
&i.IssueNumber,
&i.Title,
&i.Body,
&i.Labels,
&i.Status,
&i.Workflow,
&i.Stage,
&i.Branch,
&i.Plan,
&i.Notes,
&i.PrNumber,
&i.TokensUsed,
&i.Iterations,
&i.Attempt,
&i.ParkReason,
&i.WatchCommentID,
&i.ParkClass,
&i.RemediationRounds,
&i.RetryCount,
&i.Source,
&i.Identity,
&i.BindingID,
&i.BindingVersion,
&i.ReviewPayload,
&i.WorkflowDefinitionVersion,
&i.WorkflowDefinitionDigest,
&i.WorkflowDefinitionYaml,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const transitionTask = `-- name: TransitionTask :execrows
UPDATE tasks
SET status = $2,
park_reason = CASE WHEN $2 = 'parked' THEN $3 ELSE park_reason END,
park_class = CASE WHEN $2 = 'parked' THEN $4 ELSE park_class END,
updated_at = now()
WHERE id = $1 AND status = $5
`
type TransitionTaskParams struct {
ID int64
Status string
ParkReason string
ParkClass string
Status_2 string
}
// Arriving at 'parked' also records why. The class is normalized by the
// caller, so an unknown value persists as needs_human rather than as itself.
func (q *Queries) TransitionTask(ctx context.Context, arg TransitionTaskParams) (int64, error) {
result, err := q.db.Exec(ctx, transitionTask,
arg.ID,
arg.Status,
arg.ParkReason,
arg.ParkClass,
arg.Status_2,
)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const updateTask = `-- name: UpdateTask :exec
UPDATE tasks SET workflow = $2, stage = $3, branch = $4, plan = $5, notes = $6,
pr_number = $7, tokens_used = $8, iterations = $9, park_reason = $10,
watch_comment_id = $11, retry_count = $12, remediation_rounds = $13,
review_payload = $14, workflow_definition_version = $15,
workflow_definition_digest = $16, workflow_definition_yaml = $17,
updated_at = now()
WHERE id = $1
`
type UpdateTaskParams struct {
ID int64
Workflow string
Stage string
Branch string
Plan string
Notes string
PrNumber int64
TokensUsed int64
Iterations int64
ParkReason string
WatchCommentID int64
RetryCount int64
RemediationRounds int64
ReviewPayload string
WorkflowDefinitionVersion int64
WorkflowDefinitionDigest string
WorkflowDefinitionYaml string
}
func (q *Queries) UpdateTask(ctx context.Context, arg UpdateTaskParams) error {
_, err := q.db.Exec(ctx, updateTask,
arg.ID,
arg.Workflow,
arg.Stage,
arg.Branch,
arg.Plan,
arg.Notes,
arg.PrNumber,
arg.TokensUsed,
arg.Iterations,
arg.ParkReason,
arg.WatchCommentID,
arg.RetryCount,
arg.RemediationRounds,
arg.ReviewPayload,
arg.WorkflowDefinitionVersion,
arg.WorkflowDefinitionDigest,
arg.WorkflowDefinitionYaml,
)
return err
}
@@ -0,0 +1,91 @@
-- name: ClaimNextTask :one
-- FOR UPDATE SKIP LOCKED replaces the SQLite single-writer assumption: two
-- claimers running at once take different rows instead of blocking, so the
-- daemon no longer depends on holding the only connection to the file.
UPDATE tasks
SET status = 'running', attempt = attempt + 1, updated_at = now()
WHERE id = (
SELECT id FROM tasks
WHERE status = 'queued'
ORDER BY id
FOR UPDATE SKIP LOCKED
LIMIT 1
)
RETURNING *;
-- name: TaskByID :one
SELECT * FROM tasks WHERE id = $1;
-- name: TaskByIssue :one
SELECT * FROM tasks WHERE owner = $1 AND repo = $2 AND issue_number = $3;
-- name: TaskByPR :one
SELECT * FROM tasks WHERE owner = $1 AND repo = $2 AND pr_number = $3;
-- name: ListTaskSummaries :many
-- The dashboard's list. This projection is deliberately narrow: Plan gates
-- the "Decision required" panel and Source labels the row, and widening it
-- back would send rows without them.
SELECT id, owner, repo, issue_number, title, status, workflow, stage,
pr_number, tokens_used, iterations, attempt, park_reason, retry_count,
created_at, updated_at, plan, source, identity, binding_id, binding_version
FROM tasks ORDER BY updated_at DESC LIMIT $1;
-- name: CountTasksByStatus :many
SELECT status, count(*)::int AS count FROM tasks GROUP BY status;
-- name: InsertChatTask :one
-- The synthetic issue number keeps chat-sourced tasks off the forge's real
-- issue numbers; this allocator is the single source of truth for it.
-- fallback_issue_number is only the seed for a repo's first chat task -- the
-- passed value is not the issue number that lands.
INSERT INTO tasks (owner, repo, issue_number, title, body, labels, workflow, source, identity)
VALUES (
sqlc.arg(owner), sqlc.arg(repo),
COALESCE((
SELECT MAX(existing.issue_number) FROM tasks existing
WHERE existing.owner = sqlc.arg(owner)
AND existing.repo = sqlc.arg(repo)
AND existing.source = 'chat'
), sqlc.arg(fallback_issue_number)) + 1,
sqlc.arg(title), sqlc.arg(body), 'chat', sqlc.arg(workflow), 'chat', sqlc.arg(identity)
)
RETURNING *;
-- name: StampTaskBinding :exec
UPDATE tasks SET binding_id = $2, binding_version = $3 WHERE id = $1;
-- name: UpdateTask :exec
UPDATE tasks SET workflow = $2, stage = $3, branch = $4, plan = $5, notes = $6,
pr_number = $7, tokens_used = $8, iterations = $9, park_reason = $10,
watch_comment_id = $11, retry_count = $12, remediation_rounds = $13,
review_payload = $14, workflow_definition_version = $15,
workflow_definition_digest = $16, workflow_definition_yaml = $17,
updated_at = now()
WHERE id = $1;
-- name: TransitionTask :execrows
-- Arriving at 'parked' also records why. The class is normalized by the
-- caller, so an unknown value persists as needs_human rather than as itself.
UPDATE tasks
SET status = $2,
park_reason = CASE WHEN $2 = 'parked' THEN $3 ELSE park_reason END,
park_class = CASE WHEN $2 = 'parked' THEN $4 ELSE park_class END,
updated_at = now()
WHERE id = $1 AND status = $5;
-- name: InsertTransition :exec
INSERT INTO transitions (task_id, from_status, to_status, detail)
VALUES ($1, $2, $3, $4);
-- name: ParkTask :execrows
UPDATE tasks
SET status = 'parked', park_reason = $2, park_class = $3, updated_at = now()
WHERE id = $1 AND status = $4;
-- name: ClearTerminalTasks :execrows
DELETE FROM tasks
WHERE status IN ('merged', 'rejected', 'dead', 'closed_wont_do');
-- name: RecoverStaleTasks :execrows
UPDATE tasks SET status = 'queued', updated_at = now() WHERE status = 'running';
@@ -0,0 +1,18 @@
version: "2"
sql:
- engine: "postgresql"
schema: "migrations"
queries: "queries"
gen:
go:
package: "postgresdb"
out: "postgresdb"
sql_package: "pgx/v5"
# The store's list methods return nil for an empty result and its
# callers test that; empty slices here would be a silent change.
emit_empty_slices: false
overrides:
# The domain carries every timestamp as time.Time; pgtype would put
# a .Time unwrap at each of the mapping sites instead.
- db_type: "timestamptz"
go_type: "time.Time"
@@ -0,0 +1,163 @@
package postgres
import (
"errors"
"testing"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
)
// syntheticIssueBase mirrors the store's chat issue-number seed. It is the
// fallback for a repo's first chat task, not the number that lands: the
// allocator adds one to it.
const syntheticIssueBase = 1_000_000_000_000_000
// migrated is a pool with the State Store schema applied, and its queries.
func migrated(t *testing.T) (*pgxpool.Pool, *postgresdb.Queries) {
t.Helper()
pool, err := Open(t.Context(), pgtest.URL(t))
if err != nil {
t.Fatalf("Open: %v", err)
}
t.Cleanup(pool.Close)
if err := Migrate(t.Context(), pool, Migrations()); err != nil {
t.Fatalf("Migrate: %v", err)
}
return pool, postgresdb.New(pool)
}
// queriesFor is migrated's queries without the pool, for tests that only read
// and write through sqlc.
func queriesFor(t *testing.T) *postgresdb.Queries {
t.Helper()
_, q := migrated(t)
return q
}
// insertChatTask queues one chat-sourced task.
func insertChatTask(t *testing.T, q *postgresdb.Queries) postgresdb.Task {
t.Helper()
task, err := q.InsertChatTask(t.Context(), postgresdb.InsertChatTaskParams{
Owner: "acme", Repo: "widget", Title: "t", Body: "b",
Workflow: "tdd", Identity: "bot",
FallbackIssueNumber: syntheticIssueBase,
})
if err != nil {
t.Fatalf("InsertChatTask: %v", err)
}
return task
}
func TestSchemaAppliesAndTasksRoundTrip(t *testing.T) {
q := queriesFor(t)
task := insertChatTask(t, q)
if task.Status != "queued" {
t.Fatalf("new task status = %q, want queued", task.Status)
}
if task.CreatedAt.IsZero() || task.UpdatedAt.IsZero() {
t.Error("created_at/updated_at were not populated")
}
if task.IssueNumber != syntheticIssueBase+1 {
t.Fatalf("first chat task issue number = %d, want %d", task.IssueNumber, syntheticIssueBase+1)
}
got, err := q.TaskByIssue(t.Context(), postgresdb.TaskByIssueParams{
Owner: task.Owner, Repo: task.Repo, IssueNumber: task.IssueNumber,
})
if err != nil {
t.Fatalf("TaskByIssue: %v", err)
}
if got.ID != task.ID {
t.Fatalf("TaskByIssue = %d, want %d", got.ID, task.ID)
}
}
// The chat allocator hands out the next number per repo, so two chat tasks in
// one repo never share an issue number.
func TestChatIssueNumberAllocatorIsPerRepo(t *testing.T) {
q := queriesFor(t)
first := insertChatTask(t, q)
second := insertChatTask(t, q)
if second.IssueNumber != first.IssueNumber+1 {
t.Fatalf("second chat issue number = %d, want %d", second.IssueNumber, first.IssueNumber+1)
}
}
// The issue-number uniqueness the SQLite schema carried as a table constraint
// survives the move.
func TestTaskIssueNumberIsUnique(t *testing.T) {
pool, q := migrated(t)
task := insertChatTask(t, q)
_, err := pool.Exec(t.Context(), `
INSERT INTO tasks (owner, repo, issue_number) VALUES ($1, $2, $3)`,
task.Owner, task.Repo, task.IssueNumber)
if err == nil {
t.Fatal("a second task for the same owner/repo/issue was accepted, want the unique constraint refused it")
}
}
// Claiming takes the oldest queued task, in id order, and counts the attempt.
func TestClaimNextTakesTheOldestAndCountsTheAttempt(t *testing.T) {
q := queriesFor(t)
first := insertChatTask(t, q)
second := insertChatTask(t, q)
claimed, err := q.ClaimNextTask(t.Context())
if err != nil {
t.Fatalf("ClaimNextTask: %v", err)
}
if claimed.ID != first.ID || claimed.Status != "running" || claimed.Attempt != 1 {
t.Fatalf("first claim = {id:%d status:%q attempt:%d}, want {id:%d running 1}", claimed.ID, claimed.Status, claimed.Attempt, first.ID)
}
claimed, err = q.ClaimNextTask(t.Context())
if err != nil {
t.Fatalf("second ClaimNextTask: %v", err)
}
if claimed.ID != second.ID {
t.Fatalf("second claim = %d, want %d", claimed.ID, second.ID)
}
if _, err := q.ClaimNextTask(t.Context()); !errors.Is(err, pgx.ErrNoRows) {
t.Fatalf("claim on an empty queue = %v, want pgx.ErrNoRows", err)
}
}
// A claimer must not wait behind a row another transaction holds: it takes the
// next one. This is what FOR UPDATE SKIP LOCKED buys over the SQLite version,
// where a second claimer could only ever have blocked on the writer lock.
func TestClaimSkipsARowAnotherTransactionHolds(t *testing.T) {
pool, q := migrated(t)
held := insertChatTask(t, q)
free := insertChatTask(t, q)
tx, err := pool.Begin(t.Context())
if err != nil {
t.Fatal(err)
}
defer func() { _ = tx.Rollback(t.Context()) }()
var lockedID int64
if err := tx.QueryRow(t.Context(),
`SELECT id FROM tasks WHERE status = 'queued' ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1`,
).Scan(&lockedID); err != nil {
t.Fatalf("lock the oldest queued row: %v", err)
}
if lockedID != held.ID {
t.Fatalf("locked row %d, want the oldest queued row %d", lockedID, held.ID)
}
claimed, err := q.ClaimNextTask(t.Context())
if err != nil {
t.Fatalf("ClaimNextTask while a row is held: %v", err)
}
if claimed.ID != free.ID {
t.Fatalf("claimed %d while %d was held, want the skipped-to row %d", claimed.ID, free.ID, held.ID)
}
}