ARTEX/db/planner_progress_bounds_test.go
BaaRai c781277d2f fix(planner): keep needs_attention across automatic resumes
Resume now only lifts the pause and notifies; ResumePlanning owns the
planner_progress reset, and only the operator resume and resume_planning
call it. A compensated pause, queue admission or goal revive no longer
clears needs_attention.

A queued task keeps its pause in resume_planning: that pause is the
admission barrier. The operator resume is still the only path that lifts
it.

The migration test derives its expected versions from the embedded files
and requires a contiguous sequence, so 0020 and 0021 must both be present.
The fingerprint no longer includes the encrypted password.
2026-11-30 03:16:35 +01:00

279 lines
9.9 KiB
Go

package db
import (
"context"
"io/fs"
"os"
"strings"
"testing"
"time"
)
// These need PostgreSQL (ARTEX_PG_DSN); they skip without it.
func planningFixture(t *testing.T) (*DB, *ExplorationStore, int64) {
t.Helper()
d, err := Open(testDSN(t))
if err != nil {
SkipPGUnavailable(t, err)
}
t.Cleanup(func() { _ = d.Close() })
task, err := d.CreateTask("planning breaker fixture", "compare fixtures", nil, 0, 0)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = d.DeleteTask(task.ID) })
s := d.Exploration(task.ExplorationID)
if _, err := s.AddGoal(map[string]any{"text": "compare fixtures"}, "fixture"); err != nil {
t.Fatal(err)
}
return d, s, task.ID
}
// tripBreaker records MaxPlanningFailures failed rounds on the current input.
func tripBreaker(t *testing.T, s *ExplorationStore) {
t.Helper()
ctx := context.Background()
for range MaxPlanningFailures {
snap, err := s.PlanningSnapshot(ctx)
if err != nil {
t.Fatal(err)
}
next := time.Now().Add(30 * time.Second)
if err := s.SavePlanningProgress(ctx, snap, "stalled", "fixture empty round", &next); err != nil {
t.Fatal(err)
}
}
p, err := s.PlanningProgress(ctx)
if err != nil || p.State != "needs_attention" {
t.Fatalf("breaker not tripped: %+v %v", p, err)
}
}
func planningAllowedLater(t *testing.T, s *ExplorationStore) bool {
t.Helper()
ok, err := s.PlanningAllowed(context.Background(), time.Now().Add(24*time.Hour))
if err != nil {
t.Fatal(err)
}
return ok
}
// The retry schedule itself; no PostgreSQL needed.
func TestPlanningRetryDelaySchedule(t *testing.T) {
for failures, want := range map[int]time.Duration{1: 30 * time.Second, 2: 5 * time.Minute, 3: 30 * time.Minute} {
if got, ok := PlanningRetryDelay(failures); !ok || got != want {
t.Errorf("failures=%d: delay=%v ok=%v, want %v", failures, got, ok, want)
}
}
for _, failures := range []int{0, MaxPlanningFailures + 1, MaxPlanningFailures + 2} {
if got, ok := PlanningRetryDelay(failures); ok {
t.Errorf("failures=%d: delay=%v, want no further retry", failures, got)
}
}
}
// A retrying save (provider, storage or timeout error) counts like an empty
// round and never resets the counter. Each failure on unchanged input waits
// longer, 30 s, 5 min, then 30 min, and the failure after the 30 min wait
// stops at needs_attention instead of retrying forever. The stored next_check
// is compared with the injected failure time.
func TestPlanningRetryBackoffThenNeedsAttention(t *testing.T) {
_, s, _ := planningFixture(t)
ctx := context.Background()
snap, err := s.PlanningSnapshot(ctx)
if err != nil {
t.Fatal(err)
}
allowedAt := func(at time.Time) bool {
t.Helper()
ok, err := s.PlanningAllowed(ctx, at)
if err != nil {
t.Fatal(err)
}
return ok
}
now := time.Date(2026, 11, 29, 12, 0, 0, 0, time.UTC)
for i, wait := range []time.Duration{30 * time.Second, 5 * time.Minute, 30 * time.Minute} {
if err := s.RecordPlanningRetry(ctx, snap, "synthetic provider outage", now); err != nil {
t.Fatal(err)
}
p, err := s.PlanningProgress(ctx)
if err != nil {
t.Fatal(err)
}
if p.State != "retrying" || p.Failures != i+1 || p.NextCheck == nil || !p.NextCheck.Equal(now.Add(wait)) {
t.Fatalf("failure %d: %+v, want retrying with next_check=%v (+%v)", i+1, p, now.Add(wait), wait)
}
if allowedAt(now.Add(wait - time.Second)) {
t.Fatalf("failure %d: planning allowed before the %v wait ended", i+1, wait)
}
if !allowedAt(now.Add(wait)) {
t.Fatalf("failure %d: planning still held at next_check", i+1)
}
now = now.Add(wait) // the next attempt runs at the deadline
}
if err := s.RecordPlanningRetry(ctx, snap, "synthetic provider outage", now); err != nil {
t.Fatal(err)
}
if p, err := s.PlanningProgress(ctx); err != nil || p.State != "needs_attention" || p.Failures != MaxPlanningFailures+1 || p.NextCheck != nil {
t.Fatalf("failure after the 30 min wait: %+v %v, want needs_attention without a next check", p, err)
}
if planningAllowedLater(t, s) {
t.Fatal("a persistent error keeps consuming provider calls")
}
if err := s.SavePlanningProgress(ctx, snap, "retrying", "x", nil); err == nil {
t.Fatal("SavePlanningProgress recorded a retrying round without its backoff")
}
// Real progress still resets the counter.
if err := s.SavePlanningProgress(ctx, snap, "active", "work dispatched", nil); err != nil {
t.Fatal(err)
}
if p, err := s.PlanningProgress(ctx); err != nil || p.Failures != 0 || p.State != "active" {
t.Fatalf("after progress: %+v %v", p, err)
}
}
// Nodes the planner writes do not re-arm the breaker; worker and human nodes,
// a planner intent that a worker moved, task scope set by a human, and assets
// linked to the task do.
func TestPlanningFingerprintPlannerWritesVersusNewInput(t *testing.T) {
d, s, taskID := planningFixture(t)
tripBreaker(t, s)
// Planner writes: a fact, a hint, a scheduled intent, agent task scope.
if _, err := s.AddNode("fact", map[string]any{"summary": "planner note"}, 0, "confirmed", "planner", nil); err != nil {
t.Fatal(err)
}
if _, err := s.AddNode("hint", map[string]any{"text": "planner hint"}, 0, "active", "planner", nil); err != nil {
t.Fatal(err)
}
intent, err := s.AddIntent(map[string]any{"summary": "scheduled planner step", "not_before": time.Now().Add(time.Hour).Format(time.RFC3339)}, 0, nil, "planner")
if err != nil {
t.Fatal(err)
}
if _, err := d.Exec(`INSERT INTO task_scope(task_id, kind, value, source, reason) VALUES($1,'keyword','planner-widened','agent','fixture')`, taskID); err != nil {
t.Fatal(err)
}
if planningAllowedLater(t, s) {
t.Fatal("planner-written nodes or agent scope re-armed the breaker")
}
reopen := []struct {
name string
do func() error
}{
{"worker fact", func() error {
_, err := s.AddNode("fact", map[string]any{"summary": "worker observed fixture C"}, 0, "confirmed", "worker-1", nil)
return err
}},
{"human hint", func() error {
_, err := s.AddNode("hint", map[string]any{"text": "operator hint"}, 0, "active", "human", nil)
return err
}},
{"planner intent moved by a human", func() error { return s.SetIntentState(intent, "paused") }},
{"manual task scope", func() error {
_, err := d.Exec(`INSERT INTO task_scope(task_id, kind, value, source, reason) VALUES($1,'keyword','operator-added','manual','fixture')`, taskID)
return err
}},
{"manual task scope removed", func() error {
_, err := d.Exec(`DELETE FROM task_scope WHERE task_id=$1 AND source='manual' AND value='operator-added'`, taskID)
return err
}},
{"asset linked to the task", func() error {
_, err := d.Exec(`INSERT INTO assets(type, domain, root_domain, task_ids) VALUES('subdomain', $1, 'fixture.test', ARRAY[$2::bigint])`,
"a"+strings.ReplaceAll(time.Now().Format("150405.000000000"), ".", "")+".fixture.test", taskID)
return err
}},
}
for _, step := range reopen {
if err := step.do(); err != nil {
t.Fatalf("%s: %v", step.name, err)
}
if !planningAllowedLater(t, s) {
t.Fatalf("%s did not reopen planning", step.name)
}
tripBreaker(t, s) // re-arm on the new input for the next step
}
t.Cleanup(func() {
_, _ = d.Exec(`DELETE FROM assets WHERE root_domain='fixture.test' AND $1::bigint = ANY(task_ids)`, taskID)
})
}
// Saving the same credential twice seals its password again with a new
// ciphertext; the fingerprint must not change, or the save re-arms the breaker.
func TestPlanningFingerprintIgnoresCredentialResave(t *testing.T) {
d, s, taskID := planningFixture(t)
in := TaskCredentialInput{Domain: "fixture.invalid", Username: "fixture-user", Password: "fixture-only-not-a-real-secret", Source: "user"}
sealed := func() string {
t.Helper()
var v string
if err := d.QueryRow(`SELECT password FROM task_credentials WHERE task_id=$1`, taskID).Scan(&v); err != nil {
t.Fatal(err)
}
return v
}
if _, err := d.UpsertTaskCredential(taskID, in); err != nil {
t.Fatal(err)
}
first, firstSealed := snapshotFingerprint(t, s), sealed()
if _, err := d.UpsertTaskCredential(taskID, in); err != nil {
t.Fatal(err)
}
if sealed() == firstSealed {
t.Fatal("fixture: the second save kept the same ciphertext")
}
if second := snapshotFingerprint(t, s); second != first {
t.Fatalf("fingerprint changed on an identical credential save: %s -> %s", first, second)
}
}
func snapshotFingerprint(t *testing.T, s *ExplorationStore) string {
t.Helper()
snap, err := s.PlanningSnapshot(context.Background())
if err != nil {
t.Fatal(err)
}
return snap.Fingerprint
}
// planner_progress is created by a numbered migration, not schema.sql, and the
// migration replaces a state constraint written by the earlier boot-time DDL.
func TestPlannerProgressMigration(t *testing.T) {
schema, err := os.ReadFile("schema.sql")
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(schema), "planner_progress") {
t.Fatal("schema.sql still carries planner_progress DDL; it belongs in a numbered migration")
}
d, s, _ := planningFixture(t)
ctx := context.Background()
migration, err := fs.ReadFile(migrationsFS(), "0021_planner_progress.sql")
if err != nil {
t.Fatal(err)
}
// A database that ran the earlier boot-time DDL has the constraint
// without 'retrying'.
if _, err := d.Exec(`DELETE FROM planner_progress WHERE exploration_id=$1`, s.ID()); err != nil {
t.Fatal(err)
}
if _, err := d.Exec(`ALTER TABLE planner_progress DROP CONSTRAINT planner_progress_state_check;
ALTER TABLE planner_progress ADD CONSTRAINT planner_progress_state_check CHECK(state IN ('active','waiting','stalled','needs_attention')) NOT VALID`); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _, _ = d.Exec(string(migration)) }) // never leave the old constraint behind
snap, err := s.PlanningSnapshot(ctx)
if err != nil {
t.Fatal(err)
}
if err := s.RecordPlanningRetry(ctx, snap, "x", time.Now()); err == nil {
t.Fatal("old constraint accepted retrying; fixture did not take effect")
}
if _, err := d.Exec(string(migration)); err != nil {
t.Fatal(err)
}
if err := s.RecordPlanningRetry(ctx, snap, "x", time.Now()); err != nil {
t.Fatalf("after the migration: %v", err)
}
}