Add stage-exclusive resource waiting
Add durable FIFO capacity-one resource leases for executable stages, including cleanup-confirmed release, conservative restart quarantine, queue state events, and CLI/TUI/Android waiting presentation. Add scheduler, cleanup, protocol, client, and Android coverage plus a proposed Android v3 resource draft. Checked packaged templates and authoring skill references: neither needs updating in this item. The per-item docs note records the shared documentation that docs-fold must update; no shared README or packaged reference was edited.
This commit is contained in:
@@ -10,7 +10,7 @@ import (
|
||||
)
|
||||
|
||||
func decodeControl(text string, value any) error {
|
||||
// Both control blocks are flat objects. Reject duplicate keys before decoding.
|
||||
// Control blocks are flat objects. Reject duplicate keys before decoding.
|
||||
keys := json.NewDecoder(strings.NewReader(text))
|
||||
if token, err := keys.Token(); err != nil || token != json.Delim('{') {
|
||||
return fmt.Errorf("expected object")
|
||||
@@ -44,6 +44,12 @@ func decodeControl(text string, value any) error {
|
||||
}
|
||||
|
||||
func parseControl(s *Stage, fields map[string]string) error {
|
||||
if text, ok := fields["resources"]; ok {
|
||||
if err := decodeControl(text, &s.Resources); err != nil || s.Resources == nil || !ValidResourceKey(s.Resources.Exclusive) {
|
||||
return fmt.Errorf("resources must contain exactly one exclusive key (1–128 ASCII letters, digits, _ or -; start with a letter)")
|
||||
}
|
||||
delete(fields, "resources")
|
||||
}
|
||||
if text, ok := fields["limits"]; ok {
|
||||
if err := decodeControl(text, &s.Limits); err != nil || s.Limits == nil {
|
||||
return fmt.Errorf("limits must be an object with max_visits and optional on outcomes")
|
||||
@@ -76,6 +82,9 @@ func parseControl(s *Stage, fields map[string]string) error {
|
||||
}
|
||||
|
||||
func validateControl(s Stage, stages map[string]bool) error {
|
||||
if s.Resources != nil && s.Type == "human" {
|
||||
return fmt.Errorf("stage %s: human stages cannot declare resources", s.Key)
|
||||
}
|
||||
if s.Limits != nil {
|
||||
for _, outcome := range s.Limits.On {
|
||||
target, exists := s.Edges[outcome]
|
||||
@@ -95,3 +104,7 @@ func validateControl(s Stage, stages map[string]bool) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidResourceKey(key string) bool {
|
||||
return len(key) <= 128 && identifier.MatchString(key)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// ResourceVisit identifies a pending visit, before it consumes execution accounting.
|
||||
type ResourceVisit struct {
|
||||
Resource string
|
||||
RunID int64
|
||||
Stage string
|
||||
Sequence int
|
||||
}
|
||||
|
||||
// ResourceLease is an opaque capability. Its credential is deliberately not exported
|
||||
// or serializable, and must never be put in model input or public wire metadata.
|
||||
type ResourceLease struct {
|
||||
ResourceVisit
|
||||
token string
|
||||
}
|
||||
|
||||
// RequestResource acquires immediately or registers one FIFO waiter/channel. The
|
||||
// mutex covers only short DB transactions and channel bookkeeping, never execution.
|
||||
func (s *Store) RequestResource(ctx context.Context, visit ResourceVisit) (ResourceLease, <-chan ResourceLease, *protocol.ResourceWait, error) {
|
||||
s.resourceMu.Lock()
|
||||
defer s.resourceMu.Unlock()
|
||||
if !ValidResourceKey(visit.Resource) || visit.RunID <= 0 || visit.Sequence <= 0 || !identifier.MatchString(visit.Stage) {
|
||||
return ResourceLease{}, nil, nil, fmt.Errorf("invalid resource visit")
|
||||
}
|
||||
if ch := s.resourceWaiters[visit]; ch != nil {
|
||||
wait, err := s.resourceWait(ctx, visit.RunID)
|
||||
return ResourceLease{}, ch, wait, err
|
||||
}
|
||||
credential := make([]byte, 32)
|
||||
if _, err := rand.Read(credential); err != nil {
|
||||
return ResourceLease{}, nil, nil, err
|
||||
}
|
||||
lease := ResourceLease{ResourceVisit: visit, token: hex.EncodeToString(credential)}
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return ResourceLease{}, nil, nil, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var status string
|
||||
if err := tx.QueryRowContext(ctx, "SELECT status FROM pipeline_runs WHERE id=?", visit.RunID).Scan(&status); err != nil {
|
||||
return ResourceLease{}, nil, nil, err
|
||||
}
|
||||
if status != protocol.RunStatusQueued && status != protocol.RunStatusRunning {
|
||||
return ResourceLease{}, nil, nil, fmt.Errorf("run is not active")
|
||||
}
|
||||
var existing ResourceLease
|
||||
err = tx.QueryRowContext(ctx, "SELECT resource_key,run_id,stage_key,sequence,token FROM resource_owners WHERE run_id=?", visit.RunID).Scan(&existing.Resource, &existing.RunID, &existing.Stage, &existing.Sequence, &existing.token)
|
||||
if err == nil {
|
||||
if existing.ResourceVisit != visit {
|
||||
return ResourceLease{}, nil, nil, fmt.Errorf("run already owns another resource visit")
|
||||
}
|
||||
return existing, nil, nil, nil
|
||||
}
|
||||
if err != sql.ErrNoRows {
|
||||
return ResourceLease{}, nil, nil, err
|
||||
}
|
||||
result, err := tx.ExecContext(ctx, `INSERT INTO resource_owners(resource_key,run_id,stage_key,sequence,token)
|
||||
VALUES(?,?,?,?,?) ON CONFLICT(resource_key) DO NOTHING`, visit.Resource, visit.RunID, visit.Stage, visit.Sequence, lease.token)
|
||||
if err != nil {
|
||||
return ResourceLease{}, nil, nil, err
|
||||
}
|
||||
n, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return ResourceLease{}, nil, nil, err
|
||||
}
|
||||
if n == 1 {
|
||||
return lease, nil, nil, tx.Commit()
|
||||
}
|
||||
wait := &protocol.ResourceWait{Resource: visit.Resource, Stage: visit.Stage, Sequence: visit.Sequence, QueuedSince: time.Now().UTC().Format(time.RFC3339Nano)}
|
||||
encoded, err := json.Marshal(wait)
|
||||
if err != nil {
|
||||
return ResourceLease{}, nil, nil, err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `INSERT INTO resource_waiters(resource_key,run_id,stage_key,sequence,token,queued_at) VALUES(?,?,?,?,?,?)`, visit.Resource, visit.RunID, visit.Stage, visit.Sequence, lease.token, wait.QueuedSince); err != nil {
|
||||
return ResourceLease{}, nil, nil, err
|
||||
}
|
||||
if err := affected(tx.ExecContext(ctx, "UPDATE pipeline_runs SET status='queued',current_stage=?,resource_wait=? WHERE id=? AND status IN ('queued','running')", visit.Stage, string(encoded), visit.RunID)); err != nil {
|
||||
return ResourceLease{}, nil, nil, err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return ResourceLease{}, nil, nil, err
|
||||
}
|
||||
if s.resourceWaiters == nil {
|
||||
s.resourceWaiters = make(map[ResourceVisit]chan ResourceLease)
|
||||
}
|
||||
ch := make(chan ResourceLease, 1)
|
||||
s.resourceWaiters[visit] = ch
|
||||
return ResourceLease{}, ch, wait, nil
|
||||
}
|
||||
|
||||
func (s *Store) resourceWait(ctx context.Context, id int64) (*protocol.ResourceWait, error) {
|
||||
var wait protocol.ResourceWait
|
||||
err := s.db.QueryRowContext(ctx, "SELECT resource_key,stage_key,sequence,queued_at FROM resource_waiters WHERE run_id=?", id).Scan(&wait.Resource, &wait.Stage, &wait.Sequence, &wait.QueuedSince)
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
return &wait, err
|
||||
}
|
||||
|
||||
// CancelResource removes a queued visit, or returns a concurrently reserved grant
|
||||
// to the queue before any execution is allowed. It cannot cancel another visit.
|
||||
func (s *Store) CancelResource(ctx context.Context, visit ResourceVisit) error {
|
||||
s.resourceMu.Lock()
|
||||
defer s.resourceMu.Unlock()
|
||||
defer delete(s.resourceWaiters, visit)
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
deleted, err := tx.ExecContext(ctx, "DELETE FROM resource_waiters WHERE resource_key=? AND run_id=? AND stage_key=? AND sequence=?", visit.Resource, visit.RunID, visit.Stage, visit.Sequence)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, err := deleted.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n > 0 {
|
||||
if _, err := tx.ExecContext(ctx, "UPDATE pipeline_runs SET resource_wait='' WHERE id=?", visit.RunID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
ch := s.resourceWaiters[visit]
|
||||
// A grant is buffered while this registry entry exists. Cancellation can
|
||||
// reclaim only that not-yet-accepted capability, never an executing owner.
|
||||
var grant ResourceLease
|
||||
if ch != nil {
|
||||
select {
|
||||
case grant = <-ch:
|
||||
default:
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return err
|
||||
}
|
||||
if grant.token != "" {
|
||||
if err := s.SetResourceCleanup(ctx, grant, true); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.releaseResourceLocked(ctx, grant)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// AcceptResource removes the channel exactly once. Cancellation is rechecked by
|
||||
// the runner before BeginStep; a canceled accepted grant is released as unused.
|
||||
func (s *Store) AcceptResource(lease ResourceLease) {
|
||||
s.resourceMu.Lock()
|
||||
delete(s.resourceWaiters, lease.ResourceVisit)
|
||||
s.resourceMu.Unlock()
|
||||
}
|
||||
|
||||
// HasResourceOwner is used only for orphan/restart reconciliation, never for a
|
||||
// resource-free stage visit.
|
||||
func (s *Store) HasResourceOwner(ctx context.Context, runID int64) (bool, error) {
|
||||
var exists bool
|
||||
err := s.db.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM resource_owners WHERE run_id=?)", runID).Scan(&exists)
|
||||
return exists, err
|
||||
}
|
||||
|
||||
func (s *Store) ConfirmRecoveredSession(ctx context.Context, owner SessionOwner) error {
|
||||
_, err := s.db.ExecContext(ctx, "UPDATE run_steps SET agent_active=0 WHERE run_id=? AND session_id=?", owner.RunID, owner.ID)
|
||||
return err
|
||||
}
|
||||
|
||||
// SetResourceCleanup records positive quiescence durably before release. False
|
||||
// quarantines the owner; neither age nor another run can remove the lease.
|
||||
func (s *Store) SetResourceCleanup(ctx context.Context, lease ResourceLease, confirmed bool) error {
|
||||
diagnostic := ""
|
||||
if !confirmed {
|
||||
diagnostic = "Cleanup/restoration unconfirmed; resource quarantined pending inspected reconciliation"
|
||||
}
|
||||
return affected(s.db.ExecContext(ctx, `UPDATE resource_owners SET cleanup_confirmed=?,diagnostic=? WHERE resource_key=? AND run_id=? AND stage_key=? AND sequence=? AND token=?`, confirmed, diagnostic, lease.Resource, lease.RunID, lease.Stage, lease.Sequence, lease.token))
|
||||
}
|
||||
|
||||
// ReleaseResource requires the complete capability AND positive cleanup evidence.
|
||||
// Mismatches and repeated releases are harmless, including after transfer.
|
||||
func (s *Store) ReleaseResource(ctx context.Context, lease ResourceLease) error {
|
||||
s.resourceMu.Lock()
|
||||
defer s.resourceMu.Unlock()
|
||||
return s.releaseResourceLocked(ctx, lease)
|
||||
}
|
||||
|
||||
func (s *Store) releaseResourceLocked(ctx context.Context, lease ResourceLease) error {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
n, err := deleteResourceOwner(ctx, tx, lease)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n == 0 {
|
||||
return nil
|
||||
}
|
||||
var next ResourceLease
|
||||
next.Resource = lease.Resource
|
||||
err = tx.QueryRowContext(ctx, `SELECT run_id,stage_key,sequence,token FROM resource_waiters WHERE resource_key=? ORDER BY queue_order LIMIT 1`, lease.Resource).Scan(&next.RunID, &next.Stage, &next.Sequence, &next.token)
|
||||
if err != nil && err != sql.ErrNoRows {
|
||||
return err
|
||||
}
|
||||
if err == nil {
|
||||
if s.resourceWaiters[next.ResourceVisit] == nil {
|
||||
return fmt.Errorf("resource waiter has no live runner; refusing handoff")
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `INSERT INTO resource_owners(resource_key,run_id,stage_key,sequence,token) VALUES(?,?,?,?,?)`, next.Resource, next.RunID, next.Stage, next.Sequence, next.token); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "DELETE FROM resource_waiters WHERE run_id=?", next.RunID); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "UPDATE pipeline_runs SET resource_wait='' WHERE id=?", next.RunID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return err
|
||||
}
|
||||
if next.token != "" {
|
||||
s.resourceWaiters[next.ResourceVisit] <- next
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func deleteResourceOwner(ctx context.Context, tx *sql.Tx, lease ResourceLease) (int64, error) {
|
||||
result, err := tx.ExecContext(ctx, `DELETE FROM resource_owners WHERE resource_key=? AND run_id=? AND stage_key=? AND sequence=? AND token=? AND cleanup_confirmed=1`, lease.Resource, lease.RunID, lease.Stage, lease.Sequence, lease.token)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected()
|
||||
}
|
||||
|
||||
// recoverResourceOwners runs only at startup, after pending waiters have been
|
||||
// interrupted and removed. Every reclamation uses the persisted capability;
|
||||
// absent cleanup evidence is never replaced with a timestamp-based expiry.
|
||||
func recoverResourceOwners(ctx context.Context, tx *sql.Tx) error {
|
||||
rows, err := tx.QueryContext(ctx, "SELECT resource_key,run_id,stage_key,sequence,token FROM resource_owners WHERE cleanup_confirmed=1")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var leases []ResourceLease
|
||||
for rows.Next() {
|
||||
var lease ResourceLease
|
||||
if err := rows.Scan(&lease.Resource, &lease.RunID, &lease.Stage, &lease.Sequence, &lease.token); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
leases = append(leases, lease)
|
||||
}
|
||||
err = rows.Err()
|
||||
rows.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, lease := range leases {
|
||||
if _, err := deleteResourceOwner(ctx, tx, lease); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, "UPDATE resource_owners SET diagnostic='Server stopped; resource quarantined pending inspected cleanup/restoration'")
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestResourceDeclaration(t *testing.T) {
|
||||
base := Template([]string{"work"}, true)
|
||||
for _, value := range []string{`{"exclusive":"phone-X"}`, `{ "exclusive" : "A_1" }`} {
|
||||
graph, err := Parse(base + "```resources\n" + value + "\n```\n")
|
||||
if err != nil || graph.Stages[0].Resources == nil {
|
||||
t.Fatalf("%s: %v", value, err)
|
||||
}
|
||||
if _, ok := StageDefinition(graph.Stages[0]).Blocks["resources"]; ok {
|
||||
t.Fatal("runner control reached executor")
|
||||
}
|
||||
encoded, _ := json.Marshal(graph)
|
||||
if !strings.Contains(string(encoded), `"resources"`) {
|
||||
t.Fatal("resource lost in persisted graph")
|
||||
}
|
||||
}
|
||||
for _, value := range []string{`{}`, `null`, `[]`, `{"exclusive":""}`, `{"exclusive":"a b"}`, `{"exclusive":"a","exclusive":"b"}`, `{"exclusive":"a","extra":1}`, `{"exclusive":["a","b"]}`, fmt.Sprintf(`{"exclusive":%q}`, strings.Repeat("a", 129))} {
|
||||
if _, err := Parse(base + "```resources\n" + value + "\n```\n"); err == nil {
|
||||
t.Fatalf("accepted %s", value)
|
||||
}
|
||||
}
|
||||
human := "# stage gate\n```prompt\nChoose\n```\n```configs\ntype=human\n```\n```edges\ngo -> #success\n```\n```resources\n{\"exclusive\":\"phone\"}\n```\n"
|
||||
if _, err := Parse(human); err == nil {
|
||||
t.Fatal("human acquired a resource")
|
||||
}
|
||||
}
|
||||
|
||||
func resourceStore(t *testing.T) (*Store, func(string) ResourceVisit) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
s, err := Open(filepath.Join(t.TempDir(), "resources.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { s.Close() })
|
||||
if _, err := s.Submit(ctx, "resource", Template([]string{"work"}, true)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, _ := s.List(ctx)
|
||||
d, _ := s.Get(ctx, items[0].ID, 1)
|
||||
count := 0
|
||||
return s, func(resource string) ResourceVisit {
|
||||
count++
|
||||
id, _, err := s.CreateRun(ctx, d, fmt.Sprint(count), "workspace", false, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return ResourceVisit{Resource: resource, RunID: id, Stage: "work", Sequence: 1}
|
||||
}
|
||||
}
|
||||
|
||||
func acquireTestResource(t *testing.T, s *Store, visit ResourceVisit) ResourceLease {
|
||||
t.Helper()
|
||||
l, ch, _, err := s.RequestResource(context.Background(), visit)
|
||||
if err != nil || ch != nil {
|
||||
t.Fatalf("acquire: %v %v", ch, err)
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
func releaseTestResource(t *testing.T, s *Store, lease ResourceLease) {
|
||||
t.Helper()
|
||||
if err := s.SetResourceCleanup(context.Background(), lease, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.ReleaseResource(context.Background(), lease); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResourceFIFOOwnershipCancellationAndRegistry(t *testing.T) {
|
||||
s, create := resourceStore(t)
|
||||
ctx := context.Background()
|
||||
a := acquireTestResource(t, s, create("X"))
|
||||
duplicate := acquireTestResource(t, s, a.ResourceVisit)
|
||||
if duplicate != a {
|
||||
t.Fatal("duplicate acquisition changed capability")
|
||||
}
|
||||
var visits []ResourceVisit
|
||||
var channels []<-chan ResourceLease
|
||||
for i := 0; i < 4; i++ {
|
||||
v := create("X")
|
||||
_, ch, wait, err := s.RequestResource(ctx, v)
|
||||
if err != nil || ch == nil || wait == nil {
|
||||
t.Fatal("missing waiter", err)
|
||||
}
|
||||
_, again, _, err := s.RequestResource(ctx, v)
|
||||
if err != nil || again != ch {
|
||||
t.Fatal("duplicate waiter registered", err)
|
||||
}
|
||||
visits = append(visits, v)
|
||||
channels = append(channels, ch)
|
||||
}
|
||||
if err := s.ReleaseResource(ctx, a); err != nil {
|
||||
t.Fatal(err)
|
||||
} // no cleanup receipt
|
||||
for _, ch := range channels {
|
||||
select {
|
||||
case <-ch:
|
||||
t.Fatal("unconfirmed release granted")
|
||||
default:
|
||||
}
|
||||
}
|
||||
if err := s.SetResourceCleanup(ctx, a, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, corrupt := range []func(*ResourceLease){func(l *ResourceLease) { l.RunID++ }, func(l *ResourceLease) { l.Stage = "other" }, func(l *ResourceLease) { l.Sequence++ }, func(l *ResourceLease) { l.token = "wrong" }} {
|
||||
bad := a
|
||||
corrupt(&bad)
|
||||
if err := s.ReleaseResource(ctx, bad); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, ch := range channels {
|
||||
select {
|
||||
case <-ch:
|
||||
t.Fatal("unconfirmed/mismatched release granted")
|
||||
default:
|
||||
}
|
||||
}
|
||||
if err := s.CancelResource(ctx, visits[1]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
releaseTestResource(t, s, a)
|
||||
for _, i := range []int{0, 2, 3} {
|
||||
var grant ResourceLease
|
||||
select {
|
||||
case grant = <-channels[i]:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("FIFO grant not delivered")
|
||||
}
|
||||
s.AcceptResource(grant)
|
||||
if grant.ResourceVisit != visits[i] {
|
||||
t.Fatal("wrong FIFO owner")
|
||||
}
|
||||
// An old owner's repeated release cannot release the next owner.
|
||||
if err := s.ReleaseResource(ctx, a); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, j := range []int{2, 3} {
|
||||
if j > i {
|
||||
select {
|
||||
case <-channels[j]:
|
||||
t.Fatal("multiple grants")
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
releaseTestResource(t, s, grant)
|
||||
}
|
||||
if len(s.resourceWaiters) != 0 {
|
||||
t.Fatal("channel registry leaked")
|
||||
}
|
||||
for i := 0; i < 30; i++ {
|
||||
owner := acquireTestResource(t, s, create("X"))
|
||||
v := create("X")
|
||||
_, _, _, err := s.RequestResource(ctx, v)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
releaseTestResource(t, s, owner) // race window: granted but not accepted
|
||||
if err := s.CancelResource(ctx, v); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(s.resourceWaiters) != 0 {
|
||||
t.Fatal("grant/cancel leaked channel")
|
||||
}
|
||||
}
|
||||
for i := 0; i < 30; i++ {
|
||||
owner := acquireTestResource(t, s, create("X"))
|
||||
v := create("X")
|
||||
if _, _, _, err := s.RequestResource(ctx, v); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.SetResourceCleanup(ctx, owner, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(2)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
if err := s.ReleaseResource(ctx, owner); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
if err := s.CancelResource(ctx, v); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}()
|
||||
wg.Wait()
|
||||
if len(s.resourceWaiters) != 0 {
|
||||
t.Fatal("concurrent grant/cancel leaked channel")
|
||||
}
|
||||
}
|
||||
var owners, waiters int
|
||||
s.db.QueryRow("SELECT COUNT(*) FROM resource_owners").Scan(&owners)
|
||||
s.db.QueryRow("SELECT COUNT(*) FROM resource_waiters").Scan(&waiters)
|
||||
if owners != 0 || waiters != 0 {
|
||||
t.Fatalf("stranded owners/waiters: %d/%d", owners, waiters)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResourceCancellationPersistenceFailureRemovesChannel(t *testing.T) {
|
||||
s, create := resourceStore(t)
|
||||
acquireTestResource(t, s, create("X"))
|
||||
v := create("X")
|
||||
if _, _, _, err := s.RequestResource(context.Background(), v); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.CancelResource(context.Background(), v); err == nil {
|
||||
t.Fatal("closed DB cancellation claimed success")
|
||||
}
|
||||
if len(s.resourceWaiters) != 0 {
|
||||
t.Fatal("persistence failure leaked channel")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResourceRestartQuarantineAndRetention(t *testing.T) {
|
||||
for _, confirmed := range []bool{false, true} {
|
||||
t.Run(fmt.Sprint(confirmed), func(t *testing.T) {
|
||||
s, create := resourceStore(t)
|
||||
ctx := context.Background()
|
||||
a := acquireTestResource(t, s, create("X"))
|
||||
b := create("X")
|
||||
if _, _, _, err := s.RequestResource(ctx, b); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if confirmed {
|
||||
if err := s.SetResourceCleanup(ctx, a, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
path := s.path
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reopened, err := Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer reopened.Close()
|
||||
if err := reopened.RecoverRuns(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := reopened.RecoverRuns(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
detail, err := reopened.GetRun(ctx, b.RunID)
|
||||
if err != nil || detail.Status != "interrupted" || detail.ResourceWait != nil || len(detail.Steps) != 0 || !strings.Contains(detail.Diagnostic, "resource") {
|
||||
t.Fatal("queued visit replayed/lost diagnostic", detail, err)
|
||||
}
|
||||
exists, err := reopened.HasResourceOwner(ctx, a.RunID)
|
||||
if err != nil || exists == confirmed {
|
||||
t.Fatal("incorrect recovery disposition", exists, err)
|
||||
}
|
||||
report, err := reopened.RetentionReport(ctx, RetentionPolicy{Keep: 0}, "", time.Now())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
protected := false
|
||||
for _, p := range report.Protected {
|
||||
if p.ID == a.RunID {
|
||||
protected = true
|
||||
}
|
||||
}
|
||||
if protected == confirmed {
|
||||
t.Fatal("quarantined evidence not protected")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -130,11 +130,12 @@ type retentionQuerier interface {
|
||||
// retentionRunInfo is one pipeline_runs row plus the step aggregates protection
|
||||
// needs, read in the same statement so the report never issues a per-run query.
|
||||
type retentionRunInfo struct {
|
||||
id int64
|
||||
status string
|
||||
createdAt time.Time
|
||||
waitingSteps int
|
||||
activeSteps int
|
||||
id int64
|
||||
status string
|
||||
createdAt time.Time
|
||||
waitingSteps int
|
||||
activeSteps int
|
||||
resourceOwners int
|
||||
}
|
||||
|
||||
// protectionReasons lists why a run must not be removed for a reason intrinsic
|
||||
@@ -155,6 +156,9 @@ func (r retentionRunInfo) protectionReasons() []string {
|
||||
if r.activeSteps > 0 {
|
||||
reasons = append(reasons, "cleanup agent still active (agent_active=1)")
|
||||
}
|
||||
if r.resourceOwners > 0 {
|
||||
reasons = append(reasons, "resource ownership retained (possibly quarantined)")
|
||||
}
|
||||
return reasons
|
||||
}
|
||||
|
||||
@@ -171,9 +175,20 @@ type retentionSelection struct {
|
||||
// report is a bounded number of round trips rather than one query per run.
|
||||
func selectRetentionRuns(ctx context.Context, q retentionQuerier, policy RetentionPolicy, now time.Time) (retentionSelection, error) {
|
||||
var sel retentionSelection
|
||||
// Maintenance is deliberately non-migrating and may inspect a database
|
||||
// whose server predates resource support.
|
||||
var resources bool
|
||||
if err := q.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name='resource_owners')").Scan(&resources); err != nil {
|
||||
return sel, err
|
||||
}
|
||||
owners := "0"
|
||||
if resources {
|
||||
owners = "(SELECT COUNT(*) FROM resource_owners o WHERE o.run_id=r.id)"
|
||||
}
|
||||
rows, err := q.QueryContext(ctx, `SELECT r.id,r.status,strftime('%Y-%m-%dT%H:%M:%SZ',r.created_at),
|
||||
COALESCE((SELECT COUNT(*) FROM run_steps s WHERE s.run_id=r.id AND s.status=?),0),
|
||||
COALESCE((SELECT COUNT(*) FROM run_steps s WHERE s.run_id=r.id AND s.agent_active=1),0) `+
|
||||
COALESCE((SELECT COUNT(*) FROM run_steps s WHERE s.run_id=r.id AND s.agent_active=1),0),
|
||||
`+owners+` `+
|
||||
runFrom+` ORDER BY r.id DESC`, protocol.StepStatusWaiting)
|
||||
if err != nil {
|
||||
return sel, err
|
||||
@@ -182,7 +197,7 @@ COALESCE((SELECT COUNT(*) FROM run_steps s WHERE s.run_id=r.id AND s.agent_activ
|
||||
for rows.Next() {
|
||||
var run retentionRunInfo
|
||||
var created string
|
||||
if err := rows.Scan(&run.id, &run.status, &created, &run.waitingSteps, &run.activeSteps); err != nil {
|
||||
if err := rows.Scan(&run.id, &run.status, &created, &run.waitingSteps, &run.activeSteps, &run.resourceOwners); err != nil {
|
||||
return sel, err
|
||||
}
|
||||
run.createdAt = parseRetentionTime(created)
|
||||
|
||||
@@ -21,14 +21,19 @@ const runStamps = `strftime('%Y-%m-%dT%H:%M:%SZ',r.created_at),COALESCE(strftime
|
||||
const runSelect = `SELECT r.id,r.pipeline_id,p.name,r.version,v.content_hash,r.status,r.outcome,r.current_stage,
|
||||
` + runStamps + `,r.diagnostic,
|
||||
CASE WHEN r.status='succeeded' THEN r.output_json ELSE COALESCE((SELECT output_json FROM run_steps WHERE run_id=r.id AND status='completed' ORDER BY sequence DESC LIMIT 1),'{}') END,
|
||||
(SELECT COUNT(*) FROM run_steps WHERE run_id=r.id AND status='completed'),r.workspace,r.title,r.model,r.stage_models
|
||||
(SELECT COUNT(*) FROM run_steps WHERE run_id=r.id AND status='completed'),r.workspace,r.title,r.model,r.stage_models,r.resource_wait
|
||||
` + runFrom + ` JOIN pipeline_versions v ON v.pipeline_id=r.pipeline_id AND v.version=r.version`
|
||||
|
||||
func scanRun(row interface{ Scan(...any) error }, r *protocol.RunSummary) error {
|
||||
var output, stageModels string
|
||||
if err := row.Scan(&r.ID, &r.PipelineID, &r.Name, &r.Version, &r.ContentHash, &r.Status, &r.Outcome, &r.CurrentStage, &r.CreatedAt, &r.FinishedAt, &r.Diagnostic, &output, &r.CompletedSteps, &r.Workspace, &r.Title, &r.Model, &stageModels); err != nil {
|
||||
var output, stageModels, resourceWait string
|
||||
if err := row.Scan(&r.ID, &r.PipelineID, &r.Name, &r.Version, &r.ContentHash, &r.Status, &r.Outcome, &r.CurrentStage, &r.CreatedAt, &r.FinishedAt, &r.Diagnostic, &output, &r.CompletedSteps, &r.Workspace, &r.Title, &r.Model, &stageModels, &resourceWait); err != nil {
|
||||
return err
|
||||
}
|
||||
if resourceWait != "" {
|
||||
if err := json.Unmarshal([]byte(resourceWait), &r.ResourceWait); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if stageModels != "" && stageModels != "{}" {
|
||||
if err := json.Unmarshal([]byte(stageModels), &r.StageModels); err != nil {
|
||||
return err
|
||||
|
||||
@@ -44,7 +44,7 @@ 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')", key, id)); err != nil {
|
||||
if err := affected(tx.ExecContext(ctx, "UPDATE pipeline_runs SET status='running',current_stage=?,resource_wait='' WHERE id=? AND status IN ('queued','running')", 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 {
|
||||
@@ -310,5 +310,5 @@ func (s *Store) FinishRun(ctx context.Context, id int64, status, outcome, diagno
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return affected(s.db.ExecContext(ctx, "UPDATE pipeline_runs SET status=?,outcome=?,diagnostic=?,output_json=?,finished_at=CURRENT_TIMESTAMP WHERE id=? AND status IN ('queued','running')", status, outcome, diagnostic, string(data), id))
|
||||
return affected(s.db.ExecContext(ctx, "UPDATE pipeline_runs SET status=?,outcome=?,diagnostic=?,output_json=?,finished_at=CURRENT_TIMESTAMP,resource_wait='' WHERE id=? AND status IN ('queued','running')", status, outcome, diagnostic, string(data), id))
|
||||
}
|
||||
|
||||
@@ -51,13 +51,28 @@ CREATE TABLE IF NOT EXISTS run_session_owners (
|
||||
run_id INTEGER NOT NULL, sequence INTEGER NOT NULL, backend TEXT NOT NULL, reference TEXT NOT NULL DEFAULT '',
|
||||
PRIMARY KEY(run_id,sequence), FOREIGN KEY(run_id,sequence) REFERENCES run_steps(run_id,sequence));
|
||||
CREATE TABLE IF NOT EXISTS run_retries (
|
||||
run_id INTEGER PRIMARY KEY REFERENCES pipeline_runs(id), original_run_id INTEGER NOT NULL REFERENCES pipeline_runs(id));`)
|
||||
run_id INTEGER PRIMARY KEY REFERENCES pipeline_runs(id), original_run_id INTEGER NOT NULL REFERENCES pipeline_runs(id));
|
||||
CREATE TABLE IF NOT EXISTS resource_owners (
|
||||
resource_key TEXT PRIMARY KEY, run_id INTEGER NOT NULL REFERENCES pipeline_runs(id),
|
||||
stage_key TEXT NOT NULL, sequence INTEGER NOT NULL, token TEXT NOT NULL,
|
||||
cleanup_confirmed INTEGER NOT NULL DEFAULT 0, diagnostic TEXT NOT NULL DEFAULT '',
|
||||
acquired_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP);
|
||||
CREATE INDEX IF NOT EXISTS resource_owner_run ON resource_owners(run_id);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS resource_owner_visit ON resource_owners(run_id);
|
||||
CREATE TABLE IF NOT EXISTS resource_waiters (
|
||||
queue_order INTEGER PRIMARY KEY AUTOINCREMENT, resource_key TEXT NOT NULL,
|
||||
run_id INTEGER NOT NULL UNIQUE REFERENCES pipeline_runs(id), stage_key TEXT NOT NULL,
|
||||
sequence INTEGER NOT NULL, token TEXT NOT NULL, queued_at TEXT NOT NULL);
|
||||
CREATE INDEX IF NOT EXISTS resource_wait_fifo ON resource_waiters(resource_key,queue_order);`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.migrateRunTitles(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.addColumnIfMissing("pipeline_runs", "resource_wait", "TEXT NOT NULL DEFAULT ''"); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.migrateRunModels()
|
||||
}
|
||||
|
||||
@@ -122,16 +137,29 @@ func (s *Store) addColumnIfMissing(table, column, definition string) error {
|
||||
}
|
||||
|
||||
func (s *Store) RecoverRuns(ctx context.Context) error {
|
||||
s.resourceMu.Lock()
|
||||
defer s.resourceMu.Unlock()
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err := tx.ExecContext(ctx, "UPDATE run_steps SET status='interrupted',agent_active=0,diagnostic='Server stopped; stage was not resumed',finished_at=CURRENT_TIMESTAMP WHERE (status='running' OR agent_active=1) AND status<>?", protocol.StepStatusWaiting); err != nil {
|
||||
// No replay: pending visits never began. Uncertain owners survive recovery,
|
||||
// including the crash window before BeginStep/session registration.
|
||||
if _, err := tx.ExecContext(ctx, "UPDATE pipeline_runs SET diagnostic='Server stopped while queued for a resource; pending visit was not resumed',status='interrupted',finished_at=CURRENT_TIMESTAMP,resource_wait='' WHERE id IN (SELECT run_id FROM resource_waiters); DELETE FROM resource_waiters"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := recoverResourceOwners(ctx, tx); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "UPDATE run_steps SET status='interrupted',agent_active=CASE WHEN EXISTS(SELECT 1 FROM resource_owners o WHERE o.run_id=run_steps.run_id AND o.sequence=run_steps.sequence) THEN agent_active ELSE 0 END,diagnostic='Server stopped; stage was not resumed',finished_at=CURRENT_TIMESTAMP WHERE (status='running' OR agent_active=1) AND status<>?", protocol.StepStatusWaiting); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "UPDATE pipeline_runs SET status='interrupted',diagnostic='Server stopped; run was not resumed',finished_at=CURRENT_TIMESTAMP WHERE status IN ('queued','running') AND status<>?", protocol.RunStatusWaiting); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "UPDATE pipeline_runs SET diagnostic='Server stopped; resource ownership quarantined: inspect retained session, tool termination and restoration before reconciliation' WHERE id IN (SELECT run_id FROM resource_owners)"); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ func StageDefinition(s Stage) stage.Definition {
|
||||
delete(blocks, "input") // Retired contracts in historical graph JSON are ignored.
|
||||
delete(blocks, "limits")
|
||||
delete(blocks, "memory")
|
||||
delete(blocks, "resources")
|
||||
for name, value := range map[string]string{"output": s.Output, "prompt": s.Prompt} {
|
||||
if value != "" {
|
||||
blocks[name] = value
|
||||
|
||||
@@ -18,10 +18,12 @@ import (
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
db *sql.DB
|
||||
dir string
|
||||
path string
|
||||
mu sync.Mutex
|
||||
db *sql.DB
|
||||
dir string
|
||||
path string
|
||||
mu sync.Mutex
|
||||
resourceMu sync.Mutex
|
||||
resourceWaiters map[ResourceVisit]chan ResourceLease
|
||||
}
|
||||
|
||||
// openDB opens one SQLite connection pool for a DSN. Every open path shares it
|
||||
|
||||
Reference in New Issue
Block a user