Release session export gates whose recovery is exhausted or overdue
An exhausted export recovery job left its run parked forever in the export wait, reserving the workspace and refusing later scheduled runs (runs 221/226: OpenCode sessions above the 8 MiB export bound are always truncated, so every retry stays partial). A gate is now releasable when its job is exhausted: the visit keeps its partial/unavailable evidence and diagnostic (still repairable), the run continues to its next stage or terminal, and the workspace is freed. Gates older than 15 minutes with a pending, lease-expired or missing job are exhausted by a bounded wait. The worker reconciles on its first tick after startup and every 30 seconds, so existing wedged runs recover after a restart. Truncation diagnostics now name the size bound.
This commit is contained in:
@@ -58,7 +58,7 @@ func (s *Store) BeginStep(ctx context.Context, id int64, sequence int, key strin
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if err := affected(tx.ExecContext(ctx, `UPDATE pipeline_runs SET status='running',current_stage=? WHERE id=? AND status IN ('queued','running') AND cancel_requested=0
|
||||
AND NOT EXISTS(SELECT 1 FROM session_export_gates g LEFT JOIN session_export_jobs j ON j.run_id=g.run_id AND j.sequence=g.sequence WHERE g.run_id=pipeline_runs.id AND COALESCE(j.status,'')<>'complete')`, key, id)); err != nil {
|
||||
AND NOT EXISTS(SELECT 1 FROM session_export_gates g LEFT JOIN session_export_jobs j ON j.run_id=g.run_id AND j.sequence=g.sequence WHERE g.run_id=pipeline_runs.id AND COALESCE(j.status,'') NOT IN ('complete','exhausted'))`, key, id)); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "INSERT INTO run_steps(run_id,sequence,stage_key,input_json) VALUES (?,?,?,?)", id, sequence, key, string(encoded)); err != nil {
|
||||
@@ -396,8 +396,9 @@ AND NOT EXISTS(SELECT 1 FROM run_steps WHERE run_id=pipeline_runs.id AND agent_a
|
||||
if err := enqueueRunTransitionNotification(ctx, tx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
// Terminal targets have no successor BeginStep to consume their gate.
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM session_export_gates WHERE run_id=? AND EXISTS(SELECT 1 FROM session_export_jobs j WHERE j.run_id=session_export_gates.run_id AND j.sequence=session_export_gates.sequence AND j.status='complete')`, id); err != nil {
|
||||
// Terminal targets have no successor BeginStep to consume their gate. An
|
||||
// exhausted job is terminal too: its incomplete evidence stays recorded.
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM session_export_gates WHERE run_id=? AND EXISTS(SELECT 1 FROM session_export_jobs j WHERE j.run_id=session_export_gates.run_id AND j.sequence=session_export_gates.sequence AND j.status IN ('complete','exhausted'))`, id); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
package pipeline
|
||||
|
||||
import "context"
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func (s *Store) SessionExportBlocked(ctx context.Context, id int64) (bool, error) {
|
||||
var blocked bool
|
||||
@@ -47,8 +54,8 @@ func (s *Store) ReadySessionExportGates(ctx context.Context) (map[int64]int, err
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT g.run_id,g.sequence FROM session_export_gates g
|
||||
JOIN session_export_jobs j ON j.run_id=g.run_id AND j.sequence=g.sequence
|
||||
JOIN pipeline_runs r ON r.id=g.run_id
|
||||
WHERE j.status='complete' AND r.status IN ('waiting','failed','interrupted') AND r.cancel_requested=0 AND r.cleanup_unconfirmed=0
|
||||
AND NOT EXISTS(SELECT 1 FROM run_steps a WHERE a.run_id=g.run_id AND (a.agent_active<>0 OR a.sequence>g.sequence)) AND `+exactExportJobOwner+` LIMIT 64`)
|
||||
WHERE r.status IN ('waiting','failed','interrupted') AND r.cancel_requested=0 AND r.cleanup_unconfirmed=0
|
||||
AND NOT EXISTS(SELECT 1 FROM run_steps a WHERE a.run_id=g.run_id AND (a.agent_active<>0 OR a.sequence>g.sequence)) AND `+releasableGateJob+` LIMIT 64`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -65,10 +72,93 @@ AND NOT EXISTS(SELECT 1 FROM run_steps a WHERE a.run_id=g.run_id AND (a.agent_ac
|
||||
return ready, rows.Err()
|
||||
}
|
||||
|
||||
// ResumeSessionExportGate is a CAS, not a retry of the model invocation.
|
||||
// ResumeSessionExportGate is a CAS, not a retry of the model invocation. A
|
||||
// gate whose recovery job is exhausted is released exactly like a completed
|
||||
// one: the visit keeps its partial/unavailable export evidence and the job's
|
||||
// diagnostic, and the operator can still repair it later. When no export
|
||||
// evidence was recorded at all, one unavailable record carries the diagnostic.
|
||||
func (s *Store) ResumeSessionExportGate(ctx context.Context, id int64, sequence int) error {
|
||||
return affected(s.db.ExecContext(ctx, `UPDATE pipeline_runs SET status='running',outcome='',diagnostic='',finished_at=NULL
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if err := affected(tx.ExecContext(ctx, `UPDATE pipeline_runs SET status='running',outcome='',diagnostic='',finished_at=NULL
|
||||
WHERE id=? AND status IN ('waiting','failed','interrupted') AND cancel_requested=0 AND cleanup_unconfirmed=0
|
||||
AND EXISTS(SELECT 1 FROM session_export_gates g JOIN session_export_jobs j ON j.run_id=g.run_id AND j.sequence=g.sequence WHERE g.run_id=pipeline_runs.id AND g.sequence=? AND j.status='complete' AND `+exactExportJobOwner+`)
|
||||
AND NOT EXISTS(SELECT 1 FROM run_steps a WHERE a.run_id=pipeline_runs.id AND (a.agent_active<>0 OR a.sequence>?))`, id, sequence, sequence))
|
||||
AND EXISTS(SELECT 1 FROM session_export_gates g JOIN session_export_jobs j ON j.run_id=g.run_id AND j.sequence=g.sequence WHERE g.run_id=pipeline_runs.id AND g.sequence=? AND `+releasableGateJob+`)
|
||||
AND NOT EXISTS(SELECT 1 FROM run_steps a WHERE a.run_id=pipeline_runs.id AND (a.agent_active<>0 OR a.sequence>?))`, id, sequence, sequence)); err != nil {
|
||||
return err
|
||||
}
|
||||
var job SessionExportJob
|
||||
if err := tx.QueryRowContext(ctx, `SELECT session_id,backend,directory,status,diagnostic FROM session_export_jobs WHERE run_id=? AND sequence=?`, id, sequence).Scan(&job.SessionID, &job.Backend, &job.Directory, &job.Status, &job.Diagnostic); err != nil {
|
||||
return err
|
||||
}
|
||||
if job.Status == "exhausted" {
|
||||
var recorded bool
|
||||
if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM step_session_exports WHERE run_id=? AND sequence=?) OR EXISTS(SELECT 1 FROM session_export_repairs WHERE run_id=? AND sequence=?)`, id, sequence, id, sequence).Scan(&recorded); err != nil {
|
||||
return err
|
||||
}
|
||||
if !recorded {
|
||||
diagnostic := job.Diagnostic
|
||||
if diagnostic == "" {
|
||||
diagnostic = "Automatic session export recovery exhausted"
|
||||
}
|
||||
body, err := json.Marshal(protocol.SessionExport{Status: "unavailable", Source: "unavailable", SessionID: job.SessionID, Backend: job.Backend, Directory: job.Directory, RecordedAt: time.Now().UTC().Format(time.RFC3339), Diagnostic: diagnostic})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "INSERT INTO session_export_repairs(run_id,sequence,export_json) VALUES(?,?,?)", id, sequence, string(body)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// releasableGateJob is a gate's terminal recovery state. A complete job must
|
||||
// still match the exact original owner. An exhausted job is terminal whatever
|
||||
// the reason (including changed ownership): waiting longer cannot help, so the
|
||||
// handoff proceeds with the incomplete evidence instead of wedging the run and
|
||||
// its workspace forever.
|
||||
const releasableGateJob = `(j.status='exhausted' OR (j.status='complete' AND ` + exactExportJobOwner + `))`
|
||||
|
||||
// SessionExportGateMaxWait bounds how long a computed visit may wait for its
|
||||
// export. The normal budget (three attempts with 45-second leases and up to a
|
||||
// minute of backoff) finishes in a few minutes; this only catches a job that
|
||||
// can never be claimed or acknowledged.
|
||||
const SessionExportGateMaxWait = 15 * time.Minute
|
||||
|
||||
// ExpireSessionExportGates exhausts the recovery job of every gate older than
|
||||
// maxWait whose job is still pending, or running past its lease, and gives a
|
||||
// gate with no recovery job at all an exhausted one. A live lease is never
|
||||
// stolen; it expires within its own bound and is exhausted on the next pass.
|
||||
func (s *Store) ExpireSessionExportGates(ctx context.Context, now time.Time, maxWait time.Duration) (int64, error) {
|
||||
cutoff := now.Add(-maxWait).UTC().Format(time.DateTime)
|
||||
diagnostic := fmt.Sprintf("Session export wait exceeded %s; automatic recovery stopped", maxWait)
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
result, err := tx.ExecContext(ctx, `UPDATE session_export_jobs AS j SET status='exhausted',token='',lease_until=0,next_at=0,
|
||||
diagnostic=substr(?||CASE WHEN j.diagnostic<>'' THEN ' (last: '||j.diagnostic||')' ELSE '' END,1,2048)
|
||||
WHERE (j.status='pending' OR (j.status='running' AND j.lease_until<=?))
|
||||
AND EXISTS(SELECT 1 FROM session_export_gates g JOIN run_steps s ON s.run_id=g.run_id AND s.sequence=g.sequence
|
||||
WHERE g.run_id=j.run_id AND g.sequence=j.sequence AND s.finished_at IS NOT NULL AND s.finished_at<=?)`, diagnostic, now.UnixMilli(), cutoff)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
expired, _ := result.RowsAffected()
|
||||
result, err = tx.ExecContext(ctx, `INSERT INTO session_export_jobs(run_id,sequence,session_id,backend,directory,reference,status,attempts,next_at,diagnostic)
|
||||
SELECT g.run_id,g.sequence,s.session_id,COALESCE(o.backend,''),r.workspace,COALESCE(o.reference,''),'exhausted',0,0,?
|
||||
FROM session_export_gates g JOIN run_steps s ON s.run_id=g.run_id AND s.sequence=g.sequence JOIN pipeline_runs r ON r.id=g.run_id
|
||||
LEFT JOIN run_session_owners o ON o.run_id=g.run_id AND o.sequence=g.sequence
|
||||
WHERE s.finished_at IS NOT NULL AND s.finished_at<=?
|
||||
AND NOT EXISTS(SELECT 1 FROM session_export_jobs j WHERE j.run_id=g.run_id AND j.sequence=g.sequence)
|
||||
ON CONFLICT(run_id,sequence) DO NOTHING`, "No automatic session export recovery exists for this visit; "+diagnostic, cutoff)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
created, _ := result.RowsAffected()
|
||||
return expired + created, tx.Commit()
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -73,3 +74,83 @@ func TestSessionExportGateCheckpointAndSuccessorAreAtomic(t *testing.T) {
|
||||
t.Fatal("successor started twice")
|
||||
}
|
||||
}
|
||||
|
||||
// A recovery job wedged in running past its lease (or pending and never
|
||||
// claimable) is bounded by the gate's overall wait; a live lease is not stolen.
|
||||
func TestSessionExportGateWaitIsBoundedForStuckJob(t *testing.T) {
|
||||
s, id, _ := exportJobFixture(t)
|
||||
ctx := context.Background()
|
||||
step := protocol.RunStep{Sequence: 1, Stage: "one", Status: "completed", Outcome: "success", Target: "#success", Output: map[string]any{"markdown": "actual result"}, SessionExport: &protocol.SessionExport{Status: "partial", SessionID: "ses_original", Backend: "v2", Truncated: true}}
|
||||
if err := s.FinishStepExportBlocked(ctx, id, step); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
job, _ := s.SessionExportJob(ctx, id, 1)
|
||||
start := time.UnixMilli(job.NextAt)
|
||||
if claimed, err := s.ClaimSessionExportJob(ctx, start, time.Hour); err != nil || claimed == nil {
|
||||
t.Fatalf("claim: %+v %v", claimed, err)
|
||||
}
|
||||
if n, err := s.ExpireSessionExportGates(ctx, start.Add(5*time.Minute), SessionExportGateMaxWait); err != nil || n != 0 {
|
||||
t.Fatalf("young gate expired: %d %v", n, err)
|
||||
}
|
||||
if n, err := s.ExpireSessionExportGates(ctx, start.Add(20*time.Minute), SessionExportGateMaxWait); err != nil || n != 0 {
|
||||
t.Fatalf("live lease stolen: %d %v", n, err)
|
||||
}
|
||||
if ready, _ := s.ReadySessionExportGates(ctx); ready[id] != 0 {
|
||||
t.Fatal("running job released its gate")
|
||||
}
|
||||
if n, err := s.ExpireSessionExportGates(ctx, start.Add(2*time.Hour), SessionExportGateMaxWait); err != nil || n != 1 {
|
||||
t.Fatalf("stuck job not bounded: %d %v", n, err)
|
||||
}
|
||||
job, _ = s.SessionExportJob(ctx, id, 1)
|
||||
if job.Status != "exhausted" || !strings.Contains(job.Diagnostic, "wait exceeded") {
|
||||
t.Fatalf("job not exhausted: %+v", job)
|
||||
}
|
||||
ready, err := s.ReadySessionExportGates(ctx)
|
||||
if err != nil || ready[id] != 1 {
|
||||
t.Fatalf("exhausted gate not ready: %v %v", ready, err)
|
||||
}
|
||||
if err := s.ResumeSessionExportGate(ctx, id, 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.FinishRun(ctx, id, "succeeded", "success", "", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if blocked, err := s.SessionExportBlocked(ctx, id); err != nil || blocked {
|
||||
t.Fatalf("terminal finish kept exhausted gate: %v %v", blocked, err)
|
||||
}
|
||||
d, _ := s.GetRun(ctx, id)
|
||||
if d.Status != "succeeded" || d.Steps[0].SessionExport == nil || d.Steps[0].SessionExport.Status != "partial" || len(d.Steps[0].SessionExportRepairs) != 0 {
|
||||
t.Fatalf("partial evidence not retained as-is: %+v", d)
|
||||
}
|
||||
}
|
||||
|
||||
// A gate whose visit never got a recovery job (no exact owner) is given an
|
||||
// exhausted job after the bounded wait, and the release records why.
|
||||
func TestSessionExportGateWithoutJobIsReleasedAfterWait(t *testing.T) {
|
||||
s, id, _ := exportJobFixture(t)
|
||||
ctx := context.Background()
|
||||
if _, err := s.db.Exec(`DELETE FROM run_session_owners WHERE run_id=?`, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
step := protocol.RunStep{Sequence: 1, Stage: "one", Status: "completed", Outcome: "success", Target: "two", Output: map[string]any{"markdown": "actual result"}}
|
||||
if err := s.FinishStepExportBlocked(ctx, id, step); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if job, _ := s.SessionExportJob(ctx, id, 1); job != nil {
|
||||
t.Fatalf("fixture unexpectedly has a job: %+v", job)
|
||||
}
|
||||
if n, err := s.ExpireSessionExportGates(ctx, time.Now().Add(time.Hour), SessionExportGateMaxWait); err != nil || n != 1 {
|
||||
t.Fatalf("jobless gate not bounded: %d %v", n, err)
|
||||
}
|
||||
if err := s.ResumeSessionExportGate(ctx, id, 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.BeginStep(ctx, id, 2, "two", nil); err != nil {
|
||||
t.Fatalf("successor refused after release: %v", err)
|
||||
}
|
||||
d, _ := s.GetRun(ctx, id)
|
||||
repairs := d.Steps[0].SessionExportRepairs
|
||||
if len(repairs) != 1 || repairs[0].Status != "unavailable" || !strings.Contains(repairs[0].Diagnostic, "No automatic session export recovery") {
|
||||
t.Fatalf("release did not record unavailable evidence: %+v", repairs)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user