package postgres import ( "backend/internal/adapter/storage" "backend/internal/application/usecase" "backend/internal/config" "backend/internal/domain/model" "backend/internal/domain/port" "bytes" "context" "crypto/sha256" "encoding/hex" "errors" "github.com/google/uuid" "github.com/jackc/pgx/v5/pgxpool" "io" "os" "reflect" "sync" "syscall" "testing" "time" ) func TestReplayAfterCompletedPreviousVersionCleanup(t *testing.T) { if os.Getenv("RUN_PIPELINE_DB_TESTS") != "1" { t.Skip("explicit isolated database required") } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() raw, e := config.ReadSecret("/run/secrets/database_url") if e != nil { t.Fatal("database file unavailable") } pool, e := pgxpool.New(ctx, raw) if e != nil { t.Fatal("database connection unavailable") } defer pool.Close() s := New(pool, nil) user, e := s.CreateUser(ctx, model.UserDraft{Username: "v2_" + uuid.NewString()[:8], DisplayName: "Synthetic version test", PasswordHash: "disabled-synthetic"}) if e != nil { t.Fatal(e) } var chatID, attachmentID uuid.UUID defer func() { cleanup, c := context.WithTimeout(context.Background(), 5*time.Second) defer c() for _, q := range []struct { sql string id uuid.UUID }{{"DELETE FROM attachment_jobs WHERE attachment_id=$1", attachmentID}, {"DELETE FROM attachments WHERE id=$1", attachmentID}, {"DELETE FROM chat_members WHERE chat_id=$1", chatID}, {"DELETE FROM chats WHERE id=$1", chatID}, {"DELETE FROM users WHERE id=$1", user.ID}} { if _, e := pool.Exec(cleanup, q.sql, q.id); e != nil { t.Error("version fixture cleanup failed") } } }() chat, e := s.CreateChat(ctx, model.ChatDraft{Title: "Owned version fixture", Creator: user.ID, MemberIDs: []uuid.UUID{user.ID}}) if e != nil { t.Fatal(e) } chatID = chat.ID attachmentID = uuid.New() a, e := s.ReserveAttachment(ctx, model.Attachment{ID: attachmentID, ChatID: chatID, OwnerID: user.ID, Filename: "test.png", ContentType: "image/png", SizeBytes: 3, SHA256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}) if e != nil { t.Fatal(e) } if _, e = s.QueueAttachment(ctx, a, "", ""); e != nil { t.Fatal(e) } jobs, e := s.PendingJobs(ctx) if e != nil { t.Fatal(e) } var j model.Job for _, candidate := range jobs { if candidate.AttachmentID == attachmentID { j = candidate } } lease := uuid.New() j, _, ok, e := s.AcquireJob(ctx, j, lease, 30*time.Second) if e != nil || !ok { t.Fatal("version1 acquisition failed") } if ok, e = s.CompleteJob(ctx, j, lease, []model.Variant{}); e != nil || !ok { t.Fatal("version1 completion failed") } if _, e = s.StagingCleanup(ctx); e != nil { t.Fatal(e) } if e = s.StagingCleaned(ctx, attachmentID); e != nil { t.Fatal(e) } if ok, e = s.AdvancePipeline(ctx, attachmentID); e != nil || !ok { t.Fatal("version2 advance failed") } jobs, e = s.PendingJobs(ctx) if e != nil { t.Fatal(e) } for _, candidate := range jobs { if candidate.AttachmentID == attachmentID && candidate.PipelineVersion == 2 { j = candidate } } lease = uuid.New() j, _, ok, e = s.AcquireJob(ctx, j, lease, 30*time.Second) if e != nil || !ok { t.Fatal("version2 acquisition failed") } if e = s.RetryJob(ctx, j, lease, "retry_exhausted", 0, true); e != nil { t.Fatal(e) } ok, e = s.ReplayJob(ctx, attachmentID) if e != nil { t.Fatal(e) } if !ok { t.Fatal("ready version1 staging cleanup permanently blocked replay of failed version2 despite retained original") } var replays int var replayed time.Time if e = pool.QueryRow(ctx, "SELECT replay_count,replayed_at FROM attachment_jobs WHERE attachment_id=$1 AND pipeline_version=2", attachmentID).Scan(&replays, &replayed); e != nil || replays != 1 || replayed.IsZero() { t.Fatal("explicit replay has no durable audit count/timestamp") } } // This deterministic transformer makes v1/v2 effects distinguishable; the Store, // pipeline ownership/leases, transactions and S3 operations remain real. type versionTransformer struct { body string err error } func (v versionTransformer) Transform(context.Context, io.Reader) ([]port.ProcessedVariant, error) { if v.err != nil { return nil, v.err } out := []port.ProcessedVariant{} for _, name := range []string{"thumbnail", "crop", "optimized"} { body := []byte(v.body + name) sum := sha256.Sum256(body) out = append(out, port.ProcessedVariant{Metadata: model.Variant{Name: name, ContentType: "image/jpeg", SHA256: hex.EncodeToString(sum[:]), SizeBytes: int64(len(body)), Width: 1, Height: 1}, Bytes: body}) } return out, nil } func TestVersionedPipelineDuplicateReorderRetryAndCleanup(t *testing.T) { if os.Getenv("RUN_PIPELINE_DB_TESTS") != "1" { t.Skip("explicit isolated database and S3 required") } ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second) defer cancel() raw, e := config.ReadSecret("/run/secrets/database_url") if e != nil { t.Fatal("database file unavailable") } pool, e := pgxpool.New(ctx, raw) if e != nil { t.Fatal("database unavailable") } defer pool.Close() s := New(pool, nil) cfg, e := storage.ReadConfig("/run/secrets/s3_credentials") if e != nil { t.Fatal("S3 config unavailable") } objects, e := storage.FromConfig(cfg) if e != nil { t.Fatal(e) } user, e := s.CreateUser(ctx, model.UserDraft{Username: "matrix_" + uuid.NewString()[:8], DisplayName: "Synthetic fault matrix", PasswordHash: "disabled"}) if e != nil { t.Fatal(e) } chat, e := s.CreateChat(ctx, model.ChatDraft{Title: "Owned pipeline matrix", Creator: user.ID, MemberIDs: []uuid.UUID{user.ID}}) if e != nil { t.Fatal(e) } id := uuid.New() body := []byte("immutable-original") sum := sha256.Sum256(body) defer func() { c, stop := context.WithTimeout(context.Background(), 5*time.Second) defer stop() for _, key := range []string{"staging/" + id.String(), usecase.ObjectKey(id)} { if e := objects.Remove(c, key); e != nil { t.Error("object fixture cleanup failed") } } for version := int32(1); version <= 3; version++ { for _, name := range []string{"thumbnail", "crop", "optimized"} { if e := objects.Remove(c, usecase.VariantKey(id, version, name)); e != nil { t.Error("variant fixture cleanup failed") } } } for _, q := range []struct { sql string id uuid.UUID }{{"DELETE FROM attachment_jobs WHERE attachment_id=$1", id}, {"DELETE FROM attachments WHERE id=$1", id}, {"DELETE FROM chat_members WHERE chat_id=$1", chat.ID}, {"DELETE FROM chats WHERE id=$1", chat.ID}, {"DELETE FROM users WHERE id=$1", user.ID}} { if _, e := pool.Exec(c, q.sql, q.id); e != nil { t.Error("database fixture cleanup failed") } } }() a, e := s.ReserveAttachment(ctx, model.Attachment{ID: id, ChatID: chat.ID, OwnerID: user.ID, Filename: "matrix.png", ContentType: "image/png", SizeBytes: int64(len(body)), SHA256: hex.EncodeToString(sum[:])}) if e != nil { t.Fatal(e) } if e = objects.Put(ctx, "staging/"+id.String(), bytes.NewReader(body), int64(len(body)), "image/png"); e != nil { t.Fatal(e) } if _, e = s.QueueAttachment(ctx, a, "", ""); e != nil { t.Fatal(e) } next := func(version int32) model.Job { t.Helper() jobs, e := s.PendingJobs(ctx) if e != nil { t.Fatal(e) } for _, j := range jobs { if j.AttachmentID == id && j.PipelineVersion == version { return j } } t.Fatal("owned current job not found") return model.Job{} } j1 := next(1) p1 := usecase.NewPipeline(s, objects, versionTransformer{body: "version1-"}, 5) p1.Fault = func(point string) error { if point == "after_commit" { return errors.New("synthetic crash after commit") } return nil } if e = p1.Process(ctx, j1); e == nil { t.Fatal("fault did not interrupt after commit") } a, e = s.GetAttachment(ctx, id) if e != nil || a.Status != "ready" || a.StagingCleaned { t.Fatal("commit fault did not preserve ready/pending cleanup") } if e = p1.Process(ctx, j1); e != nil { t.Fatal(e) } if _, e = objects.Get(ctx, "staging/"+id.String()); !errors.Is(e, model.ErrNotFound) { t.Fatal("completed redelivery did not remove staging") } if ok, e := s.AdvancePipeline(ctx, id); e != nil || !ok { t.Fatal("advance v2 failed") } j2 := next(2) // Old delivery arriving before v2 and a fabricated future delivery are no-ops. if e = p1.Process(ctx, j1); e != nil { t.Fatal(e) } future := j2 future.PipelineVersion = 3 if e = p1.Process(ctx, future); e != nil { t.Fatal(e) } p2 := usecase.NewPipeline(s, objects, versionTransformer{body: "version2-"}, 5) var group sync.WaitGroup errs := make(chan error, 2) for i := 0; i < 2; i++ { group.Add(1) go func() { defer group.Done(); errs <- p2.Process(ctx, j2) }() } group.Wait() close(errs) for e := range errs { if e != nil { t.Fatal(e) } } a, e = s.GetAttachment(ctx, id) if e != nil || a.PipelineVersion != 2 || a.Status != "ready" || len(a.Variants) != 3 { t.Fatal("duplicate current job lost result") } snapshot := a.Variants for _, j := range []model.Job{j1, j2, j1, future, j2} { if e = p1.Process(ctx, j); e != nil { t.Fatal(e) } } a, e = s.GetAttachment(ctx, id) if e != nil || !reflect.DeepEqual(snapshot, a.Variants) { t.Fatal("stale or duplicate job overwrote current metadata") } for _, v := range a.Variants { r, e := objects.Get(ctx, usecase.VariantKey(id, 2, v.Name)) if e != nil { t.Fatal(e) } got, e := io.ReadAll(r) r.Close() if e != nil || string(got) != "version2-"+v.Name { t.Fatal("old transformation overwrote v2 objects") } } if ok, e := s.AdvancePipeline(ctx, id); e != nil || !ok { t.Fatal("advance v3 failed") } j3 := next(3) broken := usecase.NewPipeline(s, objects, versionTransformer{err: syscall.ENOSPC}, 5) for i := 0; i < 5; i++ { if _, e = pool.Exec(ctx, "UPDATE attachment_jobs SET next_attempt='epoch' WHERE id=$1", j3.ID); e != nil { t.Fatal(e) } if e = broken.Process(ctx, j3); e != nil { t.Fatal(e) } } a, e = s.GetAttachment(ctx, id) if e != nil || a.Status != "failed" || a.ErrorCode != "retry_exhausted" { t.Fatal("transient infrastructure failure did not exhaust bounded retry") } if ok, e := s.ReplayJob(ctx, id); e != nil || !ok { t.Fatal("explicit replay blocked despite retained immutable source") } if e = p2.Process(ctx, j3); e != nil { t.Fatal(e) } a, e = s.GetAttachment(ctx, id) if e != nil || a.Status != "ready" || a.PipelineVersion != 3 { t.Fatal("replayed job did not recover") } }