package equipotest import ( "bytes" "context" "database/sql" "errors" "fmt" "io" "log/slog" "os" "path/filepath" "reflect" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/equipo/team" "amadan.net/rastrillo/rastrillo/db" "amadan.net/rastrillo/rastrillo/migrate" "gorm.io/gorm" "gorm.io/plugin/dbresolver" ) func executionMust(t *testing.T, err error) { t.Helper() if err != nil { t.Fatal(err) } } func executionOptions() team.Options { clock := team.NewFakeClock(time.Date(2026, 11, 2, 12, 0, 0, 0, time.UTC)) return team.Options{Clock: clock, Authority: team.NewFakeAuthority(clock, time.Minute)} } func executionDB(t *testing.T) (*db.DB, string) { t.Helper() path := filepath.Join(t.TempDir(), "activation.db") d, err := db.Open(path, slog.New(slog.NewTextHandler(io.Discard, nil))) executionMust(t, err) t.Cleanup(func() { d.Close() }) _, err = migrate.Apply(context.Background(), d, equipo.BootSchema) executionMust(t, err) return d, path } func executionRevision(t *testing.T, d *db.DB) int64 { t.Helper() var rev int64 executionMust(t, d.Writer().QueryRow(`SELECT revision FROM service`).Scan(&rev)) return rev } func TestExecutionSharedPool(t *testing.T) { d, path := executionDB(t) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() s := equipo.NewStore(d) x, err := s.AttachExecution(ctx, path, executionOptions()) executionMust(t, err) before := executionRevision(t, d) executionMust(t, s.Bootstrap(ctx, []string{ownerAddress})) if executionRevision(t, d) != before+1 { t.Fatal("app write bypassed witnessed transaction") } if _, err := s.AttachExecution(ctx, path, executionOptions()); !errors.Is(err, equipo.ErrConflict) { t.Fatalf("duplicate attachment: %v", err) } executionMust(t, s.SetMember(ctx, equipo.Actor{Address: ownerAddress}, "member@example.com", equipo.RoleMember, true, 0)) var auditCount int executionMust(t, d.Writer().QueryRow(`SELECT count(*) FROM audit_events WHERE actor=?`, ownerAddress).Scan(&auditCount)) if auditCount != 1 { t.Fatalf("attached roster audit count = %d", auditCount) } if err := s.SetMember(ctx, equipo.Actor{Address: "outsider@example.com"}, "other@example.com", equipo.RoleMember, true, 0); !errors.Is(err, equipo.ErrForbidden) { t.Fatalf("attached write lost authority error: %v", err) } waits := d.Writer().Stats().WaitCount abort := errors.New("abort app/core/audit") before = executionRevision(t, d) err = x.Write(ctx, func(tx *gorm.DB) error { if !tx.SkipDefaultTransaction || !tx.DisableNestedTransaction { t.Fatal("nested transactions enabled") } if _, ok := tx.Statement.ConnPool.(*sql.Tx); !ok { t.Fatal("GORM is not using core SQL transaction") } executionMust(t, tx.Create(&equipo.Account{Label: "rollback"}).Error) executionMust(t, tx.Exec(`INSERT INTO period_budgets(account,revision,config) VALUES ('rollback',1,'{}')`).Error) executionMust(t, tx.Create(&equipo.AuditEvent{Actor: ownerAddress, Kind: "rollback", At: time.Now()}).Error) var count int64 executionMust(t, tx.Clauses(dbresolver.Read).Model(&equipo.Account{}).Where("label = ?", "rollback").Count(&count).Error) if count != 1 { t.Fatal("transaction read escaped to replica") } return tx.Transaction(func(nested *gorm.DB) error { return abort }) }) if !errors.Is(err, abort) { t.Fatalf("rollback error = %v", err) } for _, q := range []string{`SELECT count(*) FROM accounts WHERE label='rollback'`, `SELECT count(*) FROM period_budgets WHERE account='rollback'`, `SELECT count(*) FROM audit_events WHERE kind='rollback'`} { var n int executionMust(t, d.Writer().QueryRow(q).Scan(&n)) if n != 0 { t.Fatalf("partial rollback: %s", q) } } if executionRevision(t, d) != before { t.Fatal("rollback advanced witness revision") } executionMust(t, x.Write(ctx, func(tx *gorm.DB) error { return tx.Create(&equipo.Account{Label: "committed"}).Error })) executionMust(t, x.Core.ConfigureBudgets(ctx, "team", 0, team.BudgetSet{Team: team.PeriodLimits{Calls: 10, InputTokens: 10, OutputTokens: 10, Seconds: 10}})) if d.Writer().Stats().WaitCount != waits { t.Fatal("nested writer pool acquisition") } executionMust(t, x.Core.Close()) executionMust(t, d.Writer().PingContext(ctx)) var committedCount int64 executionMust(t, d.G.WithContext(ctx).Model(&equipo.Account{}).Where("label = ?", "committed").Count(&committedCount).Error) if committedCount != 1 || d.G.SkipDefaultTransaction || d.G.DisableNestedTransaction { t.Fatal("execution changed the app GORM session") } if err := s.Bootstrap(ctx, []string{ownerAddress}); !errors.Is(err, equipo.ErrUnavailable) { t.Fatalf("closed execution allowed app write: %v", err) } var paused int executionMust(t, d.Writer().QueryRow(`SELECT admission_paused FROM service`).Scan(&paused)) marker, err := os.ReadFile(path + ".incarnation") executionMust(t, err) if paused != 1 || !bytes.Contains(marker, []byte("clean=true")) { t.Fatal("shared close did not publish clean pause") } } func TestExecutionSchemaParity(t *testing.T) { ctx := context.Background() d, path := executionDB(t) if _, err := d.Writer().Exec(`INSERT INTO service (id,schema_version,incarnation,admission_paused,quarantine,quarantine_why) VALUES (2,3,0,1,0,'')`); err == nil { t.Fatal("service singleton check missing") } expected, err := migrate.Read(ctx, d.Writer()) executionMust(t, err) t.Run("foundation upgrade", func(t *testing.T) { oldPath := filepath.Join(t.TempDir(), "foundation.db") old, err := db.Open(oldPath, slog.New(slog.NewTextHandler(io.Discard, nil))) executionMust(t, err) defer old.Close() before := &migrate.Set{} for _, m := range equipo.BootSchema.All() { if schemaBefore(m.ID, "0006") { before.Add(m) } } _, err = migrate.Apply(ctx, old, before) executionMust(t, err) executionMust(t, old.G.Create(&equipo.Account{Label: "existing account"}).Error) result, err := migrate.Apply(ctx, old, equipo.BootSchema) executionMust(t, err) if !reflect.DeepEqual(result.Applied, schemaAfter("0006")) { t.Fatalf("upgrade migrations: %v", result.Applied) } var account equipo.Account executionMust(t, old.G.First(&account).Error) if account.Label != "existing account" { t.Fatal("upgrade lost app record") } result, err = migrate.Apply(ctx, old, equipo.BootSchema) executionMust(t, err) if len(result.Applied) != 0 { t.Fatal("upgrade repeated") } }) t.Run("task one upgrade", func(t *testing.T) { old, err := db.Open(filepath.Join(t.TempDir(), "task1.db"), slog.New(slog.NewTextHandler(io.Discard, nil))) executionMust(t, err) defer old.Close() before := &migrate.Set{} for _, m := range equipo.BootSchema.All() { if schemaBefore(m.ID, "0007") { before.Add(m) } } _, err = migrate.Apply(ctx, old, before) executionMust(t, err) executionMust(t, seedExecutionJob(old.Writer())) _, err = old.Writer().Exec(`INSERT INTO projects(id,repository,app_name,revision) VALUES(1,'amadan.net/oficina/shop','shop',7)`) executionMust(t, err) result, err := migrate.Apply(ctx, old, equipo.BootSchema) executionMust(t, err) if !reflect.DeepEqual(result.Applied, schemaAfter("0007")) { t.Fatalf("task one upgrade migrations: %v", result.Applied) } var evidence string executionMust(t, old.Writer().QueryRow(`SELECT evidence FROM jobs WHERE id=1`).Scan(&evidence)) if evidence != "preserved evidence" || scalar(t, old, "SELECT grant_version FROM projects WHERE id=1") != 7 { t.Fatal("task one upgrade lost data or grant version") } got, err := migrate.Read(ctx, old.Writer()) executionMust(t, err) if diff := expected.Diff(got); len(diff) != 0 { t.Fatalf("task one upgrade schema: %v", diff) } }) for _, bad := range []bool{false, true} { t.Run(fmt.Sprintf("task two upgrade bad=%v", bad), func(t *testing.T) { old, err := db.Open(filepath.Join(t.TempDir(), "task2.db"), slog.New(slog.NewTextHandler(io.Discard, nil))) executionMust(t, err) defer old.Close() before := &migrate.Set{} for _, m := range equipo.BootSchema.All() { if schemaBefore(m.ID, "0008") { before.Add(m) } } _, err = migrate.Apply(ctx, old, before) executionMust(t, err) executionMust(t, seedExecutionJob(old.Writer())) stamp := "2026-10-31T23:59:59.999999999Z" if bad { stamp = "2026-02-31T00:00:00Z" } _, err = old.Writer().Exec(`UPDATE jobs SET project_id=7`) executionMust(t, err) _, err = old.Writer().Exec(`INSERT INTO reservations(account,job_id,step_id,attempt_id,action_id,r_calls,r_input,r_output,r_cost,s_calls,s_input,s_output,s_cost,state,receipt_id,settled_by,created_at,settled_at) VALUES('team',1,0,0,0,1,13,5,99,0,0,0,0,'open','','',?,'')`, stamp) executionMust(t, err) result, err := migrate.Apply(ctx, old, equipo.BootSchema) if bad { if err == nil { t.Fatal("app migration accepted invalid timestamp") } if scalar(t, old, "SELECT schema_version FROM service") != 4 { t.Fatal("failed migration advanced schema") } return } executionMust(t, err) if !reflect.DeepEqual(result.Applied, schemaAfter("0008")) { t.Fatal("wrong task two upgrade", result.Applied) } var project, input, cost int var month string executionMust(t, old.Writer().QueryRow(`SELECT project_id,period,r_input,r_cost FROM reservations`).Scan(&project, &month, &input, &cost)) if project != 7 || month != "2026-10" || input != 13 || cost != 99 { t.Fatal("migration changed reservation", project, month, input, cost) } got, err := migrate.Read(ctx, old.Writer()) executionMust(t, err) if diff := expected.Diff(got); len(diff) != 0 { t.Fatal("task two schema", diff) } }) } t.Run("task six upgrade", func(t *testing.T) { old, err := db.Open(filepath.Join(t.TempDir(), "task6.db"), slog.New(slog.NewTextHandler(io.Discard, nil))) executionMust(t, err) defer old.Close() before := &migrate.Set{} for _, m := range equipo.BootSchema.All() { if schemaBefore(m.ID, "0011") { before.Add(m) } } _, err = migrate.Apply(ctx, old, before) executionMust(t, err) executionMust(t, seedExecutionJob(old.Writer())) result, err := migrate.Apply(ctx, old, equipo.BootSchema) executionMust(t, err) if !reflect.DeepEqual(result.Applied, schemaAfter("0011")) { t.Fatal("task six upgrade migrations", result.Applied) } var key, hash string executionMust(t, old.Writer().QueryRow("SELECT request_key,request_hash FROM jobs WHERE id=1").Scan(&key, &hash)) if key != "" || hash != "" { t.Fatal("legacy request identity invented") } if scalar(t, old, "SELECT schema_version FROM service") != team.SchemaVersion { t.Fatal("core version not current") } for i := 0; i < 2; i++ { result, err = migrate.Apply(ctx, old, equipo.BootSchema) executionMust(t, err) if len(result.Applied) != 0 { t.Fatal("migration replayed") } } }) coreNames := map[string]bool{"coordinator_limits": true, "admission_tickets": true, "grant_fences": true, "recovery_charges": true, "recovery_events": true, "service": true, "jobs": true, "steps": true, "attempts": true, "reservations": true, "actions": true, "events": true, "artifacts": true, "period_budgets": true, "time_reservations": true} var appCore migrate.Snapshot for _, table := range expected.Tables { if coreNames[table.Name] { appCore.Tables = append(appCore.Tables, table) } } if len(appCore.Tables) != len(coreNames) { t.Fatalf("execution tables = %d, want %d", len(appCore.Tables), len(coreNames)) } for _, version := range []int{1, 2, 3, 4, 5, 6, 7, 8} { t.Run(fmt.Sprint(version), func(t *testing.T) { standalonePath := filepath.Join(t.TempDir(), "core.db") core, err := team.Open(ctx, standalonePath, executionOptions()) executionMust(t, err) executionMust(t, core.Close()) raw, err := sql.Open("sqlite", standalonePath) executionMust(t, err) defer raw.Close() raw.SetMaxOpenConns(1) executionMust(t, seedExecutionJob(raw)) if version < 8 { _, err = raw.Exec("DROP TABLE coordinator_limits") executionMust(t, err) } if version < 7 { _, err = raw.Exec("DROP TABLE admission_tickets") executionMust(t, err) } if version < 6 { for _, q := range []string{"DROP INDEX jobs_request", "ALTER TABLE jobs DROP COLUMN request_key", "ALTER TABLE jobs DROP COLUMN request_hash"} { _, err = raw.Exec(q) executionMust(t, err) } } if version < 5 { for _, q := range []string{"DROP INDEX reservations_period_account", "DROP INDEX reservations_period_project", "DROP INDEX time_period_account", "DROP INDEX time_period_project", "DROP INDEX recovery_charges_scope", "ALTER TABLE reservations DROP COLUMN project_id", "ALTER TABLE reservations DROP COLUMN period", "ALTER TABLE reservations DROP COLUMN cost_unavailable", "ALTER TABLE reservations DROP COLUMN s_cached", "ALTER TABLE period_budgets DROP COLUMN content_hash"} { _, err = raw.Exec(q) executionMust(t, err) } } if version < 4 { for _, q := range []string{`DROP TABLE recovery_events`, `DROP TABLE recovery_charges`, `DROP TABLE grant_fences`, `ALTER TABLE service DROP COLUMN release_required`, `ALTER TABLE service DROP COLUMN recovery_revision`, `ALTER TABLE service DROP COLUMN reconciled_revision`, `ALTER TABLE service DROP COLUMN clock_high_water`, `ALTER TABLE jobs DROP COLUMN grant_stale`, `ALTER TABLE time_reservations DROP COLUMN elapsed_unknown`} { _, err = raw.Exec(q) executionMust(t, err) } } if version < 3 { for _, q := range []string{`DROP TABLE time_reservations`, `DROP TABLE period_budgets`, `ALTER TABLE jobs DROP COLUMN project_id`} { _, err = raw.Exec(q) executionMust(t, err) } } if version == 1 { for _, q := range []string{`ALTER TABLE service DROP COLUMN revision`, `ALTER TABLE service DROP COLUMN restore_uncertain`, `ALTER TABLE actions DROP COLUMN admitted_incarnation`} { _, err = raw.Exec(q) executionMust(t, err) } } _, err = raw.Exec(`UPDATE service SET schema_version=?`, version) executionMust(t, err) _, err = raw.Exec(`CREATE TRIGGER ordered_schema_bumps BEFORE UPDATE OF schema_version ON service WHEN NEW.schema_version != OLD.schema_version + 1 BEGIN SELECT RAISE(ABORT, 'schema bump skipped or repeated'); END`) executionMust(t, err) for reopen := 0; reopen < 3; reopen++ { core, err = team.Open(ctx, standalonePath, executionOptions()) executionMust(t, err) executionMust(t, core.Close()) got, err := migrate.Read(ctx, raw) executionMust(t, err) if diff := appCore.Diff(got); len(diff) != 0 { t.Fatalf("schema parity: %v", diff) } var evidence string executionMust(t, raw.QueryRow(`SELECT evidence FROM jobs WHERE id=1`).Scan(&evidence)) if evidence != "preserved evidence" { t.Fatal("upgrade lost job data") } for name := range coreNames { if !reflect.DeepEqual(executionConstraints(t, d.Writer(), name), executionConstraints(t, raw, name)) { t.Fatalf("constraints differ for %s", name) } } } }) } for reopen := 0; reopen < 2; reopen++ { result, err := migrate.Apply(ctx, d, equipo.BootSchema) executionMust(t, err) if len(result.Applied) != 0 { t.Fatalf("second migration applied %v", result.Applied) } core, err := team.OpenShared(ctx, d.Writer(), path, executionOptions()) executionMust(t, err) executionMust(t, core.Close()) } _, err = d.Writer().Exec(`UPDATE service SET schema_version=?`, team.SchemaVersion+1) executionMust(t, err) if _, err = team.OpenShared(ctx, d.Writer(), path, executionOptions()); team.CodeOf(err) != team.CodeStaleStore { t.Fatalf("newer schema accepted: %v", err) } } func executionConstraints(t *testing.T, d *sql.DB, table string) []string { t.Helper() var result []string for _, q := range []string{`SELECT "from", "table", "to", on_update, on_delete FROM pragma_foreign_key_list(?) ORDER BY "from"`, `SELECT name, "unique", origin, partial FROM pragma_index_list(?) ORDER BY name`, `SELECT il.name, ii.seqno, ii.name FROM pragma_index_list(?) il JOIN pragma_index_info(il.name) ii ORDER BY il.name, ii.seqno`} { rows, err := d.Query(q, table) executionMust(t, err) cols, err := rows.Columns() executionMust(t, err) for rows.Next() { values := make([]any, len(cols)) dest := make([]any, len(cols)) for i := range values { dest[i] = &values[i] } executionMust(t, rows.Scan(dest...)) result = append(result, fmt.Sprint(values)) } executionMust(t, rows.Err()) executionMust(t, rows.Close()) } rows, err := d.Query(`SELECT sql FROM sqlite_master WHERE type='index' AND tbl_name=? AND sql IS NOT NULL ORDER BY name`, table) executionMust(t, err) for rows.Next() { var ddl string executionMust(t, rows.Scan(&ddl)) result = append(result, migrate.Checksum(ddl)) } executionMust(t, rows.Err()) executionMust(t, rows.Close()) return result } func seedExecutionJob(d *sql.DB) error { _, err := d.Exec(`INSERT INTO jobs (id,account,parent,depth,requester,target,evidence,policy_version,policy,grant_ref,grant_version,grant_epoch,grant_observed_at,state,wait,revision,outcome,created_at,updated_at) VALUES (1,'team',0,0,'requester','{}','preserved evidence',1,'{}','grant',1,1,'','queued','',1,'','','')`) return err } func TestExecutionBackupIncludesArtifacts(t *testing.T) { d, path := executionDB(t) ctx := context.Background() options := executionOptions() options.Authority.(*team.FakeAuthority).Issue("backup-grant", team.Grant{Account: "team", Operations: map[team.Operation]bool{team.OpJobContinue: true, team.OpAttemptContinue: true}}) x, err := equipo.NewStore(d).AttachExecution(ctx, path, options) executionMust(t, err) defer x.Core.Close() _, err = x.Core.Resume(ctx) executionMust(t, err) job, err := x.Core.CreateJob(ctx, team.JobSpec{ Account: "team", Requester: ownerAddress, GrantRef: "backup-grant", Target: team.TargetBinding{Kind: team.TargetRepository, Repository: "example/shop", Ref: "team/backup-test", DefaultRef: "main", BaseRevision: fmt.Sprintf("%064x", 1)}, Evidence: team.EvidenceRequirement{Predicate: team.PredicateSoftwareFix, ExpectedSymptom: team.FixtureSymptom, CheckDefinitionHash: team.CheckDefinitionHash}, Policy: team.DefaultPolicy(5_000_000, team.Rates{Version: 1}), Steps: team.SoftwareSteps(false), }) executionMust(t, err) scope := team.Scope{Account: job.Account, Job: job.ID} handle, err := x.Core.Claim(ctx, scope, "reproduce", "backup-runner", "backup-workspace") executionMust(t, err) reproduction := []byte{0, 1, 2, 255, 'r', 'e', 'p', 'r', 'o'} _, err = x.Core.Register(ctx, scope, handle, team.ArtifactSpec{Role: team.RoleReproduction, MediaType: "application/octet-stream", Payload: reproduction, Provenance: team.Provenance{Producer: "backup-runner", Provider: "offline-fake", Context: "backup-context"}}) executionMust(t, err) executionMust(t, x.Write(ctx, func(tx *gorm.DB) error { return tx.Create(&equipo.Account{Label: "backup account"}).Error })) backup := filepath.Join(t.TempDir(), "backup.db") _, err = d.Writer().Exec(`VACUUM INTO ?`, backup) executionMust(t, err) restored, err := sql.Open("sqlite", backup) executionMust(t, err) defer restored.Close() var label, requester string var payload []byte executionMust(t, restored.QueryRow(`SELECT label FROM accounts`).Scan(&label)) executionMust(t, restored.QueryRow(`SELECT requester FROM jobs`).Scan(&requester)) executionMust(t, restored.QueryRow(`SELECT payload FROM artifacts`).Scan(&payload)) if label != "backup account" || requester != ownerAddress || !bytes.Equal(payload, reproduction) { t.Fatal("activation backup lost app, job or reproduction bytes") } } func schemaBefore(id, version string) bool { // Oficina ID stores arrived with 0082, after these historical snapshots. for _, prefix := range []string{"oficina_handoff/", "oficina_connect_link/", "equipo_identity/"} { if strings.HasPrefix(id, prefix) { return version >= "0082" } } return !strings.HasPrefix(id, "equipo/") || strings.Split(strings.TrimPrefix(id, "equipo/"), "_")[0] <= version } func schemaAfter(version string) []string { var ids []string for _, m := range equipo.BootSchema.All() { if !schemaBefore(m.ID, version) { ids = append(ids, m.ID) } } return ids }