diff --git a/internal/app/archied/state_store_pool.go b/internal/app/archied/state_store_pool.go index e54959173..5f51809d4 100644 --- a/internal/app/archied/state_store_pool.go +++ b/internal/app/archied/state_store_pool.go @@ -35,7 +35,7 @@ func (b *boot) openStateStorePool(ctx context.Context) error { b.log.Error("migrate state store postgres schema", "err", err) return err } - ownership, err := postgres.AcquireOwnership(ctx, pool, "state-store") + ownership, err := postgres.AcquireOwnership(ctx, pool, postgres.OwnerStateStore) if err != nil { pool.Close() b.log.Error("claim state store ownership", "err", err) diff --git a/internal/infrastructure/postgres/maintenance.go b/internal/infrastructure/postgres/maintenance.go new file mode 100644 index 000000000..90bf84ca9 --- /dev/null +++ b/internal/infrastructure/postgres/maintenance.go @@ -0,0 +1,264 @@ +package postgres + +import ( + "bytes" + "context" + "errors" + "fmt" + "io/fs" + "net/url" + "os" + "os/exec" + "path/filepath" + "slices" + "strings" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + "github.com/pressly/goose/v3" +) + +// The serving roles that each hold an ownership claim for their whole life. +const ( + OwnerStateStore = "state-store" + OwnerGateway = "gateway" +) + +// ServiceOwners is every serving role that reads or writes the database. A +// destructive offline operation must hold all of them: one database backs +// every service, so the State Store being stopped alone proves nothing about +// the Gateway. +var ServiceOwners = []string{OwnerStateStore, OwnerGateway} + +// ErrSchemaTooNew is returned for a database migrated by a newer release than +// this binary. goose Down is not a rollback (it drops tables), so the only way +// back is restoring the snapshot taken before that migration. +var ErrSchemaTooNew = errors.New("postgres: database schema is newer than this binary supports") + +// gooseTable is goose's version table; its presence is what marks an archive +// as a dump of an archie database rather than of anything pg_restore can read. +const gooseTable = "public.goose_db_version" + +// SupportedSchemaVersion is the highest migration this binary embeds. +func SupportedSchemaVersion() int64 { + names, err := fs.Glob(Migrations(), "*.sql") + if err != nil { + // Unreachable: the pattern is well formed. + panic(err) + } + var highest int64 + for _, name := range names { + if version, err := goose.NumericComponent(name); err == nil { + highest = max(highest, version) + } + } + return highest +} + +// CheckSchemaVersion refuses a schema this binary cannot serve. +func CheckSchemaVersion(version int64) error { + if supported := SupportedSchemaVersion(); version > supported { + return fmt.Errorf("%w (database at %d, binary supports %d)", ErrSchemaTooNew, version, supported) + } + return nil +} + +// SchemaVersion reads the applied goose version without migrating. An +// unmigrated database is version 0. +func SchemaVersion(ctx context.Context, pool *pgxpool.Pool) (int64, error) { + var version int64 + err := pool.QueryRow(ctx, `SELECT CASE WHEN to_regclass('public.goose_db_version') IS NULL THEN 0 + ELSE (SELECT coalesce(max(version_id), 0) FROM public.goose_db_version WHERE is_applied) END`).Scan(&version) + if err != nil { + return 0, fmt.Errorf("postgres: read schema version: %w", err) + } + return version, nil +} + +// AcquireAll claims every name, or none: on any failure the claims already +// taken are released before the error returns. +func AcquireAll(ctx context.Context, pool *pgxpool.Pool, names []string) (release func(context.Context), err error) { + held := make([]*Ownership, 0, len(names)) + release = func(ctx context.Context) { + for _, o := range slices.Backward(held) { + _ = o.Release(ctx) + } + } + for _, name := range names { + o, err := AcquireOwnership(ctx, pool, name) + if err != nil { + release(ctx) + return nil, err + } + held = append(held, o) + } + return release, nil +} + +// Backup writes a whole-database pg_dump archive to out. It takes no claim: +// pg_dump reads one consistent snapshot, so it is safe against serving +// processes, which is what the update installer needs. The archive goes to a +// scratch file and replaces out only once pg_restore can read it back, so a +// failed run never costs the previous good snapshot. +func Backup(ctx context.Context, databaseURL, out string) error { + tmp, err := os.CreateTemp(filepath.Dir(out), filepath.Base(out)+".tmp*") + if err != nil { + return fmt.Errorf("postgres: backup: %w", err) + } + scratch := tmp.Name() + _ = tmp.Close() + defer func() { _ = os.Remove(scratch) }() + + dbname, env := libpqTarget(databaseURL) + if _, err := runTool(ctx, env, "pg_dump", dumpArgs(dbname, scratch)...); err != nil { + return fmt.Errorf("postgres: backup: %w", err) + } + if _, err := ValidateSnapshot(ctx, scratch); err != nil { + return fmt.Errorf("postgres: backup produced an unreadable snapshot: %w", err) + } + if err := os.Rename(scratch, out); err != nil { + return fmt.Errorf("postgres: backup: %w", err) + } + return nil +} + +// ValidateSnapshot reads the archive's table of contents and returns the +// tables it holds. An archive without goose's version table is not a dump of +// an archie database. +func ValidateSnapshot(ctx context.Context, path string) ([]string, error) { + if _, err := os.Stat(path); err != nil { + return nil, fmt.Errorf("postgres: snapshot: %w", err) + } + list, err := runTool(ctx, nil, "pg_restore", "--list", path) + if err != nil { + return nil, fmt.Errorf("postgres: snapshot %s: %w", path, err) + } + tables := snapshotTables(list) + if !slices.Contains(tables, gooseTable) { + return nil, fmt.Errorf("postgres: snapshot %s holds no %s; it is not an archie database dump", path, gooseTable) + } + return tables, nil +} + +// Restore replaces the whole database with the snapshot at from. It is +// destructive: every write after the snapshot is lost. It refuses unless it +// can claim every service role, so no serving process is running and none can +// start until it finishes; a claim that cannot be checked is a refusal too. +// +// pg_restore --clean drops only what the archive holds, so tables a later +// migration created are dropped first; otherwise they would survive into the +// restored schema and break the next upgrade's migration. +func Restore(ctx context.Context, databaseURL, from string) error { + tables, err := ValidateSnapshot(ctx, from) + if err != nil { + return err + } + pool, err := Open(ctx, databaseURL) + if err != nil { + return fmt.Errorf("postgres: restore cannot confirm every service is stopped: %w", err) + } + defer pool.Close() + release, err := AcquireAll(ctx, pool, ServiceOwners) + if err != nil { + return fmt.Errorf("postgres: restore refused, stop every archie service first: %w", err) + } + defer release(context.WithoutCancel(ctx)) + + if err := dropTablesNotIn(ctx, pool, tables); err != nil { + return err + } + dbname, env := libpqTarget(databaseURL) + if _, err := runTool(ctx, env, "pg_restore", restoreArgs(dbname, from)...); err != nil { + return fmt.Errorf("postgres: restore: %w", err) + } + return nil +} + +func dropTablesNotIn(ctx context.Context, pool *pgxpool.Pool, keep []string) error { + rows, err := pool.Query(ctx, `SELECT schemaname, tablename FROM pg_tables + WHERE schemaname NOT IN ('pg_catalog', 'information_schema')`) + if err != nil { + return fmt.Errorf("postgres: restore: list tables: %w", err) + } + var drop []pgx.Identifier + for rows.Next() { + var schema, table string + if err := rows.Scan(&schema, &table); err != nil { + rows.Close() + return fmt.Errorf("postgres: restore: list tables: %w", err) + } + if !slices.Contains(keep, schema+"."+table) { + drop = append(drop, pgx.Identifier{schema, table}) + } + } + rows.Close() + if err := rows.Err(); err != nil { + return fmt.Errorf("postgres: restore: list tables: %w", err) + } + for _, table := range drop { + if _, err := pool.Exec(ctx, "DROP TABLE IF EXISTS "+table.Sanitize()+" CASCADE"); err != nil { + return fmt.Errorf("postgres: restore: drop %s: %w", table.Sanitize(), err) + } + } + return nil +} + +// snapshotTables extracts schema.table for every TABLE entry of a +// `pg_restore --list` listing, sorted. +func snapshotTables(list string) []string { + var tables []string + for line := range strings.Lines(list) { + if strings.HasPrefix(line, ";") { + continue + } + _, entry, ok := strings.Cut(line, ";") + if !ok { + continue + } + fields := strings.Fields(entry) + // "tableoid oid TABLE schema name owner"; "TABLE DATA" entries are rows. + if len(fields) >= 5 && fields[2] == "TABLE" && fields[3] != "DATA" { + tables = append(tables, fields[3]+"."+fields[4]) + } + } + slices.Sort(tables) + return tables +} + +func dumpArgs(dbname, out string) []string { + return []string{"--format=custom", "--no-password", "--file=" + out, "--dbname=" + dbname} +} + +func restoreArgs(dbname, from string) []string { + return []string{"--clean", "--if-exists", "--single-transaction", "--exit-on-error", "--no-owner", "--no-password", "--dbname=" + dbname, from} +} + +// libpqTarget splits a connection URL into the dbname argument and the +// environment the client tools read, moving the password to PGPASSWORD so it +// never appears in a process listing. A key=value connection string is passed +// through as-is. +func libpqTarget(databaseURL string) (string, []string) { + u, err := url.Parse(databaseURL) + if err != nil || (u.Scheme != "postgres" && u.Scheme != "postgresql") || u.User == nil { + return databaseURL, nil + } + password, ok := u.User.Password() + if !ok { + return databaseURL, nil + } + u.User = url.User(u.User.Username()) + return u.String(), []string{"PGPASSWORD=" + password} +} + +// runTool runs a PostgreSQL client tool and returns its stdout; a failure +// carries its stderr, which is where the tools explain themselves. +func runTool(ctx context.Context, env []string, name string, args ...string) (string, error) { + cmd := exec.CommandContext(ctx, name, args...) + cmd.Env = append(os.Environ(), env...) + var stdout, stderr bytes.Buffer + cmd.Stdout, cmd.Stderr = &stdout, &stderr + if err := cmd.Run(); err != nil { + return "", fmt.Errorf("%s: %w: %s", name, err, strings.TrimSpace(stderr.String())) + } + return stdout.String(), nil +} diff --git a/internal/infrastructure/postgres/maintenance_test.go b/internal/infrastructure/postgres/maintenance_test.go new file mode 100644 index 000000000..6c1244fa7 --- /dev/null +++ b/internal/infrastructure/postgres/maintenance_test.go @@ -0,0 +1,302 @@ +package postgres + +import ( + "errors" + "os" + "os/exec" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest" +) + +func TestLibpqTargetKeepsThePasswordOffTheCommandLine(t *testing.T) { + tests := []struct { + name string + url string + wantDB string + wantEnv []string + leakFree string + }{ + { + name: "url with password", + url: "postgres://archie:s3cret@db.example:5432/archie?sslmode=require", + wantDB: "postgres://archie@db.example:5432/archie?sslmode=require", + wantEnv: []string{"PGPASSWORD=s3cret"}, + leakFree: "s3cret", + }, + { + name: "url without password", + url: "postgresql://archie@db.example/archie", + wantDB: "postgresql://archie@db.example/archie", + }, + { + name: "key value connection string passes through", + url: "host=db.example dbname=archie", + wantDB: "host=db.example dbname=archie", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + db, env := libpqTarget(tt.url) + if db != tt.wantDB { + t.Errorf("dbname = %q, want %q", db, tt.wantDB) + } + if !slices.Equal(env, tt.wantEnv) { + t.Errorf("env = %q, want %q", env, tt.wantEnv) + } + if tt.leakFree != "" && strings.Contains(db, tt.leakFree) { + t.Errorf("dbname %q carries the password", db) + } + }) + } +} + +func TestToolArguments(t *testing.T) { + tests := []struct { + name string + got []string + want []string + }{ + { + name: "dump is a whole-database custom-format archive", + got: dumpArgs("postgres://h/db", "/tmp/out.dump"), + want: []string{"--format=custom", "--no-password", "--file=/tmp/out.dump", "--dbname=postgres://h/db"}, + }, + { + name: "restore cleans, stops on the first error and is atomic", + got: restoreArgs("postgres://h/db", "/tmp/in.dump"), + want: []string{"--clean", "--if-exists", "--single-transaction", "--exit-on-error", "--no-owner", "--no-password", "--dbname=postgres://h/db", "/tmp/in.dump"}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if !slices.Equal(tt.got, tt.want) { + t.Errorf("args = %q, want %q", tt.got, tt.want) + } + }) + } +} + +func TestSnapshotTablesReadsTheArchiveList(t *testing.T) { + list := `; +; Archive created at 2026-09-24 10:00:00 UTC +; +215; 1259 16390 TABLE public tasks archie +216; 1259 16391 SEQUENCE public tasks_id_seq archie +3401; 0 16390 TABLE DATA public tasks archie +217; 1259 16400 TABLE public goose_db_version archie +` + got := snapshotTables(list) + want := []string{"public.goose_db_version", "public.tasks"} + if !slices.Equal(got, want) { + t.Fatalf("snapshotTables = %q, want %q", got, want) + } +} + +func requireTools(t *testing.T) { + t.Helper() + for _, tool := range []string{"pg_dump", "pg_restore"} { + if _, err := exec.LookPath(tool); err != nil { + t.Skipf("%s is not on PATH; the integration test needs the PostgreSQL 18 client tools", tool) + } + } +} + +// migratedURL is a migrated database and a pool on it. +func migratedURL(t *testing.T) (string, *pgxpool.Pool) { + t.Helper() + url := pgtest.URL(t) + pool := openPool(t, url) + if err := Migrate(t.Context(), pool, Migrations()); err != nil { + t.Fatalf("Migrate: %v", err) + } + return url, pool +} + +func titles(t *testing.T, pool *pgxpool.Pool) []string { + t.Helper() + rows, err := pool.Query(t.Context(), "SELECT title FROM tasks ORDER BY id") + if err != nil { + t.Fatalf("list tasks: %v", err) + } + defer rows.Close() + var out []string + for rows.Next() { + var title string + if err := rows.Scan(&title); err != nil { + t.Fatal(err) + } + out = append(out, title) + } + return out +} + +func enqueue(t *testing.T, pool *pgxpool.Pool, title string) { + t.Helper() + if _, err := New(pool).EnqueueChatTask(t.Context(), "acme", "widget", title, "body", "implement", ""); err != nil { + t.Fatalf("enqueue %q: %v", title, err) + } +} + +// A restore after a forward migration is the case restore exists for: the +// tables the later migration added are not in the snapshot, so --clean alone +// would leave them behind for the next upgrade to trip over. +func TestBackupThenRestoreReturnsTheDatabaseToTheSnapshot(t *testing.T) { + requireTools(t) + url, pool := migratedURL(t) + enqueue(t, pool, "before") + before, err := SchemaVersion(t.Context(), pool) + if err != nil { + t.Fatalf("SchemaVersion: %v", err) + } + snapshot := filepath.Join(t.TempDir(), "snapshot.dump") + if err := Backup(t.Context(), url, snapshot); err != nil { + t.Fatalf("Backup: %v", err) + } + if leftovers, _ := filepath.Glob(snapshot + ".tmp*"); len(leftovers) != 0 { + t.Errorf("backup left scratch files: %v", leftovers) + } + + enqueue(t, pool, "after") + if _, err := pool.Exec(t.Context(), "CREATE TABLE later_migration (id bigint)"); err != nil { + t.Fatal(err) + } + if _, err := pool.Exec(t.Context(), "INSERT INTO goose_db_version (version_id, is_applied) VALUES ($1, true)", before+1); err != nil { + t.Fatal(err) + } + + if err := Restore(t.Context(), url, snapshot); err != nil { + t.Fatalf("Restore: %v", err) + } + if got := titles(t, pool); !slices.Equal(got, []string{"before"}) { + t.Errorf("tasks after restore = %q, want only the snapshot's", got) + } + var extra bool + if err := pool.QueryRow(t.Context(), "SELECT to_regclass('public.later_migration') IS NOT NULL").Scan(&extra); err != nil { + t.Fatal(err) + } + if extra { + t.Error("restore left a table the snapshot does not contain") + } + if after, err := SchemaVersion(t.Context(), pool); err != nil || after != before { + t.Errorf("schema version after restore = %d, %v; want %d", after, err, before) + } + enqueue(t, pool, "writable") +} + +func TestRestoreRefusesWhileAnyServiceIsServing(t *testing.T) { + requireTools(t) + for _, owner := range ServiceOwners { + t.Run(owner, func(t *testing.T) { + url, pool := migratedURL(t) + enqueue(t, pool, "snapshot") + snapshot := filepath.Join(t.TempDir(), "snapshot.dump") + if err := Backup(t.Context(), url, snapshot); err != nil { + t.Fatalf("Backup: %v", err) + } + enqueue(t, pool, "live") + claimOther(t, url, owner, false, false) + + err := Restore(t.Context(), url, snapshot) + if !errors.Is(err, ErrOwned) { + t.Fatalf("Restore with %s serving = %v, want ErrOwned", owner, err) + } + if !strings.Contains(err.Error(), owner) { + t.Errorf("refusal must name the serving role %q: %v", owner, err) + } + if got := titles(t, pool); !slices.Equal(got, []string{"snapshot", "live"}) { + t.Errorf("refused restore changed the database: %q", got) + } + // Every claim the refused restore took is dropped again. + for _, other := range ServiceOwners { + if other == owner { + continue + } + claim, err := AcquireOwnership(t.Context(), pool, other) + if err != nil { + t.Fatalf("%s still held after a refused restore: %v", other, err) + } + _ = claim.Release(t.Context()) + } + }) + } +} + +func TestRestoreRefusesWhatItCannotCheck(t *testing.T) { + requireTools(t) + url, pool := migratedURL(t) + snapshot := filepath.Join(t.TempDir(), "snapshot.dump") + if err := Backup(t.Context(), url, snapshot); err != nil { + t.Fatalf("Backup: %v", err) + } + notASnapshot := filepath.Join(t.TempDir(), "garbage.dump") + if err := os.WriteFile(notASnapshot, []byte("not an archive"), 0o600); err != nil { + t.Fatal(err) + } + enqueue(t, pool, "live") + + tests := []struct { + name string + url string + from string + }{ + {name: "unreachable server", url: "postgres://archie:archie@127.0.0.1:1/none?connect_timeout=2", from: snapshot}, + {name: "not a snapshot", url: url, from: notASnapshot}, + {name: "missing snapshot", url: url, from: filepath.Join(t.TempDir(), "absent.dump")}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if err := Restore(t.Context(), tt.url, tt.from); err == nil { + t.Fatal("Restore succeeded, want refusal") + } + if got := titles(t, pool); !slices.Equal(got, []string{"live"}) { + t.Errorf("refused restore changed the database: %q", got) + } + }) + } +} + +func TestBackupFailureKeepsThePreviousSnapshot(t *testing.T) { + requireTools(t) + out := filepath.Join(t.TempDir(), "snapshot.dump") + if err := os.WriteFile(out, []byte("good snapshot"), 0o600); err != nil { + t.Fatal(err) + } + if err := Backup(t.Context(), "postgres://archie:archie@127.0.0.1:1/none?connect_timeout=2", out); err == nil { + t.Fatal("Backup of an unreachable database succeeded") + } + if data, _ := os.ReadFile(out); string(data) != "good snapshot" { + t.Errorf("failed backup replaced the previous snapshot: %q", data) + } + if leftovers, _ := filepath.Glob(out + ".tmp*"); len(leftovers) != 0 { + t.Errorf("failed backup left scratch files: %v", leftovers) + } +} + +func TestCheckSchemaVersion(t *testing.T) { + supported := SupportedSchemaVersion() + if supported < 4 { + t.Fatalf("SupportedSchemaVersion = %d, want the highest embedded migration", supported) + } + tests := []struct { + name string + version int64 + wantErr error + }{ + {name: "current", version: supported}, + {name: "older is upgradable", version: 1}, + {name: "newer than this binary", version: supported + 1, wantErr: ErrSchemaTooNew}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if err := CheckSchemaVersion(tt.version); !errors.Is(err, tt.wantErr) { + t.Fatalf("CheckSchemaVersion(%d) = %v, want %v", tt.version, err, tt.wantErr) + } + }) + } +} diff --git a/internal/infrastructure/postgres/normalisation_test.go b/internal/infrastructure/postgres/normalisation_test.go new file mode 100644 index 000000000..7609c8c0b --- /dev/null +++ b/internal/infrastructure/postgres/normalisation_test.go @@ -0,0 +1,216 @@ +package postgres + +import ( + "context" + "strings" + "testing" + "unicode/utf8" + + "github.com/samcharles93/archie-core/internal/domain/workflow" + "github.com/samcharles93/archie-core/internal/events" + "github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest" +) + +func storeFor(t *testing.T) *Store { + t.Helper() + pool := openPool(t, pgtest.URL(t)) + if err := Migrate(t.Context(), pool, Migrations()); err != nil { + t.Fatalf("Migrate: %v", err) + } + return New(pool) +} + +// runningTask enqueues one issue and claims it, the state every park starts in. +func runningTask(t *testing.T, s *Store) *workflow.Task { + t.Helper() + if _, err := s.EnqueueIssue(t.Context(), "acme", "widgets", 1, "t", "b", "", ""); err != nil { + t.Fatal(err) + } + task, err := s.ClaimNext(t.Context()) + if err != nil || task == nil { + t.Fatalf("ClaimNext = %v, %v", task, err) + } + return task +} + +type transitionRow struct{ from, to, detail string } + +func transitions(t *testing.T, s *Store, taskID int64) []transitionRow { + t.Helper() + rows, err := s.pool.Query(t.Context(), "SELECT from_status, to_status, detail FROM transitions WHERE task_id = $1 ORDER BY id", taskID) + if err != nil { + t.Fatal(err) + } + defer rows.Close() + var out []transitionRow + for rows.Next() { + var r transitionRow + if err := rows.Scan(&r.from, &r.to, &r.detail); err != nil { + t.Fatal(err) + } + out = append(out, r) + } + return out +} + +// Every free-text column the SQLite store clipped to 4000 bytes on a rune +// boundary is clipped the same way here. The oversized value ends in a +// multi-byte rune straddling the limit, so a byte cut would store invalid +// UTF-8 and a missing clip would store all of it. +func TestWritesClipFreeTextTo4000Bytes(t *testing.T) { + oversized := strings.Repeat("x", 3999) + "é" + strings.Repeat("y", 1000) + want := strings.Repeat("x", 3999) + + tests := []struct { + name string + write func(t *testing.T, s *Store) string + }{ + {name: "transition to parked: park reason and transition detail", write: func(t *testing.T, s *Store) string { + task := runningTask(t, s) + if err := s.Transition(t.Context(), task.ID, workflow.StatusRunning, workflow.StatusParked, oversized); err != nil { + t.Fatal(err) + } + rows := transitions(t, s, task.ID) + if len(rows) == 0 || rows[len(rows)-1].detail != want { + t.Errorf("transition detail not clipped: %d rows", len(rows)) + } + got, _ := s.TaskByID(t.Context(), task.ID) + return got.ParkReason + }}, + {name: "park task: park reason and transition detail", write: func(t *testing.T, s *Store) string { + task := runningTask(t, s) + if err := s.ParkTask(t.Context(), task.ID, workflow.StatusRunning, oversized, "transient"); err != nil { + t.Fatal(err) + } + rows := transitions(t, s, task.ID) + if len(rows) == 0 || rows[len(rows)-1].detail != want { + t.Errorf("transition detail not clipped: %d rows", len(rows)) + } + got, _ := s.TaskByID(t.Context(), task.ID) + return got.ParkReason + }}, + {name: "update: park reason", write: func(t *testing.T, s *Store) string { + task := runningTask(t, s) + task.ParkReason = oversized + if err := s.Update(t.Context(), task); err != nil { + t.Fatal(err) + } + got, _ := s.TaskByID(t.Context(), task.ID) + return got.ParkReason + }}, + {name: "begin remediation: review payload", write: func(t *testing.T, s *Store) string { + task := runningTask(t, s) + if err := s.Transition(t.Context(), task.ID, workflow.StatusRunning, workflow.StatusPROpen, "pr"); err != nil { + t.Fatal(err) + } + if err := s.BeginRemediation(t.Context(), task.ID, oversized); err != nil { + t.Fatal(err) + } + got, _ := s.TaskByID(t.Context(), task.ID) + return got.ReviewPayload + }}, + {name: "update review payload", write: func(t *testing.T, s *Store) string { + task := runningTask(t, s) + if err := s.Transition(t.Context(), task.ID, workflow.StatusRunning, workflow.StatusPROpen, "pr"); err != nil { + t.Fatal(err) + } + if err := s.BeginRemediation(t.Context(), task.ID, "first"); err != nil { + t.Fatal(err) + } + if err := s.UpdateReviewPayload(t.Context(), task.ID, oversized); err != nil { + t.Fatal(err) + } + got, _ := s.TaskByID(t.Context(), task.ID) + return got.ReviewPayload + }}, + {name: "event detail", write: func(t *testing.T, s *Store) string { + if _, err := s.InsertEvent(t.Context(), events.Event{Kind: events.KindLog, Detail: oversized}); err != nil { + t.Fatal(err) + } + got, err := s.EventsSince(t.Context(), "", 1) + if err != nil || len(got) != 1 { + t.Fatalf("EventsSince = %d, %v", len(got), err) + } + return got[0].Detail + }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := tt.write(t, storeFor(t)) + if got != want || !utf8.ValidString(got) { + t.Errorf("stored %d bytes (valid UTF-8 %v), want the %d-byte rune-boundary clip", len(got), utf8.ValidString(got), len(want)) + } + }) + } +} + +func TestParkClassNormalisation(t *testing.T) { + tests := []struct { + name string + park func(ctx context.Context, s *Store, id int64) error + want string + }{ + {name: "generic transition to parked is needs_human", want: "needs_human", park: func(ctx context.Context, s *Store, id int64) error { + return s.Transition(ctx, id, workflow.StatusRunning, workflow.StatusParked, "gate failed") + }}, + {name: "known class is kept", want: "transient", park: func(ctx context.Context, s *Store, id int64) error { + return s.ParkTask(ctx, id, workflow.StatusRunning, "container acquire failed", "transient") + }}, + {name: "unknown class falls back to needs_human", want: "needs_human", park: func(ctx context.Context, s *Store, id int64) error { + return s.ParkTask(ctx, id, workflow.StatusRunning, "x", "urgent") + }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := storeFor(t) + task := runningTask(t, s) + if err := tt.park(t.Context(), s, task.ID); err != nil { + t.Fatal(err) + } + got, _ := s.TaskByID(t.Context(), task.ID) + if got.Status != workflow.StatusParked || got.ParkClass != tt.want { + t.Fatalf("status %q class %q, want parked %q", got.Status, got.ParkClass, tt.want) + } + // Requeue clears class and reason together: a stale class on a + // queued task would group a live task with parked ones. + if err := s.Requeue(t.Context(), task.ID, workflow.StatusParked, "implement"); err != nil { + t.Fatal(err) + } + got, _ = s.TaskByID(t.Context(), task.ID) + if got.ParkClass != "needs_human" || got.ParkReason != "" { + t.Errorf("after requeue: class %q reason %q, want cleared", got.ParkClass, got.ParkReason) + } + }) + } +} + +// A transition that leaves parked alone keeps the previous park fields, and +// every guarded write leaves exactly one audit row in order. +func TestTransitionsRecordEachMoveInOrder(t *testing.T) { + s := storeFor(t) + task := runningTask(t, s) + ctx := t.Context() + if err := s.ParkTask(ctx, task.ID, workflow.StatusRunning, "why", "transient"); err != nil { + t.Fatal(err) + } + if err := s.Requeue(ctx, task.ID, workflow.StatusParked, "implement"); err != nil { + t.Fatal(err) + } + // A stale transition writes no audit row. + if err := s.Transition(ctx, task.ID, workflow.StatusRunning, workflow.StatusPROpen, "stale"); err == nil { + t.Fatal("stale Transition succeeded") + } + got := transitions(t, s, task.ID) + want := []transitionRow{ + {workflow.StatusRunning, workflow.StatusParked, "why"}, + {workflow.StatusParked, workflow.StatusQueued, "requeued implement"}, + } + if len(got) != len(want) { + t.Fatalf("transitions = %+v, want %+v", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Errorf("transition %d = %+v, want %+v", i, got[i], want[i]) + } + } +}