ARTEX/server/engine_budget_test.go
BaaRai d07abf006e fix(server): keep operator chat revival and prove the budget reservation
Review of #714 found three issues before it could ship in 0.7.1.

The Main Agent chat path used reviveTaskFromAgent, which refuses a timed-out
task by logging only, so an operator could no longer resume from the chat and
got no explanation. The chat is an explicit operator turn: it uses reviveTask
like the console again, and the admission guards still refuse a settling or
budget-exhausted task. Automatic agent revival through delegateToTask keeps
the stricter guard.

TestBudgetStopReservesPlannerRoundCost pre-marked the wrap-up before calling
budgetStop, so it passed because wrap-up was already set, not because the
planner+worker reservation worked. It now calls budgetStop from Plan alone,
with a bounded context that only shortens the settle wait.

README documents the planner+worker reservation, the skipped final judgment
past the hard ceiling, and which revivals are refused.

Verified: gofmt on the committed blobs, go build ./..., go vet ./...,
and the full ./agent ./server suites on disposable PostgreSQL 16, including
TestHardExhaustedBudgetSkipsFinalPlannerRound.
2026-11-30 22:39:55 +01:00

280 lines
12 KiB
Go

package server
import (
"context"
"errors"
"strconv"
"strings"
"testing"
"time"
"github.com/Autumn-27/artex/agent"
pgdb "github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/llmrec"
"github.com/Autumn-27/norma/llm"
)
// With the budget env vars unset the engine decides exactly as before (no round
// stopped, no claim blocked, contexts untouched, every tool call let through);
// a task budget flips the same decisions once the task cannot afford a worker.
func TestEngineBudgetPassthroughAndGate(t *testing.T) {
for _, k := range []string{"ARTEX_TASK_BUDGET_TOKENS", "ARTEX_TASK_BUDGET_TURNS", "ARTEX_INTENT_BUDGET_TOKENS", "ARTEX_INTENT_BUDGET_TURNS"} {
t.Setenv(k, "")
}
ctx, task := context.Background(), &Task{ID: "7"}
noSteer := func() (string, bool) { return "", false }
e := NewEngine(nil)
wctx, meter := e.budgetIntent(ctx, task.ID)
if e.budgetStop(ctx, task) || e.budgetBlocksClaim(task.ID) || e.budgetRoundCtx(ctx, task, false) != ctx || wctx != ctx || meter != nil {
t.Fatal("no budget: a decision or a context changed")
}
if block, _, _ := (steerHooks{drain: noSteer}).PreToolUse(ctx, "Bash", nil); block {
t.Fatal("no budget: a tool call was refused")
}
t.Setenv("ARTEX_TASK_BUDGET_TOKENS", "100000")
e = NewEngine(nil)
_, meter = e.budgetIntent(ctx, task.ID)
meter.Record(llm.Usage{InputTokens: 60_000}) // remaining 40k < default worker estimate 50k
h := steerHooks{drain: noSteer, budget: meter}
if block, _, _ := h.PreToolUse(ctx, "Bash", nil); !e.budgetBlocksClaim(task.ID) || block {
t.Fatal("budget: claim must be blocked, the running worker (above the reserve) not")
}
meter.Record(llm.Usage{OutputTokens: 20_000}) // reaches the 20k reserve
if block, msg, _ := h.PreToolUse(ctx, "Bash", nil); !block || msg != agent.WorkerBudgetWrapup {
t.Fatalf("budget: exhausted run not sent to wrap-up (block=%v msg=%q)", block, msg)
}
if block, _, _ := h.PreToolUse(ctx, "record_fact", nil); block {
t.Fatal("budget: write-back tool refused during the wrap-up")
}
}
// A finished run that settled with the budget wrap-up must not gate its revive:
// after resetSettledRun the task plans and claims again, with a fresh ledger.
func TestResetSettledRunRestartsBudget(t *testing.T) {
t.Setenv("ARTEX_TASK_BUDGET_TOKENS", "100000")
t.Setenv("ARTEX_TASK_BUDGET_TURNS", "")
t.Setenv("ARTEX_INTENT_BUDGET_TOKENS", "")
t.Setenv("ARTEX_INTENT_BUDGET_TURNS", "")
ctx, task := context.Background(), &Task{ID: "9"}
e := NewEngine(nil)
e.settling.Store(task.ID, true)
l := e.budgetFor(task.ID)
l.Record(llm.Usage{InputTokens: 90_000})
l.BeginWrapup()
if !e.isSettling(task.ID) || !e.budgetStop(ctx, task) || !e.budgetBlocksClaim(task.ID) {
t.Fatal("settled run: wrap-up must gate the planner and the workers before the revive")
}
e.resetSettledRun(task.ID)
if e.isSettling(task.ID) || e.budgetStop(ctx, task) || e.budgetBlocksClaim(task.ID) {
t.Fatal("revived run: planner or workers still gated by the previous run")
}
if got := e.budgetFor(task.ID).State().Spent.Tokens; got != 0 {
t.Fatalf("revived run: ledger not fresh, spent %d tokens", got)
}
}
// With Postgres, resetSettledRun drops the ledger and the next one is seeded
// again from llm_usage. In-memory spend that was never written does not come
// back. A restore that lands on the wrap-up reserve leaves only that reserve,
// and the worker estimate starts from the defaults.
func TestResetSettledRunReseedsBudgetFromUsage(t *testing.T) {
for _, k := range []string{"ARTEX_TASK_BUDGET_TURNS", "ARTEX_INTENT_BUDGET_TOKENS", "ARTEX_INTENT_BUDGET_TURNS"} {
t.Setenv(k, "")
}
t.Setenv("ARTEX_TASK_BUDGET_TOKENS", "100000")
m, err := NewManager(t.TempDir(), "")
if err != nil {
pgdb.SkipPGUnavailable(t, err)
}
t.Cleanup(func() { _ = m.Close() })
taskID := strconv.FormatInt(time.Now().UnixNano(), 10)
t.Cleanup(func() {
_, _ = m.pg.Exec(`DELETE FROM llm_usage WHERE task_id=$1`, taskID)
})
// 100000 - wrap-up reserve (max(5%, 20000)) = 80000. One planner row.
if err := m.pg.InsertLLMUsage(&pgdb.LLMUsage{
TaskID: taskID, Worker: "planner", InputTokens: 80_000, Status: "ok",
}); err != nil {
t.Fatal(err)
}
e := NewEngine(m)
task := &Task{ID: taskID}
l := e.budgetFor(task.ID)
st := l.State()
if st.Spent.Tokens != 80_000 || st.Spent.Turns != 1 {
t.Fatalf("seed spent=%+v, want 80000 tokens and 1 turn", st.Spent)
}
if st.Remaining.Tokens != st.Margin.Tokens || !st.AtMargin || st.Dispatch {
t.Fatalf("restored task near the cap: remaining=%d margin=%d at=%v dispatch=%v",
st.Remaining.Tokens, st.Margin.Tokens, st.AtMargin, st.Dispatch)
}
if st.Estimate.Tokens != agent.DefaultWorkerEstimateTokens || st.Estimate.Turns != agent.DefaultWorkerEstimateTurns {
t.Fatalf("estimate=%+v, want the defaults (worker history is not restored)", st.Estimate)
}
l.Record(llm.Usage{InputTokens: 1000})
l.BeginWrapup()
e.settling.Store(task.ID, true)
e.resetSettledRun(task.ID)
if e.isSettling(task.ID) {
t.Fatal("revived run is still marked settling")
}
again := e.budgetFor(task.ID)
if again == l {
t.Fatal("revive reused the deleted ledger")
}
got := again.State()
if got.Spent.Tokens != 80_000 || got.Spent.Turns != 1 {
t.Fatalf("reseed spent=%+v, want the usage row and not the in-memory extra", got.Spent)
}
if got.Remaining.Tokens != got.Margin.Tokens || got.Dispatch {
t.Fatalf("reseed still past the wrap-up margin: remaining=%d margin=%d dispatch=%v",
got.Remaining.Tokens, got.Margin.Tokens, got.Dispatch)
}
}
// Repro for #705: a task whose lifetime spend has already exceeded its budget
// plus wrap-up reserve must cancel any in-flight exec and skip the final
// planner round during settleTask (0 additional LLM calls).
func TestHardExhaustedBudgetSkipsFinalPlannerRound(t *testing.T) {
for _, k := range []string{"ARTEX_TASK_BUDGET_TURNS", "ARTEX_INTENT_BUDGET_TOKENS", "ARTEX_INTENT_BUDGET_TURNS"} {
t.Setenv(k, "")
}
t.Setenv("ARTEX_TASK_BUDGET_TOKENS", "250000")
e := NewEngine(nil)
plannerCalls := 0
e.SetAuthoritativeAgentResolver(func(*Task) (*agent.Planner, *agent.Worker) {
plannerCalls++
return nil, nil
})
task := &Task{ID: "705"}
execCtx := e.execContextFor(context.Background(), task.ID)
l := e.budgetFor(task.ID)
// Exact scale from #705: 347,003 tokens spent against a 250,000 token cap.
l.RestoreSpend(agent.Spend{Tokens: 347_003, Turns: 12})
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
if !e.budgetStop(ctx, task) {
t.Fatal("budgetStop did not stop a hard-exhausted task")
}
if plannerCalls != 0 {
t.Fatalf("hard-exhausted budgetStop attempted final planner round (resolver called %d times)", plannerCalls)
}
if !errors.Is(context.Cause(execCtx), agent.AbortSettleDrainTimeout) {
t.Fatalf("hard-exhausted settle did not cancel in-flight exec context: cause=%v", context.Cause(execCtx))
}
}
// budgetStop must account for the planner round's own estimated cost, not just
// the next worker's estimate, so it stops before starting a planner round whose
// cost would leave too little budget to dispatch any worker.
func TestBudgetStopReservesPlannerRoundCost(t *testing.T) {
t.Setenv("ARTEX_TASK_BUDGET_TOKENS", "250000")
t.Setenv("ARTEX_TASK_BUDGET_TURNS", "150")
t.Setenv("ARTEX_INTENT_BUDGET_TOKENS", "30000")
t.Setenv("ARTEX_INTENT_BUDGET_TURNS", "10")
e := NewEngine(nil)
task := &Task{ID: "706"}
// Run one metered planner round via budgetRoundCtx + llmrec.Wrap (40k tokens).
rctx := e.budgetRoundCtx(context.Background(), task, false)
rec := llmrec.Wrap(stopReasonProvider{stop: "end_turn"}, nil, "model", "profile", "", "", func() bool { return false })
for _, err := range rec.Stream(rctx, llm.CompletionRequest{}) {
if err != nil {
t.Fatal(err)
}
}
// Simulate a 40k-token planner round and finish its meter.
l := e.budgetFor(task.ID)
pm := l.StartPlannerRound(false)
pm.Record(llm.Usage{InputTokens: 39_959}) // +41 from stream = 40,000 total
pm.Finish()
// Add 155k worker/other spend -> 195k spent, 55k remaining:
// Worker estimate (30k) still fits (budgetBlocksClaim == false),
// but planner (40k) + worker (30k) = 70k > 55k (budgetBlocksPlan == true).
l.Record(llm.Usage{InputTokens: 155_000})
if e.budgetBlocksClaim(task.ID) {
t.Fatal("worker claim should still fit at 55k remaining vs 30k intent cap")
}
if !e.budgetBlocksPlan(task.ID) {
t.Fatal("budgetBlocksPlan must stop new planner round when planner+worker estimate exceeds remaining")
}
// budgetStop must reach the same decision from Plan alone, without a pre-marked
// wrap-up. The bounded context only shortens the settle sequence's final-round
// wait; it does not affect the gate under test.
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
if !e.budgetStop(ctx, task) {
t.Fatal("budgetStop did not stop a planner round that cannot afford planner+worker")
}
}
// Repro for #705: agent-triggered revival (set_goals / add_intent via
// reviveTaskFromAgent) must not revive timed-out, settling, or budget-exhausted
// tasks, and admitTask must refuse reviving any terminal task whose configured
// run budget is already exhausted.
func TestReviveGuardsPreventTimeoutSettlingAndBudgetLoops(t *testing.T) {
newTestServer := func(task *Task) *Server {
e := NewEngine(nil)
m := &Manager{tasks: map[string]*Task{task.ID: task}}
return &Server{m: m, engine: e, ctx: context.Background()}
}
t.Run("agent revival refuses timed-out task even without token budget", func(t *testing.T) {
for _, k := range []string{"ARTEX_TASK_BUDGET_TOKENS", "ARTEX_TASK_BUDGET_TURNS", "ARTEX_INTENT_BUDGET_TOKENS", "ARTEX_INTENT_BUDGET_TURNS"} {
t.Setenv(k, "")
}
task := &Task{ID: "101", Status: "timeout"}
s := newTestServer(task)
if _, err := s.admitTaskWhen(task, "resume", false, true); err == nil || !strings.Contains(err.Error(), "timed out") {
t.Fatalf("agent revival of timed-out task = %v, want timed-out refusal", err)
}
s.reviveTaskFromAgent(task)
if got := task.lifecycleSnapshot().Status; got != "timeout" {
t.Fatalf("status after reviveTaskFromAgent = %q, want timeout", got)
}
})
t.Run("admission refuses while in-flight settlement is active", func(t *testing.T) {
for _, k := range []string{"ARTEX_TASK_BUDGET_TOKENS", "ARTEX_TASK_BUDGET_TURNS", "ARTEX_INTENT_BUDGET_TOKENS", "ARTEX_INTENT_BUDGET_TURNS"} {
t.Setenv(k, "")
}
task := &Task{ID: "102", Status: "running"}
s := newTestServer(task)
s.engine.settling.Store(task.ID, true)
if _, err := s.admitTask(task, "resume"); err == nil || !strings.Contains(err.Error(), "settling") {
t.Fatalf("admitTask during in-flight settle = %v, want settling refusal", err)
}
if _, err := s.admitTaskWhen(task, "resume", false, true); err == nil || !strings.Contains(err.Error(), "settling") {
t.Fatalf("agent revival during in-flight settle = %v, want settling refusal", err)
}
if !s.engine.isSettling(task.ID) {
t.Fatal("refused revival cleared settling barrier")
}
})
t.Run("terminal task with exhausted budget cannot be revived", func(t *testing.T) {
t.Setenv("ARTEX_TASK_BUDGET_TOKENS", "250000")
t.Setenv("ARTEX_TASK_BUDGET_TURNS", "")
t.Setenv("ARTEX_INTENT_BUDGET_TOKENS", "30000")
t.Setenv("ARTEX_INTENT_BUDGET_TURNS", "")
for _, status := range []string{"timeout", "done"} {
task := &Task{ID: "103", Status: status}
s := newTestServer(task)
l := s.engine.budgetFor(task.ID)
l.RestoreSpend(agent.Spend{Tokens: 250_000, Turns: 20})
if _, err := s.admitTask(task, "resume"); err == nil || !strings.Contains(err.Error(), "budget is exhausted") {
t.Fatalf("admitTask on budget-exhausted %s task = %v, want budget exhaustion refusal", status, err)
}
if _, err := s.admitTaskWhen(task, "resume", false, true); err == nil {
t.Fatalf("agent revival on budget-exhausted %s task succeeded, want refusal", status)
}
if got := s.engine.budgetFor(task.ID); got != l {
t.Fatal("refused revival dropped or replaced the budget ledger")
}
}
})
}