ARTEX/server/task_pause_deadline_test.go
Marco Azarmaneche 8450cdc720 fix(server): do not time out a paused task
The deadline coordinator kept counting while a task was user-paused and
settled it at the original deadline (final planner round, then timeout),
also at startup for a task restored paused. After a resume the engine
still used the deadline cached before the pause, so the paused interval
credited onto deadline_at was ignored.

The coordinator now waits while the task is user-paused and re-reads the
deadline afterwards, and admission refreshes the cached deadline when it
ends a pause.

Refs #1
2026-12-01 23:08:55 +02:00

264 lines
8.9 KiB
Go

package server
import (
"context"
"database/sql"
"strconv"
"sync/atomic"
"testing"
"time"
"github.com/Autumn-27/artex/agent"
)
// Pausing a task must freeze its wall-clock timeout budget: the admission that
// ends the pause credits the paused interval back onto deadline_at, so a task
// paused overnight (or while the machine is off) resumes with its remaining
// time instead of immediately settling into the timeout terminal state (#1).
func TestPauseShiftsTaskDeadlineOnResume(t *testing.T) {
s, _, _ := trafficEvidenceServer(t)
m := s.m
pg := s.m.pg
task, err := m.CreateTask("pause deadline test", "verify the deadline is frozen while paused", nil, 3600, 0)
if err != nil {
t.Fatal(err)
}
id, err := strconv.ParseInt(task.ID, 10, 64)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = pg.DeleteTask(id) })
// A running task with a stamped deadline (first_run_at + 1h budget).
if _, err := m.StampTaskFirstRun(task.ID); err != nil {
t.Fatal(err)
}
if _, err := pg.Exec(`UPDATE tasks SET status='running' WHERE id=$1`, id); err != nil {
t.Fatal(err)
}
var before time.Time
if err := pg.QueryRow(`SELECT deadline_at FROM tasks WHERE id=$1`, id).Scan(&before); err != nil {
t.Fatal(err)
}
// Pause stamps paused_at alongside the user pause.
if err := m.ApplyTaskPause(task.ID); err != nil {
t.Fatal(err)
}
var pausedAt sql.NullTime
if err := pg.QueryRow(`SELECT paused_at FROM tasks WHERE id=$1`, id).Scan(&pausedAt); err != nil {
t.Fatal(err)
}
if !pausedAt.Valid || pausedAt.Time.After(time.Now()) {
t.Fatalf("pause should stamp paused_at at the current time, got %v", pausedAt.Time)
}
// Keep the task parked long enough for the credited interval to be measurable.
const paused = 1100 * time.Millisecond
time.Sleep(paused)
// Admission out of the paused state (a paused task keeps its lifecycle status).
if err := m.ApplyTaskAdmission(task.ID, "running", "running", false, "resume", false); err != nil {
t.Fatal(err)
}
var after time.Time
var cleared sql.NullTime
if err := pg.QueryRow(`SELECT deadline_at, paused_at FROM tasks WHERE id=$1`, id).Scan(&after, &cleared); err != nil {
t.Fatal(err)
}
if shifted := after.Sub(before); shifted < paused-100*time.Millisecond {
t.Fatalf("resume should credit the paused interval onto the deadline, got shift=%v (paused=%v)", shifted, paused)
}
if cleared.Valid {
t.Fatalf("admission should clear paused_at, got %v", cleared.Time)
}
// The live handle must mirror the shifted deadline (the engine clock context
// is built from it).
if got := task.lifecycleSnapshot().DeadlineAt; got != after.Unix() {
t.Fatalf("live handle deadline = %d, want the shifted %d", got, after.Unix())
}
}
// pausedPastDeadlineTask creates a running timeout task, user-pauses it and moves
// its deadline into the past, as after a long pause (#1).
func pausedPastDeadlineTask(t *testing.T, s *Server) (*Task, int64) {
t.Helper()
m, pg := s.m, s.m.pg
task, err := m.CreateTask("paused past deadline", "verify a paused task never times out", nil, 600, 0)
if err != nil {
t.Fatal(err)
}
id, err := strconv.ParseInt(task.ID, 10, 64)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = pg.DeleteTask(id) })
if _, err := m.StampTaskFirstRun(task.ID); err != nil {
t.Fatal(err)
}
if _, err := pg.Exec(`UPDATE tasks SET status='running' WHERE id=$1`, id); err != nil {
t.Fatal(err)
}
task.updateLifecycle(func(state *taskLifecycleState) { state.Status = "running" })
if err := m.ApplyTaskPause(task.ID); err != nil {
t.Fatal(err)
}
var past time.Time
if err := pg.QueryRow(`UPDATE tasks SET deadline_at=now()-interval '1 minute' WHERE id=$1 RETURNING deadline_at`, id).Scan(&past); err != nil {
t.Fatal(err)
}
task.updateLifecycle(func(state *taskLifecycleState) { state.DeadlineAt = past.Unix() })
return task, id
}
// countPlannerResolves makes the engine resolve no planner and counts the
// lookups: the settle sequence resolves the planner for its final round.
func countPlannerResolves(s *Server) *atomic.Int32 {
var n atomic.Int32
s.engine.SetAuthoritativeAgentResolver(func(*Task) (*agent.Planner, *agent.Worker) {
n.Add(1)
return nil, nil
})
return &n
}
func taskDBStatus(t *testing.T, s *Server, id int64) string {
t.Helper()
var status string
if err := s.m.pg.QueryRow(`SELECT status FROM tasks WHERE id=$1`, id).Scan(&status); err != nil {
t.Fatal(err)
}
return status
}
// A user-paused task whose deadline has passed must not be settled by a running
// deadline coordinator: no final planner round, no timeout terminal state.
func TestDeadlineCoordinatorDoesNotSettlePausedTask(t *testing.T) {
s, _, _ := trafficEvidenceServer(t)
task, id := pausedPastDeadlineTask(t, s)
resolves := countPlannerResolves(s)
ctx, cancel := context.WithTimeout(context.Background(), 2500*time.Millisecond)
defer cancel()
s.engine.deadlineCoordinator(ctx, task)
if s.engine.isSettling(task.ID) {
t.Fatal("paused task entered the settle sequence")
}
if n := resolves.Load(); n != 0 {
t.Fatalf("paused task ran a final planner round (planner resolved %d times)", n)
}
if status := taskDBStatus(t, s, id); isTerminalStatus(status) {
t.Fatalf("paused task settled to %q", status)
}
}
// Restart path (#1's original repro): a task paused past its deadline is
// restored paused and must stay so until the user resumes it.
func TestRestoredPausedTaskPastDeadlineIsNotSettled(t *testing.T) {
s, _, _ := trafficEvidenceServer(t)
task, id := pausedPastDeadlineTask(t, s)
// The restored loops resolve agents for readiness checks; only the settle
// state and the persisted status tell whether a final round ran.
countPlannerResolves(s)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
s.ctx = ctx
s.restoreTaskRuntimes()
stopAll := func() {
cancel()
for _, task := range s.m.List() {
s.engine.StopTask(task.ID)
}
}
t.Cleanup(stopAll)
restored, ok := s.m.Task(task.ID)
if !ok || !restored.lifecycleSnapshot().Paused {
t.Fatal("task was not restored paused")
}
time.Sleep(2500 * time.Millisecond)
if s.engine.isSettling(task.ID) {
t.Fatal("restored paused task entered the settle sequence")
}
stopAll()
if status := taskDBStatus(t, s, id); isTerminalStatus(status) {
t.Fatalf("restored paused task settled to %q", status)
}
}
// After pause + resume the engine must use the credited deadline: the cached
// deadline follows deadline_at, and the coordinator settles at the new
// deadline, not the original one.
func TestResumedTaskSettlesAtCreditedDeadline(t *testing.T) {
s, _, _ := trafficEvidenceServer(t)
m, pg := s.m, s.m.pg
task, err := m.CreateTask("resume deadline", "verify the credited deadline is used", nil, 600, 0)
if err != nil {
t.Fatal(err)
}
id, _ := strconv.ParseInt(task.ID, 10, 64)
t.Cleanup(func() { _ = pg.DeleteTask(id) })
if _, err := m.StampTaskFirstRun(task.ID); err != nil {
t.Fatal(err)
}
if _, err := pg.Exec(`UPDATE tasks SET status='running' WHERE id=$1`, id); err != nil {
t.Fatal(err)
}
task.updateLifecycle(func(state *taskLifecycleState) { state.Status = "running" })
// The original deadline is 2s away and cached by the engine, as after the
// first real run.
var orig time.Time
if err := pg.QueryRow(`UPDATE tasks SET deadline_at=now()+interval '2 seconds' WHERE id=$1 RETURNING deadline_at`, id).Scan(&orig); err != nil {
t.Fatal(err)
}
task.updateLifecycle(func(state *taskLifecycleState) { state.DeadlineAt = orig.Unix() })
if got := s.engine.taskDeadline(task); got != orig.Unix() {
t.Fatalf("cached deadline = %d, want %d", got, orig.Unix())
}
if _, err := s.applyTaskControl(task, "pause"); err != nil {
t.Fatal(err)
}
time.Sleep(3 * time.Second) // the original deadline passes while paused
if _, err := s.applyTaskControl(task, "resume"); err != nil {
t.Fatal(err)
}
var credited time.Time
if err := pg.QueryRow(`SELECT deadline_at FROM tasks WHERE id=$1`, id).Scan(&credited); err != nil {
t.Fatal(err)
}
if credited.Sub(orig) < 2900*time.Millisecond {
t.Fatalf("resume did not credit the paused interval: orig=%v credited=%v", orig, credited)
}
if got := s.engine.taskDeadline(task); got != credited.Unix() {
t.Fatalf("engine deadline after resume = %d, want the credited %d (original %d)", got, credited.Unix(), orig.Unix())
}
countPlannerResolves(s)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
done := make(chan struct{})
go func() {
defer close(done)
s.engine.deadlineCoordinator(ctx, task)
}()
defer func() { cancel(); <-done }()
time.Sleep(500 * time.Millisecond)
if s.engine.isSettling(task.ID) {
t.Fatal("coordinator settled at the original deadline")
}
for !s.engine.isSettling(task.ID) {
if time.Until(credited) < -3*time.Second {
t.Fatal("coordinator did not settle at the credited deadline")
}
time.Sleep(50 * time.Millisecond)
}
if now := time.Now().Unix(); now < credited.Unix() {
t.Fatalf("settled at %d, before the credited deadline %d", now, credited.Unix())
}
}