diff --git a/db/task_archives.go b/db/task_archives.go index a8c8101..bf4fa36 100644 --- a/db/task_archives.go +++ b/db/task_archives.go @@ -456,7 +456,10 @@ func (d *DB) FailTaskArchiveJob(id int64, activeState string, cause error) error if cause != nil { message = cause.Error() } - _, err := d.Exec(`UPDATE task_archives SET state=$2,phase='failed',error=$3 WHERE id=$1`, id, failed, message) + // Only a job still in its active state fails. The worker also reports a panic + // it recovered after the job committed: a ready archive marked archive_failed + // could be neither restored nor deleted. + _, err := d.Exec(`UPDATE task_archives SET state=$2,phase='failed',error=$3 WHERE id=$1 AND state=$4`, id, failed, message, activeState) return err } diff --git a/db/task_archives_test.go b/db/task_archives_test.go index 15198a9..c6cd934 100644 --- a/db/task_archives_test.go +++ b/db/task_archives_test.go @@ -524,3 +524,45 @@ func TestFillArchiveDefaults(t *testing.T) { t.Fatalf("activity changed: %s err=%v", out, err) } } + +// FailTaskArchiveJob fails a job that is still running. A failure reported after +// the archive committed (the worker recovers a panic in the cleanup that follows +// the commit) must not turn a ready archive into archive_failed: it could then +// be neither restored nor deleted. +func TestFailTaskArchiveJobKeepsCommittedState(t *testing.T) { + d, err := Open(testDSN(t)) + if err != nil { + SkipPGUnavailable(t, err) + } + defer d.Close() + task, err := d.CreateTaskWithOptions("late archive failure", "must stay ready", TaskCreateOptions{}) + if err != nil { + t.Fatal(err) + } + defer func() { + _, _ = d.Exec(`DELETE FROM task_archives WHERE task_id=$1`, task.ID) + _ = d.DeleteTask(task.ID) + }() + if err := d.SetPaused(task.ID, true); err != nil { + t.Fatal(err) + } + queued, err := d.QueueTaskArchive(task.ID) + if err != nil { + t.Fatal(err) + } + for _, c := range []struct{ state, want string }{{Archiving, ArchiveFailed}, {ArchiveReady, ArchiveReady}} { + if _, err := d.Exec(`UPDATE task_archives SET state=$2,error='' WHERE id=$1`, queued.ID, c.state); err != nil { + t.Fatal(err) + } + if err := d.FailTaskArchiveJob(queued.ID, Archiving, errors.New("late failure")); err != nil { + t.Fatal(err) + } + item, err := d.GetTaskArchive(queued.ID) + if err != nil || item == nil { + t.Fatalf("archive %d: %v", queued.ID, err) + } + if item.State != c.want || (c.want == ArchiveFailed) != (item.Error == "late failure") { + t.Fatalf("failing a job in state %s: state=%s error=%q, want state %s", c.state, item.State, item.Error, c.want) + } + } +} diff --git a/server/task_archive_panic_test.go b/server/task_archive_panic_test.go new file mode 100644 index 0000000..1f3c7ca --- /dev/null +++ b/server/task_archive_panic_test.go @@ -0,0 +1,131 @@ +package server + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/Autumn-27/artex/archivestore" + pgdb "github.com/Autumn-27/artex/db" +) + +// An S3-compatible endpoint that answers CreateMultipartUpload with 200 and no +// UploadId makes the SDK's upload manager dereference a nil pointer. The panic +// happens in the archive worker goroutine: it must fail that one job like any +// other upload error, keep the source data, and leave the process running. +func TestReview318ArchiveWorkerSurvivesUploadPanic(t *testing.T) { + skipWithoutDSN(t) + t.Setenv("ARTEX_ARCHIVE_STORAGE", "local") + m, err := NewManager(t.TempDir(), "") + if err != nil { + t.Fatal(err) + } + defer m.Close() + ctx, cancel := context.WithCancel(context.Background()) + cancel() + s := New(ctx, m, t.TempDir(), t.TempDir(), t.TempDir()) + s.archiveWG.Wait() + + var creates, unexpected atomic.Int32 + remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + switch { + case r.Method == http.MethodPost && r.URL.Query().Has("uploads"): + creates.Add(1) + w.Header().Set("Content-Type", "application/xml") + _, _ = io.WriteString(w, `test`) + case r.Method == http.MethodDelete: + // The worker's deferred cleanup of the upload that never committed. + w.WriteHeader(http.StatusNoContent) + default: + unexpected.Add(1) + w.WriteHeader(http.StatusBadRequest) + } + })) + defer remote.Close() + s.archiveStore, err = archivestore.New(archivestore.Config{Endpoint: remote.URL, Bucket: "test", Prefix: "tasks", AccessKey: "test", SecretKey: "test", PathStyle: true}) + if err != nil { + t.Fatal(err) + } + + task, err := m.CreateTask("multipart panic", "keep the source", nil, 0, 0) + if err != nil { + t.Fatal(err) + } + id, _ := strconv.ParseInt(task.ID, 10, 64) + defer func() { _, _ = m.pg.Exec(`DELETE FROM task_archives WHERE task_id=$1`, id); _ = m.pg.DeleteTask(id) }() + if err := m.pg.SetPaused(id, true); err != nil { + t.Fatal(err) + } + // The package must exceed the 8 MiB part size of archivestore.Upload for the + // upload manager to choose multipart: 9 MiB of random bytes do not compress. + source := make([]byte, 9<<20) + if _, err := rand.Read(source); err != nil { + t.Fatal(err) + } + file := filepath.Join(m.dir, "tasks", task.ID, "workspace", "large.bin") + if err := os.MkdirAll(filepath.Dir(file), 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(file, source, 0600); err != nil { + t.Fatal(err) + } + job, err := m.pg.QueueTaskArchive(id) + if err != nil { + t.Fatal(err) + } + + // Run the server's own worker goroutine, as New starts it. + workerCtx, stopWorker := context.WithCancel(context.Background()) + s.ctx = workerCtx + s.startTaskArchiveWorker() + defer func() { stopWorker(); s.archiveWG.Wait() }() + + deadline := time.Now().Add(2 * time.Minute) + var item *pgdb.TaskArchive + for { + item, err = m.pg.GetTaskArchive(job.ID) + if err != nil { + t.Fatal(err) + } + if item == nil { + t.Fatal("archive job disappeared") + } + if item.State != pgdb.ArchiveQueued && item.State != pgdb.Archiving { + break + } + if time.Now().After(deadline) { + t.Fatalf("archive job still %s (%s)", item.State, item.Phase) + } + time.Sleep(50 * time.Millisecond) + } + if creates.Load() != 1 { + t.Fatalf("expected one CreateMultipartUpload, got %d: the package did not take the multipart path", creates.Load()) + } + if item.State != pgdb.ArchiveFailed || !strings.Contains(item.Error, "panic") { + t.Fatalf("job must be archive_failed with the panic as its error: state=%s error=%q", item.State, item.Error) + } + if item.ArchivePath != "" || item.SHA256 != "" || item.ArchivedAt != nil { + t.Fatalf("a location was committed for a failed archive: path=%q sha256=%q archived_at=%v", item.ArchivePath, item.SHA256, item.ArchivedAt) + } + got, err := os.ReadFile(file) + if err != nil || sha256.Sum256(got) != sha256.Sum256(source) { + t.Fatalf("source file lost or changed after the panic: %v", err) + } + if pgTask, err := m.pg.GetTask(id); err != nil || pgTask == nil { + t.Fatalf("task lost after the panic: %v", err) + } + if unexpected.Load() != 0 { + t.Fatalf("%d unexpected S3 requests", unexpected.Load()) + } +} diff --git a/server/task_archives.go b/server/task_archives.go index 68e0d8a..daca52f 100644 --- a/server/task_archives.go +++ b/server/task_archives.go @@ -9,6 +9,7 @@ import ( "net/http" "os" "path/filepath" + "runtime/debug" "strconv" "strings" "time" @@ -114,18 +115,7 @@ func (s *Server) runOneTaskArchiveJob() error { if err != nil || job == nil { return err } - var runErr error - switch job.State { - case pgdb.Archiving: - runErr = s.archiveTask(job) - case pgdb.Restoring: - runErr = s.restoreTaskArchive(job) - case pgdb.Deleting: - runErr = s.deleteTaskArchive(job) - default: - runErr = fmt.Errorf("unknown claimed archive state %q", job.State) - } - if runErr != nil { + if runErr := s.runClaimedTaskArchiveJob(job); runErr != nil { if failErr := s.m.pg.FailTaskArchiveJob(job.ID, job.State, runErr); failErr != nil { return errors.Join(runErr, failErr) } @@ -136,6 +126,31 @@ func (s *Server) runOneTaskArchiveJob() error { return nil } +// runClaimedTaskArchiveJob runs one claimed job and turns a panic below it into +// an ordinary job failure. The worker goroutine has no other recover: a panic +// there (the S3 upload manager dereferences a nil UploadId when an endpoint +// answers CreateMultipartUpload without one) would end the whole server with the +// job half done. The job's deferred rollbacks have already run when the panic is +// recovered here, so the caller fails the job with its source data in place. +func (s *Server) runClaimedTaskArchiveJob(job *pgdb.TaskArchive) (runErr error) { + defer func() { + if r := recover(); r != nil { + log.Printf("[task-archive] archive job %d (%s) panicked: %v\n%s", job.ID, job.State, r, debug.Stack()) + runErr = fmt.Errorf("archive worker panic: %v", r) + } + }() + switch job.State { + case pgdb.Archiving: + return s.archiveTask(job) + case pgdb.Restoring: + return s.restoreTaskArchive(job) + case pgdb.Deleting: + return s.deleteTaskArchive(job) + default: + return fmt.Errorf("unknown claimed archive state %q", job.State) + } +} + func (s *Server) archiveTask(job *pgdb.TaskArchive) (runErr error) { if s.archiveStoreErr != nil { return s.archiveStoreErr