Merge branch 'main' into worktree-agent-a7c8c1a6937e97e84

Resolve chat_room.go: keep main's bounded chatSub queue (ready channel, no ch) in attachSub; the subscribe live-turn marker is still queued at attach under h.mu through enqueueChatLocked, and an existing subscriber whose queue is full is overflowed (resync) after the hub lock is released.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 01:11:11 +00:00
150 changed files with 7656 additions and 901 deletions
+25
View File
@@ -474,14 +474,39 @@ func (s *session) emit(frame protocol.ChatEventFrame) {
targets = append(targets, ch)
}
s.mu.Unlock()
lifecycle := frameIsLifecycle(frame)
for _, ch := range targets {
select {
case ch <- frame:
continue
default:
}
if !lifecycle {
continue
}
// A full watcher may lose a delta (the hub repairs text from
// history), but never a step start or end: a lost end leaves the
// turn "working" forever. Wait, bounded, for the watcher to drain.
timer := time.NewTimer(lifecycleDeliveryTimeout)
select {
case ch <- frame:
case <-timer.C:
log.Printf("claude session %s: a watcher did not accept the %s frame within %s; it was dropped", s.id, frame.Kind, lifecycleDeliveryTimeout)
}
timer.Stop()
}
}
// lifecycleDeliveryTimeout bounds how long emit waits for a full watcher to
// accept a turn lifecycle frame before it gives up on that watcher.
var lifecycleDeliveryTimeout = 5 * time.Second
// frameIsLifecycle reports whether a frame changes the turn's state, so it
// must reach every watcher even when that watcher's buffer is full.
func frameIsLifecycle(frame protocol.ChatEventFrame) bool {
return frame.Kind == protocol.ChatEventStep || frame.Kind == protocol.ChatEventResync
}
func (s *session) subscribe() chan protocol.ChatEventFrame {
ch := make(chan protocol.ChatEventFrame, 256)
s.mu.Lock()
+61
View File
@@ -0,0 +1,61 @@
package claude
import (
"context"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// A watcher whose buffer is full of streamed text may lose a delta, but never
// the turn's end: a lost end left the chat "working" forever.
func TestEmitDeliversTheTurnEndToAFullWatcher(t *testing.T) {
c := newChat(context.Background())
t.Cleanup(c.cancel)
s := c.sessionFor("ses_full", t.TempDir())
ch := s.subscribe()
defer s.unsubscribe(ch)
for len(ch) < cap(ch) {
s.emit(protocol.ChatEventFrame{Kind: protocol.ChatEventText, Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "p", Text: "x"}})
}
emitted := make(chan struct{})
go func() {
defer close(emitted)
s.emit(protocol.ChatEventFrame{Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: "turn_1"}})
}()
// The watcher is slow, not gone: it drains only after the end was emitted.
time.Sleep(100 * time.Millisecond)
deadline := time.After(3 * time.Second)
for {
select {
case frame := <-ch:
if frame.Kind == protocol.ChatEventStep && frame.Step != nil && frame.Step.Status == protocol.ChatStepEnded {
<-emitted
return
}
case <-deadline:
t.Fatal("the turn end never reached the full watcher")
}
}
}
// A watcher that never drains does not hold the CLI reader forever.
func TestEmitGivesUpOnAStuckWatcher(t *testing.T) {
prior := lifecycleDeliveryTimeout
lifecycleDeliveryTimeout = 50 * time.Millisecond
t.Cleanup(func() { lifecycleDeliveryTimeout = prior })
c := newChat(context.Background())
t.Cleanup(c.cancel)
s := c.sessionFor("ses_stuck", t.TempDir())
ch := s.subscribe()
defer s.unsubscribe(ch)
for len(ch) < cap(ch) {
s.emit(protocol.ChatEventFrame{Kind: protocol.ChatEventText, Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "p", Text: "x"}})
}
start := time.Now()
s.emit(protocol.ChatEventFrame{Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: "turn_1"}})
if waited := time.Since(start); waited > 2*time.Second {
t.Fatalf("emit blocked %s on a stuck watcher", waited)
}
}
+115
View File
@@ -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_at<? AND status NOT IN ('pending','sending')`, now.Add(-chatNotificationRetention).Unix()); err != nil {
return err
}
_, err := s.db.ExecContext(ctx, `INSERT INTO chat_notifications(id,session_id,title,body,click,sequence_id,priority,created_at)
VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(id) DO NOTHING`, n.ID, n.SessionID, n.Title, n.Body, n.Click, n.SequenceID, n.Priority, now.Unix())
return err
}
// ClaimChatNotification atomically leases one due push. A push whose app
// notification was cleared before it went out (the operator already answered
// in the app) is settled as cleared instead of published.
func (s *Store) ClaimChatNotification(ctx context.Context, now int64) (*ChatNotification, error) {
if _, err := s.db.ExecContext(ctx, `UPDATE chat_notifications SET status='cleared',diagnostic='cleared in the app before publication'
WHERE status IN ('pending','sending') AND next_attempt<=? AND EXISTS(SELECT 1 FROM app_notifications a WHERE a.id=chat_notifications.id AND a.cleared_at<>0)`, 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<? AND next_attempt<=? ORDER BY next_attempt,rowid LIMIT 1)
RETURNING id,session_id,title,body,click,sequence_id,priority,attempts`, now+chatNotificationLease, ChatNotificationAttempts, now).Scan(&n.ID, &n.SessionID, &n.Title, &n.Body, &n.Click, &n.SequenceID, &n.Priority, &n.Attempts)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
return n, nil
}
// FinishChatNotification settles a claimed attempt: sent, or pending again
// after an exponential backoff (5 s, 10 s, 20 s, ...) until attempts run out.
func (s *Store) FinishChatNotification(ctx context.Context, n ChatNotification, now int64, messageID string, failure error) error {
status, diagnostic, next := "sent", "", now
if failure != nil {
status, diagnostic = "pending", failure.Error()
next = now + int64(5)<<min(n.Attempts-1, 8)
if n.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
}
@@ -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)
}
}
+21 -5
View File
@@ -41,6 +41,9 @@ type OperatorSession struct {
// protocol.ChatColors by name, or "" for none. The name, not a shade, is
// stored so every client renders its own theme-tuned colour.
Color string
// Revision increases with every change to the row (a trigger bumps it), so
// a client receiving list metadata pushes out of order keeps the newest.
Revision int64
}
// ChatCreateBootstrap is the durable progress record for one chat_create
@@ -175,7 +178,20 @@ func (s *Store) migrateOperatorSessions() error {
// replaced_by names the native session a chat moved to when the operator
// started a fresh session (/new). The replaced row is kept, unlisted, so the
// old id still resolves; existing rows default to '' (current).
return s.addColumnIfMissing("operator_sessions", "replaced_by", "TEXT NOT NULL DEFAULT ''")
if err := s.addColumnIfMissing("operator_sessions", "replaced_by", "TEXT NOT NULL DEFAULT ''"); err != nil {
return err
}
// revision orders a row's states: every update that does not set it bumps
// it, so the chat_session_changed pushes (sent concurrently) can be ordered
// by the client. SQLite does not re-fire a trigger from its own update.
if err := s.addColumnIfMissing("operator_sessions", "revision", "INTEGER NOT NULL DEFAULT 0"); err != nil {
return err
}
_, err := s.db.Exec(`CREATE TRIGGER IF NOT EXISTS operator_sessions_revision AFTER UPDATE ON operator_sessions
FOR EACH ROW WHEN NEW.revision = OLD.revision BEGIN
UPDATE operator_sessions SET revision = OLD.revision + 1 WHERE session_id = NEW.session_id;
END`)
return err
}
// ErrOperatorSessionReplaced reports that a chat was already moved to another
@@ -409,9 +425,9 @@ func (s *Store) SetOperatorSessionColor(ctx context.Context, sessionID, color st
// returned). It is one indexed lookup and never mutates the row.
func (s *Store) OperatorSession(ctx context.Context, sessionID string) (OperatorSession, bool, error) {
var session OperatorSession
row := s.db.QueryRowContext(ctx, `SELECT session_id,directory,title,tag,backend,created_at,last_used_at,closed_at,starred_at,color
row := s.db.QueryRowContext(ctx, `SELECT session_id,directory,title,tag,backend,created_at,last_used_at,closed_at,starred_at,color,revision
FROM operator_sessions WHERE session_id=? AND tag <> ''`, sessionID)
if err := row.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.Backend, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt, &session.StarredAt, &session.Color); err != nil {
if err := row.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.Backend, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt, &session.StarredAt, &session.Color, &session.Revision); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return OperatorSession{}, false, nil
}
@@ -430,7 +446,7 @@ FROM operator_sessions WHERE session_id=? AND tag <> ''`, sessionID)
// operator can still see and reopen what they finished. It is one bounded
// statement; recency is never mutated here.
func (s *Store) OperatorSessions(ctx context.Context) ([]OperatorSession, error) {
rows, err := s.db.QueryContext(ctx, `SELECT session_id,directory,title,tag,backend,created_at,last_used_at,closed_at,starred_at,color
rows, err := s.db.QueryContext(ctx, `SELECT session_id,directory,title,tag,backend,created_at,last_used_at,closed_at,starred_at,color,revision
FROM operator_sessions WHERE tag <> '' AND ephemeral = 0 AND replaced_by = '' ORDER BY last_used_at DESC, session_id LIMIT ?`, operatorSessionListLimit)
if err != nil {
return nil, err
@@ -439,7 +455,7 @@ FROM operator_sessions WHERE tag <> '' AND ephemeral = 0 AND replaced_by = '' OR
sessions := []OperatorSession{}
for rows.Next() {
var session OperatorSession
if err := rows.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.Backend, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt, &session.StarredAt, &session.Color); err != nil {
if err := rows.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.Backend, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt, &session.StarredAt, &session.Color, &session.Revision); err != nil {
return nil, err
}
sessions = append(sessions, session)
@@ -320,3 +320,45 @@ func TestOperatorSessionsMigrationAddsEphemeral(t *testing.T) {
t.Fatalf("verification session listed after migration: %+v err=%v", listed, err)
}
}
// Every change to an operator session bumps its revision, so clients can order
// concurrent chat_session_changed pushes.
func TestOperatorSessionRevisionIncreasesOnEveryChange(t *testing.T) {
ctx := context.Background()
store, err := Open(filepath.Join(t.TempDir(), "revision.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
if err := store.RecordOperatorSession(ctx, "ses_a", "/work/a", "A", "operator"); err != nil {
t.Fatal(err)
}
revision := func() int64 {
t.Helper()
session, found, err := store.OperatorSession(ctx, "ses_a")
if err != nil || !found {
t.Fatalf("read: %v %v", found, err)
}
return session.Revision
}
last := revision()
for i, change := range []func() error{
func() error { return store.SetOperatorSessionColor(ctx, "ses_a", "red") },
func() error { return store.SetOperatorSessionStar(ctx, "ses_a", true) },
func() error { return store.SetOperatorSessionTitle(ctx, "ses_a", "Renamed") },
func() error { return store.SetOperatorSessionColor(ctx, "ses_a", "") },
} {
if err := change(); err != nil {
t.Fatal(err)
}
next := revision()
if next != last+1 {
t.Fatalf("change %d: revision %d after %d", i, next, last)
}
last = next
}
sessions, err := store.OperatorSessions(ctx)
if err != nil || len(sessions) != 1 || sessions[0].Revision != last {
t.Fatalf("listed %+v %v, want revision %d", sessions, err, last)
}
}
+6 -1
View File
@@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"strings"
@@ -20,6 +21,10 @@ func (s *Store) SaveNotifications(ctx context.Context, id int64, sequence int, r
return err
}
// ErrInvalidRunTransition reports a conditional run update that matched no row:
// the run is not in a state the transition applies to. Retrying cannot help.
var ErrInvalidRunTransition = errors.New("invalid run state transition")
func affected(result sql.Result, err error) error {
if err != nil {
return err
@@ -29,7 +34,7 @@ func affected(result sql.Result, err error) error {
return err
}
if n != 1 {
return fmt.Errorf("invalid run state transition")
return ErrInvalidRunTransition
}
return nil
}
+1
View File
@@ -26,6 +26,7 @@ session_id TEXT NOT NULL DEFAULT '', agent_active INTEGER NOT NULL DEFAULT 0, tr
started_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, finished_at TEXT, PRIMARY KEY(run_id,sequence));
CREATE INDEX IF NOT EXISTS run_latest ON pipeline_runs(id DESC);
CREATE INDEX IF NOT EXISTS run_steps_session ON run_steps(session_id);
CREATE INDEX IF NOT EXISTS run_steps_agent_active ON run_steps(run_id) WHERE agent_active<>0;
CREATE TABLE IF NOT EXISTS step_notifications (
run_id INTEGER NOT NULL, sequence INTEGER NOT NULL, receipts_json TEXT NOT NULL,
PRIMARY KEY(run_id,sequence), FOREIGN KEY(run_id,sequence) REFERENCES run_steps(run_id,sequence));
+19
View File
@@ -143,3 +143,22 @@ func (s *Store) ActiveAgentSessionsForRun(ctx context.Context, runID int64) ([]s
}
return ids, rows.Err()
}
// RunsWithActiveAgents reports every run with a step whose agent is still
// active, in one query.
func (s *Store) RunsWithActiveAgents(ctx context.Context) (map[int64]bool, error) {
rows, err := s.db.QueryContext(ctx, "SELECT DISTINCT run_id FROM run_steps WHERE agent_active<>0")
if err != nil {
return nil, err
}
defer rows.Close()
runs := map[int64]bool{}
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
return nil, err
}
runs[id] = true
}
return runs, rows.Err()
}
+4
View File
@@ -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
+11
View File
@@ -357,6 +357,10 @@ type ChatSession struct {
Tag string `json:"tag,omitempty"`
CreatedAt int64 `json:"created_at,omitempty"`
UpdatedAt int64 `json:"updated_at,omitempty"`
// Revision increases with every change to the chat's registry row. The
// chat_session_changed pushes may arrive out of order; a client ignores one
// older than the row it holds. 0 (older servers) is unordered.
Revision int64 `json:"revision,omitempty"`
// Busy is retained for wire compatibility only: it is never set by this
// server. A session is never read-only, any number of clients may watch and
// write it, and only a turn is serialised (a waiting prompt is acknowledged
@@ -758,6 +762,13 @@ type ChatEventFrame struct {
// Seq numbers a text or reasoning delta within its session, increasing;
// see ChatHistoryPage.LiveSeq. Zero when the harness does not number them.
Seq int64 `json:"seq,omitempty"`
// SeqFrom and DeltaLens are set on a frame joining consecutive numbered
// deltas of one part (a slow client's queue coalesced them, see
// chatSub): SeqFrom is the first joined delta's Seq (Seq the last), and
// DeltaLens each joined delta's length in UTF-16 code units, so a client
// whose history page already holds a prefix (LiveSeq) drops exactly it.
SeqFrom int64 `json:"seq_from,omitempty"`
DeltaLens []int `json:"delta_lens,omitempty"`
}
// ChatCompaction is session activity, never a transcript message or tool.
+4
View File
@@ -11,6 +11,10 @@ const (
Subscribe = "subscribe"
Unsubscribe = "unsubscribe"
RunEvent = "run_event"
// RunsResync is the last frame of a subscription the server detached
// because its client fell too far behind: the client must send subscribe
// again and re-read the runs it shows, since frames were discarded.
RunsResync = "runs_resync"
)
// RunEventFrame is the server-pushed run_event delta. It carries only the values
+26
View File
@@ -84,8 +84,22 @@ type SearchRequest struct {
// and private/ scratch, see ClassifyArtifacts). Off by default: artifact
// search surfaces only deliverables.
IncludeDebug bool `json:"include_debug,omitempty"`
// Scope narrows a kind=chat search to one chat ("chat:<session id>").
// A scoped search returns every text-part occurrence of Query in that
// chat's messages, newest message first, one result per occurrence with
// its message id, part index and offset, paged by Cursor/NextCursor.
Scope string `json:"scope,omitempty"`
// Cursor continues a scoped chat search: a previous reply's NextCursor,
// or a chat_messages next_cursor to start just before the messages a
// client already holds. Empty starts at the newest message.
Cursor string `json:"cursor,omitempty"`
// CaseSensitive makes a scoped chat search match case exactly.
CaseSensitive bool `json:"case_sensitive,omitempty"`
}
// SearchChatScope is a scoped chat search's Scope for one session.
func SearchChatScope(sessionID string) string { return "chat:" + sessionID }
// SearchResponse is the bounded set of matches. Results are ordered by recency
// descending (a chat's last use for kind chat), numeric entity/visit IDs
// descending, then target ascending, before the cap applies; Score records the
@@ -105,6 +119,11 @@ type SearchResponse struct {
// ScannedChats is how many chat transcripts a chat search read message
// text from (kind chat only); additive, so older peers ignore it.
ScannedChats int `json:"scanned_chats,omitempty"`
// NextCursor continues a scoped chat search that stopped before the
// chat's oldest message (result cap or scan budget); empty when done.
NextCursor string `json:"next_cursor,omitempty"`
// ScannedMessages is how many messages a scoped chat search read.
ScannedMessages int `json:"scanned_messages,omitempty"`
}
// SearchResult is one typed, navigable match. Kind selects which payload is
@@ -202,6 +221,13 @@ type SearchChat struct {
MessageID string `json:"message_id,omitempty"`
Role string `json:"role,omitempty"`
Snippet string `json:"snippet,omitempty"`
// Part and Offset locate one occurrence in a scoped chat search: the
// index of the text part in the message's parts and the match's start
// in that part's text, in UTF-16 code units (as a browser or Dart string
// counts). Length is the match's length in the same units.
Part int `json:"part,omitempty"`
Offset int `json:"offset,omitempty"`
Length int `json:"length,omitempty"`
}
// SearchChatTarget is a chat hit's target token.
+1 -1
View File
@@ -173,7 +173,7 @@ func TestChatBackgroundTasksKeepUnattendedRoom(t *testing.T) {
if tasks > 0 {
h.turnLocked(id).applyShell(&protocol.ChatShell{ID: "sh_1", Status: protocol.ChatShellRunning})
}
sub := &chatSub{hub: h, room: room, clientID: "c", ch: make(chan protocol.Message, 1), done: make(chan struct{})}
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)
+4 -6
View File
@@ -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)})
}()
}
+4 -6
View File
@@ -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
@@ -288,10 +287,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,
})
@@ -299,7 +299,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})
}
+1
View File
@@ -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
+4 -4
View File
@@ -35,7 +35,7 @@ func (h *chatHub) replayCompaction(sub *chatSub) {
}
h.mu.Unlock()
if slow {
sub.close()
sub.overflow()
}
}
@@ -56,9 +56,9 @@ func (h *chatHub) clearCompactionLocked(room *chatRoom) {
}
for _, sub := range room.subs {
if !enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &frame}) {
// close detaches under h.mu; never block the folding lock. A full
// queue must reconnect rather than silently miss terminal cleanup.
go sub.close()
// overflow detaches under h.mu; never block the folding lock. A
// full queue must resync rather than silently miss terminal cleanup.
go sub.overflow()
}
}
}
+16 -16
View File
@@ -14,63 +14,63 @@ func TestCompactionRetainedReplayIsolationAndTerminalClear(t *testing.T) {
room.running, room.nativeTurnID = true, "turn_new"
room.turnDone = make(chan struct{})
h.rooms[room.sessionID] = room
sub := &chatSub{hub: h, room: room, clientID: "watcher", ch: make(chan protocol.Message, 32), done: make(chan struct{})}
sub := &chatSub{hub: h, room: room, clientID: "watcher", limit: 32, done: make(chan struct{})}
room.subs[sub.clientID] = sub
emit := func(id, status, nativeID string) {
h.emitRoom(room, protocol.ChatEventFrame{SessionID: room.sessionID, NativeTurnID: nativeID, Kind: protocol.ChatEventCompaction, Compaction: &protocol.ChatCompaction{ID: id, Status: status}})
}
emit("old", "running", "turn_old")
if len(sub.ch) != 0 {
if sub.queued() != 0 {
t.Fatal("old native turn surfaced")
}
emit("first", "running", "turn_new")
<-sub.ch
sub.take()
if got := h.snapshot(room.sessionID); len(got) != 0 {
t.Fatalf("fake message: %+v", got)
}
h.replayCompaction(sub)
if f := (<-sub.ch).ChatEvent; f == nil || f.Compaction.ID != "first" || f.MessageID != "" {
if f := (sub.take()).ChatEvent; f == nil || f.Compaction.ID != "first" || f.MessageID != "" {
t.Fatalf("replay without assistant: %+v", f)
}
other := newChatRoom(context.Background(), "ses_other")
defer other.cancel()
h.rooms[other.sessionID] = other
otherSub := &chatSub{hub: h, room: other, clientID: "other", ch: make(chan protocol.Message, 4), done: make(chan struct{})}
otherSub := &chatSub{hub: h, room: other, clientID: "other", limit: 4, done: make(chan struct{})}
other.subs[otherSub.clientID] = otherSub
h.replayCompaction(otherSub)
if len(otherSub.ch) != 0 {
if otherSub.queued() != 0 {
t.Fatal("foreign-session replay")
}
resetOld := h.compactionReset(room.sessionID)
emit("second", "running", "turn_new")
<-sub.ch
sub.take()
resetOld()
emit("first", "completed", "turn_new")
if len(sub.ch) != 0 || h.turns[room.sessionID].compaction.ID != "second" {
if sub.queued() != 0 || h.turns[room.sessionID].compaction.ID != "second" {
t.Fatal("old lifecycle cleared newer compaction")
}
h.emitRoom(room, protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, Intermediate: true}})
<-sub.ch
sub.take()
if h.turns[room.sessionID].compaction == nil || !room.running {
t.Fatal("provider step settled compaction or turn")
}
emit("second", "completed", "turn_new")
<-sub.ch
sub.take()
if !room.running {
t.Fatal("compaction completion released turn queue")
}
emit("third", "running", "turn_new")
<-sub.ch
sub.take()
h.emitRoom(room, protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: "turn_new"}})
if f := (<-sub.ch).ChatEvent; f.Compaction == nil || f.Compaction.Status != "failed" {
if f := (sub.take()).ChatEvent; f.Compaction == nil || f.Compaction.Status != "failed" {
t.Fatalf("terminal cleanup: %+v", f)
}
<-sub.ch // authoritative step completion
sub.take() // authoritative step completion
if room.running || h.turns[room.sessionID].compaction != nil {
t.Fatal("terminal state stuck")
}
emit("third", "running", "turn_new")
if len(sub.ch) != 0 {
if sub.queued() != 0 {
t.Fatal("late old-turn activity revived label")
}
}
@@ -83,10 +83,10 @@ func TestCompactionTransportLossAndInterruptClearDoNotReleaseTurn(t *testing.T)
defer room.cancel()
h.rooms[room.sessionID] = room
room.running = true
sub := &chatSub{hub: h, room: room, clientID: "watcher", ch: make(chan protocol.Message, 8), done: make(chan struct{})}
sub := &chatSub{hub: h, room: room, clientID: "watcher", limit: 8, done: make(chan struct{})}
room.subs[sub.clientID] = sub
h.emitRoom(room, protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventCompaction, Compaction: &protocol.ChatCompaction{Status: "running", ID: "compact"}})
<-sub.ch
sub.take()
switch mode {
case "interrupt":
h.compactionReset(room.sessionID)()
+5 -2
View File
@@ -294,8 +294,11 @@ func (h *chatHub) endObservedTurnLocked(room *chatRoom) {
h.finishTurnLocked(room)
resync := protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventResync}
for _, sub := range room.subs {
enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &resync})
enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &end})
if !enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &resync}) ||
!enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &end}) {
// overflow detaches under h.mu: never from inside the fold lock.
go sub.overflow()
}
}
}
+4 -1
View File
@@ -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{}
@@ -409,7 +412,7 @@ func (h *chatHub) replayUsage(sub *chatSub) {
}
h.mu.Unlock()
if slow {
sub.close()
sub.overflow()
}
}
+90
View File
@@ -0,0 +1,90 @@
package server
import (
"context"
"path/filepath"
"sync"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// reportingChat is an observedChat that also reports its turn state without
// I/O, as Claude Code does.
type reportingChat struct {
*observedChat
rmu sync.Mutex
running bool
}
func (c *reportingChat) TurnRunning(string) bool {
c.rmu.Lock()
defer c.rmu.Unlock()
return c.running
}
// Prompt starts a turn, as Claude Code's does before it returns.
func (c *reportingChat) Prompt(ctx context.Context, sessionID, text string) error {
if err := c.observedChat.Prompt(ctx, sessionID, text); err != nil {
return err
}
c.setRunning(true)
return nil
}
func (c *reportingChat) setRunning(running bool) {
c.rmu.Lock()
c.running = running
c.rmu.Unlock()
}
// The live incident: a Claude turn's end frame was dropped on the way (a full
// watcher buffer), so the room's own turn stayed "working" forever and every
// later prompt queued behind it. Once the harness reports itself idle for the
// settle period and its probe agrees, the turn is ended, the client told to
// resync, and the queued prompt delivered. While it reports running, it waits.
func TestChatRunnerEndsItsTurnWhoseEndFrameWasLost(t *testing.T) {
fastUnattended(t)
fastStaleTurnSettle(t)
t.Setenv("PIPELINES_NTFY_URL", "")
store := openQueueStore(t, filepath.Join(t.TempDir(), "queue.db"))
broker := &reportingChat{observedChat: newObservedChat()}
server := startQueueServer(t, broker, store)
conn := dialChatConn(t, server.ctx, server.srv)
broker.setProbe(true)
sendPrompt(t, server.ctx, conn, "p1", "build it", "op-1")
waitFor(t, "first prompt", func() bool { return broker.promptCount() == 1 })
broker.push(stepFrameFor(protocol.ChatStepStarted, "turn_1"))
waitStepFrame(t, server.ctx, conn, protocol.ChatStepStarted, "turn_1")
if ack := sendPrompt(t, server.ctx, conn, "p2", "continue", "op-2"); !ack.ChatQueued {
t.Fatalf("second prompt was not queued behind the running turn: %+v", ack)
}
time.Sleep(4 * chatQueueStaleTurnSettle)
if n := broker.promptCount(); n != 1 {
t.Fatalf("prompt delivered while the harness reports its turn running: %v", broker.promptTexts())
}
// The turn ends in the harness, but its end frame never arrives.
broker.setRunning(false)
broker.setProbe(false)
sawResync := false
for {
message := readChatMessage(t, server.ctx, conn)
if message.Type != protocol.ChatEvent || message.ChatEvent == nil {
continue
}
if message.ChatEvent.Kind == protocol.ChatEventResync {
sawResync = true
}
if step := message.ChatEvent.Step; step != nil && step.Status == protocol.ChatStepEnded && step.TurnID == "turn_1" {
break
}
}
if !sawResync {
t.Fatal("the client was not told to resync after the lost end")
}
waitFor(t, "queued prompt delivered after the lost end", func() bool { return broker.promptCount() == 2 })
if texts := broker.promptTexts(); texts[1] != "continue" {
t.Fatalf("delivered = %v", texts)
}
}
+14
View File
@@ -834,6 +834,20 @@ func (m *chatManager) TurnRunning(sessionID string) bool {
return ok && reporter.TurnRunning(sessionID)
}
// TracksTurnState reports whether the routed harness reports its own turn
// state through TurnRunning (Claude Code does; OpenCode and Codex are probed).
func (m *chatManager) TracksTurnState(sessionID string) bool {
m.mu.Lock()
backend := m.cache[sessionID]
m.mu.Unlock()
adapter := m.opencode
if backend != "" && backend != "opencode" {
adapter = m.attached(backend)
}
_, ok := adapter.(chatTurnReporter)
return ok
}
// ProbeTurn asks the session's own harness whether a turn is in flight. It is
// the server-start probe (chat_unattended.go): a harness that can be asked
// (OpenCode, Codex) is asked; otherwise its in-memory state is used, which for
+2 -1
View File
@@ -313,8 +313,9 @@ func TestChatFanoutToSeveralClients(t *testing.T) {
name string
conn *websocket.Conn
}{{"phone", phone}, {"tablet", tablet}} {
// Deltas still queued for a client may arrive joined into one frame.
var text strings.Builder
for i := 0; i < 2; i++ {
for i := 0; text.Len() < len("hello"); i++ {
frame := nextEvent(t, ctx, client.conn)
if frame.Kind != protocol.ChatEventText {
t.Fatalf("%s frame %d = %+v, want text", client.name, i, frame)
+128
View File
@@ -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()
}
}
+61
View File
@@ -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)
}
}
+101 -39
View File
@@ -190,6 +190,22 @@ func errChatQueueFull(sessionID string) error {
return errors.New("session " + sessionID + " already has the maximum number of prompts queued")
}
// chatTurnTracker is implemented by a broker that routes to several harnesses
// and knows whether the one serving a session reports its own turn state.
type chatTurnTracker interface {
TracksTurnState(sessionID string) bool
}
// brokerTracksTurns reports whether brokerTurnRunning's answer for sessionID
// comes from a harness that tracks its turn, rather than a constant false.
func brokerTracksTurns(broker chatBroker, sessionID string) bool {
if tracker, ok := broker.(chatTurnTracker); ok {
return tracker.TracksTurnState(sessionID)
}
_, ok := broker.(chatTurnReporter)
return ok
}
// brokerTurnRunning asks a harness that knows its own turn state without I/O.
func brokerTurnRunning(broker chatBroker, sessionID string) bool {
reporter, ok := broker.(chatTurnReporter)
@@ -221,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,
@@ -239,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
@@ -253,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))
@@ -411,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 })
}
+276 -38
View File
@@ -46,17 +46,29 @@ const (
// chatSub is one client's attachment to a session's shared stream. Frames reach
// it through a dedicated writer goroutine so a slow or broken client never stalls
// the turn or the other subscribers; the buffered channel bounds how far behind
// it may fall.
// the turn or the other subscribers; the bounded queue limits how far behind it
// may fall. Consecutive text or reasoning deltas of one part are joined in the
// queue, so a streaming burst takes one slot. A client that still falls behind
// is detached, and its writer ends the stream with a resync frame so the client
// re-attaches and re-reads the authoritative history instead of silently
// missing frames.
type chatSub struct {
hub *chatHub
room *chatRoom
clientID string
label string
ch chan protocol.Message
done chan struct{}
once sync.Once
write func(protocol.Message) error
// qmu guards the queue. It is taken under h.mu (enqueue) and never
// takes h.mu itself.
qmu sync.Mutex
queue []protocol.Message
limit int // 0 means chatRoomSubscriberBuffer
ready chan struct{} // signalled when the queue gains a frame
overflowed bool
overOnce sync.Once
}
func (s *chatSub) run() {
@@ -64,28 +76,118 @@ func (s *chatSub) run() {
select {
case <-s.done:
return
case msg := <-s.ch:
if err := s.write(msg); err != nil {
s.close()
default:
}
msg, ok, overflowed := s.next()
if overflowed {
// The terminal frame: everything still queued was discarded, so
// the client must re-attach and re-read the history.
resync := protocol.ChatEventFrame{SessionID: s.room.sessionID, Kind: protocol.ChatEventResync}
_ = s.write(protocol.Message{Type: protocol.ChatEvent, ChatEvent: &resync})
s.close()
return
}
if !ok {
select {
case <-s.done:
return
case <-s.ready:
}
continue
}
if err := s.write(msg); err != nil {
s.close()
return
}
}
}
func (s *chatSub) send(msg protocol.Message) {
// next pops the oldest queued frame, or reports that the subscription
// overflowed.
func (s *chatSub) next() (protocol.Message, bool, bool) {
s.qmu.Lock()
defer s.qmu.Unlock()
if s.overflowed {
return protocol.Message{}, false, true
}
if len(s.queue) == 0 {
return protocol.Message{}, false, false
}
msg := s.queue[0]
s.queue[0] = protocol.Message{}
s.queue = s.queue[1:]
return msg, true, false
}
// queued is the number of frames waiting for the writer.
func (s *chatSub) queued() int {
s.qmu.Lock()
defer s.qmu.Unlock()
return len(s.queue)
}
// enqueue queues msg without blocking, joining it to the previous delta of the
// same part. It reports false when the queue is full; the caller must then
// call overflow, outside h.mu. It never detaches, so it may run under h.mu.
func (s *chatSub) enqueue(msg protocol.Message) bool {
select {
case <-s.done:
return
return true
default:
}
select {
case s.ch <- msg:
default:
// The client is not draining: drop it rather than block the fan-out. Its
// next attach re-syncs from history.
s.close()
s.qmu.Lock()
defer s.qmu.Unlock()
if s.overflowed {
return true // discarded: the client is told to resync
}
if n := len(s.queue); n > 0 {
if joined, ok := joinChatDeltas(s.queue[n-1], msg); ok {
s.queue[n-1] = joined
return true
}
}
limit := s.limit
if limit <= 0 {
limit = chatRoomSubscriberBuffer
}
if len(s.queue) >= limit {
return false
}
s.queue = append(s.queue, msg)
if s.ready != nil {
select {
case s.ready <- struct{}{}:
default:
}
}
return true
}
func (s *chatSub) send(msg protocol.Message) {
if !s.enqueue(msg) {
// The client is not draining: detach it rather than block the
// fan-out. Its writer tells it to resync.
s.overflow()
}
}
// overflow detaches a subscription whose client fell too far behind and lets
// its writer end the stream with a resync frame. Callers must not hold h.mu.
func (s *chatSub) overflow() {
s.overOnce.Do(func() {
s.qmu.Lock()
s.overflowed = true
s.queue = nil
if s.ready != nil {
select {
case s.ready <- struct{}{}:
default:
}
}
s.qmu.Unlock()
log.Printf("chat session %s: client %s fell %d frames behind; it is told to resync", s.room.sessionID, s.clientID, chatRoomSubscriberBuffer)
s.hub.detach(s.room.sessionID, s)
})
}
// close detaches the subscription and stops its writer goroutine exactly once.
@@ -96,6 +198,61 @@ func (s *chatSub) close() {
})
}
// joinChatDeltas joins next onto last when both are plain text or reasoning
// deltas of the same part, so a burst takes one queue slot. Numbered deltas
// join only when consecutive; the joined frame names its first delta
// (SeqFrom) and each delta's length, so a client whose history page already
// holds a prefix can drop exactly that prefix.
func joinChatDeltas(last, next protocol.Message) (protocol.Message, bool) {
a, b := last.ChatEvent, next.ChatEvent
if last.Type != protocol.ChatEvent || next.Type != protocol.ChatEvent || a == nil || b == nil || last.ID != "" || next.ID != "" {
return last, false
}
if !plainChatDelta(a) || !plainChatDelta(b) || a.Kind != b.Kind || a.SessionID != b.SessionID || a.MessageID != b.MessageID ||
a.NativeTurnID != b.NativeTurnID || a.MessageKind != b.MessageKind || a.Part.ID != b.Part.ID || a.Part.Type != b.Part.Type {
return last, false
}
if (a.Seq == 0) != (b.Seq == 0) || (a.Seq != 0 && b.Seq != a.Seq+1) {
return last, false
}
joined := *a
part := *a.Part
joined.Part = &part
joined.Delta = a.Delta + b.Delta
if a.Seq != 0 {
lens := a.DeltaLens
if a.SeqFrom == 0 {
joined.SeqFrom = a.Seq
lens = []int{utf16Len(a.Delta)}
}
joined.DeltaLens = append(slices.Clip(lens), utf16Len(b.Delta))
joined.Seq = b.Seq
}
last.ChatEvent = &joined
return last, true
}
// plainChatDelta reports whether f carries only a text or reasoning delta.
func plainChatDelta(f *protocol.ChatEventFrame) bool {
return (f.Kind == protocol.ChatEventText || f.Kind == protocol.ChatEventReasoning) && f.Delta != "" && f.Part != nil &&
f.Part.Text == "" && f.Step == nil && f.Usage == nil && f.Shell == nil && f.Form == nil && f.Compaction == nil &&
len(f.Attachments) == 0 && f.Client == "" && f.OperationID == ""
}
// utf16Len is the length of s in UTF-16 code units, the unit a Dart client
// indexes strings by.
func utf16Len(s string) int {
n := 0
for _, r := range s {
if r >= 0x10000 {
n += 2
} else {
n++
}
}
return n
}
// chatQueuedPrompt is one prompt waiting for the session's in-flight turn to
// finish. acked marks a prompt the handler already acknowledged as queued, so the
// turn runner does not send a second (success) acknowledgement for the same
@@ -320,7 +477,6 @@ func (h *chatHub) attachSub(sessionID, clientID, label string, broker chatBroker
return nil, false
}
h.mu.Lock()
defer h.mu.Unlock()
room := h.roomLocked(sessionID)
if room.broker == nil {
room.broker = broker
@@ -336,21 +492,26 @@ func (h *chatHub) attachSub(sessionID, clientID, label string, broker chatBroker
room: room,
clientID: clientID,
label: label,
ch: make(chan protocol.Message, chatRoomSubscriberBuffer),
ready: make(chan struct{}, 1),
done: make(chan struct{}),
write: write,
}
room.subs[clientID] = sub
}
full := false
if replayTurn && (room.running || room.observedTurn || busy) {
// A fresh channel has room; an existing subscriber that cannot take
// it is already being dropped.
_ = enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &protocol.ChatEventFrame{
// A fresh queue always has room; an existing subscriber that cannot
// take it has fallen behind and is told to resync.
full = !enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &protocol.ChatEventFrame{
SessionID: sessionID,
Kind: protocol.ChatEventStep,
Step: &protocol.ChatStep{Status: protocol.ChatStepStarted},
}})
}
h.mu.Unlock()
if full {
sub.overflow()
}
return sub, !ok
}
@@ -424,7 +585,7 @@ func (h *chatHub) roomBacklog(sessionID string) int {
most := 0
if room := h.rooms[sessionID]; room != nil {
for _, sub := range room.subs {
most = max(most, len(sub.ch))
most = max(most, sub.queued())
}
}
return most
@@ -557,7 +718,7 @@ func (h *chatHub) emitRoom(source *chatRoom, frame protocol.ChatEventFrame) {
}
h.mu.Unlock()
for _, sub := range slow {
sub.close()
sub.overflow()
}
return
}
@@ -571,19 +732,10 @@ func (h *chatHub) emitRoom(source *chatRoom, frame protocol.ChatEventFrame) {
}
}
// enqueueChatLocked never blocks or calls detach under the hub mutex.
// enqueueChatLocked never blocks or calls detach under the hub mutex. A false
// result means the client overflowed: call sub.overflow once h.mu is released.
func enqueueChatLocked(sub *chatSub, msg protocol.Message) bool {
select {
case <-sub.done:
return true
default:
}
select {
case sub.ch <- msg:
return true
default:
return false
}
return sub.enqueue(msg)
}
func (h *chatHub) replayShells(sub *chatSub) {
@@ -602,7 +754,7 @@ func (h *chatHub) replayShells(sub *chatSub) {
}
h.mu.Unlock()
if slow {
sub.close()
sub.overflow()
}
}
@@ -689,7 +841,7 @@ func (h *chatHub) flushBuffered(sessionID string) {
}
h.mu.Unlock()
for _, sub := range slow {
sub.close()
sub.overflow()
}
}
@@ -934,10 +1086,96 @@ func (h *chatHub) runTurn(room *chatRoom, p *chatQueuedPrompt, done chan struct{
// Start the approval poller once, after the first ack, so a pending request
// is surfaced after the prompt is acknowledged and shared with every client.
h.startRoomPoller(room, broker)
select {
case <-done:
case <-room.ctx.Done():
h.awaitTurnEnd(room, broker, done)
}
// awaitTurnEnd waits for the turn runner's turn to end. Its end normally
// arrives as a step frame; the safety net covers an end that was lost on the
// way (a full watcher buffer, a stream that reconnected): once a harness that
// tracks its own turn state has reported itself idle for the settle period
// (chatQueueStaleTurnSettle) and its own probe confirms no turn is in flight,
// the turn is ended here and attached clients re-read the history. A harness
// that cannot report or be probed is never second-guessed.
func (h *chatHub) awaitTurnEnd(room *chatRoom, broker chatBroker, done chan struct{}) {
prober, probes := broker.(chatTurnProber)
if !probes || !brokerTracksTurns(broker, room.sessionID) {
select {
case <-done:
case <-room.ctx.Done():
}
return
}
settle := h.unattended.staleTurn
if settle <= 0 {
settle = 10 * time.Second
}
ticker := time.NewTicker(min(chatQueueBusyPoll, settle/4))
defer ticker.Stop()
var idleSince time.Time
for {
select {
case <-done:
return
case <-room.ctx.Done():
return
case <-ticker.C:
}
if brokerTurnRunning(broker, room.sessionID) {
idleSince = time.Time{}
continue
}
now := h.clock()
if idleSince.IsZero() {
idleSince = now
}
if now.Sub(idleSince) < settle {
continue
}
probeCtx, cancel := context.WithTimeout(room.ctx, 5*time.Second)
busy, err := prober.ProbeTurn(probeCtx, room.sessionID)
cancel()
if err != nil || busy {
// Look again only after another settle period.
idleSince = h.clock()
continue
}
if h.endLostTurn(room, done, now.Sub(idleSince)) {
return
}
}
}
// endLostTurn ends the runner's turn whose end frame never arrived, exactly
// as that frame would have, and asks attached clients to resync. It reports
// false when the turn already ended (or the room was released) meanwhile.
func (h *chatHub) endLostTurn(room *chatRoom, done chan struct{}, idle time.Duration) bool {
h.mu.Lock()
if h.rooms[room.sessionID] != room || room.ctx.Err() != nil || room.turnDone != done {
h.mu.Unlock()
return true
}
log.Printf("chat session %s: the harness reports no turn running for %s but the turn %q never reported its end; ending it",
room.sessionID, idle.Round(time.Second), room.nativeTurnID)
end := protocol.ChatEventFrame{SessionID: room.sessionID, NativeTurnID: room.nativeTurnID, Kind: protocol.ChatEventStep,
Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: room.nativeTurnID}}
priorStep := h.turnLocked(room.sessionID).step
h.applyLocked(end)
h.noteTurnDiffLocked(room, end)
h.noteReplyAttentionLocked(priorStep, end)
h.finishTurnLocked(room)
resync := protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventResync}
var slow []*chatSub
for _, sub := range room.subs {
if !enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &resync}) ||
!enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &end}) {
slow = append(slow, sub)
}
}
h.mu.Unlock()
for _, sub := range slow {
sub.overflow()
}
return true
}
// endRoomTurn releases the turn slot after a prompt that never entered flight,
+125
View File
@@ -0,0 +1,125 @@
package server
import (
"strings"
"sync"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// take pops the oldest queued frame (the zero Message when none is queued).
func (s *chatSub) take() protocol.Message {
msg, _, _ := s.next()
return msg
}
func deltaMessage(seq int64, delta string) protocol.Message {
frame := protocol.ChatEventFrame{SessionID: "ses_1", MessageID: "msg_1", Kind: protocol.ChatEventText, Delta: delta, Seq: seq,
Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "msg_1-text-0"}}
return protocol.Message{Type: protocol.ChatEvent, ChatEvent: &frame}
}
// A streaming burst must not overflow a client that is merely a little slow:
// consecutive deltas of one part take one queue slot, and the joined frame
// says which numbered deltas it holds and how long each one is.
func TestChatSubJoinsConsecutiveDeltasOfOnePart(t *testing.T) {
sub := &chatSub{limit: 2, done: make(chan struct{})}
pieces := []string{"héllo ", "wörld ", "😀!"}
for i, piece := range pieces {
if !sub.enqueue(deltaMessage(int64(10+i), piece)) {
t.Fatalf("delta %d overflowed a two-slot queue", i)
}
}
if sub.queued() != 1 {
t.Fatalf("queued = %d, want the burst joined into one frame", sub.queued())
}
// A frame of another kind is never joined.
step := protocol.ChatEventFrame{SessionID: "ses_1", Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded}}
if !sub.enqueue(protocol.Message{Type: protocol.ChatEvent, ChatEvent: &step}) {
t.Fatal("step frame refused")
}
if sub.enqueue(deltaMessage(13, "late")) {
t.Fatal("a delta after the step joined across it")
}
joined := sub.take().ChatEvent
if joined.Delta != strings.Join(pieces, "") || joined.SeqFrom != 10 || joined.Seq != 12 {
t.Fatalf("joined = %+v", joined)
}
if want := []int{6, 6, 3}; len(joined.DeltaLens) != 3 || joined.DeltaLens[0] != want[0] || joined.DeltaLens[1] != want[1] || joined.DeltaLens[2] != want[2] {
t.Fatalf("delta lengths = %v, want %v (UTF-16 units)", joined.DeltaLens, want)
}
// A gap in the numbering is never joined over.
sub2 := &chatSub{limit: 4, done: make(chan struct{})}
sub2.enqueue(deltaMessage(1, "a"))
sub2.enqueue(deltaMessage(3, "c"))
if sub2.queued() != 2 {
t.Fatal("deltas with a numbering gap were joined")
}
}
// The frame a delta came from is shared by every subscriber, so joining for
// one slow client must not change what another client is sent.
func TestChatSubJoinDoesNotMutateSharedFrames(t *testing.T) {
sub := &chatSub{limit: 4, done: make(chan struct{})}
first := deltaMessage(1, "a")
sub.enqueue(first)
sub.enqueue(deltaMessage(2, "b"))
if first.ChatEvent.Delta != "a" || first.ChatEvent.Seq != 1 || first.ChatEvent.SeqFrom != 0 {
t.Fatalf("shared frame mutated: %+v", first.ChatEvent)
}
}
// The live incident: a slow client's 64-frame buffer filled and the server
// silently dropped its subscription, so the app kept showing a frozen
// transcript until the next reconnect. Now the client's last frame is a
// resync, which makes the app re-attach and re-read the history.
func TestChatSubOverflowEndsWithAResyncFrame(t *testing.T) {
h := newChatHub()
h.mu.Lock()
room := h.roomLocked("ses_1")
h.mu.Unlock()
defer room.cancel()
release := make(chan struct{})
var mu sync.Mutex
var written []protocol.Message
write := func(msg protocol.Message) error {
<-release // the client does not read until the burst is over
mu.Lock()
written = append(written, msg)
mu.Unlock()
return nil
}
sub := h.attach("ses_1", "slow", "Phone", nil, write)
for i := range chatRoomSubscriberBuffer + 8 {
// Tool frames never join, so the queue fills.
frame := protocol.ChatEventFrame{SessionID: "ses_1", MessageID: "msg_1", Kind: protocol.ChatEventTool,
Part: &protocol.ChatPart{Type: protocol.ChatPartTool, ID: "tool", Name: strings.Repeat("x", i%3+1)}}
h.fanout("ses_1", protocol.Message{Type: protocol.ChatEvent, ChatEvent: &frame}, "")
}
h.mu.Lock()
attached := room.subs["slow"] == sub
h.mu.Unlock()
if attached {
t.Fatal("an overflowed client stayed attached")
}
close(release)
select {
case <-sub.done:
case <-time.After(5 * time.Second):
t.Fatal("the overflowed subscription never closed")
}
mu.Lock()
defer mu.Unlock()
last := written[len(written)-1]
if last.Type != protocol.ChatEvent || last.ChatEvent == nil || last.ChatEvent.Kind != protocol.ChatEventResync || last.ChatEvent.SessionID != "ses_1" {
t.Fatalf("the overflowed client's last frame was %+v, want a resync", last)
}
// The client re-attaches with its own subscribe: a fresh subscription.
again := h.attach("ses_1", "slow", "Phone", nil, func(protocol.Message) error { return nil })
if again == nil || again == sub {
t.Fatal("re-attaching after an overflow did not create a fresh subscription")
}
again.close()
}
+7 -4
View File
@@ -549,10 +549,12 @@ func TestChatPromptStreamsEvents(t *testing.T) {
t.Fatalf("ack = %+v", ack)
}
frames := readChatTurn(t, ctx, conn)
if len(frames) != 4 {
t.Fatalf("got %d frames, want 4", len(frames))
// The two text deltas may arrive joined into one frame.
if len(frames) != 4 && len(frames) != 3 {
t.Fatalf("got %d frames, want 4 (or 3 with the deltas joined)", len(frames))
}
sawText, sawStep := false, false
var text strings.Builder
for _, frame := range frames {
if frame.SessionID != "ses_1" || frame.MessageID != "msg_1" {
t.Fatalf("frame missing stable ids: %+v", frame)
@@ -560,6 +562,7 @@ func TestChatPromptStreamsEvents(t *testing.T) {
switch frame.Kind {
case protocol.ChatEventText:
sawText = true
text.WriteString(frame.Delta)
case protocol.ChatEventStep:
sawStep = true
if frame.Step == nil || frame.Step.Status != protocol.ChatStepEnded {
@@ -567,8 +570,8 @@ func TestChatPromptStreamsEvents(t *testing.T) {
}
}
}
if !sawText || !sawStep {
t.Fatalf("missing text or step frame: %+v", frames)
if !sawText || !sawStep || text.String() != "hello world" {
t.Fatalf("missing text or step frame (text %q): %+v", text.String(), frames)
}
if prompts, _, _ := broker.counts(); prompts != 1 {
t.Fatalf("prompt forwarded %d times, want 1", prompts)
+15 -4
View File
@@ -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
+40 -4
View File
@@ -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,11 +369,11 @@ 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
sub := &chatSub{hub: h, room: room, clientID: "c", ch: make(chan protocol.Message, 1), done: make(chan struct{})}
room.observedTurn = 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)
+7 -7
View File
@@ -15,20 +15,20 @@ func TestUsageRetainedWithoutMessageReplayResetAndAdmissionIsolation(t *testing.
room.nativeTurnID = "turn_keep"
room.turnDone = make(chan struct{})
h.rooms[room.sessionID] = room
sub := &chatSub{hub: h, room: room, clientID: "watcher", ch: make(chan protocol.Message, 32), done: make(chan struct{})}
sub := &chatSub{hub: h, room: room, clientID: "watcher", limit: 32, done: make(chan struct{})}
room.subs[sub.clientID] = sub
h.apply(protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventCompaction, Compaction: &protocol.ChatCompaction{Status: "running"}})
for _, n := range []int64{123, 123, 0, 5} {
total := n
u := &protocol.ChatUsage{Scope: "session", TotalTokens: &total}
h.emitRoom(room, protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventUsage, Usage: u})
live := (<-sub.ch).ChatEvent
live := (sub.take()).ChatEvent
if live.MessageID != "" || *live.Usage.TotalTokens != n {
t.Fatalf("live=%+v", live)
}
total = 999 // producer-owned data must not mutate retained state
h.replayUsage(sub)
frame := (<-sub.ch).ChatEvent
frame := (sub.take()).ChatEvent
if frame == nil || frame.Kind != protocol.ChatEventUsage || frame.MessageID != "" || frame.Usage.TotalTokens == nil || *frame.Usage.TotalTokens != n {
t.Fatalf("replay=%+v", frame)
}
@@ -47,18 +47,18 @@ func TestUsageRetainedWithoutMessageReplayResetAndAdmissionIsolation(t *testing.
}
// A full snapshot may legitimately reset every unknown field to nil.
h.emitRoom(room, protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventUsage, Usage: &protocol.ChatUsage{Scope: "session"}})
<-sub.ch
sub.take()
h.replayUsage(sub)
if f := (<-sub.ch).ChatEvent; f.Usage.TotalTokens != nil {
if f := (sub.take()).ChatEvent; f.Usage.TotalTokens != nil {
t.Fatal("unknown snapshot accumulated old counter")
}
other := newChatRoom(context.Background(), "ses_other")
defer other.cancel()
h.rooms[other.sessionID] = other
otherSub := &chatSub{hub: h, room: other, clientID: "other", ch: make(chan protocol.Message, 4), done: make(chan struct{})}
otherSub := &chatSub{hub: h, room: other, clientID: "other", limit: 4, done: make(chan struct{})}
other.subs[otherSub.clientID] = otherSub
h.replayUsage(otherSub)
if len(otherSub.ch) != 0 {
if otherSub.queued() != 0 {
t.Fatal("foreign usage replayed")
}
}
@@ -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 {
+60 -2
View File
@@ -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.
+34
View File
@@ -194,6 +194,40 @@ func TestStageRunWithHarnessGoneFallsBackWithReason(t *testing.T) {
}
}
// TestUninterruptibleStageSessionInterruptsOnlyItsRun: one stage session that
// start-up cannot confirm stopped (a crashed Pi owner, a missing Claude
// evidence directory) used to fail the whole runner, disabling every run.
// Now only its run is interrupted, naming why, and the runner starts.
func TestUninterruptibleStageSessionInterruptsOnlyItsRun(t *testing.T) {
seamRestartRecovery(t, nil)
interruptRecoveredSession = func(context.Context, pipeline.SessionOwner) error {
return fmt.Errorf("retained Pi owner: %w", stage.ErrStageCleanup)
}
f := stopMidStage(t, func(ctx context.Context, s *pipeline.Store, id int64) (stage.Result, error) {
if err := s.RunSession(context.Background(), id, 1, "ses_pi", true, "pi", "/nonexistent/pi-ref"); err != nil {
return stage.Result{}, err
}
<-ctx.Done()
return stage.Result{}, stage.ErrDetached
})
r, s := f.restart(t, func(context.Context, *pipeline.Store, stage.Definition) (stage.Result, error) {
t.Error("an interrupted run executed again")
return stage.Result{}, nil
})
r.reattachRuns()
r.wg.Wait()
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 confirmed stopped") || !strings.Contains(d.Diagnostic, "ses_pi") {
t.Fatalf("uninterruptible session's run lacks a clear reason: status=%s run=%q", d.Status, d.Diagnostic)
}
if owners, _ := s.ActiveSessionOwners(context.Background()); len(owners) != 0 {
t.Fatalf("the interrupted run's session still blocks recovery at the next start: %+v", owners)
}
}
// TestStageNotYetAdmittedStartsAgainAfterRestart: a visit the stopped server
// had begun but not handed to any session is started again, nothing replayed.
func TestStageNotYetAdmittedStartsAgainAfterRestart(t *testing.T) {
+33 -4
View File
@@ -1,6 +1,7 @@
package server
import (
"log"
"sync"
"time"
@@ -90,6 +91,11 @@ type runSubscription struct {
mu sync.Mutex
snapshotting bool
pending []protocol.Message
// overflowed is closed once the subscriber fell too far behind: it is
// already detached, and its writer ends the stream with runs_resync.
overflowed chan struct{}
overOnce sync.Once
}
func newRunEventHub() *runEventHub {
@@ -129,6 +135,7 @@ func (h *runEventHub) subscribe(clientID, workspace string, runIDs []int64, writ
workspace: workspace,
ch: make(chan protocol.Message, runEventSubscriberBuffer),
done: make(chan struct{}),
overflowed: make(chan struct{}),
write: write,
snapshotting: true,
}
@@ -378,9 +385,19 @@ func (s *runSubscription) matches(workspace string, runID int64) bool {
func (s *runSubscription) run() {
for {
select {
case <-s.overflowed:
// The terminal frame: the frames still queued are discarded, so
// the client must subscribe again and re-read the runs.
_ = s.write(protocol.Message{Type: protocol.RunsResync})
s.close()
return
default:
}
select {
case <-s.done:
return
case <-s.overflowed:
case msg := <-s.ch:
if err := s.write(msg); err != nil {
s.close()
@@ -450,7 +467,7 @@ func (s *runSubscription) sendMessage(msg protocol.Message) {
// the snapshot and the ack are written directly by the subscriber.
if len(s.pending) >= runEventSubscriberBuffer {
s.mu.Unlock()
s.close()
s.overflow()
return
}
s.pending = append(s.pending, msg)
@@ -461,12 +478,24 @@ func (s *runSubscription) sendMessage(msg protocol.Message) {
select {
case s.ch <- msg:
default:
// The subscriber is not draining: drop it rather than block the
// producer. Its next subscribe re-syncs from a fresh snapshot.
s.close()
// The subscriber is not draining: detach it rather than block the
// producer. Its writer tells it to subscribe again for a fresh
// snapshot.
s.overflow()
}
}
// overflow detaches a subscriber that fell too far behind and lets its writer
// (started by ready, if the snapshot is still being written) end the stream
// with runs_resync.
func (s *runSubscription) overflow() {
s.overOnce.Do(func() {
close(s.overflowed)
log.Printf("run events: client %s fell %d frames behind; it is told to resync", s.clientID, runEventSubscriberBuffer)
s.hub.remove(s)
})
}
// close unregisters the subscription and stops its writer goroutine exactly
// once. It is safe to call from the writer goroutine, from unsubscribe and from
// the disconnect path.
@@ -0,0 +1,47 @@
package server
import (
"sync"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// A run subscriber that falls behind used to be dropped silently: the app's
// run list and open detail froze until the next reconnect. Now it is detached
// and its last frame is runs_resync, which makes the app subscribe again.
func TestRunSubscriptionOverflowEndsWithRunsResync(t *testing.T) {
h := newRunEventHub()
release := make(chan struct{})
var mu sync.Mutex
var written []protocol.Message
sub := h.subscribe("conn", "", nil, func(msg protocol.Message) error {
<-release
mu.Lock()
written = append(written, msg)
mu.Unlock()
return nil
})
sub.ready()
for i := range runEventSubscriberBuffer + 4 {
sub.send(protocol.RunEventFrame{RunID: int64(i + 1), Status: protocol.RunStatusRunning})
}
h.mu.Lock()
_, attached := h.subs[sub]
h.mu.Unlock()
if attached {
t.Fatal("an overflowed run subscriber stayed attached")
}
close(release)
select {
case <-sub.done:
case <-time.After(5 * time.Second):
t.Fatal("the overflowed subscription never closed")
}
mu.Lock()
defer mu.Unlock()
if last := written[len(written)-1]; last.Type != protocol.RunsResync {
t.Fatalf("the overflowed client's last frame was %q, want %q", last.Type, protocol.RunsResync)
}
}
+217 -69
View File
@@ -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.
@@ -152,7 +158,15 @@ func newRunnerReattaching(ctx context.Context, s *pipeline.Store, artifactsRoot
cancel()
}
if err != nil {
return nil, fmt.Errorf("cannot interrupt previously active agent %s: %w", owner.ID, err)
// One session that cannot be confirmed stopped must not disable
// every run: interrupt only its run, saying why, and go on.
reason := fmt.Sprintf("its previous %s stage agent (session %s) could not be confirmed stopped (%v); check for a leftover agent process before reusing the workspace", owner.Backend, owner.ID, err)
if prior := reasons[owner.RunID]; prior != "" {
reason = prior + "; " + reason
}
reasons[owner.RunID] = reason
log.Printf("run %d: cannot interrupt previously active agent %s: %v; the run is marked interrupted", owner.RunID, owner.ID, err)
continue
}
if err := s.ConfirmRecoveredSession(ctx, owner); err != nil {
return nil, err
@@ -175,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
}
@@ -326,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
@@ -428,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 {
@@ -527,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
}
@@ -576,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 {
@@ -1585,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 {
@@ -1637,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 {
+274
View File
@@ -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)
})
}
+2
View File
@@ -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 {
+77 -49
View File
@@ -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)
}
}
+14 -1
View File
@@ -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 {
+210
View File
@@ -0,0 +1,210 @@
package server
import (
"context"
"errors"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf16"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// Scoped chat search ("find in chat"): every occurrence of a query in one
// chat's message text, newest message first, paged. A client uses it to count
// and reach matches in history it has not loaded yet.
const (
// scopedChatPageMessages is how many messages one broker read returns.
scopedChatPageMessages = 200
// scopedChatMaxMessages bounds the messages one scoped request reads;
// a longer history continues through NextCursor.
scopedChatMaxMessages = 2000
)
// scopedChatBudget bounds how long one scoped request reads history before it
// replies with what it found and a cursor. A variable so a test can shorten it.
var scopedChatBudget = 2 * time.Second
// scopedChatSession returns the session id a chat search's Scope names, or ""
// when the request is not scoped.
func scopedChatSession(req protocol.SearchRequest) string {
scope := strings.TrimSpace(req.Scope)
if scope == "" {
return ""
}
return strings.TrimPrefix(scope, "chat:")
}
// scopedCursor is where a scoped search resumes: the broker's history cursor
// for a page (empty for the newest) and how many of that page's newest
// messages were already searched. It travels as "<skip>|<history cursor>"; a
// cursor without the separator is a chat_messages next_cursor.
type scopedCursor struct {
history string
skip int
}
func parseScopedCursor(value string) scopedCursor {
skip, history, found := strings.Cut(value, "|")
if !found {
return scopedCursor{history: value}
}
n, err := strconv.Atoi(skip)
if err != nil || n < 0 {
return scopedCursor{history: history}
}
return scopedCursor{history: history, skip: n}
}
func (c scopedCursor) String() string { return strconv.Itoa(c.skip) + "|" + c.history }
// searchChatScoped answers a scoped chat search. Results hold one hit per
// occurrence; a message's occurrences are never split across replies, so a
// reply may exceed the cap by one message's worth.
func searchChatScoped(ctx context.Context, req protocol.SearchRequest, broker chatBroker) (*protocol.SearchResponse, error) {
sessionID := scopedChatSession(req)
if !validChatSessionID(sessionID) {
return nil, errors.New("a valid chat session id is required in scope chat:<id>")
}
if broker == nil {
return nil, errors.New("chat is not configured on this server")
}
response := &protocol.SearchResponse{
Query: req.Query,
Kind: protocol.SearchKindChat,
Results: []protocol.SearchResult{},
Cap: chatSearchLimit(req.Limit),
ScanBoundBytes: protocol.SearchMaxScanBytes,
}
// Find matches the query as typed, spaces included, like the client's
// own matching of the loaded transcript.
query := []rune(req.Query)
if strings.TrimSpace(req.Query) == "" {
return response, nil
}
ctx, cancel := context.WithTimeout(ctx, scopedChatBudget)
defer cancel()
cursor := parseScopedCursor(req.Cursor)
for {
page, err := broker.Messages(ctx, sessionID, scopedChatPageMessages, cursor.history)
if err != nil {
if ctx.Err() != nil && response.ScannedMessages > 0 {
// Out of time: what was found stands; the client continues.
response.Truncated = true
response.NextCursor = cursor.String()
return response, nil
}
return nil, err
}
messages := page.Messages
for index := len(messages) - 1 - cursor.skip; index >= 0; index-- {
message := messages[index]
response.Results = append(response.Results, scopedMessageHits(sessionID, message, query, req.CaseSensitive)...)
response.ScannedMessages++
cursor.skip++
done := index == 0 && (!page.HasMore || page.NextCursor == "")
if done {
return response, nil
}
if len(response.Results) >= response.Cap ||
response.ScannedMessages >= scopedChatMaxMessages || ctx.Err() != nil {
response.Truncated = true
if index == 0 {
cursor = scopedCursor{history: page.NextCursor}
}
response.NextCursor = cursor.String()
return response, nil
}
}
if !page.HasMore || page.NextCursor == "" {
return response, nil
}
cursor = scopedCursor{history: page.NextCursor}
}
}
// scopedMessageHits is one hit per occurrence of query in message's text parts.
func scopedMessageHits(sessionID string, message protocol.ChatMessage, query []rune, caseSensitive bool) []protocol.SearchResult {
var hits []protocol.SearchResult
for partIndex, part := range message.Parts {
if part.Type != protocol.ChatPartText || part.Text == "" {
continue
}
for _, match := range runeMatches([]rune(part.Text), query, caseSensitive) {
hits = append(hits, protocol.SearchResult{
Kind: protocol.SearchKindChat,
Target: protocol.SearchChatTarget(sessionID),
Score: chatScoreMessage,
MatchedField: "message",
Chat: &protocol.SearchChat{
SessionID: sessionID,
MessageID: message.ID,
Role: message.Role,
Snippet: protocol.SearchSnippet(part.Text, string(query)),
Part: partIndex,
Offset: match.offset,
Length: match.length,
},
})
}
}
return hits
}
type runeMatch struct{ offset, length int }
// runeMatches finds the non-overlapping occurrences of query in text, folding
// case unless caseSensitive, and reports each in UTF-16 code units.
func runeMatches(text, query []rune, caseSensitive bool) []runeMatch {
if len(query) == 0 || len(query) > len(text) {
return nil
}
var matches []runeMatch
units := 0 // UTF-16 units before text[i]
for i := 0; i <= len(text)-len(query); {
if runesEqual(text[i:i+len(query)], query, caseSensitive) {
length := utf16RunesLen(text[i : i+len(query)])
matches = append(matches, runeMatch{offset: units, length: length})
units += length
i += len(query)
continue
}
units += utf16.RuneLen(text[i])
i++
}
return matches
}
func runesEqual(a, b []rune, caseSensitive bool) bool {
for i := range a {
if a[i] == b[i] {
continue
}
if caseSensitive || !foldEqual(a[i], b[i]) {
return false
}
}
return true
}
func foldEqual(a, b rune) bool {
if unicode.ToLower(a) == unicode.ToLower(b) {
return true
}
for folded := unicode.SimpleFold(a); folded != a; folded = unicode.SimpleFold(folded) {
if folded == b {
return true
}
}
return false
}
func utf16RunesLen(runes []rune) int {
n := 0
for _, r := range runes {
n += utf16.RuneLen(r)
}
return n
}
+147
View File
@@ -0,0 +1,147 @@
package server
import (
"context"
"fmt"
"strconv"
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// scopedHistoryChat serves one session's history oldest first in pages of the
// requested size; a cursor is the index one past the page's oldest message.
type scopedHistoryChat struct {
*fakeChat
messages []protocol.ChatMessage
}
func (c *scopedHistoryChat) Messages(_ context.Context, _ string, limit int, cursor string) (protocol.ChatHistoryPage, error) {
end := len(c.messages)
if cursor != "" {
n, err := strconv.Atoi(cursor)
if err != nil {
return protocol.ChatHistoryPage{}, err
}
end = n
}
start := max(end-limit, 0)
page := protocol.ChatHistoryPage{Messages: c.messages[start:end]}
if start > 0 {
page.HasMore = true
page.NextCursor = strconv.Itoa(start)
}
return page, nil
}
func pagedHistory(n int) []protocol.ChatMessage {
messages := make([]protocol.ChatMessage, n)
for i := range messages {
text := fmt.Sprintf("message %d", i)
if i%10 == 0 {
text = fmt.Sprintf("Needle %d and needle again", i)
}
messages[i] = chatText(fmt.Sprintf("m%d", i), protocol.ChatRoleAssistant, text)
}
return messages
}
func TestScopedChatSearchReturnsEveryOccurrenceNewestFirst(t *testing.T) {
broker := &scopedHistoryChat{fakeChat: scriptedChat(), messages: pagedHistory(450)}
response, err := searchChatScoped(context.Background(), protocol.SearchRequest{
Query: "needle", Kind: protocol.SearchKindChat, Scope: protocol.SearchChatScope("ses_a"), Limit: 200,
}, broker)
if err != nil {
t.Fatal(err)
}
if len(response.Results) != 90 || response.NextCursor != "" || response.Truncated {
t.Fatalf("results=%d cursor=%q truncated=%v", len(response.Results), response.NextCursor, response.Truncated)
}
first := response.Results[0].Chat
if first.MessageID != "m440" || first.Offset != 0 || first.Length != 6 {
t.Fatalf("first hit = %+v", first)
}
second := response.Results[1].Chat
if second.MessageID != "m440" || second.Offset != len("Needle 440 and ") {
t.Fatalf("second hit = %+v", second)
}
if last := response.Results[89].Chat; last.MessageID != "m0" {
t.Fatalf("last hit = %+v", last)
}
}
func TestScopedChatSearchPagesThroughCursor(t *testing.T) {
broker := &scopedHistoryChat{fakeChat: scriptedChat(), messages: pagedHistory(450)}
request := protocol.SearchRequest{Query: "needle", Kind: protocol.SearchKindChat, Scope: "chat:ses_a", Limit: 7}
var ids []string
for pages := 0; ; pages++ {
if pages > 50 {
t.Fatal("cursor never ended")
}
response, err := searchChatScoped(context.Background(), request, broker)
if err != nil {
t.Fatal(err)
}
for _, hit := range response.Results {
ids = append(ids, hit.Chat.MessageID)
}
if response.NextCursor == "" {
break
}
request.Cursor = response.NextCursor
}
if len(ids) != 90 {
t.Fatalf("hits across pages = %d", len(ids))
}
seen := map[string]int{}
for _, id := range ids {
seen[id]++
}
if len(seen) != 45 || seen["m0"] != 2 || seen["m440"] != 2 {
t.Fatalf("each needle message twice, got %v", seen)
}
}
func TestScopedChatSearchStartsAtHistoryCursorAndMatchesCase(t *testing.T) {
broker := &scopedHistoryChat{fakeChat: scriptedChat(), messages: pagedHistory(450)}
response, err := searchChatScoped(context.Background(), protocol.SearchRequest{
Query: "Needle", Kind: protocol.SearchKindChat, Scope: "chat:ses_a", Cursor: "250", CaseSensitive: true,
}, broker)
if err != nil {
t.Fatal(err)
}
if len(response.Results) != 25 || response.Results[0].Chat.MessageID != "m240" {
t.Fatalf("results=%d first=%+v", len(response.Results), response.Results[0].Chat)
}
}
func TestScopedChatSearchCountsUTF16Offsets(t *testing.T) {
matches := runeMatches([]rune("😀 Ünïcode ünïcode"), []rune("ÜNÏ"), false)
if len(matches) != 2 || matches[0].offset != 3 || matches[1].offset != 11 || matches[0].length != 3 {
t.Fatalf("matches = %+v", matches)
}
if got := runeMatches([]rune("aaaa"), []rune("aa"), true); len(got) != 2 {
t.Fatalf("overlapping matches counted: %+v", got)
}
}
func TestScopedChatSearchRejectsAnInvalidScope(t *testing.T) {
broker := &scopedHistoryChat{fakeChat: scriptedChat()}
if _, err := searchChatScoped(context.Background(), protocol.SearchRequest{Query: "x", Scope: "chat:../etc"}, broker); err == nil {
t.Fatal("invalid scope accepted")
}
}
func TestScopedChatSearchOverTheSocket(t *testing.T) {
broker := &transcriptChat{fakeChat: scriptedChat(), pages: map[string][]protocol.ChatMessage{}}
ctx, conn := chatSearchFixture(t, broker)
writeChat(t, ctx, conn, protocol.Message{Type: protocol.Search, ID: "scoped", Search: &protocol.SearchRequest{
Query: "flaky", Kind: protocol.SearchKindChat, Scope: "chat:ses_text",
}})
reply := readReply(t, ctx, conn, "scoped")
// transcriptChat refuses any page size but the global search's, so the
// scoped search's own read comes back as an error reply.
if reply.Type != protocol.Error {
t.Fatalf("reply = %+v", reply)
}
}
+7
View File
@@ -40,6 +40,13 @@ func isChatSearch(request protocol.Message) bool {
// chatSearchReply answers one kind=chat search request.
func chatSearchReply(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry) protocol.Message {
if scopedChatSession(*request.Search) != "" {
response, err := searchChatScoped(ctx, *request.Search, broker)
if err != nil {
return protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}
}
return protocol.Message{Type: protocol.SearchResults, ID: request.ID, SearchResults: response}
}
if registry == nil {
return protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat search unavailable: operator session registry is not configured on this server"}
}
+3
View File
@@ -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 {
+1
View File
@@ -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 {
+12 -3
View File
@@ -141,6 +141,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]
}
@@ -282,8 +283,11 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
// A chat search runs beside the read loop so its transcript readback
// never delays the run search sent with it; a newer one cancels the
// previous, whose reply the client would discard as stale anyway.
// A newer chat search replaces an older one of the same mode: the
// chat list's search and a find-in-chat search never cancel each other.
cancelChatSearch := func() {}
defer func() { cancelChatSearch() }()
cancelScopedChatSearch := func() {}
defer func() { cancelChatSearch(); cancelScopedChatSearch() }()
// Keystrokes and sizes take their own lane (terminal_lane.go), so
// they never wait behind a slow request read before them. The lane
// is drained before the deferred detaches above run.
@@ -309,9 +313,14 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
continue
}
if isChatSearch(request) {
cancelChatSearch()
searchCtx, cancel := context.WithCancel(connCtx)
cancelChatSearch = cancel
if scopedChatSession(*request.Search) != "" {
cancelScopedChatSearch()
cancelScopedChatSearch = cancel
} else {
cancelChatSearch()
cancelChatSearch = cancel
}
go func(request protocol.Message) {
defer cancel()
_ = write(chatSearchReply(searchCtx, request, options.Chat, registry))
+12 -2
View File
@@ -608,7 +608,9 @@ func piResult(data []byte) (string, error) {
}
// InterruptPi expires the retained lease. The explicit extension aborts tools and
// marks quiescence before shutting down; without that receipt recovery fails closed.
// marks quiescence before shutting down. An owner whose process and process
// group are both gone (a crash, a reboot) has nothing left to stop, so it
// counts as interrupted without that receipt; otherwise recovery fails closed.
func InterruptPi(ctx context.Context, reference string) error {
if !filepath.IsAbs(reference) {
return fmt.Errorf("invalid retained Pi reference")
@@ -623,6 +625,12 @@ func InterruptPi(ctx context.Context, reference string) error {
if json.Unmarshal(data, &owner) != nil || owner.PID <= 1 {
return errors.Join(fmt.Errorf("invalid retained Pi owner"), ErrStageCleanup)
}
gone := func() bool {
return errors.Is(syscall.Kill(owner.PID, 0), syscall.ESRCH) && errors.Is(syscall.Kill(-owner.PID, 0), syscall.ESRCH)
}
if gone() {
return nil
}
old := time.Unix(0, 0)
if err := os.Chtimes(filepath.Join(reference, "lease"), old, old); err != nil {
return err
@@ -630,7 +638,9 @@ func InterruptPi(ctx context.Context, reference string) error {
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
for {
if data, err := os.ReadFile(filepath.Join(reference, "quiescent")); err == nil && string(data) == "quiescent" && errors.Is(syscall.Kill(owner.PID, 0), syscall.ESRCH) && errors.Is(syscall.Kill(-owner.PID, 0), syscall.ESRCH) {
// The receipt is written just before a clean exit; a process that
// died without it is still gone.
if gone() {
return nil
}
select {
+28
View File
@@ -42,3 +42,31 @@ func TestPiReceiptRequiresProcessExit(t *testing.T) {
t.Fatal("confirmed process exit not accepted", err)
}
}
// A Pi owner that crashed never wrote its quiescence receipt; with its process
// and process group gone there is nothing left to stop, so recovery must not
// wait out its timeout and fail.
func TestPiOwnerGoneWithoutReceiptCountsAsInterrupted(t *testing.T) {
cmd := exec.Command("sleep", "5")
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
pid := cmd.Process.Pid
if err := cmd.Process.Kill(); err != nil {
t.Fatal(err)
}
cmd.Wait()
dir := t.TempDir()
owner, _ := json.Marshal(map[string]any{"pid": pid})
for name, data := range map[string][]byte{"owner.json": owner, "lease": []byte("lease")} {
if err := os.WriteFile(filepath.Join(dir, name), data, 0600); err != nil {
t.Fatal(err)
}
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if err := InterruptPi(ctx, dir); err != nil {
t.Fatal("a crashed owner was not accepted as gone:", err)
}
}