Unattended test: build the subscription the current way
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -2,7 +2,6 @@ package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
@@ -147,7 +146,8 @@ func (h *chatHub) clearChatAttention(sessionID, id string) {
|
||||
}
|
||||
|
||||
// startChatAttention publishes asynchronously within the 30-second notification
|
||||
// budget. It never blocks or fails chat handling; failures are only logged.
|
||||
// budget. It never blocks or fails chat handling; the phone push goes through
|
||||
// the durable outbox, which retries a failed attempt.
|
||||
func (h *chatHub) startChatAttention(a chatAttention) {
|
||||
base := h.baseCtx
|
||||
if base == nil {
|
||||
@@ -176,7 +176,7 @@ func (h *chatHub) startChatAttention(a chatAttention) {
|
||||
if a.reply {
|
||||
title, body = chatReplyText(name, a.body)
|
||||
}
|
||||
click, views := chatAttentionLinks(a.sessionID)
|
||||
click, _ := chatAttentionLinks(a.sessionID)
|
||||
kind := protocol.NotificationChatQuestion
|
||||
if a.reply {
|
||||
kind = protocol.NotificationChatReply
|
||||
@@ -192,9 +192,7 @@ func (h *chatHub) startChatAttention(a chatAttention) {
|
||||
return
|
||||
}
|
||||
// ntfy takes a single-line message of at most 2048 bytes.
|
||||
if _, err := chatAttentionPublish(stage.WithNtfySequenceID(ctx, chatNtfySequence(a.id)), "system", title, truncateUTF8(singleLine(body), 2000), "", nil, click, views...); err != nil {
|
||||
log.Printf("chat attention notification session=%s: %v", a.sessionID, err)
|
||||
}
|
||||
h.pushChatNtfy(ctx, pipeline.ChatNotification{ID: a.id, SessionID: a.sessionID, Title: title, Body: truncateUTF8(singleLine(body), 2000), Click: click, SequenceID: chatNtfySequence(a.id)})
|
||||
}()
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
"git.a-wan.net/alan/pipelines/internal/claude"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
)
|
||||
|
||||
// When Claude Code refuses an operator chat's turn because the account ran
|
||||
@@ -281,10 +280,11 @@ func (h *chatHub) publishAutoSwitchNotice(ctx context.Context, refusal claude.Us
|
||||
}
|
||||
title := truncateUTF8("Switched "+name+" to "+singleLine(email)+" and continued", 256)
|
||||
message := "Claude usage ran out, so Pipelines switched the account and asked the agent to check it is on track before continuing."
|
||||
click, views := chatAttentionLinks(refusal.SessionID)
|
||||
click, _ := chatAttentionLinks(refusal.SessionID)
|
||||
id := "chat:" + refusal.SessionID + ":auto-switch:" + refusalKey(refusal)
|
||||
if h.notes != nil {
|
||||
h.notes.record(ctx, pipeline.AppNotificationRecord{
|
||||
AppNotification: protocol.AppNotification{ID: "chat:" + refusal.SessionID + ":auto-switch:" + refusalKey(refusal), Kind: protocol.NotificationChatReply,
|
||||
AppNotification: protocol.AppNotification{ID: id, Kind: protocol.NotificationChatReply,
|
||||
Title: title, Message: message, Click: click, Priority: chatAutoSwitchPriority, Tags: []string{}, Group: "chat:" + refusal.SessionID},
|
||||
SessionID: refusal.SessionID,
|
||||
})
|
||||
@@ -292,7 +292,5 @@ func (h *chatHub) publishAutoSwitchNotice(ctx context.Context, refusal claude.Us
|
||||
if !chatAttentionConfigured() || !chatNotificationSettings(ctx, h.settings).NtfyEnabled {
|
||||
return
|
||||
}
|
||||
if _, err := chatAttentionPublish(stage.WithNtfyPriority(ctx, chatAutoSwitchPriority), "system", title, message, "", nil, click, views...); err != nil {
|
||||
log.Printf("claude auto-switch notification session=%s: %v", refusal.SessionID, err)
|
||||
}
|
||||
h.pushChatNtfy(ctx, pipeline.ChatNotification{ID: id, SessionID: refusal.SessionID, Title: title, Body: message, Click: click, Priority: chatAutoSwitchPriority})
|
||||
}
|
||||
|
||||
@@ -156,6 +156,7 @@ func chatSessionFromOperator(session pipeline.OperatorSession) protocol.ChatSess
|
||||
CreatedAt: session.CreatedAt,
|
||||
UpdatedAt: session.UpdatedAt,
|
||||
Backend: session.Backend,
|
||||
Revision: session.Revision,
|
||||
}
|
||||
if session.ClosedAt > 0 {
|
||||
out.Closed = true
|
||||
|
||||
@@ -51,6 +51,9 @@ type chatHub struct {
|
||||
attentionSeen map[string]struct{}
|
||||
attentionOrder []string
|
||||
attentionWG sync.WaitGroup
|
||||
// outbox makes chat phone pushes durable and retried (chat_ntfy_outbox.go);
|
||||
// nil publishes each push once, directly.
|
||||
outbox chatNotificationOutbox
|
||||
// notifiedTurns holds the chats whose current turn already sent an agent
|
||||
// notify, so that turn's end is not announced again (one turn, one ping).
|
||||
notifiedTurns map[string]struct{}
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
)
|
||||
|
||||
// Chat phone pushes (attention items and Claude auto-switch notices) go
|
||||
// through a durable outbox like run notifications: the push is recorded first,
|
||||
// one attempt is made at once, and a background worker retries a failed or
|
||||
// interrupted attempt with backoff, also after a restart. A push whose app
|
||||
// notification the operator already cleared is never published late, and a
|
||||
// publication that raced a clear is cleared on the phone again, so the ntfy
|
||||
// sequence-id/clear behaviour (chat_ntfy_clear.go) holds.
|
||||
|
||||
// chatNotificationOutbox is the durable chat push outbox; *pipeline.Store
|
||||
// implements it.
|
||||
type chatNotificationOutbox interface {
|
||||
EnqueueChatNotification(ctx context.Context, n pipeline.ChatNotification, now time.Time) error
|
||||
ClaimChatNotification(ctx context.Context, now int64) (*pipeline.ChatNotification, error)
|
||||
FinishChatNotification(ctx context.Context, n pipeline.ChatNotification, now int64, messageID string, failure error) error
|
||||
ChatNotificationCleared(ctx context.Context, id string) (bool, error)
|
||||
Done() <-chan struct{}
|
||||
}
|
||||
|
||||
// chatOutboxInterval is how often the worker looks for due retries.
|
||||
var chatOutboxInterval = time.Second
|
||||
|
||||
// chatOutboxSkew shifts the outbox clock; tests move it past a backoff.
|
||||
var chatOutboxSkew atomic.Int64
|
||||
|
||||
func chatOutboxNow() time.Time { return time.Now().Add(time.Duration(chatOutboxSkew.Load())) }
|
||||
|
||||
// startChatNotificationOutbox wires the durable outbox and starts its retry
|
||||
// worker for the life of ctx.
|
||||
func (h *chatHub) startChatNotificationOutbox(ctx context.Context, outbox chatNotificationOutbox) {
|
||||
h.outbox = outbox
|
||||
go func() {
|
||||
ticker := time.NewTicker(chatOutboxInterval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-outbox.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
h.deliverChatNotifications(ctx, 16)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// pushChatNtfy publishes one chat phone push. With an outbox it is recorded
|
||||
// durably and attempted at once; without one (a store-less hub) it is a single
|
||||
// direct attempt, as before.
|
||||
func (h *chatHub) pushChatNtfy(ctx context.Context, n pipeline.ChatNotification) {
|
||||
if h.outbox != nil {
|
||||
err := h.outbox.EnqueueChatNotification(ctx, n, chatOutboxNow())
|
||||
if err == nil {
|
||||
h.deliverChatNotifications(ctx, 1)
|
||||
return
|
||||
}
|
||||
log.Printf("enqueue chat notification %s: %v; publishing directly", n.ID, err)
|
||||
}
|
||||
if _, err := chatAttentionPublish(chatNtfyContext(ctx, n), "system", n.Title, n.Body, "", nil, n.Click, chatNtfyViews(n)...); err != nil {
|
||||
log.Printf("chat notification session=%s: %v", n.SessionID, err)
|
||||
}
|
||||
}
|
||||
|
||||
func chatNtfyContext(ctx context.Context, n pipeline.ChatNotification) context.Context {
|
||||
if n.SequenceID != "" {
|
||||
ctx = stage.WithNtfySequenceID(ctx, n.SequenceID)
|
||||
}
|
||||
if n.Priority > 0 {
|
||||
ctx = stage.WithNtfyPriority(ctx, n.Priority)
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
|
||||
// chatNtfyViews derives the push's actions at delivery, so a changed web
|
||||
// origin applies to a retried push.
|
||||
func chatNtfyViews(n pipeline.ChatNotification) []stage.NtfyView {
|
||||
_, views := chatAttentionLinks(n.SessionID)
|
||||
return views
|
||||
}
|
||||
|
||||
// deliverChatNotifications attempts up to limit due pushes.
|
||||
func (h *chatHub) deliverChatNotifications(ctx context.Context, limit int) {
|
||||
outbox := h.outbox
|
||||
if outbox == nil {
|
||||
return
|
||||
}
|
||||
for i := 0; i < limit && ctx.Err() == nil; i++ {
|
||||
n, err := outbox.ClaimChatNotification(ctx, chatOutboxNow().Unix())
|
||||
if err != nil {
|
||||
log.Printf("claim chat notification: %v", err)
|
||||
return
|
||||
}
|
||||
if n == nil {
|
||||
return
|
||||
}
|
||||
publish, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
result, publishErr := chatAttentionPublish(chatNtfyContext(publish, *n), "system", n.Title, n.Body, "", nil, n.Click, chatNtfyViews(*n)...)
|
||||
cancel()
|
||||
if publishErr != nil {
|
||||
log.Printf("chat notification session=%s attempt=%d: %v", n.SessionID, n.Attempts, publishErr)
|
||||
}
|
||||
messageID, _ := result["message_id"].(string)
|
||||
save, done := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
|
||||
if err := outbox.FinishChatNotification(save, *n, chatOutboxNow().Unix(), messageID, publishErr); err != nil {
|
||||
log.Printf("save chat notification %s: %v", n.ID, err)
|
||||
}
|
||||
// The operator may have cleared it in the app while it was being
|
||||
// published, after the clear went to ntfy: clear it there again.
|
||||
if publishErr == nil && n.SequenceID != "" {
|
||||
if cleared, err := outbox.ChatNotificationCleared(save, n.ID); err == nil && cleared {
|
||||
clearChatNtfy([]string{n.ID})
|
||||
}
|
||||
}
|
||||
done()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
)
|
||||
|
||||
// A chat attention push that ntfy refuses is kept in the durable outbox and
|
||||
// retried by the worker with its sequence id, not lost after one attempt.
|
||||
func TestChatAttentionPushIsRetriedFromTheOutbox(t *testing.T) {
|
||||
t.Setenv("PIPELINES_NTFY_URL", "http://ntfy.invalid/pipelines")
|
||||
t.Setenv("PIPELINES_WEB_PUBLIC_URL", "")
|
||||
interval := chatOutboxInterval
|
||||
chatOutboxInterval = 20 * time.Millisecond
|
||||
defer func() { chatOutboxInterval = interval }()
|
||||
var mu sync.Mutex
|
||||
var sequences []string
|
||||
original := chatAttentionPublish
|
||||
chatAttentionPublish = func(ctx context.Context, _, _, _, _ string, _ []byte, _ string, _ ...stage.NtfyView) (stage.Values, error) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
sequences = append(sequences, stage.NtfySequence(ctx))
|
||||
if len(sequences) == 1 {
|
||||
return nil, errors.New("ntfy unavailable")
|
||||
}
|
||||
return stage.Values{"message_id": "m1"}, nil
|
||||
}
|
||||
defer func() { chatAttentionPublish = original }()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
store := newOperatorStore(t)
|
||||
h := chatAttentionHub(t, "ses_a")
|
||||
h.settings = store
|
||||
h.notes = newAppNotifier(store)
|
||||
h.startChatNotificationOutbox(ctx, store)
|
||||
form := protocol.ChatForm{ID: "que_1", SessionID: "ses_a", Kind: "question", Title: "Ship it?"}
|
||||
h.emit(protocol.ChatEventFrame{SessionID: "ses_a", Kind: protocol.ChatEventForm, Form: &form})
|
||||
h.attentionWG.Wait()
|
||||
id := "chat:ses_a:form:que_1"
|
||||
if status, attempts, err := store.ChatNotificationStatus(ctx, id); err != nil || status != "pending" || attempts != 1 {
|
||||
t.Fatalf("after a refused attempt: %s/%d %v", status, attempts, err)
|
||||
}
|
||||
// The first backoff is 5 s; move the outbox clock past it.
|
||||
chatOutboxSkew.Store(int64(10 * time.Second))
|
||||
defer chatOutboxSkew.Store(0)
|
||||
waitFor(t, "retried push sent", func() bool {
|
||||
status, _, _ := store.ChatNotificationStatus(ctx, id)
|
||||
return status == "sent"
|
||||
})
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if len(sequences) != 2 || sequences[0] != chatNtfySequence(id) || sequences[1] != sequences[0] {
|
||||
t.Fatalf("sequence ids = %v", sequences)
|
||||
}
|
||||
}
|
||||
@@ -237,9 +237,24 @@ func chatQueueRow(sessionID string, p *chatQueuedPrompt) pipeline.ChatQueuedProm
|
||||
}
|
||||
}
|
||||
|
||||
// errChatQueuedPromptInvalid marks a stored prompt that can never be rebuilt
|
||||
// (unreadable attachment list, an attachment outside the store). Only such a
|
||||
// row is dropped; any other promptFromRow failure (the attachment directory
|
||||
// cannot be resolved right now) keeps the row for a later retry.
|
||||
var errChatQueuedPromptInvalid = errors.New("queued prompt is invalid")
|
||||
|
||||
// chatQueueRecoveryRetry is the first delay before a session whose queued
|
||||
// prompts could not be restored is tried again; it doubles up to
|
||||
// chatQueueRecoveryRetryMax.
|
||||
var (
|
||||
chatQueueRecoveryRetry = 30 * time.Second
|
||||
chatQueueRecoveryRetryMax = 10 * time.Minute
|
||||
)
|
||||
|
||||
// promptFromRow rebuilds a queued prompt read back from the store. Its files
|
||||
// must still name the server's own attachment directory; they are leased again
|
||||
// so retention cannot collect them before delivery.
|
||||
// so retention cannot collect them before delivery. A permanent failure wraps
|
||||
// errChatQueuedPromptInvalid.
|
||||
func promptFromRow(row pipeline.ChatQueuedPrompt) (*chatQueuedPrompt, error) {
|
||||
p := &chatQueuedPrompt{
|
||||
text: row.Text,
|
||||
@@ -255,7 +270,7 @@ func promptFromRow(row pipeline.ChatQueuedPrompt) (*chatQueuedPrompt, error) {
|
||||
_ = json.Unmarshal([]byte(row.PartsJSON), &p.parts)
|
||||
var stored []chatStoredFile
|
||||
if err := json.Unmarshal([]byte(row.FilesJSON), &stored); err != nil {
|
||||
return p, fmt.Errorf("queued prompt attachments are unreadable")
|
||||
return p, fmt.Errorf("%w: queued prompt attachments are unreadable", errChatQueuedPromptInvalid)
|
||||
}
|
||||
if len(stored) == 0 {
|
||||
return p, nil
|
||||
@@ -269,7 +284,7 @@ func promptFromRow(row pipeline.ChatQueuedPrompt) (*chatQueuedPrompt, error) {
|
||||
for _, file := range stored {
|
||||
u, err := url.Parse(file.URI)
|
||||
if err != nil || u.Scheme != "file" || filepath.Dir(u.Path) != dir {
|
||||
return p, fmt.Errorf("queued prompt attachment %q is outside the attachment store", file.Name)
|
||||
return p, fmt.Errorf("%w: queued prompt attachment %q is outside the attachment store", errChatQueuedPromptInvalid, file.Name)
|
||||
}
|
||||
chatAttachmentStore.leased[u.Path] = true
|
||||
p.files = append(p.files, opencode.NewPreparedPromptFile(file.URI, file.Name))
|
||||
@@ -427,49 +442,80 @@ func (h *chatHub) resumeQueued(ctx context.Context, broker chatBroker) {
|
||||
return
|
||||
}
|
||||
for _, sessionID := range sessions {
|
||||
rows, err := h.queueStore.ChatQueuedPrompts(ctx, sessionID)
|
||||
if err != nil {
|
||||
log.Printf("chat queue recovery session=%s: %v", sessionID, err)
|
||||
h.resumeQueuedSession(ctx, broker, sessionID, chatQueueRecoveryRetry)
|
||||
}
|
||||
}
|
||||
|
||||
// resumeQueuedSession restores one session's durable queue. A prompt that can
|
||||
// never be rebuilt is dropped; a transient failure (the store or the
|
||||
// attachment directory unavailable) keeps every row, restores nothing for the
|
||||
// session (so FIFO order is kept) and tries again after retry, backing off.
|
||||
// A row whose operation the live hub already knows (a retry racing a client
|
||||
// that queued or delivered it meanwhile) is left to the hub.
|
||||
func (h *chatHub) resumeQueuedSession(ctx context.Context, broker chatBroker, sessionID string, retry time.Duration) {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
later := func(err error) {
|
||||
log.Printf("chat queue recovery session=%s: %v; retrying in %s", sessionID, err, retry)
|
||||
next := min(2*retry, chatQueueRecoveryRetryMax)
|
||||
time.AfterFunc(retry, func() { h.resumeQueuedSession(ctx, broker, sessionID, next) })
|
||||
}
|
||||
rows, err := h.queueStore.ChatQueuedPrompts(ctx, sessionID)
|
||||
if err != nil {
|
||||
later(err)
|
||||
return
|
||||
}
|
||||
var prompts []*chatQueuedPrompt
|
||||
for _, row := range rows {
|
||||
h.mu.Lock()
|
||||
_, known := h.recentOps[sessionID+"\x00"+row.OperationID]
|
||||
h.mu.Unlock()
|
||||
if known && row.OperationID != "" {
|
||||
continue
|
||||
}
|
||||
var prompts []*chatQueuedPrompt
|
||||
for _, row := range rows {
|
||||
p, err := promptFromRow(row)
|
||||
if err != nil {
|
||||
releaseChatAttachments(p.files)
|
||||
log.Printf("chat queue recovery session=%s: %v", sessionID, err)
|
||||
_, _ = h.queueStore.DeleteChatQueuedPrompt(ctx, sessionID, row.OperationID)
|
||||
continue
|
||||
}
|
||||
p, err := promptFromRow(row)
|
||||
if err == nil {
|
||||
prompts = append(prompts, p)
|
||||
}
|
||||
if len(prompts) == 0 {
|
||||
continue
|
||||
}
|
||||
releaseChatAttachments(p.files)
|
||||
if !errors.Is(err, errChatQueuedPromptInvalid) {
|
||||
for _, kept := range prompts {
|
||||
releaseChatAttachments(kept.files)
|
||||
}
|
||||
later(err)
|
||||
return
|
||||
}
|
||||
log.Printf("chat queue recovery session=%s: dropping %s: %v", sessionID, row.OperationID, err)
|
||||
_, _ = h.queueStore.DeleteChatQueuedPrompt(ctx, sessionID, row.OperationID)
|
||||
}
|
||||
if len(prompts) == 0 {
|
||||
return
|
||||
}
|
||||
h.mu.Lock()
|
||||
room := h.roomLocked(sessionID)
|
||||
if room.broker == nil {
|
||||
room.broker = broker
|
||||
}
|
||||
room.notBefore = time.Now().Add(chatQueueRecoverySettle)
|
||||
for _, p := range prompts {
|
||||
if !room.holdsOp(p.operationID) {
|
||||
room.queue = append(room.queue, p)
|
||||
h.rememberOpLocked(sessionID, p.operationID)
|
||||
}
|
||||
}
|
||||
h.mu.Unlock()
|
||||
go func(room *chatRoom) {
|
||||
// Attach the stream first so a turn the harness is still running is
|
||||
// observed before the settle window lets the runner deliver.
|
||||
if err := h.ensureObserving(room, broker); err != nil && room.ctx.Err() == nil {
|
||||
log.Printf("chat queue recovery observe session=%s: %v", room.sessionID, err)
|
||||
}
|
||||
h.mu.Lock()
|
||||
room := h.roomLocked(sessionID)
|
||||
if room.broker == nil {
|
||||
room.broker = broker
|
||||
}
|
||||
room.notBefore = time.Now().Add(chatQueueRecoverySettle)
|
||||
for _, p := range prompts {
|
||||
if !room.holdsOp(p.operationID) {
|
||||
room.queue = append(room.queue, p)
|
||||
h.rememberOpLocked(sessionID, p.operationID)
|
||||
}
|
||||
}
|
||||
signalWake(room.wake)
|
||||
h.mu.Unlock()
|
||||
go func(room *chatRoom) {
|
||||
// Attach the stream first so a turn the harness is still running is
|
||||
// observed before the settle window lets the runner deliver.
|
||||
if err := h.ensureObserving(room, broker); err != nil && room.ctx.Err() == nil {
|
||||
log.Printf("chat queue recovery observe session=%s: %v", room.sessionID, err)
|
||||
}
|
||||
h.mu.Lock()
|
||||
signalWake(room.wake)
|
||||
h.mu.Unlock()
|
||||
}(room)
|
||||
}
|
||||
}(room)
|
||||
}
|
||||
|
||||
func (r *chatRoom) holdsOp(operationID string) bool {
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
)
|
||||
|
||||
func fastQueueRecovery(t *testing.T) {
|
||||
t.Helper()
|
||||
settle, retry, retryMax := chatQueueRecoverySettle, chatQueueRecoveryRetry, chatQueueRecoveryRetryMax
|
||||
chatQueueRecoverySettle, chatQueueRecoveryRetry, chatQueueRecoveryRetryMax = 10*time.Millisecond, 50*time.Millisecond, 100*time.Millisecond
|
||||
t.Cleanup(func() {
|
||||
chatQueueRecoverySettle, chatQueueRecoveryRetry, chatQueueRecoveryRetryMax = settle, retry, retryMax
|
||||
})
|
||||
}
|
||||
|
||||
func queuedPromptWithFile(t *testing.T, store *pipeline.Store, op, text, path string) {
|
||||
t.Helper()
|
||||
files, err := json.Marshal([]chatStoredFile{{URI: (&url.URL{Scheme: "file", Path: path}).String(), Name: filepath.Base(path)}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := store.EnqueueChatPrompt(context.Background(), pipeline.ChatQueuedPrompt{SessionID: "ses_1", OperationID: op, MessageID: "msg_" + op, Text: text, FilesJSON: string(files)}, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// A queued prompt whose attachment directory cannot be resolved at restart is
|
||||
// kept and restored on a later retry, not deleted.
|
||||
func TestChatQueuedPromptKeptOnTransientAttachmentFailure(t *testing.T) {
|
||||
fastQueueRecovery(t)
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(t.TempDir(), "queue.db")
|
||||
store := openQueueStore(t, path)
|
||||
queuedPromptWithFile(t, store, "op-1", "with file", filepath.Join(dir, "a.txt"))
|
||||
t.Setenv("PIPELINES_CHAT_ATTACHMENT_DIR", "relative/dir") // unresolvable for now
|
||||
broker := newChannelChat()
|
||||
startQueueServer(t, broker, store)
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
if ops := queuedOps(t, store); !slices.Equal(ops, []string{"op-1"}) {
|
||||
t.Fatalf("queued prompt dropped on a transient failure: %v", ops)
|
||||
}
|
||||
if texts := broker.promptTexts(); len(texts) != 0 {
|
||||
t.Fatalf("prompt delivered while unrestorable: %v", texts)
|
||||
}
|
||||
t.Setenv("PIPELINES_CHAT_ATTACHMENT_DIR", dir)
|
||||
waitFor(t, "prompt restored on retry", func() bool { return slices.Equal(broker.promptTexts(), []string{"with file"}) })
|
||||
waitFor(t, "delivered row deleted", func() bool { return len(queuedOps(t, store)) == 0 })
|
||||
}
|
||||
|
||||
// A queued prompt that can never be rebuilt is still dropped, and the rest of
|
||||
// the session's queue is delivered.
|
||||
func TestChatQueuedPromptDroppedOnPermanentFailure(t *testing.T) {
|
||||
fastQueueRecovery(t)
|
||||
dir := t.TempDir()
|
||||
t.Setenv("PIPELINES_CHAT_ATTACHMENT_DIR", dir)
|
||||
path := filepath.Join(t.TempDir(), "queue.db")
|
||||
store := openQueueStore(t, path)
|
||||
queuedPromptWithFile(t, store, "op-1", "outside", filepath.Join(t.TempDir(), "elsewhere.txt"))
|
||||
if _, _, err := store.EnqueueChatPrompt(context.Background(), pipeline.ChatQueuedPrompt{SessionID: "ses_1", OperationID: "op-2", MessageID: "msg_op-2", Text: "plain"}, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
broker := newChannelChat()
|
||||
startQueueServer(t, broker, store)
|
||||
waitFor(t, "valid prompt delivered", func() bool { return slices.Equal(broker.promptTexts(), []string{"plain"}) })
|
||||
waitFor(t, "rows cleared", func() bool { return len(queuedOps(t, store)) == 0 })
|
||||
}
|
||||
@@ -23,9 +23,11 @@ import (
|
||||
// is not an idle lease: it remains attached until actual completion or explicit
|
||||
// stop. Its durable journal is independent of bounded replay/room retention.
|
||||
|
||||
// chatUnattendedLimit bounds the rooms kept observing with no client attached
|
||||
// and no queued prompt.
|
||||
const chatUnattendedLimit = 16
|
||||
// chatUnattendedLimit bounds the rooms kept observing with no client attached,
|
||||
// no queued prompt and no live work of this server's own (see liveWorkLocked):
|
||||
// a turn this server started, a pending approval or question, or background
|
||||
// tasks always keep notifying, however many chats are unattended.
|
||||
const chatUnattendedLimit = 64
|
||||
|
||||
// chatRecoverSessionLimit bounds how many recently used open sessions are
|
||||
// probed for a running turn at server start.
|
||||
@@ -84,6 +86,15 @@ func (h *chatHub) keepUnattendedLocked(room *chatRoom, busy, hold bool) bool {
|
||||
return hold && h.clock().Before(room.holdUntil)
|
||||
}
|
||||
|
||||
// liveWorkLocked reports whether a room holds work this server knows is real
|
||||
// and will notify: its own turn in flight, an unanswered approval or question,
|
||||
// or running background tasks. Such a room is never refused by the idle cap,
|
||||
// which only bounds observers kept on weaker evidence (a stream-announced or
|
||||
// harness-reported turn, the start-up settle window). Callers hold h.mu.
|
||||
func (h *chatHub) liveWorkLocked(room *chatRoom) bool {
|
||||
return room.running || len(room.pending) > 0 || len(room.forms) > 0 || h.backgroundTasksLocked(room.sessionID) > 0
|
||||
}
|
||||
|
||||
// unattendedCountLocked counts the rooms kept observing with no client and no
|
||||
// queued prompt, other than except. Callers hold h.mu.
|
||||
func (h *chatHub) unattendedCountLocked(except *chatRoom) int {
|
||||
@@ -109,7 +120,7 @@ func (h *chatHub) leaveUnattendedLocked(room *chatRoom) {
|
||||
h.releaseRoomLocked(room)
|
||||
return
|
||||
}
|
||||
if !room.watching && h.backgroundTasksLocked(room.sessionID) == 0 && h.unattendedCountLocked(room) >= chatUnattendedLimit {
|
||||
if !room.watching && !h.liveWorkLocked(room) && h.unattendedCountLocked(room) >= chatUnattendedLimit {
|
||||
log.Printf("chat session %s: %d chats already observed with no client; not keeping this one", room.sessionID, chatUnattendedLimit)
|
||||
h.releaseRoomLocked(room)
|
||||
return
|
||||
|
||||
@@ -2,6 +2,7 @@ package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
@@ -320,7 +321,42 @@ func TestChatStuckUnattendedTurnIsReleased(t *testing.T) {
|
||||
waitFor(t, "stuck observer released", func() bool { active, _ := broker.streams(); return active == 0 })
|
||||
}
|
||||
|
||||
// At most chatUnattendedLimit chats are kept observing with no client.
|
||||
// A turn this server started keeps notifying however many chats are already
|
||||
// observed unattended: the idle cap never drops live work.
|
||||
func TestChatUnattendedRunningTurnsIgnoreTheCap(t *testing.T) {
|
||||
fastUnattended(t)
|
||||
h := newChatHub()
|
||||
defer func() {
|
||||
h.mu.Lock()
|
||||
for _, room := range h.rooms {
|
||||
room.cancel()
|
||||
}
|
||||
h.mu.Unlock()
|
||||
}()
|
||||
count := chatUnattendedLimit + 3
|
||||
kept := 0
|
||||
for i := 0; i < count; i++ {
|
||||
id := fmt.Sprintf("ses_run_%03d", i)
|
||||
h.mu.Lock()
|
||||
room := h.roomLocked(id)
|
||||
room.running = true
|
||||
sub := &chatSub{hub: h, room: room, clientID: "c", limit: 1, done: make(chan struct{})}
|
||||
room.subs["c"] = sub
|
||||
h.mu.Unlock()
|
||||
h.detach(id, sub)
|
||||
h.mu.Lock()
|
||||
if h.rooms[id] == room {
|
||||
kept++
|
||||
}
|
||||
h.mu.Unlock()
|
||||
}
|
||||
if kept != count {
|
||||
t.Fatalf("kept %d unattended running rooms, want all %d", kept, count)
|
||||
}
|
||||
}
|
||||
|
||||
// At most chatUnattendedLimit chats are kept observing with no client on
|
||||
// weaker evidence than live work (a stream-announced turn).
|
||||
func TestChatUnattendedRoomsAreBounded(t *testing.T) {
|
||||
fastUnattended(t)
|
||||
h := newChatHub()
|
||||
@@ -333,10 +369,10 @@ func TestChatUnattendedRoomsAreBounded(t *testing.T) {
|
||||
}()
|
||||
kept := 0
|
||||
for i := 0; i < chatUnattendedLimit+3; i++ {
|
||||
id := "ses_" + string(rune('a'+i))
|
||||
id := fmt.Sprintf("ses_obs_%03d", i)
|
||||
h.mu.Lock()
|
||||
room := h.roomLocked(id)
|
||||
room.running = true
|
||||
room.observedTurn = true
|
||||
sub := &chatSub{hub: h, room: room, clientID: "c", limit: 1, done: make(chan struct{})}
|
||||
room.subs["c"] = sub
|
||||
h.mu.Unlock()
|
||||
|
||||
@@ -120,6 +120,7 @@ func TestLegacyScheduleBindsExecutionDefaultNotOfflineOpenDirectory(t *testing.T
|
||||
if err = r.scheduleTick(due, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.scheduleAdmissions.Wait()
|
||||
r.wg.Wait()
|
||||
runs, err := store.ListRuns(ctx)
|
||||
if err != nil || len(runs) != 1 || runs[0].Workspace != resolvedB || !runs[0].Scheduled || runs[0].ScheduleID != original.ID {
|
||||
|
||||
@@ -172,9 +172,10 @@ func (r *runner) reattachRun(plan reattachPlan) {
|
||||
log.Printf("run %d: restart stage %s after server restart: %v", id, plan.step.Stage, err)
|
||||
}
|
||||
}
|
||||
detail, err := r.store.GetRun(ctx, id)
|
||||
detail, err := r.readForReattach(ctx, id)
|
||||
if err != nil {
|
||||
log.Printf("run %d: read for reattach: %v", id, err)
|
||||
log.Printf("run %d: read for reattach: %v; marking it interrupted", id, err)
|
||||
r.abandonReattach(plan, err)
|
||||
return
|
||||
}
|
||||
r.rememberRunIdentity(id, identityOfRunSummary(detail.RunSummary))
|
||||
@@ -199,6 +200,63 @@ func (r *runner) reattachRun(plan reattachPlan) {
|
||||
}
|
||||
}
|
||||
|
||||
// reattachReadBackoff bounds the retries of a reattach read; reattach runs
|
||||
// before requests are served, so it stays short.
|
||||
var reattachReadBackoff = []time.Duration{100 * time.Millisecond, 500 * time.Millisecond, 2 * time.Second}
|
||||
|
||||
// readForReattach reads a kept run, retrying a transient failure.
|
||||
func (r *runner) readForReattach(ctx context.Context, id int64) (*protocol.RunDetail, error) {
|
||||
for attempt := 0; ; attempt++ {
|
||||
detail, err := runSettleRead(r, ctx, id)
|
||||
if err == nil && detail != nil {
|
||||
return detail, nil
|
||||
}
|
||||
if err == nil {
|
||||
err = fmt.Errorf("run %d not found", id)
|
||||
}
|
||||
if attempt >= len(reattachReadBackoff) || ctx.Err() != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !r.sleepSettle(reattachReadBackoff[attempt]) {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// abandonReattach settles a kept run that cannot be continued, instead of
|
||||
// leaving it "running" with nothing executing it: an adopted session is
|
||||
// stopped first, then the run is marked interrupted. If the session cannot be
|
||||
// stopped, the run keeps its workspace reserved as cleanup-unconfirmed, as
|
||||
// start-up recovery does.
|
||||
func (r *runner) abandonReattach(plan reattachPlan, cause error) {
|
||||
id := plan.runID
|
||||
if plan.kind == reattachAdopt {
|
||||
stop, cancel := context.WithTimeout(r.ctx, 20*time.Second)
|
||||
err := interruptRecoveredSession(stop, plan.owner)
|
||||
if err == nil {
|
||||
err = r.store.ConfirmRecoveredSession(stop, plan.owner)
|
||||
}
|
||||
cancel()
|
||||
if err != nil {
|
||||
log.Printf("run %d: stop session %s after a failed reattach: %v; workspace stays reserved", id, plan.owner.ID, err)
|
||||
mark, done := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
if markErr := r.store.MarkCleanupUnconfirmed(mark, id); markErr != nil {
|
||||
log.Printf("run %d: mark cleanup unconfirmed: %v", id, markErr)
|
||||
}
|
||||
done()
|
||||
r.mu.Lock()
|
||||
if _, ok := r.active[id]; !ok {
|
||||
r.active[id] = activeRun{cancel: func() {}, workspace: plan.owner.Directory}
|
||||
}
|
||||
r.mu.Unlock()
|
||||
return
|
||||
}
|
||||
}
|
||||
r.finishRunWithRetry(id, "interrupted", "", "Server restarted; the run could not be reattached: "+cause.Error(), stage.Values{})
|
||||
r.forgetAttention(id)
|
||||
r.forgetNotifyMode(id)
|
||||
}
|
||||
|
||||
// rebuildAdoptState restores the loop state at the planned visit: memory and
|
||||
// visit counts from every other persisted step, the handoff input from the
|
||||
// visit before it, and (for an adopted visit) the session to re-adopt.
|
||||
|
||||
+208
-68
@@ -41,7 +41,10 @@ type runner struct {
|
||||
artifactsRoot string
|
||||
mu sync.Mutex
|
||||
active map[int64]activeRun
|
||||
execute func(context.Context, stage.Definition, stage.Values) (stage.Result, error)
|
||||
// admitting counts admissions creating a run worktree from each source
|
||||
// workspace outside r.mu; storage maintenance keeps those trees.
|
||||
admitting map[string]int
|
||||
execute func(context.Context, stage.Definition, stage.Values) (stage.Result, error)
|
||||
// dirEnv resolves the run workspace's own environment (direnv/mise) at
|
||||
// run start; nil uses workenv.Default.
|
||||
dirEnv *workenv.Resolver
|
||||
@@ -78,6 +81,9 @@ type runner struct {
|
||||
verifyTarget stage.VerificationRunner
|
||||
wg sync.WaitGroup
|
||||
schedulerWG sync.WaitGroup
|
||||
// scheduleAdmissions tracks schedule-claimed runs still being admitted
|
||||
// (scheduler.go); the scheduler loop waits for them before it exits.
|
||||
scheduleAdmissions sync.WaitGroup
|
||||
// attentionMu guards attentionSent, the per-run set of run-attention events
|
||||
// already delivered — by a stage's own notify policy or by the run-level
|
||||
// default — so neither republishes the same genuine event.
|
||||
@@ -183,7 +189,7 @@ func newRunnerReattaching(ctx context.Context, s *pipeline.Store, artifactsRoot
|
||||
active[row.ID] = activeRun{cancel: func() {}, workspace: row.Workspace}
|
||||
}
|
||||
}
|
||||
r := &runner{ctx: ctx, store: s, artifactsRoot: root, active: active, idents: map[int64]runIdentity{}, attentionSent: map[int64]map[string]bool{}, notifyModes: map[int64]string{}, exportSession: stage.ExportSession, detach: detach, reattach: plans}
|
||||
r := &runner{ctx: ctx, store: s, artifactsRoot: root, active: active, admitting: map[string]int{}, idents: map[int64]runIdentity{}, attentionSent: map[int64]map[string]bool{}, notifyModes: map[int64]string{}, exportSession: stage.ExportSession, detach: detach, reattach: plans}
|
||||
if err := r.startSessionExportJobs(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -334,38 +340,57 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
// Another run may have reserved this workspace while the title was
|
||||
// generated, so re-check before reserving it; a race on the request key is
|
||||
// handled by the store's idempotent insert.
|
||||
if existing == 0 {
|
||||
if err := r.checkWorkspaceFree(workspace); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
// Storage maintenance may have removed a clean inactive tree while an
|
||||
// admission was generating its title. Refuse that vanished workspace under
|
||||
// the same lock used by removal instead of launching into a missing tree.
|
||||
if info, err := os.Stat(workspace); err != nil || !info.IsDir() {
|
||||
return nil, fmt.Errorf("run workspace is no longer available: %s", workspace)
|
||||
if err := r.checkAdmissionWorkspace(workspace, existing); err != nil {
|
||||
r.mu.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
// A fresh run started from a repository's main checkout gets its own
|
||||
// worktree and branch, so runs never share a tree with each other or with
|
||||
// the operator's uncommitted work. A retry keeps its run's tree.
|
||||
// the operator's uncommitted work. A retry keeps its run's tree. Creating
|
||||
// the worktree can take up to a minute, so it runs without r.mu (listings,
|
||||
// details and cancellation must not stall behind it); storage maintenance
|
||||
// keeps the source tree meanwhile (r.admitting), and the reservation is
|
||||
// re-checked under the lock before the run is recorded.
|
||||
isolated := ""
|
||||
if existing == 0 && request.RetrySource == 0 {
|
||||
source := workspace
|
||||
if r.admitting == nil {
|
||||
r.admitting = map[string]int{}
|
||||
}
|
||||
r.admitting[source]++
|
||||
r.mu.Unlock()
|
||||
isolateCtx, isolateCancel := context.WithTimeout(r.ctx, time.Minute)
|
||||
tree, isolateErr := isolateRunWorkspace(isolateCtx, workspace, runTitle.Text)
|
||||
tree, isolateErr := isolateRunWorkspace(isolateCtx, source, runTitle.Text)
|
||||
isolateCancel()
|
||||
r.mu.Lock()
|
||||
if r.admitting[source]--; r.admitting[source] <= 0 {
|
||||
delete(r.admitting, source)
|
||||
}
|
||||
if isolateErr != nil {
|
||||
r.mu.Unlock()
|
||||
return nil, isolateErr
|
||||
}
|
||||
if tree != workspace {
|
||||
if tree != source {
|
||||
isolated = tree
|
||||
}
|
||||
workspace = tree
|
||||
request.Input["pwd"] = workspace
|
||||
recheck := r.ctx.Err()
|
||||
if recheck == nil {
|
||||
recheck = r.checkAdmissionWorkspace(workspace, existing)
|
||||
}
|
||||
if recheck != nil {
|
||||
r.mu.Unlock()
|
||||
if isolated != "" {
|
||||
discardRunWorktree(isolated)
|
||||
}
|
||||
return nil, recheck
|
||||
}
|
||||
}
|
||||
defer r.mu.Unlock()
|
||||
id, created, err := r.store.CreateRunTitled(r.ctx, d, request.RequestKey, workspace, request.AllowTools, request.WritePaths, request.Input, pipeline.RunOverrides{Schedule: origin, Model: request.Model, StageModels: request.StageModels, NotifyMode: request.NotifyMode, OutputFormat: request.OutputFormat, StageSkills: stageSkills}, runTitle, retryOf...)
|
||||
if isolated != "" && (err != nil || !created) {
|
||||
// The run was refused or an identical request won the race: the fresh
|
||||
@@ -436,42 +461,100 @@ func (r *runner) launch(id int64, workspace string, fn func(context.Context)) {
|
||||
go func() {
|
||||
defer r.wg.Done()
|
||||
defer cancel()
|
||||
defer func() {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if entry, ok := r.active[id]; !ok || entry.generation != generation {
|
||||
return // A parked launch must not remove the resumed reservation.
|
||||
}
|
||||
check, done := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer done()
|
||||
detail, err := r.store.GetRun(check, id)
|
||||
if err != nil || detail.CleanupUnconfirmed {
|
||||
return // Fail closed: execution/cleanup has not settled durably.
|
||||
}
|
||||
if detail.Status == protocol.RunStatusWaiting && detail.CancelRequested {
|
||||
if err := r.store.CancelWaiting(check, id); err != nil {
|
||||
return
|
||||
}
|
||||
r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: detail.Workspace, Status: protocol.RunStatusCanceled, CancelRequested: true, CurrentStage: detail.CurrentStage, FinishedAt: time.Now().UTC().Format(time.RFC3339)}, true)
|
||||
}
|
||||
if detail.FinishedAt != "" || detail.Status == protocol.RunStatusWaiting {
|
||||
delete(r.active, id)
|
||||
}
|
||||
// A landed (or change-free) successful run's own worktree is no
|
||||
// longer needed; anything unlanded or uncommitted is kept.
|
||||
if detail.Status == "succeeded" && detail.FinishedAt != "" {
|
||||
workspace := detail.Workspace
|
||||
go func() {
|
||||
if removeLandedRunWorktree(workspace) {
|
||||
log.Printf("run %d: removed its landed worktree %s", id, workspace)
|
||||
}
|
||||
}()
|
||||
}
|
||||
}()
|
||||
defer r.settleLaunch(id, generation)
|
||||
fn(ctx)
|
||||
}()
|
||||
}
|
||||
|
||||
// settleLaunch releases a finished launch's reservation once its run has
|
||||
// settled durably. A failed read is retried with backoff (the lock is not held
|
||||
// while waiting); a run whose cleanup is unconfirmed, or that cannot be read
|
||||
// even after the retries, keeps its reservation (fail closed).
|
||||
func (r *runner) settleLaunch(id int64, generation *byte) {
|
||||
for attempt := 0; ; attempt++ {
|
||||
settled, err := r.settleLaunchOnce(id, generation)
|
||||
if settled {
|
||||
return
|
||||
}
|
||||
if attempt >= len(runSettleBackoff) {
|
||||
log.Printf("run %d: launch teardown could not read the run; its workspace stays reserved: %v", id, err)
|
||||
return
|
||||
}
|
||||
if !r.sleepSettle(runSettleBackoff[attempt]) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// settleLaunchOnce is one teardown attempt under r.mu. It reports false only
|
||||
// when the run could not be read.
|
||||
func (r *runner) settleLaunchOnce(id int64, generation *byte) (bool, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if entry, ok := r.active[id]; !ok || entry.generation != generation {
|
||||
return true, nil // A parked launch must not remove the resumed reservation.
|
||||
}
|
||||
check, done := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer done()
|
||||
detail, err := runSettleRead(r, check, id)
|
||||
if err != nil || detail == nil {
|
||||
return false, err
|
||||
}
|
||||
if detail.CleanupUnconfirmed {
|
||||
return true, nil // Fail closed: execution/cleanup has not settled durably.
|
||||
}
|
||||
if detail.Status == protocol.RunStatusWaiting && detail.CancelRequested {
|
||||
if err := r.store.CancelWaiting(check, id); err != nil {
|
||||
// A refused transition fails closed; anything else is retried.
|
||||
return errors.Is(err, pipeline.ErrInvalidRunTransition), err
|
||||
}
|
||||
r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: detail.Workspace, Status: protocol.RunStatusCanceled, CancelRequested: true, CurrentStage: detail.CurrentStage, FinishedAt: time.Now().UTC().Format(time.RFC3339)}, true)
|
||||
}
|
||||
if detail.FinishedAt != "" || detail.Status == protocol.RunStatusWaiting {
|
||||
delete(r.active, id)
|
||||
}
|
||||
// A landed (or change-free) successful run's own worktree is no longer
|
||||
// needed; anything unlanded or uncommitted is kept.
|
||||
if detail.Status == "succeeded" && detail.FinishedAt != "" {
|
||||
workspace := detail.Workspace
|
||||
go func() {
|
||||
if removeLandedRunWorktree(workspace) {
|
||||
log.Printf("run %d: removed its landed worktree %s", id, workspace)
|
||||
}
|
||||
}()
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// runFinishWrite persists a run's terminal state; tests replace it to inject
|
||||
// transient store failures.
|
||||
var runFinishWrite = func(r *runner, ctx context.Context, id int64, status, outcome, diagnostic string, input stage.Values) error {
|
||||
return r.store.FinishRun(ctx, id, status, outcome, diagnostic, input)
|
||||
}
|
||||
|
||||
// runSettleRead reads a run for settlement; tests replace it to inject
|
||||
// transient store failures.
|
||||
var runSettleRead = func(r *runner, ctx context.Context, id int64) (*protocol.RunDetail, error) {
|
||||
return r.store.GetRun(ctx, id)
|
||||
}
|
||||
|
||||
// checkAdmissionWorkspace refuses admitting a fresh run (existing == 0) into a
|
||||
// workspace another run reserves, and any admission into a vanished workspace:
|
||||
// storage maintenance may have removed a clean inactive tree while an
|
||||
// admission was generating its title, so it is checked under the same lock
|
||||
// removal takes. Callers must hold r.mu.
|
||||
func (r *runner) checkAdmissionWorkspace(workspace string, existing int64) error {
|
||||
if existing == 0 {
|
||||
if err := r.checkWorkspaceFree(workspace); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if info, err := os.Stat(workspace); err != nil || !info.IsDir() {
|
||||
return fmt.Errorf("run workspace is no longer available: %s", workspace)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkWorkspaceFree refuses a run when an active or cleanup-unconfirmed run
|
||||
// reserves an overlapping resolved workspace. Callers must hold r.mu.
|
||||
func (r *runner) checkWorkspaceFree(workspace string) error {
|
||||
@@ -535,12 +618,15 @@ func repositoryRoot(dir string) string {
|
||||
}
|
||||
}
|
||||
|
||||
// getRun reads one run's detail. The store read runs without r.mu, so a
|
||||
// detail never waits behind admission or settlement work; only the executing
|
||||
// overlay reads the active set under the lock.
|
||||
func (r *runner) getRun(id int64) (*protocol.RunDetail, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
d, err := r.store.GetRun(r.ctx, id)
|
||||
if d != nil {
|
||||
r.mu.Lock()
|
||||
_, d.Executing = r.active[id]
|
||||
r.mu.Unlock()
|
||||
if d.ExportPendingSequence > 0 {
|
||||
d.Executing = false
|
||||
}
|
||||
@@ -584,28 +670,38 @@ func (r *runner) overlayEffectiveModels(d *protocol.RunDetail) {
|
||||
}
|
||||
}
|
||||
|
||||
// listRuns lists every run with its executing overlay. The store reads run
|
||||
// without r.mu (a listing never waits behind admission or settlement), and a
|
||||
// failed run whose cleanup agent is still active is found with one query
|
||||
// rather than a detail read per failed run.
|
||||
func (r *runner) listRuns() ([]protocol.RunSummary, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
items, err := r.store.ListRuns(r.ctx)
|
||||
if err != nil {
|
||||
return items, err
|
||||
}
|
||||
var agents map[int64]bool
|
||||
for _, item := range items {
|
||||
if item.Status == "failed" {
|
||||
if agents, err = r.store.RunsWithActiveAgents(r.ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
r.mu.Lock()
|
||||
for i := range items {
|
||||
_, items[i].Executing = r.active[items[i].ID]
|
||||
}
|
||||
r.mu.Unlock()
|
||||
for i := range items {
|
||||
if items[i].ExportPendingSequence > 0 {
|
||||
items[i].Executing = false
|
||||
}
|
||||
if items[i].Status == "failed" && !items[i].Executing {
|
||||
d, err := r.store.GetRun(r.ctx, items[i].ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, step := range d.Steps {
|
||||
if step.AgentActive {
|
||||
items[i].Executing = true
|
||||
}
|
||||
}
|
||||
if items[i].Status == "failed" && !items[i].Executing && agents[items[i].ID] {
|
||||
items[i].Executing = true
|
||||
}
|
||||
}
|
||||
return items, err
|
||||
return items, nil
|
||||
}
|
||||
|
||||
type retryCheckpoint struct {
|
||||
@@ -1593,23 +1689,26 @@ func (r *runner) emitRun(frame protocol.RunEventFrame, terminal bool) {
|
||||
}
|
||||
|
||||
func (r *runner) finishRunState(id int64, name, workspace, status, outcome, diagnostic string, completed, sequence int, currentStage string, input stage.Values) {
|
||||
r.mu.Lock()
|
||||
// The deliverable and the size walk touch files only: they run without r.mu,
|
||||
// so listings and details do not stall behind a large run finishing. The
|
||||
// run stays in r.active (its workspace reserved) until the launch teardown.
|
||||
c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if status == "succeeded" {
|
||||
if err := r.finalizeDeliverable(c, id, sequence, input); err != nil {
|
||||
status, outcome, diagnostic = "failed", "error", "deliverable contract: "+err.Error()
|
||||
}
|
||||
}
|
||||
cancel()
|
||||
// Measure the run's footprint while it is still recorded as active: its
|
||||
// files are final, and measuring after the terminal status is written would
|
||||
// widen the window in which a client sees the run finished but still owned.
|
||||
// The status write re-marks the cache stale, so the background sizer then
|
||||
// records the exact value including the final output row.
|
||||
size := r.finishedSize(id)
|
||||
if err := r.store.FinishRun(c, id, status, outcome, diagnostic, input); err != nil {
|
||||
log.Printf("finish run %d: %v", id, err)
|
||||
}
|
||||
r.finishRunWithRetry(id, status, outcome, diagnostic, input)
|
||||
r.mu.Lock()
|
||||
c, cancel = context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
// The store atomically makes a stop request win over a late success.
|
||||
detail, getErr := r.store.GetRun(c, id)
|
||||
if getErr != nil || detail == nil {
|
||||
@@ -1645,6 +1744,47 @@ func (r *runner) finishRunState(id int64, name, workspace, status, outcome, diag
|
||||
r.forgetNotifyMode(id)
|
||||
}
|
||||
|
||||
// runSettleBackoff is the retry schedule for durable run settlement writes
|
||||
// (finishing a run, reading it back at launch teardown). A transient store
|
||||
// failure (a busy or briefly unavailable database) must not leave a run
|
||||
// "running" with its workspace reserved until restart.
|
||||
var runSettleBackoff = []time.Duration{250 * time.Millisecond, 500 * time.Millisecond, time.Second, 2 * time.Second, 4 * time.Second, 8 * time.Second, 15 * time.Second}
|
||||
|
||||
// sleepSettle waits out one backoff step; false when the server is stopping.
|
||||
func (r *runner) sleepSettle(delay time.Duration) bool {
|
||||
select {
|
||||
case <-r.ctx.Done():
|
||||
return false
|
||||
case <-time.After(delay):
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// finishRunWithRetry persists a run's terminal state, retrying a transient
|
||||
// failure with backoff (each attempt under r.mu, the waits without it). A
|
||||
// refused transition (an agent still active, cleanup unconfirmed, a run
|
||||
// already settled) is final and not retried.
|
||||
func (r *runner) finishRunWithRetry(id int64, status, outcome, diagnostic string, input stage.Values) {
|
||||
for attempt := 0; ; attempt++ {
|
||||
r.mu.Lock()
|
||||
c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
err := runFinishWrite(r, c, id, status, outcome, diagnostic, input)
|
||||
cancel()
|
||||
r.mu.Unlock()
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
if errors.Is(err, pipeline.ErrInvalidRunTransition) || attempt >= len(runSettleBackoff) {
|
||||
log.Printf("finish run %d: %v", id, err)
|
||||
return
|
||||
}
|
||||
log.Printf("finish run %d (attempt %d, retrying): %v", id, attempt+1, err)
|
||||
if !r.sleepSettle(runSettleBackoff[attempt]) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// completedSteps counts the completed steps of a run detail; resume uses it to
|
||||
// seed the terminal delta without another store read.
|
||||
func completedSteps(steps []protocol.RunStep) int {
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
)
|
||||
|
||||
func fastRunSettle(t *testing.T) {
|
||||
t.Helper()
|
||||
settle, reattach := runSettleBackoff, reattachReadBackoff
|
||||
runSettleBackoff = []time.Duration{time.Millisecond, time.Millisecond, time.Millisecond}
|
||||
reattachReadBackoff = []time.Duration{time.Millisecond, time.Millisecond}
|
||||
t.Cleanup(func() { runSettleBackoff, reattachReadBackoff = settle, reattach })
|
||||
}
|
||||
|
||||
func reliabilityRunner(t *testing.T) (context.Context, *pipeline.Store, *runner, int64) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
s, err := pipeline.Open(filepath.Join(t.TempDir(), "reliability.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Submit(ctx, "workflow", pipeline.Template([]string{"one"}, true)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, _ := s.List(ctx)
|
||||
r, err := newRunner(ctx, s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "# Done"}}, nil
|
||||
}
|
||||
t.Cleanup(func() { cancel(); r.wg.Wait(); r.schedulerWG.Wait(); s.Close() })
|
||||
return ctx, s, r, items[0].ID
|
||||
}
|
||||
|
||||
// A transient failure persisting a run's end is retried: the run settles and
|
||||
// its workspace is released instead of staying "running" and reserved.
|
||||
func TestFinishRunTransientFailureIsRetried(t *testing.T) {
|
||||
fastRunSettle(t)
|
||||
ctx, s, r, pid := reliabilityRunner(t)
|
||||
var attempts atomic.Int32
|
||||
original := runFinishWrite
|
||||
runFinishWrite = func(r *runner, ctx context.Context, id int64, status, outcome, diagnostic string, input stage.Values) error {
|
||||
if attempts.Add(1) <= 2 {
|
||||
return errors.New("database is locked")
|
||||
}
|
||||
return original(r, ctx, id, status, outcome, diagnostic, input)
|
||||
}
|
||||
t.Cleanup(func() { runFinishWrite = original })
|
||||
workspace := t.TempDir()
|
||||
d, err := r.start(protocol.Message{PipelineID: pid, Version: 1, RequestKey: "transient", Workspace: workspace, Input: map[string]any{"prompt": "task"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
detail, err := s.GetRun(ctx, d.ID)
|
||||
if err != nil || detail.Status != "succeeded" || detail.FinishedAt == "" {
|
||||
t.Fatalf("run not settled after a transient failure: %+v %v", detail, err)
|
||||
}
|
||||
if attempts.Load() != 3 {
|
||||
t.Fatalf("finish attempts = %d, want 3", attempts.Load())
|
||||
}
|
||||
r.mu.Lock()
|
||||
_, reserved := r.active[d.ID]
|
||||
r.mu.Unlock()
|
||||
if reserved {
|
||||
t.Fatal("settled run still reserves its workspace")
|
||||
}
|
||||
}
|
||||
|
||||
// A refused transition is final: it is not retried.
|
||||
func TestFinishRunRefusedTransitionIsNotRetried(t *testing.T) {
|
||||
fastRunSettle(t)
|
||||
_, _, r, pid := reliabilityRunner(t)
|
||||
var attempts atomic.Int32
|
||||
original := runFinishWrite
|
||||
runFinishWrite = func(*runner, context.Context, int64, string, string, string, stage.Values) error {
|
||||
attempts.Add(1)
|
||||
return pipeline.ErrInvalidRunTransition
|
||||
}
|
||||
t.Cleanup(func() { runFinishWrite = original })
|
||||
if _, err := r.start(protocol.Message{PipelineID: pid, Version: 1, RequestKey: "refused", Workspace: t.TempDir(), Input: map[string]any{"prompt": "task"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
if attempts.Load() != 1 {
|
||||
t.Fatalf("refused transition attempted %d times", attempts.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// The launch teardown retries a failed read instead of keeping the
|
||||
// reservation forever.
|
||||
func TestLaunchTeardownRetriesAFailedRead(t *testing.T) {
|
||||
fastRunSettle(t)
|
||||
_, _, r, pid := reliabilityRunner(t)
|
||||
var reads atomic.Int32
|
||||
original := runSettleRead
|
||||
runSettleRead = func(r *runner, ctx context.Context, id int64) (*protocol.RunDetail, error) {
|
||||
if reads.Add(1) <= 2 {
|
||||
return nil, errors.New("database is locked")
|
||||
}
|
||||
return original(r, ctx, id)
|
||||
}
|
||||
t.Cleanup(func() { runSettleRead = original })
|
||||
d, err := r.start(protocol.Message{PipelineID: pid, Version: 1, RequestKey: "teardown", Workspace: t.TempDir(), Input: map[string]any{"prompt": "task"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
r.mu.Lock()
|
||||
_, reserved := r.active[d.ID]
|
||||
r.mu.Unlock()
|
||||
if reserved || reads.Load() < 3 {
|
||||
t.Fatalf("reservation kept after a transient teardown read failure (reads=%d)", reads.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// A run kept for reattachment that cannot be read is not left "running":
|
||||
// its adopted session is stopped and the run is marked interrupted.
|
||||
func TestReattachReadFailureMarksTheRunInterrupted(t *testing.T) {
|
||||
fastRunSettle(t)
|
||||
interrupts := seamRestartRecovery(t, nil)
|
||||
f := stopMidStage(t, ownedLiveStage)
|
||||
r, s := f.restart(t, func(context.Context, *pipeline.Store, stage.Definition) (stage.Result, error) {
|
||||
t.Error("an unreadable run executed")
|
||||
return stage.Result{}, nil
|
||||
})
|
||||
original := runSettleRead
|
||||
runSettleRead = func(*runner, context.Context, int64) (*protocol.RunDetail, error) {
|
||||
return nil, errors.New("database is unavailable")
|
||||
}
|
||||
t.Cleanup(func() { runSettleRead = original })
|
||||
r.reattachRuns()
|
||||
r.wg.Wait()
|
||||
runSettleRead = original
|
||||
d, err := s.GetRun(context.Background(), f.runID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if d.Status != "interrupted" || !strings.Contains(d.Diagnostic, "could not be reattached") {
|
||||
t.Fatalf("unreadable reattached run left as %s: %q", d.Status, d.Diagnostic)
|
||||
}
|
||||
if interrupts.Load() != 1 {
|
||||
t.Fatalf("adopted session interrupted %d times, want 1", interrupts.Load())
|
||||
}
|
||||
if owners, _ := s.ActiveSessionOwners(context.Background()); len(owners) != 0 {
|
||||
t.Fatalf("session still recorded active: %+v", owners)
|
||||
}
|
||||
}
|
||||
|
||||
// A failed run whose cleanup agent is still active is listed as executing,
|
||||
// found with one query rather than a detail read per failed run.
|
||||
func TestListRunsMarksFailedRunsWithActiveAgentsExecuting(t *testing.T) {
|
||||
ctx, s, r, pid := reliabilityRunner(t)
|
||||
d, _ := s.Get(ctx, pid, 1)
|
||||
var ids []int64
|
||||
for _, key := range []string{"a", "b"} {
|
||||
id, _, err := s.CreateRun(ctx, d, key, t.TempDir(), false, nil, map[string]any{"prompt": "task"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.BeginStep(ctx, id, 1, "one", map[string]any{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.FinishRun(ctx, id, "failed", "error", "boom", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
db, err := sql.Open("sqlite", s.DatabasePath())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
if _, err := db.ExecContext(ctx, `UPDATE run_steps SET agent_active=1 WHERE run_id=?`, ids[0]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runs, err := r.listRuns()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
executing := map[int64]bool{}
|
||||
for _, run := range runs {
|
||||
executing[run.ID] = run.Executing
|
||||
}
|
||||
if !executing[ids[0]] || executing[ids[1]] {
|
||||
t.Fatalf("executing = %v", executing)
|
||||
}
|
||||
}
|
||||
|
||||
// Creating a run's worktree (a git hook can make it arbitrarily slow) no
|
||||
// longer holds the runner lock: listings, details and another admission in a
|
||||
// different workspace proceed meanwhile.
|
||||
func TestRunWorktreeCreationDoesNotBlockListings(t *testing.T) {
|
||||
if _, err := exec.LookPath("git"); err != nil {
|
||||
t.Skip("git not installed")
|
||||
}
|
||||
_, _, r, pid := reliabilityRunner(t)
|
||||
repo := filepath.Join(t.TempDir(), "repo")
|
||||
git := func(args ...string) {
|
||||
t.Helper()
|
||||
cmd := exec.Command("git", append([]string{"-C", repo, "-c", "user.name=t", "-c", "user.email=t@example.invalid", "-c", "commit.gpgsign=false"}, args...)...)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("git %v: %v: %s", args, err, out)
|
||||
}
|
||||
}
|
||||
if err := os.MkdirAll(repo, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
git("init", "-q")
|
||||
git("commit", "-q", "--allow-empty", "-m", "root")
|
||||
started, release := filepath.Join(t.TempDir(), "started"), filepath.Join(t.TempDir(), "release")
|
||||
hook := "#!/bin/sh\ntouch '" + started + "'\nfor i in $(seq 1 200); do [ -e '" + release + "' ] && exit 0; sleep 0.05; done\n"
|
||||
if err := os.WriteFile(filepath.Join(repo, ".git", "hooks", "post-checkout"), []byte(hook), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
admitted := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := r.start(protocol.Message{PipelineID: pid, Version: 1, RequestKey: "slow-tree", Title: "slow tree", Workspace: repo, Input: map[string]any{"prompt": "task"}})
|
||||
admitted <- err
|
||||
}()
|
||||
waitFor(t, "worktree hook running", func() bool { _, err := os.Stat(started); return err == nil })
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
if _, err := r.listRuns(); err != nil {
|
||||
done <- err
|
||||
return
|
||||
}
|
||||
_, err := r.start(protocol.Message{PipelineID: pid, Version: 1, RequestKey: "elsewhere", Title: "elsewhere", Workspace: t.TempDir(), Input: map[string]any{"prompt": "task"}})
|
||||
done <- err
|
||||
}()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("listing or another admission blocked behind worktree creation")
|
||||
}
|
||||
if err := os.WriteFile(release, nil, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := <-admitted; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
runs, err := r.listRuns()
|
||||
if err != nil || len(runs) != 2 {
|
||||
t.Fatalf("runs = %+v %v", runs, err)
|
||||
}
|
||||
for _, run := range runs {
|
||||
if run.Workspace == repo {
|
||||
t.Fatalf("run used the main checkout instead of its own worktree: %+v", run)
|
||||
}
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
// Remove the run worktree sibling the admission created.
|
||||
os.RemoveAll(repo + runWorktreesDirSuffix)
|
||||
})
|
||||
}
|
||||
@@ -73,6 +73,7 @@ func TestScheduledRunPreservesWriteScopeAndWorkflowPermissions(t *testing.T) {
|
||||
if err = r.scheduleTick(dueOf(t, entry), false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.scheduleAdmissions.Wait()
|
||||
r.wg.Wait()
|
||||
runs, err := s.ListRuns(ctx)
|
||||
if err != nil || len(runs) != 1 || runs[0].Status != "succeeded" || calls != 1 {
|
||||
@@ -111,6 +112,7 @@ func TestScheduleRechecksWriteScopeBeforeTitleOrExecution(t *testing.T) {
|
||||
if err = r.scheduleTick(dueOf(t, entry), false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.scheduleAdmissions.Wait()
|
||||
r.wg.Wait()
|
||||
// The exact same shared policy rejects manual admission as well.
|
||||
if _, err = r.start(protocol.Message{PipelineID: pid, Version: 1, Workspace: workspace, Input: spec.Input, WritePaths: spec.WritePaths, AllowTools: true, RequestKey: "manual-unsafe"}); err == nil {
|
||||
|
||||
@@ -11,6 +11,8 @@ import (
|
||||
|
||||
func (r *runner) scheduleLoop() {
|
||||
defer r.schedulerWG.Done()
|
||||
// Admissions run beside the loop; shutdown waits for the ones it started.
|
||||
defer r.scheduleAdmissions.Wait()
|
||||
if err := r.scheduleTick(time.Now(), true); err != nil {
|
||||
log.Printf("scheduler startup: %v", err)
|
||||
}
|
||||
@@ -22,14 +24,21 @@ func (r *runner) scheduleLoop() {
|
||||
return
|
||||
case <-r.store.Done():
|
||||
return
|
||||
case now := <-ticker.C:
|
||||
if err := r.scheduleTick(now, false); err != nil {
|
||||
case <-ticker.C:
|
||||
// Lateness is measured against the time of the claim, not the
|
||||
// (possibly delayed) tick.
|
||||
if err := r.scheduleTick(time.Now(), false); err != nil {
|
||||
log.Printf("scheduler: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// scheduleTick claims every enabled schedule due at now. A schedule that
|
||||
// cannot be read or claimed is logged and skipped, never stopping the others.
|
||||
// A claimed run is admitted on its own goroutine (scheduleAdmissions): run
|
||||
// admission can take up to a minute (git worktree creation), and an inline
|
||||
// start would make the next due schedule look missed by the time it is seen.
|
||||
func (r *runner) scheduleTick(now time.Time, recovery bool) error {
|
||||
items, err := r.store.ListSchedules(r.ctx, 0)
|
||||
if err != nil {
|
||||
@@ -39,54 +48,73 @@ func (r *runner) scheduleTick(now time.Time, recovery bool) error {
|
||||
if !item.Enabled {
|
||||
continue
|
||||
}
|
||||
due, err := time.Parse(time.RFC3339Nano, item.NextDue)
|
||||
if err != nil {
|
||||
return err
|
||||
if err := r.claimSchedule(item, now, recovery); err != nil {
|
||||
log.Printf("schedule id=%d pipeline=%d: %v", item.ID, item.PipelineID, err)
|
||||
}
|
||||
if due.After(now) {
|
||||
continue
|
||||
}
|
||||
next, err := pipeline.NextSchedule(item.Rule, now)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if item.Rule.Every != "" {
|
||||
interval, _ := time.ParseDuration(item.Rule.Every)
|
||||
next = due.Add((now.Sub(due)/interval + 1) * interval)
|
||||
}
|
||||
status := "claimed"
|
||||
if recovery || now.Sub(due) > 5*time.Second {
|
||||
status = "skipped_missed"
|
||||
}
|
||||
loc, err := pipeline.ScheduleLocation(item.Rule)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !pipeline.ScheduleDay(item.Rule, due.In(loc)) {
|
||||
status = "skipped_day"
|
||||
}
|
||||
claimed, err := r.store.ClaimSavedSchedule(r.ctx, item, due, next, status)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !claimed || status != "claimed" {
|
||||
continue
|
||||
}
|
||||
request := protocol.Message{PipelineID: item.PipelineID, Version: item.Version, RequestKey: fmt.Sprintf("saved-schedule:%d:%d", item.ID, due.UnixNano()), Input: item.Input, Workspace: item.Workspace, WritePaths: item.WritePaths, AllowTools: item.AllowTools, Model: item.Model, StageModels: item.StageModels, NotifyMode: item.NotifyMode, Title: item.Title, OutputFormat: item.OutputFormat}
|
||||
run, err := r.startWithSchedule(request, &pipeline.ScheduleAdmission{ID: item.ID, Revision: item.Revision, Due: due, Name: item.Name})
|
||||
diagnostic := ""
|
||||
status = "started"
|
||||
var runID int64
|
||||
if err != nil {
|
||||
status = "skipped"
|
||||
diagnostic = err.Error()
|
||||
} else {
|
||||
runID = run.ID
|
||||
}
|
||||
if err := r.store.FinishSavedSchedule(r.ctx, item.ID, due, status, diagnostic); err != nil {
|
||||
return err
|
||||
}
|
||||
log.Printf("schedule id=%d pipeline=%d version=%d due=%s status=%s run=%d %s", item.ID, item.PipelineID, item.Version, due.Format(time.RFC3339), status, runID, diagnostic)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *runner) claimSchedule(item protocol.SavedSchedule, now time.Time, recovery bool) error {
|
||||
due, err := time.Parse(time.RFC3339Nano, item.NextDue)
|
||||
if err != nil {
|
||||
return fmt.Errorf("next due %q: %w", item.NextDue, err)
|
||||
}
|
||||
if due.After(now) {
|
||||
return nil
|
||||
}
|
||||
next, err := pipeline.NextSchedule(item.Rule, now)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if item.Rule.Every != "" {
|
||||
interval, err := time.ParseDuration(item.Rule.Every)
|
||||
if err != nil || interval <= 0 {
|
||||
return fmt.Errorf("interval %q is invalid", item.Rule.Every)
|
||||
}
|
||||
next = due.Add((now.Sub(due)/interval + 1) * interval)
|
||||
}
|
||||
status := "claimed"
|
||||
if recovery || now.Sub(due) > 5*time.Second {
|
||||
status = "skipped_missed"
|
||||
}
|
||||
loc, err := pipeline.ScheduleLocation(item.Rule)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !pipeline.ScheduleDay(item.Rule, due.In(loc)) {
|
||||
status = "skipped_day"
|
||||
}
|
||||
claimed, err := r.store.ClaimSavedSchedule(r.ctx, item, due, next, status)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !claimed || status != "claimed" {
|
||||
return nil
|
||||
}
|
||||
r.scheduleAdmissions.Add(1)
|
||||
go func() {
|
||||
defer r.scheduleAdmissions.Done()
|
||||
r.admitScheduled(item, due)
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
// admitScheduled starts one claimed schedule's run and records the outcome.
|
||||
func (r *runner) admitScheduled(item protocol.SavedSchedule, due time.Time) {
|
||||
request := protocol.Message{PipelineID: item.PipelineID, Version: item.Version, RequestKey: fmt.Sprintf("saved-schedule:%d:%d", item.ID, due.UnixNano()), Input: item.Input, Workspace: item.Workspace, WritePaths: item.WritePaths, AllowTools: item.AllowTools, Model: item.Model, StageModels: item.StageModels, NotifyMode: item.NotifyMode, Title: item.Title, OutputFormat: item.OutputFormat}
|
||||
run, err := r.startWithSchedule(request, &pipeline.ScheduleAdmission{ID: item.ID, Revision: item.Revision, Due: due, Name: item.Name})
|
||||
diagnostic := ""
|
||||
status := "started"
|
||||
var runID int64
|
||||
if err != nil {
|
||||
status = "skipped"
|
||||
diagnostic = err.Error()
|
||||
} else if run != nil {
|
||||
runID = run.ID
|
||||
}
|
||||
if err := r.store.FinishSavedSchedule(r.ctx, item.ID, due, status, diagnostic); err != nil {
|
||||
log.Printf("schedule id=%d record admission: %v", item.ID, err)
|
||||
}
|
||||
log.Printf("schedule id=%d pipeline=%d version=%d due=%s status=%s run=%d %s", item.ID, item.PipelineID, item.Version, due.Format(time.RFC3339), status, runID, diagnostic)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
"git.a-wan.net/alan/pipelines/internal/summarise"
|
||||
)
|
||||
|
||||
// One schedule whose stored due time cannot be parsed is logged and skipped;
|
||||
// every other due schedule still runs on the same tick.
|
||||
func TestScheduleTickSkipsAnUnreadableScheduleAndRunsTheRest(t *testing.T) {
|
||||
ctx, s, r, pid := scheduleFixture(t)
|
||||
now := time.Now()
|
||||
broken := saveTestSchedule(t, ctx, s, pid, "broken", t.TempDir(), "1m", now)
|
||||
good := saveTestSchedule(t, ctx, s, pid, "good", t.TempDir(), "1m", now)
|
||||
db, err := sql.Open("sqlite", s.DatabasePath())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
if _, err := db.ExecContext(ctx, `UPDATE saved_schedules SET next_due='not a time' WHERE id=?`, broken.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "# Done"}}, nil
|
||||
}
|
||||
if err := r.scheduleTick(dueOf(t, good), false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.scheduleAdmissions.Wait()
|
||||
r.wg.Wait()
|
||||
runs, err := s.ListRuns(ctx)
|
||||
if err != nil || len(runs) != 1 || runs[0].ScheduleID != good.ID {
|
||||
t.Fatalf("runs = %+v %v", runs, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A slow admission (title generation, worktree creation) no longer holds the
|
||||
// scheduler: the tick returns at once and a schedule due a moment later is
|
||||
// claimed and started, not recorded as missed.
|
||||
func TestSlowScheduledAdmissionDoesNotMissTheNextSchedule(t *testing.T) {
|
||||
ctx, s, r, pid := scheduleFixture(t)
|
||||
now := time.Now()
|
||||
save := func(prompt string) *protocol.SavedSchedule {
|
||||
item, err := s.SaveSchedule(ctx, protocol.SavedSchedule{Name: prompt, PipelineID: pid, Version: 1, Enabled: true, Workspace: t.TempDir(), Input: map[string]any{"prompt": prompt}, Rule: protocol.Schedule{Every: "1m"}, NotifyMode: "off"}, now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return item
|
||||
}
|
||||
a, b := save("first"), save("second")
|
||||
release := make(chan struct{})
|
||||
titling := make(chan string, 2)
|
||||
r.title = func(_ context.Context, prompt string) summarise.Title {
|
||||
titling <- prompt
|
||||
if prompt == "first" {
|
||||
<-release
|
||||
}
|
||||
return summarise.Title{Text: prompt}
|
||||
}
|
||||
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "# Done"}}, nil
|
||||
}
|
||||
at := dueOf(t, a)
|
||||
if dueB := dueOf(t, b); dueB.After(at) {
|
||||
at = dueB
|
||||
}
|
||||
// Both are due on this tick; the first one's admission blocks.
|
||||
returned := make(chan error, 1)
|
||||
go func() { returned <- r.scheduleTick(at, false) }()
|
||||
select {
|
||||
case err := <-returned:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("scheduler tick blocked on a slow admission")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for len(seen) < 2 {
|
||||
select {
|
||||
case got := <-titling:
|
||||
seen[got] = true
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("second schedule not admitted while the first was slow: %v", seen)
|
||||
}
|
||||
}
|
||||
close(release)
|
||||
r.scheduleAdmissions.Wait()
|
||||
r.wg.Wait()
|
||||
runs, err := s.ListRuns(ctx)
|
||||
if err != nil || len(runs) != 2 {
|
||||
t.Fatalf("runs = %+v %v", runs, err)
|
||||
}
|
||||
}
|
||||
@@ -82,6 +82,7 @@ func TestIndependentScheduledRunsAndProvenance(t *testing.T) {
|
||||
if err := r.scheduleTick(dueOf(t, item), false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.scheduleAdmissions.Wait()
|
||||
r.wg.Wait()
|
||||
}
|
||||
runs, err := s.ListRuns(ctx)
|
||||
@@ -183,6 +184,7 @@ func TestScheduleDeletionDoesNotCancelAdmittedRun(t *testing.T) {
|
||||
if err := r.scheduleTick(dueOf(t, item), false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.scheduleAdmissions.Wait()
|
||||
<-entered
|
||||
if err := s.DeleteSchedule(ctx, item.ID, item.Revision); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -190,6 +192,7 @@ func TestScheduleDeletionDoesNotCancelAdmittedRun(t *testing.T) {
|
||||
if err := r.scheduleTick(dueOf(t, item).Add(time.Minute), false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.scheduleAdmissions.Wait()
|
||||
close(release)
|
||||
r.wg.Wait()
|
||||
runs, err := s.ListRuns(ctx)
|
||||
@@ -211,21 +214,26 @@ func TestSavedScheduleRecoveryAndOverlap(t *testing.T) {
|
||||
if err := r.scheduleTick(due, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.scheduleAdmissions.Wait()
|
||||
<-entered
|
||||
if err := r.scheduleTick(due.Add(time.Minute), false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.scheduleAdmissions.Wait()
|
||||
close(release)
|
||||
r.wg.Wait()
|
||||
if err := r.scheduleTick(due.Add(time.Minute), false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.scheduleAdmissions.Wait()
|
||||
if err := r.scheduleTick(due.Add(time.Hour), true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.scheduleAdmissions.Wait()
|
||||
if err := r.scheduleTick(due.Add(time.Hour), false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.scheduleAdmissions.Wait()
|
||||
runs, err := s.ListRuns(ctx)
|
||||
if err != nil || len(runs) != 1 {
|
||||
t.Fatal("replayed or overlapping work", runs, err)
|
||||
@@ -242,6 +250,7 @@ func TestSavedScheduleRecoveryAndOverlap(t *testing.T) {
|
||||
if err = r.scheduleTick(dueOf(t, item), false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.scheduleAdmissions.Wait()
|
||||
runs, _ = s.ListRuns(ctx)
|
||||
if len(runs) != 1 {
|
||||
t.Fatal("excluded day dispatched", runs)
|
||||
@@ -259,7 +268,10 @@ func TestScheduleEditBetweenClaimAndAdmission(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
due := dueOf(t, item)
|
||||
r.title = func(context.Context, string) summarise.Title {
|
||||
// Admission runs on its own goroutine: keep its error local.
|
||||
var err error
|
||||
if operation == "delete" {
|
||||
err = s.DeleteSchedule(ctx, item.ID, item.Revision)
|
||||
} else {
|
||||
@@ -279,9 +291,10 @@ func TestScheduleEditBetweenClaimAndAdmission(t *testing.T) {
|
||||
t.Error("invalidated occurrence executed")
|
||||
return stage.Result{}, nil
|
||||
}
|
||||
if err = r.scheduleTick(dueOf(t, item), false); err != nil {
|
||||
if err = r.scheduleTick(due, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.scheduleAdmissions.Wait()
|
||||
r.wg.Wait()
|
||||
runs, _ := s.ListRuns(ctx)
|
||||
if len(runs) != 0 {
|
||||
|
||||
@@ -190,6 +190,9 @@ func (m *storageManager) apply(ctx context.Context, preview protocol.StorageClea
|
||||
for _, active := range m.runner.active {
|
||||
config.ProtectedWorkspaces = append(config.ProtectedWorkspaces, active.workspace)
|
||||
}
|
||||
for source := range m.runner.admitting {
|
||||
config.ProtectedWorkspaces = append(config.ProtectedWorkspaces, source)
|
||||
}
|
||||
var tree storageWorktree
|
||||
found := false
|
||||
for _, known := range before.Worktrees {
|
||||
|
||||
@@ -57,6 +57,7 @@ func TestWebStagesCanRunWithoutMutationApproval(t *testing.T) {
|
||||
if err := r.scheduleTick(due, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.scheduleAdmissions.Wait()
|
||||
r.wg.Wait()
|
||||
runs, _ := store.ListRuns(ctx)
|
||||
if len(runs) != 2 {
|
||||
|
||||
@@ -145,6 +145,7 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
|
||||
// Prompts queued behind a running turn are durable and owned by their
|
||||
// session; resume delivering any a previous process left queued.
|
||||
hub.queueStore = stores[0]
|
||||
hub.startChatNotificationOutbox(ctx, stores[0])
|
||||
hub.liveStore = stores[0]
|
||||
hub.turnDiffStore = stores[0]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user