| 1 | package equipotest |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "database/sql" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "io" |
| 10 | "log/slog" |
| 11 | "os" |
| 12 | "path/filepath" |
| 13 | "reflect" |
| 14 | "strings" |
| 15 | "testing" |
| 16 | "time" |
| 17 | |
| 18 | "amadan.net/oficina/equipo/internal/equipo" |
| 19 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 20 | "amadan.net/rastrillo/rastrillo/db" |
| 21 | "amadan.net/rastrillo/rastrillo/migrate" |
| 22 | "gorm.io/gorm" |
| 23 | "gorm.io/plugin/dbresolver" |
| 24 | ) |
| 25 | |
| 26 | func executionMust(t *testing.T, err error) { |
| 27 | t.Helper() |
| 28 | if err != nil { |
| 29 | t.Fatal(err) |
| 30 | } |
| 31 | } |
| 32 | func executionOptions() team.Options { |
| 33 | clock := team.NewFakeClock(time.Date(2026, 11, 2, 12, 0, 0, 0, time.UTC)) |
| 34 | return team.Options{Clock: clock, Authority: team.NewFakeAuthority(clock, time.Minute)} |
| 35 | } |
| 36 | func executionDB(t *testing.T) (*db.DB, string) { |
| 37 | t.Helper() |
| 38 | path := filepath.Join(t.TempDir(), "activation.db") |
| 39 | d, err := db.Open(path, slog.New(slog.NewTextHandler(io.Discard, nil))) |
| 40 | executionMust(t, err) |
| 41 | t.Cleanup(func() { d.Close() }) |
| 42 | _, err = migrate.Apply(context.Background(), d, equipo.BootSchema) |
| 43 | executionMust(t, err) |
| 44 | return d, path |
| 45 | } |
| 46 | func executionRevision(t *testing.T, d *db.DB) int64 { |
| 47 | t.Helper() |
| 48 | var rev int64 |
| 49 | executionMust(t, d.Writer().QueryRow(`SELECT revision FROM service`).Scan(&rev)) |
| 50 | return rev |
| 51 | } |
| 52 | |
| 53 | func TestExecutionSharedPool(t *testing.T) { |
| 54 | d, path := executionDB(t) |
| 55 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 56 | defer cancel() |
| 57 | s := equipo.NewStore(d) |
| 58 | x, err := s.AttachExecution(ctx, path, executionOptions()) |
| 59 | executionMust(t, err) |
| 60 | before := executionRevision(t, d) |
| 61 | executionMust(t, s.Bootstrap(ctx, []string{ownerAddress})) |
| 62 | if executionRevision(t, d) != before+1 { |
| 63 | t.Fatal("app write bypassed witnessed transaction") |
| 64 | } |
| 65 | if _, err := s.AttachExecution(ctx, path, executionOptions()); !errors.Is(err, equipo.ErrConflict) { |
| 66 | t.Fatalf("duplicate attachment: %v", err) |
| 67 | } |
| 68 | executionMust(t, s.SetMember(ctx, equipo.Actor{Address: ownerAddress}, "member@example.com", equipo.RoleMember, true, 0)) |
| 69 | var auditCount int |
| 70 | executionMust(t, d.Writer().QueryRow(`SELECT count(*) FROM audit_events WHERE actor=?`, ownerAddress).Scan(&auditCount)) |
| 71 | if auditCount != 1 { |
| 72 | t.Fatalf("attached roster audit count = %d", auditCount) |
| 73 | } |
| 74 | if err := s.SetMember(ctx, equipo.Actor{Address: "outsider@example.com"}, "other@example.com", equipo.RoleMember, true, 0); !errors.Is(err, equipo.ErrForbidden) { |
| 75 | t.Fatalf("attached write lost authority error: %v", err) |
| 76 | } |
| 77 | waits := d.Writer().Stats().WaitCount |
| 78 | abort := errors.New("abort app/core/audit") |
| 79 | before = executionRevision(t, d) |
| 80 | err = x.Write(ctx, func(tx *gorm.DB) error { |
| 81 | if !tx.SkipDefaultTransaction || !tx.DisableNestedTransaction { |
| 82 | t.Fatal("nested transactions enabled") |
| 83 | } |
| 84 | if _, ok := tx.Statement.ConnPool.(*sql.Tx); !ok { |
| 85 | t.Fatal("GORM is not using core SQL transaction") |
| 86 | } |
| 87 | executionMust(t, tx.Create(&equipo.Account{Label: "rollback"}).Error) |
| 88 | executionMust(t, tx.Exec(`INSERT INTO period_budgets(account,revision,config) VALUES ('rollback',1,'{}')`).Error) |
| 89 | executionMust(t, tx.Create(&equipo.AuditEvent{Actor: ownerAddress, Kind: "rollback", At: time.Now()}).Error) |
| 90 | var count int64 |
| 91 | executionMust(t, tx.Clauses(dbresolver.Read).Model(&equipo.Account{}).Where("label = ?", "rollback").Count(&count).Error) |
| 92 | if count != 1 { |
| 93 | t.Fatal("transaction read escaped to replica") |
| 94 | } |
| 95 | return tx.Transaction(func(nested *gorm.DB) error { return abort }) |
| 96 | }) |
| 97 | if !errors.Is(err, abort) { |
| 98 | t.Fatalf("rollback error = %v", err) |
| 99 | } |
| 100 | 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'`} { |
| 101 | var n int |
| 102 | executionMust(t, d.Writer().QueryRow(q).Scan(&n)) |
| 103 | if n != 0 { |
| 104 | t.Fatalf("partial rollback: %s", q) |
| 105 | } |
| 106 | } |
| 107 | if executionRevision(t, d) != before { |
| 108 | t.Fatal("rollback advanced witness revision") |
| 109 | } |
| 110 | executionMust(t, x.Write(ctx, func(tx *gorm.DB) error { return tx.Create(&equipo.Account{Label: "committed"}).Error })) |
| 111 | executionMust(t, x.Core.ConfigureBudgets(ctx, "team", 0, team.BudgetSet{Team: team.PeriodLimits{Calls: 10, InputTokens: 10, OutputTokens: 10, Seconds: 10}})) |
| 112 | if d.Writer().Stats().WaitCount != waits { |
| 113 | t.Fatal("nested writer pool acquisition") |
| 114 | } |
| 115 | executionMust(t, x.Core.Close()) |
| 116 | executionMust(t, d.Writer().PingContext(ctx)) |
| 117 | var committedCount int64 |
| 118 | executionMust(t, d.G.WithContext(ctx).Model(&equipo.Account{}).Where("label = ?", "committed").Count(&committedCount).Error) |
| 119 | if committedCount != 1 || d.G.SkipDefaultTransaction || d.G.DisableNestedTransaction { |
| 120 | t.Fatal("execution changed the app GORM session") |
| 121 | } |
| 122 | if err := s.Bootstrap(ctx, []string{ownerAddress}); !errors.Is(err, equipo.ErrUnavailable) { |
| 123 | t.Fatalf("closed execution allowed app write: %v", err) |
| 124 | } |
| 125 | var paused int |
| 126 | executionMust(t, d.Writer().QueryRow(`SELECT admission_paused FROM service`).Scan(&paused)) |
| 127 | marker, err := os.ReadFile(path + ".incarnation") |
| 128 | executionMust(t, err) |
| 129 | if paused != 1 || !bytes.Contains(marker, []byte("clean=true")) { |
| 130 | t.Fatal("shared close did not publish clean pause") |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | func TestExecutionSchemaParity(t *testing.T) { |
| 135 | ctx := context.Background() |
| 136 | d, path := executionDB(t) |
| 137 | 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 { |
| 138 | t.Fatal("service singleton check missing") |
| 139 | } |
| 140 | expected, err := migrate.Read(ctx, d.Writer()) |
| 141 | executionMust(t, err) |
| 142 | t.Run("foundation upgrade", func(t *testing.T) { |
| 143 | oldPath := filepath.Join(t.TempDir(), "foundation.db") |
| 144 | old, err := db.Open(oldPath, slog.New(slog.NewTextHandler(io.Discard, nil))) |
| 145 | executionMust(t, err) |
| 146 | defer old.Close() |
| 147 | before := &migrate.Set{} |
| 148 | for _, m := range equipo.BootSchema.All() { |
| 149 | if schemaBefore(m.ID, "0006") { |
| 150 | before.Add(m) |
| 151 | } |
| 152 | } |
| 153 | _, err = migrate.Apply(ctx, old, before) |
| 154 | executionMust(t, err) |
| 155 | executionMust(t, old.G.Create(&equipo.Account{Label: "existing account"}).Error) |
| 156 | result, err := migrate.Apply(ctx, old, equipo.BootSchema) |
| 157 | executionMust(t, err) |
| 158 | if !reflect.DeepEqual(result.Applied, schemaAfter("0006")) { |
| 159 | t.Fatalf("upgrade migrations: %v", result.Applied) |
| 160 | } |
| 161 | var account equipo.Account |
| 162 | executionMust(t, old.G.First(&account).Error) |
| 163 | if account.Label != "existing account" { |
| 164 | t.Fatal("upgrade lost app record") |
| 165 | } |
| 166 | result, err = migrate.Apply(ctx, old, equipo.BootSchema) |
| 167 | executionMust(t, err) |
| 168 | if len(result.Applied) != 0 { |
| 169 | t.Fatal("upgrade repeated") |
| 170 | } |
| 171 | }) |
| 172 | t.Run("task one upgrade", func(t *testing.T) { |
| 173 | old, err := db.Open(filepath.Join(t.TempDir(), "task1.db"), slog.New(slog.NewTextHandler(io.Discard, nil))) |
| 174 | executionMust(t, err) |
| 175 | defer old.Close() |
| 176 | before := &migrate.Set{} |
| 177 | for _, m := range equipo.BootSchema.All() { |
| 178 | if schemaBefore(m.ID, "0007") { |
| 179 | before.Add(m) |
| 180 | } |
| 181 | } |
| 182 | _, err = migrate.Apply(ctx, old, before) |
| 183 | executionMust(t, err) |
| 184 | executionMust(t, seedExecutionJob(old.Writer())) |
| 185 | _, err = old.Writer().Exec(`INSERT INTO projects(id,repository,app_name,revision) VALUES(1,'amadan.net/oficina/shop','shop',7)`) |
| 186 | executionMust(t, err) |
| 187 | result, err := migrate.Apply(ctx, old, equipo.BootSchema) |
| 188 | executionMust(t, err) |
| 189 | if !reflect.DeepEqual(result.Applied, schemaAfter("0007")) { |
| 190 | t.Fatalf("task one upgrade migrations: %v", result.Applied) |
| 191 | } |
| 192 | var evidence string |
| 193 | executionMust(t, old.Writer().QueryRow(`SELECT evidence FROM jobs WHERE id=1`).Scan(&evidence)) |
| 194 | if evidence != "preserved evidence" || scalar(t, old, "SELECT grant_version FROM projects WHERE id=1") != 7 { |
| 195 | t.Fatal("task one upgrade lost data or grant version") |
| 196 | } |
| 197 | got, err := migrate.Read(ctx, old.Writer()) |
| 198 | executionMust(t, err) |
| 199 | if diff := expected.Diff(got); len(diff) != 0 { |
| 200 | t.Fatalf("task one upgrade schema: %v", diff) |
| 201 | } |
| 202 | }) |
| 203 | |
| 204 | for _, bad := range []bool{false, true} { |
| 205 | t.Run(fmt.Sprintf("task two upgrade bad=%v", bad), func(t *testing.T) { |
| 206 | old, err := db.Open(filepath.Join(t.TempDir(), "task2.db"), slog.New(slog.NewTextHandler(io.Discard, nil))) |
| 207 | executionMust(t, err) |
| 208 | defer old.Close() |
| 209 | before := &migrate.Set{} |
| 210 | for _, m := range equipo.BootSchema.All() { |
| 211 | if schemaBefore(m.ID, "0008") { |
| 212 | before.Add(m) |
| 213 | } |
| 214 | } |
| 215 | _, err = migrate.Apply(ctx, old, before) |
| 216 | executionMust(t, err) |
| 217 | executionMust(t, seedExecutionJob(old.Writer())) |
| 218 | stamp := "2026-10-31T23:59:59.999999999Z" |
| 219 | if bad { |
| 220 | stamp = "2026-02-31T00:00:00Z" |
| 221 | } |
| 222 | _, err = old.Writer().Exec(`UPDATE jobs SET project_id=7`) |
| 223 | executionMust(t, err) |
| 224 | _, 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) |
| 225 | executionMust(t, err) |
| 226 | result, err := migrate.Apply(ctx, old, equipo.BootSchema) |
| 227 | if bad { |
| 228 | if err == nil { |
| 229 | t.Fatal("app migration accepted invalid timestamp") |
| 230 | } |
| 231 | if scalar(t, old, "SELECT schema_version FROM service") != 4 { |
| 232 | t.Fatal("failed migration advanced schema") |
| 233 | } |
| 234 | return |
| 235 | } |
| 236 | executionMust(t, err) |
| 237 | if !reflect.DeepEqual(result.Applied, schemaAfter("0008")) { |
| 238 | t.Fatal("wrong task two upgrade", result.Applied) |
| 239 | } |
| 240 | var project, input, cost int |
| 241 | var month string |
| 242 | executionMust(t, old.Writer().QueryRow(`SELECT project_id,period,r_input,r_cost FROM reservations`).Scan(&project, &month, &input, &cost)) |
| 243 | if project != 7 || month != "2026-10" || input != 13 || cost != 99 { |
| 244 | t.Fatal("migration changed reservation", project, month, input, cost) |
| 245 | } |
| 246 | got, err := migrate.Read(ctx, old.Writer()) |
| 247 | executionMust(t, err) |
| 248 | if diff := expected.Diff(got); len(diff) != 0 { |
| 249 | t.Fatal("task two schema", diff) |
| 250 | } |
| 251 | }) |
| 252 | } |
| 253 | |
| 254 | t.Run("task six upgrade", func(t *testing.T) { |
| 255 | old, err := db.Open(filepath.Join(t.TempDir(), "task6.db"), slog.New(slog.NewTextHandler(io.Discard, nil))) |
| 256 | executionMust(t, err) |
| 257 | defer old.Close() |
| 258 | before := &migrate.Set{} |
| 259 | for _, m := range equipo.BootSchema.All() { |
| 260 | if schemaBefore(m.ID, "0011") { |
| 261 | before.Add(m) |
| 262 | } |
| 263 | } |
| 264 | _, err = migrate.Apply(ctx, old, before) |
| 265 | executionMust(t, err) |
| 266 | executionMust(t, seedExecutionJob(old.Writer())) |
| 267 | result, err := migrate.Apply(ctx, old, equipo.BootSchema) |
| 268 | executionMust(t, err) |
| 269 | if !reflect.DeepEqual(result.Applied, schemaAfter("0011")) { |
| 270 | t.Fatal("task six upgrade migrations", result.Applied) |
| 271 | } |
| 272 | var key, hash string |
| 273 | executionMust(t, old.Writer().QueryRow("SELECT request_key,request_hash FROM jobs WHERE id=1").Scan(&key, &hash)) |
| 274 | if key != "" || hash != "" { |
| 275 | t.Fatal("legacy request identity invented") |
| 276 | } |
| 277 | if scalar(t, old, "SELECT schema_version FROM service") != team.SchemaVersion { |
| 278 | t.Fatal("core version not current") |
| 279 | } |
| 280 | for i := 0; i < 2; i++ { |
| 281 | result, err = migrate.Apply(ctx, old, equipo.BootSchema) |
| 282 | executionMust(t, err) |
| 283 | if len(result.Applied) != 0 { |
| 284 | t.Fatal("migration replayed") |
| 285 | } |
| 286 | } |
| 287 | }) |
| 288 | |
| 289 | 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} |
| 290 | var appCore migrate.Snapshot |
| 291 | for _, table := range expected.Tables { |
| 292 | if coreNames[table.Name] { |
| 293 | appCore.Tables = append(appCore.Tables, table) |
| 294 | } |
| 295 | } |
| 296 | if len(appCore.Tables) != len(coreNames) { |
| 297 | t.Fatalf("execution tables = %d, want %d", len(appCore.Tables), len(coreNames)) |
| 298 | } |
| 299 | for _, version := range []int{1, 2, 3, 4, 5, 6, 7, 8} { |
| 300 | t.Run(fmt.Sprint(version), func(t *testing.T) { |
| 301 | standalonePath := filepath.Join(t.TempDir(), "core.db") |
| 302 | core, err := team.Open(ctx, standalonePath, executionOptions()) |
| 303 | executionMust(t, err) |
| 304 | executionMust(t, core.Close()) |
| 305 | raw, err := sql.Open("sqlite", standalonePath) |
| 306 | executionMust(t, err) |
| 307 | defer raw.Close() |
| 308 | raw.SetMaxOpenConns(1) |
| 309 | executionMust(t, seedExecutionJob(raw)) |
| 310 | if version < 8 { |
| 311 | _, err = raw.Exec("DROP TABLE coordinator_limits") |
| 312 | executionMust(t, err) |
| 313 | } |
| 314 | if version < 7 { |
| 315 | _, err = raw.Exec("DROP TABLE admission_tickets") |
| 316 | executionMust(t, err) |
| 317 | } |
| 318 | if version < 6 { |
| 319 | for _, q := range []string{"DROP INDEX jobs_request", "ALTER TABLE jobs DROP COLUMN request_key", "ALTER TABLE jobs DROP COLUMN request_hash"} { |
| 320 | _, err = raw.Exec(q) |
| 321 | executionMust(t, err) |
| 322 | } |
| 323 | } |
| 324 | if version < 5 { |
| 325 | 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"} { |
| 326 | _, err = raw.Exec(q) |
| 327 | executionMust(t, err) |
| 328 | } |
| 329 | } |
| 330 | if version < 4 { |
| 331 | 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`} { |
| 332 | _, err = raw.Exec(q) |
| 333 | executionMust(t, err) |
| 334 | } |
| 335 | } |
| 336 | if version < 3 { |
| 337 | for _, q := range []string{`DROP TABLE time_reservations`, `DROP TABLE period_budgets`, `ALTER TABLE jobs DROP COLUMN project_id`} { |
| 338 | _, err = raw.Exec(q) |
| 339 | executionMust(t, err) |
| 340 | } |
| 341 | } |
| 342 | if version == 1 { |
| 343 | for _, q := range []string{`ALTER TABLE service DROP COLUMN revision`, `ALTER TABLE service DROP COLUMN restore_uncertain`, `ALTER TABLE actions DROP COLUMN admitted_incarnation`} { |
| 344 | _, err = raw.Exec(q) |
| 345 | executionMust(t, err) |
| 346 | } |
| 347 | } |
| 348 | _, err = raw.Exec(`UPDATE service SET schema_version=?`, version) |
| 349 | executionMust(t, err) |
| 350 | _, 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`) |
| 351 | executionMust(t, err) |
| 352 | for reopen := 0; reopen < 3; reopen++ { |
| 353 | core, err = team.Open(ctx, standalonePath, executionOptions()) |
| 354 | executionMust(t, err) |
| 355 | executionMust(t, core.Close()) |
| 356 | got, err := migrate.Read(ctx, raw) |
| 357 | executionMust(t, err) |
| 358 | if diff := appCore.Diff(got); len(diff) != 0 { |
| 359 | t.Fatalf("schema parity: %v", diff) |
| 360 | } |
| 361 | var evidence string |
| 362 | executionMust(t, raw.QueryRow(`SELECT evidence FROM jobs WHERE id=1`).Scan(&evidence)) |
| 363 | if evidence != "preserved evidence" { |
| 364 | t.Fatal("upgrade lost job data") |
| 365 | } |
| 366 | for name := range coreNames { |
| 367 | if !reflect.DeepEqual(executionConstraints(t, d.Writer(), name), executionConstraints(t, raw, name)) { |
| 368 | t.Fatalf("constraints differ for %s", name) |
| 369 | } |
| 370 | } |
| 371 | } |
| 372 | }) |
| 373 | } |
| 374 | for reopen := 0; reopen < 2; reopen++ { |
| 375 | result, err := migrate.Apply(ctx, d, equipo.BootSchema) |
| 376 | executionMust(t, err) |
| 377 | if len(result.Applied) != 0 { |
| 378 | t.Fatalf("second migration applied %v", result.Applied) |
| 379 | } |
| 380 | core, err := team.OpenShared(ctx, d.Writer(), path, executionOptions()) |
| 381 | executionMust(t, err) |
| 382 | executionMust(t, core.Close()) |
| 383 | } |
| 384 | _, err = d.Writer().Exec(`UPDATE service SET schema_version=?`, team.SchemaVersion+1) |
| 385 | executionMust(t, err) |
| 386 | if _, err = team.OpenShared(ctx, d.Writer(), path, executionOptions()); team.CodeOf(err) != team.CodeStaleStore { |
| 387 | t.Fatalf("newer schema accepted: %v", err) |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | func executionConstraints(t *testing.T, d *sql.DB, table string) []string { |
| 392 | t.Helper() |
| 393 | var result []string |
| 394 | 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`} { |
| 395 | rows, err := d.Query(q, table) |
| 396 | executionMust(t, err) |
| 397 | cols, err := rows.Columns() |
| 398 | executionMust(t, err) |
| 399 | for rows.Next() { |
| 400 | values := make([]any, len(cols)) |
| 401 | dest := make([]any, len(cols)) |
| 402 | for i := range values { |
| 403 | dest[i] = &values[i] |
| 404 | } |
| 405 | executionMust(t, rows.Scan(dest...)) |
| 406 | result = append(result, fmt.Sprint(values)) |
| 407 | } |
| 408 | executionMust(t, rows.Err()) |
| 409 | executionMust(t, rows.Close()) |
| 410 | } |
| 411 | rows, err := d.Query(`SELECT sql FROM sqlite_master WHERE type='index' AND tbl_name=? AND sql IS NOT NULL ORDER BY name`, table) |
| 412 | executionMust(t, err) |
| 413 | for rows.Next() { |
| 414 | var ddl string |
| 415 | executionMust(t, rows.Scan(&ddl)) |
| 416 | result = append(result, migrate.Checksum(ddl)) |
| 417 | } |
| 418 | executionMust(t, rows.Err()) |
| 419 | executionMust(t, rows.Close()) |
| 420 | return result |
| 421 | } |
| 422 | |
| 423 | func seedExecutionJob(d *sql.DB) error { |
| 424 | _, 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,'','','')`) |
| 425 | return err |
| 426 | } |
| 427 | |
| 428 | func TestExecutionBackupIncludesArtifacts(t *testing.T) { |
| 429 | d, path := executionDB(t) |
| 430 | ctx := context.Background() |
| 431 | options := executionOptions() |
| 432 | options.Authority.(*team.FakeAuthority).Issue("backup-grant", team.Grant{Account: "team", Operations: map[team.Operation]bool{team.OpJobContinue: true, team.OpAttemptContinue: true}}) |
| 433 | x, err := equipo.NewStore(d).AttachExecution(ctx, path, options) |
| 434 | executionMust(t, err) |
| 435 | defer x.Core.Close() |
| 436 | _, err = x.Core.Resume(ctx) |
| 437 | executionMust(t, err) |
| 438 | job, err := x.Core.CreateJob(ctx, team.JobSpec{ |
| 439 | Account: "team", Requester: ownerAddress, GrantRef: "backup-grant", |
| 440 | Target: team.TargetBinding{Kind: team.TargetRepository, Repository: "example/shop", Ref: "team/backup-test", DefaultRef: "main", BaseRevision: fmt.Sprintf("%064x", 1)}, |
| 441 | Evidence: team.EvidenceRequirement{Predicate: team.PredicateSoftwareFix, ExpectedSymptom: team.FixtureSymptom, CheckDefinitionHash: team.CheckDefinitionHash}, |
| 442 | Policy: team.DefaultPolicy(5_000_000, team.Rates{Version: 1}), Steps: team.SoftwareSteps(false), |
| 443 | }) |
| 444 | executionMust(t, err) |
| 445 | scope := team.Scope{Account: job.Account, Job: job.ID} |
| 446 | handle, err := x.Core.Claim(ctx, scope, "reproduce", "backup-runner", "backup-workspace") |
| 447 | executionMust(t, err) |
| 448 | reproduction := []byte{0, 1, 2, 255, 'r', 'e', 'p', 'r', 'o'} |
| 449 | _, 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"}}) |
| 450 | executionMust(t, err) |
| 451 | executionMust(t, x.Write(ctx, func(tx *gorm.DB) error { |
| 452 | return tx.Create(&equipo.Account{Label: "backup account"}).Error |
| 453 | })) |
| 454 | backup := filepath.Join(t.TempDir(), "backup.db") |
| 455 | _, err = d.Writer().Exec(`VACUUM INTO ?`, backup) |
| 456 | executionMust(t, err) |
| 457 | restored, err := sql.Open("sqlite", backup) |
| 458 | executionMust(t, err) |
| 459 | defer restored.Close() |
| 460 | var label, requester string |
| 461 | var payload []byte |
| 462 | executionMust(t, restored.QueryRow(`SELECT label FROM accounts`).Scan(&label)) |
| 463 | executionMust(t, restored.QueryRow(`SELECT requester FROM jobs`).Scan(&requester)) |
| 464 | executionMust(t, restored.QueryRow(`SELECT payload FROM artifacts`).Scan(&payload)) |
| 465 | if label != "backup account" || requester != ownerAddress || !bytes.Equal(payload, reproduction) { |
| 466 | t.Fatal("activation backup lost app, job or reproduction bytes") |
| 467 | } |
| 468 | } |
| 469 | |
| 470 | func schemaBefore(id, version string) bool { |
| 471 | // Oficina ID stores arrived with 0082, after these historical snapshots. |
| 472 | for _, prefix := range []string{"oficina_handoff/", "oficina_connect_link/", "equipo_identity/"} { |
| 473 | if strings.HasPrefix(id, prefix) { |
| 474 | return version >= "0082" |
| 475 | } |
| 476 | } |
| 477 | return !strings.HasPrefix(id, "equipo/") || strings.Split(strings.TrimPrefix(id, "equipo/"), "_")[0] <= version |
| 478 | } |
| 479 | func schemaAfter(version string) []string { |
| 480 | var ids []string |
| 481 | for _, m := range equipo.BootSchema.All() { |
| 482 | if !schemaBefore(m.ID, version) { |
| 483 | ids = append(ids, m.ID) |
| 484 | } |
| 485 | } |
| 486 | return ids |
| 487 | } |
| 488 | |