diff --git a/internal/pipeline/chat_notifications.go b/internal/pipeline/chat_notifications.go new file mode 100644 index 00000000..02e37544 --- /dev/null +++ b/internal/pipeline/chat_notifications.go @@ -0,0 +1,115 @@ +package pipeline + +import ( + "context" + "database/sql" + "errors" + "time" +) + +// ChatNotification is one chat phone push (ntfy) in the durable outbox. It +// follows the run notification outbox (run_notifications.go): a row is leased +// for a bounded attempt, a crash during a lease is recovered when the lease +// expires, and attempts are bounded. ID is the chat's app notification id, so +// an enqueue is idempotent and a notification the operator already cleared in +// the app is never published late. +type ChatNotification struct { + ID, SessionID, Title, Body, Click string + // SequenceID is the ntfy sequence id the push is published with (so a later + // clear dismisses it on the phone); "" publishes without one. + SequenceID string + Priority int + Attempts int +} + +// ChatNotificationAttempts bounds publication attempts per chat push. +const ChatNotificationAttempts = 5 + +// chatNotificationLease is how long one claimed attempt owns its row. +const chatNotificationLease = 60 + +// chatNotificationRetention bounds how long settled rows are kept. +const chatNotificationRetention = 7 * 24 * time.Hour + +func (s *Store) initChatNotifications() error { + _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS chat_notifications ( +id TEXT PRIMARY KEY, session_id TEXT NOT NULL, title TEXT NOT NULL, body TEXT NOT NULL, click TEXT NOT NULL, +sequence_id TEXT NOT NULL DEFAULT '', priority INTEGER NOT NULL DEFAULT 0, +status TEXT NOT NULL DEFAULT 'pending', attempts INTEGER NOT NULL DEFAULT 0, +next_attempt INTEGER NOT NULL DEFAULT 0, diagnostic TEXT NOT NULL DEFAULT '', message_id TEXT NOT NULL DEFAULT '', +created_at INTEGER NOT NULL); +CREATE INDEX IF NOT EXISTS chat_notifications_due ON chat_notifications(status,next_attempt);`) + return err +} + +// EnqueueChatNotification records one chat push once (by id) and prunes +// settled rows past retention. +func (s *Store) EnqueueChatNotification(ctx context.Context, n ChatNotification, now time.Time) error { + if _, err := s.db.ExecContext(ctx, `DELETE FROM chat_notifications WHERE created_at0)`, now); err != nil { + return nil, err + } + if _, err := s.db.ExecContext(ctx, `UPDATE chat_notifications SET status='failed',diagnostic='publisher acknowledgement unknown after final lease expired' +WHERE status='sending' AND attempts>=? AND next_attempt<=?`, ChatNotificationAttempts, now); err != nil { + return nil, err + } + n := new(ChatNotification) + err := s.db.QueryRowContext(ctx, `UPDATE chat_notifications SET status='sending',attempts=attempts+1,next_attempt=? +WHERE rowid=(SELECT rowid FROM chat_notifications WHERE status IN ('pending','sending') AND attempts= ChatNotificationAttempts { + status = "failed" + } + } + _, err := s.db.ExecContext(ctx, `UPDATE chat_notifications SET status=?,diagnostic=?,message_id=?,next_attempt=? +WHERE id=? AND status='sending' AND attempts=?`, status, diagnostic, messageID, next, n.ID, n.Attempts) + return err +} + +// ChatNotificationStatus reports one push's outbox status ("" when absent) +// and attempts. +func (s *Store) ChatNotificationStatus(ctx context.Context, id string) (string, int, error) { + var status string + var attempts int + err := s.db.QueryRowContext(ctx, `SELECT status,attempts FROM chat_notifications WHERE id=?`, id).Scan(&status, &attempts) + if errors.Is(err, sql.ErrNoRows) { + return "", 0, nil + } + return status, attempts, err +} + +// ChatNotificationCleared reports whether id's app notification has been +// cleared; a publication that raced a clear then clears the phone too. +func (s *Store) ChatNotificationCleared(ctx context.Context, id string) (bool, error) { + var cleared bool + err := s.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM app_notifications WHERE id=? AND cleared_at<>0)`, id).Scan(&cleared) + return cleared, err +} diff --git a/internal/pipeline/chat_notifications_test.go b/internal/pipeline/chat_notifications_test.go new file mode 100644 index 00000000..bef69429 --- /dev/null +++ b/internal/pipeline/chat_notifications_test.go @@ -0,0 +1,76 @@ +package pipeline + +import ( + "context" + "errors" + "path/filepath" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +func TestChatNotificationOutboxRetriesAndSkipsCleared(t *testing.T) { + ctx := context.Background() + s, err := Open(filepath.Join(t.TempDir(), "chat-outbox.db")) + if err != nil { + t.Fatal(err) + } + defer s.Close() + now := time.Unix(1000, 0) + n := ChatNotification{ID: "chat:ses_a:form:q1", SessionID: "ses_a", Title: "T", Body: "B", Click: "pipelines://chat/ses_a", SequenceID: "pl-1"} + for range 2 { // idempotent by id + if err := s.EnqueueChatNotification(ctx, n, now); err != nil { + t.Fatal(err) + } + } + first, err := s.ClaimChatNotification(ctx, 1000) + if err != nil || first == nil || first.Attempts != 1 || first.SequenceID != "pl-1" { + t.Fatalf("claim = %+v %v", first, err) + } + if again, err := s.ClaimChatNotification(ctx, 1000); err != nil || again != nil { + t.Fatalf("leased row claimed twice: %+v %v", again, err) + } + if err := s.FinishChatNotification(ctx, *first, 1000, "", errors.New("ntfy down")); err != nil { + t.Fatal(err) + } + if early, _ := s.ClaimChatNotification(ctx, 1004); early != nil { + t.Fatalf("retried before backoff: %+v", early) + } + second, err := s.ClaimChatNotification(ctx, 1005) + if err != nil || second == nil || second.Attempts != 2 { + t.Fatalf("retry claim = %+v %v", second, err) + } + if err := s.FinishChatNotification(ctx, *second, 1005, "m1", nil); err != nil { + t.Fatal(err) + } + if status, attempts, _ := s.ChatNotificationStatus(ctx, n.ID); status != "sent" || attempts != 2 { + t.Fatalf("status = %s/%d", status, attempts) + } + // A lease lost to a crash is reclaimed after it expires. + crashed := ChatNotification{ID: "chat:ses_a:form:q2", SessionID: "ses_a", Title: "T", Body: "B"} + _ = s.EnqueueChatNotification(ctx, crashed, now) + if c, _ := s.ClaimChatNotification(ctx, 2000); c == nil { + t.Fatal("no claim") + } + if c, _ := s.ClaimChatNotification(ctx, 2061); c == nil || c.Attempts != 2 { + t.Fatalf("expired lease not reclaimed: %+v", c) + } else if err := s.FinishChatNotification(ctx, *c, 2061, "m2", nil); err != nil { + t.Fatal(err) + } + // A push whose app notification was cleared first is never published. + cleared := ChatNotification{ID: "chat:ses_b:form:q3", SessionID: "ses_b", Title: "T", Body: "B"} + if _, _, err := s.RecordAppNotification(ctx, AppNotificationRecord{AppNotification: protocol.AppNotification{ID: cleared.ID, Kind: protocol.NotificationChatQuestion, Title: "T"}, SessionID: "ses_b"}, now); err != nil { + t.Fatal(err) + } + if _, err := s.ClearAppNotifications(ctx, []string{cleared.ID}, now); err != nil { + t.Fatal(err) + } + _ = s.EnqueueChatNotification(ctx, cleared, now) + if c, _ := s.ClaimChatNotification(ctx, 3000); c != nil { + t.Fatalf("cleared push claimed: %+v", c) + } + if status, _, _ := s.ChatNotificationStatus(ctx, cleared.ID); status != "cleared" { + t.Fatalf("cleared push status = %q", status) + } +} diff --git a/internal/pipeline/store.go b/internal/pipeline/store.go index e258892b..ae16e913 100644 --- a/internal/pipeline/store.go +++ b/internal/pipeline/store.go @@ -77,6 +77,10 @@ CREATE TABLE IF NOT EXISTS submissions (id INTEGER PRIMARY KEY, name TEXT NOT NU db.Close() return nil, err } + if err := s.initChatNotifications(); err != nil { + db.Close() + return nil, err + } if err := s.initSchedules(); err != nil { db.Close() return nil, err diff --git a/internal/server/chat_attention.go b/internal/server/chat_attention.go index 22c5d058..b7e58d88 100644 --- a/internal/server/chat_attention.go +++ b/internal/server/chat_attention.go @@ -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)}) }() } diff --git a/internal/server/chat_auto_switch.go b/internal/server/chat_auto_switch.go index fea5d75a..53b4ba9e 100644 --- a/internal/server/chat_auto_switch.go +++ b/internal/server/chat_auto_switch.go @@ -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}) } diff --git a/internal/server/chat_hub.go b/internal/server/chat_hub.go index 25a35787..5858a218 100644 --- a/internal/server/chat_hub.go +++ b/internal/server/chat_hub.go @@ -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{} diff --git a/internal/server/chat_ntfy_outbox.go b/internal/server/chat_ntfy_outbox.go new file mode 100644 index 00000000..32746049 --- /dev/null +++ b/internal/server/chat_ntfy_outbox.go @@ -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() + } +} diff --git a/internal/server/chat_ntfy_outbox_test.go b/internal/server/chat_ntfy_outbox_test.go new file mode 100644 index 00000000..12c9a89d --- /dev/null +++ b/internal/server/chat_ntfy_outbox_test.go @@ -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) + } +} diff --git a/internal/server/chat_queue.go b/internal/server/chat_queue.go index 2f5d26a6..1fba9743 100644 --- a/internal/server/chat_queue.go +++ b/internal/server/chat_queue.go @@ -221,9 +221,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, @@ -239,7 +254,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 @@ -253,7 +268,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)) @@ -411,49 +426,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 { diff --git a/internal/server/chat_queue_recovery_test.go b/internal/server/chat_queue_recovery_test.go new file mode 100644 index 00000000..6440f2d1 --- /dev/null +++ b/internal/server/chat_queue_recovery_test.go @@ -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 }) +} diff --git a/internal/server/chat_unattended.go b/internal/server/chat_unattended.go index 3819ad09..3e5895c1 100644 --- a/internal/server/chat_unattended.go +++ b/internal/server/chat_unattended.go @@ -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 diff --git a/internal/server/chat_unattended_test.go b/internal/server/chat_unattended_test.go index d6d2e23d..c2c103f0 100644 --- a/internal/server/chat_unattended_test.go +++ b/internal/server/chat_unattended_test.go @@ -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", ch: make(chan protocol.Message, 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", ch: make(chan protocol.Message, 1), done: make(chan struct{})} room.subs["c"] = sub h.mu.Unlock() diff --git a/internal/server/websocket.go b/internal/server/websocket.go index b44124b5..366970c5 100644 --- a/internal/server/websocket.go +++ b/internal/server/websocket.go @@ -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] }