runner: gate stage handoff on settled verified session export
This commit is contained in:
@@ -44,12 +44,18 @@ func (s *Store) BeginStep(ctx context.Context, id int64, sequence int, key strin
|
||||
return err
|
||||
}
|
||||
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", key, id)); err != nil {
|
||||
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 {
|
||||
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 {
|
||||
return err
|
||||
}
|
||||
// Consuming a recovered handoff and starting its successor are atomic. A
|
||||
// crash before this transaction leaves the gate available after restart.
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM session_export_gates WHERE run_id=? AND sequence<?`, id, sequence); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
@@ -73,6 +79,16 @@ type stageVerdictEvidence struct {
|
||||
}
|
||||
|
||||
func (s *Store) FinishStep(ctx context.Context, id int64, step protocol.RunStep) error {
|
||||
return s.finishStep(ctx, id, step, false)
|
||||
}
|
||||
|
||||
// FinishStepExportBlocked retains the computed step and its routing target, but
|
||||
// checkpoints the handoff separately: the output is not yet eligible for reuse.
|
||||
func (s *Store) FinishStepExportBlocked(ctx context.Context, id int64, step protocol.RunStep) error {
|
||||
return s.finishStep(ctx, id, step, true)
|
||||
}
|
||||
|
||||
func (s *Store) finishStep(ctx context.Context, id int64, step protocol.RunStep, exportBlocked bool) error {
|
||||
output, err := json.Marshal(step.Output)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -148,6 +164,11 @@ WHERE run_id=? AND sequence=? AND status='running'`, step.Status, step.Outcome,
|
||||
if err := enqueueStepExportJob(ctx, tx, id, step.Sequence); err != nil {
|
||||
return err
|
||||
}
|
||||
if exportBlocked && !requested {
|
||||
if _, err := tx.ExecContext(ctx, `INSERT INTO session_export_gates(run_id,sequence) VALUES(?,?)`, id, step.Sequence); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// The reported usage the stage already measured for budget accounting is
|
||||
// persisted as step-scoped evidence in the same transaction, mirroring the
|
||||
// other step evidence. It is written only when the stage actually reported
|
||||
@@ -302,7 +323,9 @@ func (s *Store) CancelWaiting(ctx context.Context, id int64) error {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
res, err := tx.ExecContext(ctx, `UPDATE pipeline_runs SET status='canceled',cancel_requested=1,diagnostic='Canceled while waiting for a decision',finished_at=CURRENT_TIMESTAMP WHERE id=? AND status=?`, id, protocol.RunStatusWaiting)
|
||||
res, err := tx.ExecContext(ctx, `UPDATE pipeline_runs SET status='canceled',cancel_requested=1,
|
||||
diagnostic=CASE WHEN status='waiting' THEN 'Canceled while waiting for a decision' ELSE 'Canceled while awaiting session export; computed visit retained' END,
|
||||
finished_at=CURRENT_TIMESTAMP WHERE id=? AND (status=? OR (status IN ('failed','interrupted') AND EXISTS(SELECT 1 FROM session_export_gates g WHERE g.run_id=pipeline_runs.id)))`, id, protocol.RunStatusWaiting)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -323,7 +346,7 @@ func (s *Store) CancelWaiting(ctx context.Context, id int64) error {
|
||||
func (s *Store) Cancel(ctx context.Context, id int64) error {
|
||||
return affected(s.db.ExecContext(ctx, `UPDATE pipeline_runs SET cancel_requested=1,
|
||||
diagnostic=CASE WHEN cleanup_unconfirmed=1 THEN diagnostic ELSE 'Stop requested; waiting for execution and cleanup to stop' END
|
||||
WHERE id=? AND status IN ('queued','running','waiting')`, id))
|
||||
WHERE id=? AND (status IN ('queued','running','waiting') OR (status IN ('failed','interrupted') AND EXISTS(SELECT 1 FROM session_export_gates g WHERE g.run_id=pipeline_runs.id)))`, id))
|
||||
}
|
||||
|
||||
func (s *Store) FinishRun(ctx context.Context, id int64, status, outcome, diagnostic string, output map[string]any) error {
|
||||
@@ -347,6 +370,10 @@ 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 {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package pipeline
|
||||
|
||||
import "context"
|
||||
|
||||
func (s *Store) SessionExportBlocked(ctx context.Context, id int64) (bool, error) {
|
||||
var blocked bool
|
||||
err := s.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM session_export_gates WHERE run_id=?)`, id).Scan(&blocked)
|
||||
return blocked, err
|
||||
}
|
||||
|
||||
// PendingSessionExportGate authorizes only export repair of the exact completed
|
||||
// visit, never a model call or a human decision. No live executor is implied by
|
||||
// the workspace reservation maintained for this checkpoint.
|
||||
func (s *Store) PendingSessionExportGate(ctx context.Context, id int64, sequence int) (bool, error) {
|
||||
var pending bool
|
||||
err := s.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM session_export_gates g
|
||||
JOIN pipeline_runs r ON r.id=g.run_id JOIN run_steps s ON s.run_id=g.run_id AND s.sequence=g.sequence
|
||||
WHERE g.run_id=? AND g.sequence=? AND r.cancel_requested=0 AND r.cleanup_unconfirmed=0
|
||||
AND s.status NOT IN ('running','waiting')
|
||||
AND NOT EXISTS(SELECT 1 FROM run_steps a WHERE (a.run_id=g.run_id OR a.session_id=s.session_id) AND a.agent_active<>0))`, id, sequence).Scan(&pending)
|
||||
return pending, err
|
||||
}
|
||||
|
||||
// SessionExportReservations survive process restarts and cannot be confused
|
||||
// with agent-active/executing flags in the UI.
|
||||
func (s *Store) SessionExportReservations(ctx context.Context) (map[int64]string, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT r.id,r.workspace FROM session_export_gates g JOIN pipeline_runs r ON r.id=g.run_id WHERE r.cancel_requested=0 AND r.status<>'canceled'`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
reservations := map[int64]string{}
|
||||
for rows.Next() {
|
||||
var id int64
|
||||
var workspace string
|
||||
if err := rows.Scan(&id, &workspace); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
reservations[id] = workspace
|
||||
}
|
||||
return reservations, rows.Err()
|
||||
}
|
||||
|
||||
// ReadySessionExportGates includes interrupted continuations. The gate remains
|
||||
// durable until a successor is begun (or a terminal target is committed).
|
||||
func (s *Store) ReadySessionExportGates(ctx context.Context) (map[int64]int, error) {
|
||||
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 ('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`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
ready := map[int64]int{}
|
||||
for rows.Next() {
|
||||
var id int64
|
||||
var sequence int
|
||||
if err := rows.Scan(&id, &sequence); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ready[id] = sequence
|
||||
}
|
||||
return ready, rows.Err()
|
||||
}
|
||||
|
||||
// ResumeSessionExportGate is a CAS, not a retry of the model invocation.
|
||||
func (s *Store) ResumeSessionExportGate(ctx context.Context, id int64, sequence int) error {
|
||||
return affected(s.db.ExecContext(ctx, `UPDATE pipeline_runs SET status='queued',outcome='',diagnostic='',finished_at=NULL
|
||||
WHERE id=? AND status IN ('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))
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func TestSessionExportGateCheckpointAndSuccessorAreAtomic(t *testing.T) {
|
||||
s, id, _ := exportJobFixture(t)
|
||||
ctx := context.Background()
|
||||
step := protocol.RunStep{Sequence: 1, Stage: "one", Status: "completed", Outcome: "success", Target: "two", Output: map[string]any{"markdown": "actual result"}, SessionExport: &protocol.SessionExport{Status: "failed", SessionID: "ses_original", Backend: "v2", Diagnostic: "offline"}}
|
||||
if err := s.FinishStepExportBlocked(ctx, id, step); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.BeginStep(ctx, id, 2, "two", nil); err == nil {
|
||||
t.Fatal("successor started while export was incomplete")
|
||||
}
|
||||
if err := s.FinishRun(ctx, id, "failed", "error", "export gate", step.Output); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
job, _ := s.SessionExportJob(ctx, id, 1)
|
||||
claimed, err := s.ClaimSessionExportJob(ctx, time.UnixMilli(job.NextAt), time.Minute)
|
||||
if err != nil || claimed == nil {
|
||||
t.Fatalf("missing export-only retry: %v", err)
|
||||
}
|
||||
if err := s.RecordSessionExportRepair(ctx, id, 1, &protocol.SessionExport{Status: "complete", SessionID: claimed.SessionID, Backend: claimed.Backend, Directory: claimed.Directory, Messages: 2, HTML: "session-repair-1-test.html", HTMLBytes: 100}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.FinishSessionExportJob(ctx, claimed, time.Now(), ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.ResumeSessionExportGate(ctx, id, 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.ResumeSessionExportGate(ctx, id, 1); err == nil {
|
||||
t.Fatal("duplicate continuation admitted")
|
||||
}
|
||||
// A crash after reserving the continuation but before starting its next
|
||||
// executor must retain the checkpoint for startup's interrupted run.
|
||||
if _, err := s.db.Exec(`UPDATE pipeline_runs SET status='interrupted' WHERE id=?`, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ready, err := s.ReadySessionExportGates(ctx)
|
||||
if err != nil || ready[id] != 1 {
|
||||
t.Fatalf("lost restart checkpoint: %v %v", ready, 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.Fatal(err)
|
||||
}
|
||||
if blocked, err := s.SessionExportBlocked(ctx, id); err != nil || blocked {
|
||||
t.Fatalf("successor did not consume checkpoint: %v %v", blocked, err)
|
||||
}
|
||||
if err := s.BeginStep(ctx, id, 2, "two", nil); err == nil {
|
||||
t.Fatal("successor started twice")
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,11 @@ status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','running','com
|
||||
next_at INTEGER NOT NULL, lease_until INTEGER NOT NULL DEFAULT 0, token TEXT NOT NULL DEFAULT '', diagnostic TEXT NOT NULL DEFAULT '',
|
||||
PRIMARY KEY(run_id,sequence), FOREIGN KEY(run_id,sequence) REFERENCES run_steps(run_id,sequence) ON DELETE CASCADE);
|
||||
CREATE INDEX IF NOT EXISTS session_export_jobs_due ON session_export_jobs(status,next_at,lease_until);`)
|
||||
if err == nil {
|
||||
_, err = s.db.Exec(`CREATE TABLE IF NOT EXISTS session_export_gates (
|
||||
run_id INTEGER PRIMARY KEY, sequence INTEGER NOT NULL,
|
||||
FOREIGN KEY(run_id,sequence) REFERENCES run_steps(run_id,sequence) ON DELETE CASCADE)`)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -45,7 +50,7 @@ SELECT s.run_id,s.sequence,s.session_id,o.backend,r.workspace,o.reference,?
|
||||
FROM run_steps s JOIN pipeline_runs r ON r.id=s.run_id
|
||||
JOIN run_session_owners o ON o.run_id=s.run_id AND o.sequence=s.sequence
|
||||
LEFT JOIN step_session_exports x ON x.run_id=s.run_id AND x.sequence=s.sequence
|
||||
WHERE s.status NOT IN ('running','waiting') AND s.session_id<>'' AND o.backend IN ('v1','v2')
|
||||
WHERE s.status NOT IN ('running','waiting') AND s.session_id<>'' AND (o.backend IN ('v1','v2') OR (o.backend='pi' AND o.reference<>''))
|
||||
AND NOT EXISTS(SELECT 1 FROM session_export_jobs j WHERE j.run_id=s.run_id AND j.sequence=s.sequence)
|
||||
AND NOT (COALESCE(json_extract(x.export_json,'$.status'),'complete')='complete'
|
||||
AND COALESCE(json_extract(x.export_json,'$.session_id'),'')=s.session_id
|
||||
|
||||
@@ -259,7 +259,7 @@ func TestSessionExportJobMigrationReconcilesMissingJobsWithoutReset(t *testing.T
|
||||
}
|
||||
|
||||
func TestSessionExportJobOnlyEnqueuesIncompleteNativeEvidence(t *testing.T) {
|
||||
for _, status := range []string{"complete", "failed", "empty", "partial", "missing", "unsupported", "wrong-session"} {
|
||||
for _, status := range []string{"complete", "failed", "empty", "partial", "missing", "unsupported", "pi-native", "wrong-session"} {
|
||||
t.Run(status, func(t *testing.T) {
|
||||
s, id, _ := exportJobFixture(t)
|
||||
ctx := context.Background()
|
||||
@@ -272,10 +272,16 @@ func TestSessionExportJobOnlyEnqueuesIncompleteNativeEvidence(t *testing.T) {
|
||||
evidence.SessionID = "ses_wrong"
|
||||
}
|
||||
if status == "unsupported" {
|
||||
if _, err := s.db.Exec("UPDATE run_session_owners SET backend='pi'"); err != nil {
|
||||
if _, err := s.db.Exec("UPDATE run_session_owners SET backend='pi',reference=''"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if status == "pi-native" {
|
||||
if _, err := s.db.Exec("UPDATE run_session_owners SET backend='pi',reference='/original/session.jsonl'"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
evidence.Backend, evidence.Status = "pi", "failed"
|
||||
}
|
||||
if err := s.FinishStep(ctx, id, protocol.RunStep{Sequence: 1, Stage: "one", Status: "completed", SessionExport: evidence, Output: map[string]any{}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -11,7 +11,8 @@ import (
|
||||
// legacy display lookup it never guesses a backend for a historical session.
|
||||
func (s *Store) RepairSessionOwner(ctx context.Context, id int64, sequence int) (SessionOwner, error) {
|
||||
var owner SessionOwner
|
||||
err := s.db.QueryRowContext(ctx, `SELECT s.session_id,o.backend,r.workspace,o.reference FROM run_steps s JOIN pipeline_runs r ON r.id=s.run_id JOIN run_session_owners o ON o.run_id=s.run_id AND o.sequence=s.sequence WHERE s.run_id=? AND s.sequence=? AND s.session_id<>'' AND s.agent_active=0`, id, sequence).Scan(&owner.ID, &owner.Backend, &owner.Directory, &owner.Reference)
|
||||
err := s.db.QueryRowContext(ctx, `SELECT s.session_id,o.backend,r.workspace,o.reference FROM run_steps s JOIN pipeline_runs r ON r.id=s.run_id JOIN run_session_owners o ON o.run_id=s.run_id AND o.sequence=s.sequence WHERE s.run_id=? AND s.sequence=? AND s.session_id<>'' AND s.agent_active=0
|
||||
AND NOT EXISTS(SELECT 1 FROM run_steps a WHERE a.session_id=s.session_id AND a.agent_active<>0)`, id, sequence).Scan(&owner.ID, &owner.Backend, &owner.Directory, &owner.Reference)
|
||||
return owner, err
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user