package pipeline import ( "context" "git.a-wan.net/alan/pipelines/internal/protocol" "path/filepath" "reflect" "testing" ) func TestFileChangeMigrationAndAtomicImmutableFinish(t *testing.T) { ctx := context.Background() db := filepath.Join(t.TempDir(), "old.db") s, err := Open(db) if err != nil { t.Fatal(err) } if _, err = s.Submit(ctx, "audit", Template([]string{"one"}, true)); err != nil { t.Fatal(err) } items, _ := s.List(ctx) def, _ := s.Get(ctx, items[0].ID, 1) id, _, err := s.CreateRun(ctx, def, "key", "workspace", false, nil, nil) if err != nil { t.Fatal(err) } if err = s.BeginStep(ctx, id, 1, "one", nil); err != nil { t.Fatal(err) } // Simulate the pre-diff database while retaining its existing history. if _, err = s.db.Exec("DROP TABLE step_file_changes"); err != nil { t.Fatal(err) } s.Close() s, err = Open(db) if err != nil { t.Fatal(err) } defer s.Close() run, err := s.GetRun(ctx, id) if err != nil || run.Steps[0].FileChanges != nil { t.Fatal("historical step misleading", run, err) } c := &protocol.StageFileChanges{Status: "complete", Files: []protocol.FileChange{{Path: "file", Kind: "added", Patch: "+new\n"}}} step := protocol.RunStep{Sequence: 1, Status: "completed", Outcome: "success", Target: protocol.SuccessEnd, FileChanges: c} if err = s.FinishStep(ctx, id, step); err != nil { t.Fatal(err) } step.FileChanges = &protocol.StageFileChanges{Status: "complete"} if err = s.FinishStep(ctx, id, step); err == nil { t.Fatal("finished evidence overwritten") } run, err = s.GetRun(ctx, id) if err != nil || !reflect.DeepEqual(run.Steps[0].FileChanges, c) { t.Fatal("diff lost/changed", run, err) } if err = s.BeginStep(ctx, id, 2, "one", nil); err != nil { t.Fatal(err) } if _, err = s.db.Exec(`CREATE TRIGGER fail_diff BEFORE INSERT ON step_file_changes BEGIN SELECT RAISE(ABORT,'fixture'); END`); err != nil { t.Fatal(err) } step.Sequence = 2 step.FileChanges = c if err = s.FinishStep(ctx, id, step); err == nil { t.Fatal("expected write failure") } run, err = s.GetRun(ctx, id) if err != nil || run.Steps[1].Status != "running" || run.Steps[1].FileChanges != nil { t.Fatal("partial finish committed", run, err) } }