Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,10 @@ welcome.
bisection counters through a pluggable store.~~ Completed with an opt-in bbolt
implementation via `SHUNT_STATE_PATH`; restored active batches are re-staged
on restart.
- External durable stores: adapt the checkpoint boundary to Postgres or other
deployment-specific backends without changing the engine state machine.
- ~~Postgres checkpoint store: schema plus a tested implementation of the engine
checkpoint boundary can persist the per-`(repo, base)` work queue, active batch
metadata, linger timestamp, and bisection counters.~~ Completed as a reference
external store; runtime configuration remains a follow-up.
- ~~Webhooks: react to `auto_merge_pull_request` (and `push`) to wake reconcile
immediately, keeping the poll as a backstop.~~ Completed: `/webhook` wakes the
reconcile loop for auto-merge, pull-request, review, status, and push events
Expand Down
19 changes: 19 additions & 0 deletions docs/state.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Durable queue state

shunt's default durable store is the built-in bbolt implementation enabled by
`SHUNT_STATE_PATH`. The `internal/checkpoint/postgres` package is a reference
Postgres implementation of the same engine checkpoint contract for deployments
that need an external database-backed store.

The Postgres store persists one snapshot per `(owner, repo, base)` queue in
`shunt_queue_state`:

- pending candidate batches (`pending` JSONB)
- active staging batches, including PR numbers, tested head SHAs, staging branch/SHA, base generation, and terminal outcome (`active` JSONB)
- batch-linger start time
- base generation and staging branch sequence counters

Call `postgres.New(db).ApplyMigrations(ctx)` once at startup before using the
store. Runtime configuration is intentionally not exposed yet; bbolt remains the
built-in configured store while external stores settle behind the shared
checkpoint boundary.
25 changes: 25 additions & 0 deletions internal/checkpoint/bolt/bolt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package bolt

import (
"context"
"encoding/json"
"errors"
"reflect"
"testing"
Expand Down Expand Up @@ -96,3 +97,27 @@ func TestStoreHonorsCanceledContext(t *testing.T) {
t.Fatalf("save canceled err = %v, want context.Canceled", err)
}
}

func TestQueueSnapshotJSONReadsLegacyFieldNames(t *testing.T) {
data := []byte(`{
"Key":{"Owner":"o","Repo":"r","Base":"main"},
"Pending":[[1]],
"Active":[{"PRs":[{"Number":1,"HeadSHA":"head-1"}],"StagingBranch":"mq/main/staging","StagingSHA":"stage-1","BaseGeneration":2,"Outcome":"failure"}],
"LingerSince":"0001-01-01T00:00:00Z",
"BaseGeneration":2,
"StagingSequence":7
}`)
var snapshot checkpoint.QueueSnapshot
if err := json.Unmarshal(data, &snapshot); err != nil {
t.Fatalf("unmarshal snapshot: %v", err)
}
if err := snapshot.Validate(); err != nil {
t.Fatalf("validate snapshot: %v", err)
}
if got := snapshot.Active[0].PRs[0].HeadSHA; got != "head-1" {
t.Fatalf("head SHA = %q, want head-1", got)
}
if got := snapshot.StagingSequence; got != 7 {
t.Fatalf("staging sequence = %d, want 7", got)
}
}
32 changes: 16 additions & 16 deletions internal/checkpoint/checkpoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,36 +8,36 @@ import (

// QueueKey identifies a single merge queue.
type QueueKey struct {
Owner string
Repo string
Base string
Owner string `json:"Owner"`
Repo string `json:"Repo"`
Base string `json:"Base"`
}

// QueueSnapshot is the durable shape of queue state.
type QueueSnapshot struct {
Key QueueKey
Pending [][]int
Active []ActiveBatchSnapshot
LingerSince time.Time
BaseGeneration int
StagingSequence int
Key QueueKey `json:"Key"`
Pending [][]int `json:"Pending"`
Active []ActiveBatchSnapshot `json:"Active"`
LingerSince time.Time `json:"LingerSince"`
BaseGeneration int `json:"BaseGeneration"`
StagingSequence int `json:"StagingSequence"`
}

// ActiveBatchSnapshot records a staging branch currently waiting on its gate.
// Restores re-queue active batches for fresh staging instead of trusting an old
// run from before the process restart.
type ActiveBatchSnapshot struct {
PRs []PullRequestSnapshot
StagingBranch string
StagingSHA string
BaseGeneration int
Outcome string
PRs []PullRequestSnapshot `json:"PRs"`
StagingBranch string `json:"StagingBranch"`
StagingSHA string `json:"StagingSHA"`
BaseGeneration int `json:"BaseGeneration"`
Outcome string `json:"Outcome"`
}

// PullRequestSnapshot is the PR identity needed to resume a staged batch.
type PullRequestSnapshot struct {
Number int
HeadSHA string
Number int `json:"Number"`
HeadSHA string `json:"HeadSHA"`
}

// Validate checks the snapshot before it is persisted or restored.
Expand Down
15 changes: 15 additions & 0 deletions internal/checkpoint/postgres/migrations/001_queue_state.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
CREATE TABLE IF NOT EXISTS shunt_queue_state (
owner text NOT NULL,
repo text NOT NULL,
base text NOT NULL,
pending jsonb NOT NULL DEFAULT '[]'::jsonb,
active jsonb NOT NULL DEFAULT '[]'::jsonb,
linger_since timestamptz,
base_generation integer NOT NULL DEFAULT 0,
staging_sequence integer NOT NULL DEFAULT 0,
updated_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (owner, repo, base)
);

CREATE INDEX IF NOT EXISTS shunt_queue_state_updated_at_idx
ON shunt_queue_state (updated_at);
232 changes: 232 additions & 0 deletions internal/checkpoint/postgres/postgres.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,232 @@
// Package postgres provides a database/sql-backed Postgres queue checkpoint store.
package postgres

import (
"context"
"database/sql"
_ "embed"
"encoding/json"
"errors"
"fmt"

"github.com/rbtr/shunt/internal/checkpoint"
)

// PostgresMigrationV1 creates the queue-state table used by Postgres.
//
//go:embed migrations/001_queue_state.sql
var PostgresMigrationV1 string

type rowScanner interface {
Scan(dest ...any) error
}

type sqlExecutor interface {
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
QueryRowContext(ctx context.Context, query string, args ...any) rowScanner
}

type activeBatchJSON struct {
PRs []pullRequestJSON `json:"prs"`
StagingBranch string `json:"staging_branch"`
StagingSHA string `json:"staging_sha"`
BaseGeneration int `json:"base_generation"`
Outcome string `json:"outcome,omitempty"`
}

type pullRequestJSON struct {
Number int `json:"number"`
HeadSHA string `json:"head_sha"`
}

type stdDB struct {
db *sql.DB
}

func (s stdDB) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) {
return s.db.ExecContext(ctx, query, args...)
}

func (s stdDB) QueryRowContext(ctx context.Context, query string, args ...any) rowScanner {
return s.db.QueryRowContext(ctx, query, args...)
}

// Store stores queue snapshots in a Postgres database. Call ApplyMigrations
// before the first LoadQueue or SaveQueue.
type Store struct {
db sqlExecutor
}

// New returns a Postgres-backed Store using db. The caller owns opening
// and closing db, including registering the chosen Postgres driver.
func New(db *sql.DB) *Store {
if db == nil {
return &Store{}
}
return &Store{db: stdDB{db: db}}
}

// ApplyMigrations ensures the backing table and indexes exist.
func (p *Store) ApplyMigrations(ctx context.Context) error {
if err := p.ready(); err != nil {
return err
}
_, err := p.db.ExecContext(ctx, PostgresMigrationV1)
if err != nil {
return fmt.Errorf("state: apply postgres migrations: %w", err)
}
return nil
}

// SaveQueue upserts a complete queue snapshot.
func (p *Store) SaveQueue(ctx context.Context, snapshot checkpoint.QueueSnapshot) error {
if err := p.ready(); err != nil {
return err
}
if err := snapshot.Validate(); err != nil {
return err
}
snapshot = snapshot.Clone()
pending, err := json.Marshal(snapshot.Pending)
if err != nil {
return fmt.Errorf("state: marshal pending queue: %w", err)
}
active, err := json.Marshal(activeToJSON(snapshot.Active))
if err != nil {
return fmt.Errorf("state: marshal active batches: %w", err)
}
var linger any
if !snapshot.LingerSince.IsZero() {
linger = snapshot.LingerSince.UTC()
}
_, err = p.db.ExecContext(ctx, `
INSERT INTO shunt_queue_state (
owner, repo, base, pending, active, linger_since, base_generation, staging_sequence, updated_at
) VALUES ($1, $2, $3, $4::jsonb, $5::jsonb, $6, $7, $8, now())
ON CONFLICT (owner, repo, base) DO UPDATE SET
pending = EXCLUDED.pending,
active = EXCLUDED.active,
linger_since = EXCLUDED.linger_since,
base_generation = EXCLUDED.base_generation,
staging_sequence = EXCLUDED.staging_sequence,
updated_at = now()
`, snapshot.Key.Owner, snapshot.Key.Repo, snapshot.Key.Base, string(pending), string(active), linger, snapshot.BaseGeneration, snapshot.StagingSequence)
if err != nil {
return fmt.Errorf("state: save queue %s/%s@%s: %w", snapshot.Key.Owner, snapshot.Key.Repo, snapshot.Key.Base, err)
}
return nil
}

// LoadQueue returns the stored snapshot for key. The boolean is false when the
// queue has no durable state yet.
func (p *Store) LoadQueue(ctx context.Context, key checkpoint.QueueKey) (checkpoint.QueueSnapshot, bool, error) {
if err := p.ready(); err != nil {
return checkpoint.QueueSnapshot{}, false, err
}
if err := key.Validate(); err != nil {
return checkpoint.QueueSnapshot{}, false, err
}
var pendingRaw, activeRaw []byte
var linger sql.NullTime
var baseGeneration, stagingSequence int
err := p.db.QueryRowContext(ctx, `
SELECT pending, active, linger_since, base_generation, staging_sequence
FROM shunt_queue_state
WHERE owner = $1 AND repo = $2 AND base = $3
`, key.Owner, key.Repo, key.Base).Scan(&pendingRaw, &activeRaw, &linger, &baseGeneration, &stagingSequence)
if errors.Is(err, sql.ErrNoRows) {
return checkpoint.QueueSnapshot{}, false, nil
}
if err != nil {
return checkpoint.QueueSnapshot{}, false, fmt.Errorf("state: load queue %s/%s@%s: %w", key.Owner, key.Repo, key.Base, err)
}
var pending [][]int
if err := json.Unmarshal(pendingRaw, &pending); err != nil {
return checkpoint.QueueSnapshot{}, false, fmt.Errorf("state: decode pending queue: %w", err)
}
var activeJSON []activeBatchJSON
if err := json.Unmarshal(activeRaw, &activeJSON); err != nil {
return checkpoint.QueueSnapshot{}, false, fmt.Errorf("state: decode active batches: %w", err)
}
snapshot := checkpoint.QueueSnapshot{
Key: key,
Pending: pending,
Active: activeFromJSON(activeJSON),
BaseGeneration: baseGeneration,
StagingSequence: stagingSequence,
}
if linger.Valid {
snapshot.LingerSince = linger.Time
}
if err := snapshot.Validate(); err != nil {
return checkpoint.QueueSnapshot{}, false, err
}
return snapshot.Clone(), true, nil
}

// DeleteQueue removes any durable state for key.
func (p *Store) DeleteQueue(ctx context.Context, key checkpoint.QueueKey) error {
if err := p.ready(); err != nil {
return err
}
if err := key.Validate(); err != nil {
return err
}
_, err := p.db.ExecContext(ctx, `
DELETE FROM shunt_queue_state
WHERE owner = $1 AND repo = $2 AND base = $3
`, key.Owner, key.Repo, key.Base)
if err != nil {
return fmt.Errorf("state: delete queue %s/%s@%s: %w", key.Owner, key.Repo, key.Base, err)
}
return nil
}

func (p *Store) ready() error {
if p == nil || p.db == nil {
return errors.New("state: nil postgres database")
}
return nil
}

func activeToJSON(in []checkpoint.ActiveBatchSnapshot) []activeBatchJSON {
if in == nil {
return nil
}
out := make([]activeBatchJSON, len(in))
for i, active := range in {
prs := make([]pullRequestJSON, len(active.PRs))
for j, pr := range active.PRs {
prs[j] = pullRequestJSON{Number: pr.Number, HeadSHA: pr.HeadSHA}
}
out[i] = activeBatchJSON{
PRs: prs,
StagingBranch: active.StagingBranch,
StagingSHA: active.StagingSHA,
BaseGeneration: active.BaseGeneration,
Outcome: active.Outcome,
}
}
return out
}

func activeFromJSON(in []activeBatchJSON) []checkpoint.ActiveBatchSnapshot {
if in == nil {
return nil
}
out := make([]checkpoint.ActiveBatchSnapshot, len(in))
for i, active := range in {
prs := make([]checkpoint.PullRequestSnapshot, len(active.PRs))
for j, pr := range active.PRs {
prs[j] = checkpoint.PullRequestSnapshot{Number: pr.Number, HeadSHA: pr.HeadSHA}
}
out[i] = checkpoint.ActiveBatchSnapshot{
PRs: prs,
StagingBranch: active.StagingBranch,
StagingSHA: active.StagingSHA,
BaseGeneration: active.BaseGeneration,
Outcome: active.Outcome,
}
}
return out
}
Loading
Loading