diff --git a/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart b/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart index 39b4bb54..8f375f96 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart @@ -143,6 +143,10 @@ class ChatSessionsController extends ChangeNotifier { /// Another device changed a chat's shared colour, star or title: the row /// takes the server's values at once, with no re-list. Each field the /// registry row omits is cleared, since omitted means unset on the wire. + /// The server sends these pushes concurrently, so they can arrive out of + /// order: one whose `revision` is older than the row held here is stale and + /// ignored (a row or push without a revision, from an older server, is + /// always applied). /// /// A row naming `previous_id` is a chat another device moved to a fresh /// session (`/new`): it replaces that row in place and [onSessionReplaced] @@ -165,8 +169,14 @@ class ChatSessionsController extends ChangeNotifier { if ('${row['id'] ?? ''}' == id) () { found = true; + if (chatSessionPushIsStale(row, changed)) return row; final next = {...row}; - for (final key in const ['color', 'starred', 'starred_at']) { + for (final key in const [ + 'color', + 'starred', + 'starred_at', + 'revision', + ]) { if (changed.containsKey(key)) { next[key] = changed[key]; } else { @@ -404,8 +414,14 @@ class ChatSessionsController extends ChangeNotifier { final runningRevision = _runningRevision; final sessions = await repository.sessions(); if (generation != _generation) return; + // A push applied while this list was read can be newer than its row. + final held = {for (final row in _sessions) '${row['id'] ?? ''}': row}; _sessions = [ - for (final row in sessions) _withActivity(row, runningRevision), + for (final row in sessions) + _withActivity( + newerChatSessionMetadata(row, held['${row['id'] ?? ''}']), + runningRevision, + ), ]; _seedLocal(); _loading = false; @@ -644,3 +660,41 @@ class ChatSessionsController extends ChangeNotifier { super.dispose(); } } + +/// The registry revision a chat list row or push carries; 0 when absent. +int chatSessionRevision(Map row) { + final value = row['revision']; + return value is num ? value.toInt() : 0; +} + +/// Whether [pushed] is older than [held]: both carry a revision and the +/// push's is lower. A push is never stale against a row with no revision. +bool chatSessionPushIsStale( + Map held, + Map pushed, +) { + final incoming = chatSessionRevision(pushed); + return incoming > 0 && incoming < chatSessionRevision(held); +} + +/// [fetched] with the shared metadata (colour, star, title, revision) of +/// [held] when [held] is newer: a list read that started before a push was +/// applied must not revert it. +JsonMap newerChatSessionMetadata(JsonMap fetched, JsonMap? held) { + if (held == null || !chatSessionPushIsStale(held, fetched)) return fetched; + final next = {...fetched}; + for (final key in const [ + 'color', + 'starred', + 'starred_at', + 'title', + 'revision', + ]) { + if (held.containsKey(key)) { + next[key] = held[key]; + } else { + next.remove(key); + } + } + return next; +} diff --git a/app/test/features/chat/ui/sessions/chat_color_test.dart b/app/test/features/chat/ui/sessions/chat_color_test.dart index 2c458222..017308a6 100644 --- a/app/test/features/chat/ui/sessions/chat_color_test.dart +++ b/app/test/features/chat/ui/sessions/chat_color_test.dart @@ -266,6 +266,45 @@ void main() { expect(gateway.count('chat_sessions'), lists); }); + test('a push older than the row held is ignored', () async { + JsonMap push(int revision, String color) => { + 'type': 'chat_session_changed', + 'chat_session': { + 'id': 's2', + 'title': 'Plain chat', + 'color': color, + 'revision': revision, + }, + }; + // The server sends pushes concurrently: revision 7 lands before 6. + gateway.pushed.add(push(7, 'pink')); + gateway.pushed.add(push(6, 'blue')); + await pumpEventQueue(); + expect(row('s2')['color'], 'pink'); + expect(row('s2')['revision'], 7); + gateway.pushed.add(push(8, 'amber')); + await pumpEventQueue(); + expect(row('s2')['color'], 'amber'); + // A list read older than the applied push does not revert it. + var listed = { + 'id': 's2', + 'title': 'Plain chat', + 'directory': '/w', + 'revision': 5, + }; + gateway.sessionsHandler = () async => { + 'chat_sessions': [listed], + }; + await controller.refresh(); + expect(row('s2')['color'], 'amber'); + expect(row('s2')['revision'], 8); + // A newer list row wins. + listed = {...listed, 'color': 'teal', 'revision': 9}; + await controller.refresh(); + expect(row('s2')['color'], 'teal'); + expect(row('s2')['revision'], 9); + }); + test('a refused colour is undone and the reason shown', () async { gateway.failures['chat_color'] = 'unknown chat colour'; await controller.setColor('s2', 'blue'); diff --git a/internal/pipeline/chat_notifications.go b/internal/pipeline/chat_notifications.go new file mode 100644 index 00000000..02e37544 --- /dev/null +++ b/internal/pipeline/chat_notifications.go @@ -0,0 +1,115 @@ +package pipeline + +import ( + "context" + "database/sql" + "errors" + "time" +) + +// ChatNotification is one chat phone push (ntfy) in the durable outbox. It +// follows the run notification outbox (run_notifications.go): a row is leased +// for a bounded attempt, a crash during a lease is recovered when the lease +// expires, and attempts are bounded. ID is the chat's app notification id, so +// an enqueue is idempotent and a notification the operator already cleared in +// the app is never published late. +type ChatNotification struct { + ID, SessionID, Title, Body, Click string + // SequenceID is the ntfy sequence id the push is published with (so a later + // clear dismisses it on the phone); "" publishes without one. + SequenceID string + Priority int + Attempts int +} + +// ChatNotificationAttempts bounds publication attempts per chat push. +const ChatNotificationAttempts = 5 + +// chatNotificationLease is how long one claimed attempt owns its row. +const chatNotificationLease = 60 + +// chatNotificationRetention bounds how long settled rows are kept. +const chatNotificationRetention = 7 * 24 * time.Hour + +func (s *Store) initChatNotifications() error { + _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS chat_notifications ( +id TEXT PRIMARY KEY, session_id TEXT NOT NULL, title TEXT NOT NULL, body TEXT NOT NULL, click TEXT NOT NULL, +sequence_id TEXT NOT NULL DEFAULT '', priority INTEGER NOT NULL DEFAULT 0, +status TEXT NOT NULL DEFAULT 'pending', attempts INTEGER NOT NULL DEFAULT 0, +next_attempt INTEGER NOT NULL DEFAULT 0, diagnostic TEXT NOT NULL DEFAULT '', message_id TEXT NOT NULL DEFAULT '', +created_at INTEGER NOT NULL); +CREATE INDEX IF NOT EXISTS chat_notifications_due ON chat_notifications(status,next_attempt);`) + return err +} + +// EnqueueChatNotification records one chat push once (by id) and prunes +// settled rows past retention. +func (s *Store) EnqueueChatNotification(ctx context.Context, n ChatNotification, now time.Time) error { + if _, err := s.db.ExecContext(ctx, `DELETE FROM chat_notifications WHERE created_at0)`, now); err != nil { + return nil, err + } + if _, err := s.db.ExecContext(ctx, `UPDATE chat_notifications SET status='failed',diagnostic='publisher acknowledgement unknown after final lease expired' +WHERE status='sending' AND attempts>=? AND next_attempt<=?`, ChatNotificationAttempts, now); err != nil { + return nil, err + } + n := new(ChatNotification) + err := s.db.QueryRowContext(ctx, `UPDATE chat_notifications SET status='sending',attempts=attempts+1,next_attempt=? +WHERE rowid=(SELECT rowid FROM chat_notifications WHERE status IN ('pending','sending') AND attempts= ChatNotificationAttempts { + status = "failed" + } + } + _, err := s.db.ExecContext(ctx, `UPDATE chat_notifications SET status=?,diagnostic=?,message_id=?,next_attempt=? +WHERE id=? AND status='sending' AND attempts=?`, status, diagnostic, messageID, next, n.ID, n.Attempts) + return err +} + +// ChatNotificationStatus reports one push's outbox status ("" when absent) +// and attempts. +func (s *Store) ChatNotificationStatus(ctx context.Context, id string) (string, int, error) { + var status string + var attempts int + err := s.db.QueryRowContext(ctx, `SELECT status,attempts FROM chat_notifications WHERE id=?`, id).Scan(&status, &attempts) + if errors.Is(err, sql.ErrNoRows) { + return "", 0, nil + } + return status, attempts, err +} + +// ChatNotificationCleared reports whether id's app notification has been +// cleared; a publication that raced a clear then clears the phone too. +func (s *Store) ChatNotificationCleared(ctx context.Context, id string) (bool, error) { + var cleared bool + err := s.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM app_notifications WHERE id=? AND cleared_at<>0)`, id).Scan(&cleared) + return cleared, err +} diff --git a/internal/pipeline/chat_notifications_test.go b/internal/pipeline/chat_notifications_test.go new file mode 100644 index 00000000..bef69429 --- /dev/null +++ b/internal/pipeline/chat_notifications_test.go @@ -0,0 +1,76 @@ +package pipeline + +import ( + "context" + "errors" + "path/filepath" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +func TestChatNotificationOutboxRetriesAndSkipsCleared(t *testing.T) { + ctx := context.Background() + s, err := Open(filepath.Join(t.TempDir(), "chat-outbox.db")) + if err != nil { + t.Fatal(err) + } + defer s.Close() + now := time.Unix(1000, 0) + n := ChatNotification{ID: "chat:ses_a:form:q1", SessionID: "ses_a", Title: "T", Body: "B", Click: "pipelines://chat/ses_a", SequenceID: "pl-1"} + for range 2 { // idempotent by id + if err := s.EnqueueChatNotification(ctx, n, now); err != nil { + t.Fatal(err) + } + } + first, err := s.ClaimChatNotification(ctx, 1000) + if err != nil || first == nil || first.Attempts != 1 || first.SequenceID != "pl-1" { + t.Fatalf("claim = %+v %v", first, err) + } + if again, err := s.ClaimChatNotification(ctx, 1000); err != nil || again != nil { + t.Fatalf("leased row claimed twice: %+v %v", again, err) + } + if err := s.FinishChatNotification(ctx, *first, 1000, "", errors.New("ntfy down")); err != nil { + t.Fatal(err) + } + if early, _ := s.ClaimChatNotification(ctx, 1004); early != nil { + t.Fatalf("retried before backoff: %+v", early) + } + second, err := s.ClaimChatNotification(ctx, 1005) + if err != nil || second == nil || second.Attempts != 2 { + t.Fatalf("retry claim = %+v %v", second, err) + } + if err := s.FinishChatNotification(ctx, *second, 1005, "m1", nil); err != nil { + t.Fatal(err) + } + if status, attempts, _ := s.ChatNotificationStatus(ctx, n.ID); status != "sent" || attempts != 2 { + t.Fatalf("status = %s/%d", status, attempts) + } + // A lease lost to a crash is reclaimed after it expires. + crashed := ChatNotification{ID: "chat:ses_a:form:q2", SessionID: "ses_a", Title: "T", Body: "B"} + _ = s.EnqueueChatNotification(ctx, crashed, now) + if c, _ := s.ClaimChatNotification(ctx, 2000); c == nil { + t.Fatal("no claim") + } + if c, _ := s.ClaimChatNotification(ctx, 2061); c == nil || c.Attempts != 2 { + t.Fatalf("expired lease not reclaimed: %+v", c) + } else if err := s.FinishChatNotification(ctx, *c, 2061, "m2", nil); err != nil { + t.Fatal(err) + } + // A push whose app notification was cleared first is never published. + cleared := ChatNotification{ID: "chat:ses_b:form:q3", SessionID: "ses_b", Title: "T", Body: "B"} + if _, _, err := s.RecordAppNotification(ctx, AppNotificationRecord{AppNotification: protocol.AppNotification{ID: cleared.ID, Kind: protocol.NotificationChatQuestion, Title: "T"}, SessionID: "ses_b"}, now); err != nil { + t.Fatal(err) + } + if _, err := s.ClearAppNotifications(ctx, []string{cleared.ID}, now); err != nil { + t.Fatal(err) + } + _ = s.EnqueueChatNotification(ctx, cleared, now) + if c, _ := s.ClaimChatNotification(ctx, 3000); c != nil { + t.Fatalf("cleared push claimed: %+v", c) + } + if status, _, _ := s.ChatNotificationStatus(ctx, cleared.ID); status != "cleared" { + t.Fatalf("cleared push status = %q", status) + } +} diff --git a/internal/pipeline/operator_sessions.go b/internal/pipeline/operator_sessions.go index b9d1469e..10d545b1 100644 --- a/internal/pipeline/operator_sessions.go +++ b/internal/pipeline/operator_sessions.go @@ -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) diff --git a/internal/pipeline/operator_sessions_test.go b/internal/pipeline/operator_sessions_test.go index 06140a79..ca5b98d6 100644 --- a/internal/pipeline/operator_sessions_test.go +++ b/internal/pipeline/operator_sessions_test.go @@ -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) + } +} diff --git a/internal/pipeline/runs_mutate.go b/internal/pipeline/runs_mutate.go index cefe4e2d..e1ad0efb 100644 --- a/internal/pipeline/runs_mutate.go +++ b/internal/pipeline/runs_mutate.go @@ -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 } diff --git a/internal/pipeline/runs_schema.go b/internal/pipeline/runs_schema.go index 900ad830..9766bc96 100644 --- a/internal/pipeline/runs_schema.go +++ b/internal/pipeline/runs_schema.go @@ -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)); diff --git a/internal/pipeline/runs_sessions.go b/internal/pipeline/runs_sessions.go index f566416f..5b83b96f 100644 --- a/internal/pipeline/runs_sessions.go +++ b/internal/pipeline/runs_sessions.go @@ -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() +} diff --git a/internal/pipeline/store.go b/internal/pipeline/store.go index e258892b..ae16e913 100644 --- a/internal/pipeline/store.go +++ b/internal/pipeline/store.go @@ -77,6 +77,10 @@ CREATE TABLE IF NOT EXISTS submissions (id INTEGER PRIMARY KEY, name TEXT NOT NU db.Close() return nil, err } + if err := s.initChatNotifications(); err != nil { + db.Close() + return nil, err + } if err := s.initSchedules(); err != nil { db.Close() return nil, err diff --git a/internal/protocol/chat.go b/internal/protocol/chat.go index f8252115..a054a4ff 100644 --- a/internal/protocol/chat.go +++ b/internal/protocol/chat.go @@ -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 diff --git a/internal/server/chat_attention.go b/internal/server/chat_attention.go index 22c5d058..b7e58d88 100644 --- a/internal/server/chat_attention.go +++ b/internal/server/chat_attention.go @@ -2,7 +2,6 @@ package server import ( "context" - "log" "net/url" "os" "strings" @@ -147,7 +146,8 @@ func (h *chatHub) clearChatAttention(sessionID, id string) { } // startChatAttention publishes asynchronously within the 30-second notification -// budget. It never blocks or fails chat handling; failures are only logged. +// budget. It never blocks or fails chat handling; the phone push goes through +// the durable outbox, which retries a failed attempt. func (h *chatHub) startChatAttention(a chatAttention) { base := h.baseCtx if base == nil { @@ -176,7 +176,7 @@ func (h *chatHub) startChatAttention(a chatAttention) { if a.reply { title, body = chatReplyText(name, a.body) } - click, views := chatAttentionLinks(a.sessionID) + click, _ := chatAttentionLinks(a.sessionID) kind := protocol.NotificationChatQuestion if a.reply { kind = protocol.NotificationChatReply @@ -192,9 +192,7 @@ func (h *chatHub) startChatAttention(a chatAttention) { return } // ntfy takes a single-line message of at most 2048 bytes. - if _, err := chatAttentionPublish(stage.WithNtfySequenceID(ctx, chatNtfySequence(a.id)), "system", title, truncateUTF8(singleLine(body), 2000), "", nil, click, views...); err != nil { - log.Printf("chat attention notification session=%s: %v", a.sessionID, err) - } + h.pushChatNtfy(ctx, pipeline.ChatNotification{ID: a.id, SessionID: a.sessionID, Title: title, Body: truncateUTF8(singleLine(body), 2000), Click: click, SequenceID: chatNtfySequence(a.id)}) }() } diff --git a/internal/server/chat_auto_switch.go b/internal/server/chat_auto_switch.go index fea5d75a..53b4ba9e 100644 --- a/internal/server/chat_auto_switch.go +++ b/internal/server/chat_auto_switch.go @@ -11,7 +11,6 @@ import ( "git.a-wan.net/alan/pipelines/internal/claude" "git.a-wan.net/alan/pipelines/internal/pipeline" "git.a-wan.net/alan/pipelines/internal/protocol" - "git.a-wan.net/alan/pipelines/internal/stage" ) // When Claude Code refuses an operator chat's turn because the account ran @@ -281,10 +280,11 @@ func (h *chatHub) publishAutoSwitchNotice(ctx context.Context, refusal claude.Us } title := truncateUTF8("Switched "+name+" to "+singleLine(email)+" and continued", 256) message := "Claude usage ran out, so Pipelines switched the account and asked the agent to check it is on track before continuing." - click, views := chatAttentionLinks(refusal.SessionID) + click, _ := chatAttentionLinks(refusal.SessionID) + id := "chat:" + refusal.SessionID + ":auto-switch:" + refusalKey(refusal) if h.notes != nil { h.notes.record(ctx, pipeline.AppNotificationRecord{ - AppNotification: protocol.AppNotification{ID: "chat:" + refusal.SessionID + ":auto-switch:" + refusalKey(refusal), Kind: protocol.NotificationChatReply, + AppNotification: protocol.AppNotification{ID: id, Kind: protocol.NotificationChatReply, Title: title, Message: message, Click: click, Priority: chatAutoSwitchPriority, Tags: []string{}, Group: "chat:" + refusal.SessionID}, SessionID: refusal.SessionID, }) @@ -292,7 +292,5 @@ func (h *chatHub) publishAutoSwitchNotice(ctx context.Context, refusal claude.Us if !chatAttentionConfigured() || !chatNotificationSettings(ctx, h.settings).NtfyEnabled { return } - if _, err := chatAttentionPublish(stage.WithNtfyPriority(ctx, chatAutoSwitchPriority), "system", title, message, "", nil, click, views...); err != nil { - log.Printf("claude auto-switch notification session=%s: %v", refusal.SessionID, err) - } + h.pushChatNtfy(ctx, pipeline.ChatNotification{ID: id, SessionID: refusal.SessionID, Title: title, Body: message, Click: click, Priority: chatAutoSwitchPriority}) } diff --git a/internal/server/chat_close.go b/internal/server/chat_close.go index d5eb98c6..a97e9e7a 100644 --- a/internal/server/chat_close.go +++ b/internal/server/chat_close.go @@ -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 diff --git a/internal/server/chat_hub.go b/internal/server/chat_hub.go index d9455868..730ca2cd 100644 --- a/internal/server/chat_hub.go +++ b/internal/server/chat_hub.go @@ -51,6 +51,9 @@ type chatHub struct { attentionSeen map[string]struct{} attentionOrder []string attentionWG sync.WaitGroup + // outbox makes chat phone pushes durable and retried (chat_ntfy_outbox.go); + // nil publishes each push once, directly. + outbox chatNotificationOutbox // notifiedTurns holds the chats whose current turn already sent an agent // notify, so that turn's end is not announced again (one turn, one ping). notifiedTurns map[string]struct{} diff --git a/internal/server/chat_ntfy_outbox.go b/internal/server/chat_ntfy_outbox.go new file mode 100644 index 00000000..32746049 --- /dev/null +++ b/internal/server/chat_ntfy_outbox.go @@ -0,0 +1,128 @@ +package server + +import ( + "context" + "log" + "sync/atomic" + "time" + + "git.a-wan.net/alan/pipelines/internal/pipeline" + "git.a-wan.net/alan/pipelines/internal/stage" +) + +// Chat phone pushes (attention items and Claude auto-switch notices) go +// through a durable outbox like run notifications: the push is recorded first, +// one attempt is made at once, and a background worker retries a failed or +// interrupted attempt with backoff, also after a restart. A push whose app +// notification the operator already cleared is never published late, and a +// publication that raced a clear is cleared on the phone again, so the ntfy +// sequence-id/clear behaviour (chat_ntfy_clear.go) holds. + +// chatNotificationOutbox is the durable chat push outbox; *pipeline.Store +// implements it. +type chatNotificationOutbox interface { + EnqueueChatNotification(ctx context.Context, n pipeline.ChatNotification, now time.Time) error + ClaimChatNotification(ctx context.Context, now int64) (*pipeline.ChatNotification, error) + FinishChatNotification(ctx context.Context, n pipeline.ChatNotification, now int64, messageID string, failure error) error + ChatNotificationCleared(ctx context.Context, id string) (bool, error) + Done() <-chan struct{} +} + +// chatOutboxInterval is how often the worker looks for due retries. +var chatOutboxInterval = time.Second + +// chatOutboxSkew shifts the outbox clock; tests move it past a backoff. +var chatOutboxSkew atomic.Int64 + +func chatOutboxNow() time.Time { return time.Now().Add(time.Duration(chatOutboxSkew.Load())) } + +// startChatNotificationOutbox wires the durable outbox and starts its retry +// worker for the life of ctx. +func (h *chatHub) startChatNotificationOutbox(ctx context.Context, outbox chatNotificationOutbox) { + h.outbox = outbox + go func() { + ticker := time.NewTicker(chatOutboxInterval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-outbox.Done(): + return + case <-ticker.C: + h.deliverChatNotifications(ctx, 16) + } + } + }() +} + +// pushChatNtfy publishes one chat phone push. With an outbox it is recorded +// durably and attempted at once; without one (a store-less hub) it is a single +// direct attempt, as before. +func (h *chatHub) pushChatNtfy(ctx context.Context, n pipeline.ChatNotification) { + if h.outbox != nil { + err := h.outbox.EnqueueChatNotification(ctx, n, chatOutboxNow()) + if err == nil { + h.deliverChatNotifications(ctx, 1) + return + } + log.Printf("enqueue chat notification %s: %v; publishing directly", n.ID, err) + } + if _, err := chatAttentionPublish(chatNtfyContext(ctx, n), "system", n.Title, n.Body, "", nil, n.Click, chatNtfyViews(n)...); err != nil { + log.Printf("chat notification session=%s: %v", n.SessionID, err) + } +} + +func chatNtfyContext(ctx context.Context, n pipeline.ChatNotification) context.Context { + if n.SequenceID != "" { + ctx = stage.WithNtfySequenceID(ctx, n.SequenceID) + } + if n.Priority > 0 { + ctx = stage.WithNtfyPriority(ctx, n.Priority) + } + return ctx +} + +// chatNtfyViews derives the push's actions at delivery, so a changed web +// origin applies to a retried push. +func chatNtfyViews(n pipeline.ChatNotification) []stage.NtfyView { + _, views := chatAttentionLinks(n.SessionID) + return views +} + +// deliverChatNotifications attempts up to limit due pushes. +func (h *chatHub) deliverChatNotifications(ctx context.Context, limit int) { + outbox := h.outbox + if outbox == nil { + return + } + for i := 0; i < limit && ctx.Err() == nil; i++ { + n, err := outbox.ClaimChatNotification(ctx, chatOutboxNow().Unix()) + if err != nil { + log.Printf("claim chat notification: %v", err) + return + } + if n == nil { + return + } + publish, cancel := context.WithTimeout(ctx, 30*time.Second) + result, publishErr := chatAttentionPublish(chatNtfyContext(publish, *n), "system", n.Title, n.Body, "", nil, n.Click, chatNtfyViews(*n)...) + cancel() + if publishErr != nil { + log.Printf("chat notification session=%s attempt=%d: %v", n.SessionID, n.Attempts, publishErr) + } + messageID, _ := result["message_id"].(string) + save, done := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + if err := outbox.FinishChatNotification(save, *n, chatOutboxNow().Unix(), messageID, publishErr); err != nil { + log.Printf("save chat notification %s: %v", n.ID, err) + } + // The operator may have cleared it in the app while it was being + // published, after the clear went to ntfy: clear it there again. + if publishErr == nil && n.SequenceID != "" { + if cleared, err := outbox.ChatNotificationCleared(save, n.ID); err == nil && cleared { + clearChatNtfy([]string{n.ID}) + } + } + done() + } +} diff --git a/internal/server/chat_ntfy_outbox_test.go b/internal/server/chat_ntfy_outbox_test.go new file mode 100644 index 00000000..12c9a89d --- /dev/null +++ b/internal/server/chat_ntfy_outbox_test.go @@ -0,0 +1,61 @@ +package server + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/protocol" + "git.a-wan.net/alan/pipelines/internal/stage" +) + +// A chat attention push that ntfy refuses is kept in the durable outbox and +// retried by the worker with its sequence id, not lost after one attempt. +func TestChatAttentionPushIsRetriedFromTheOutbox(t *testing.T) { + t.Setenv("PIPELINES_NTFY_URL", "http://ntfy.invalid/pipelines") + t.Setenv("PIPELINES_WEB_PUBLIC_URL", "") + interval := chatOutboxInterval + chatOutboxInterval = 20 * time.Millisecond + defer func() { chatOutboxInterval = interval }() + var mu sync.Mutex + var sequences []string + original := chatAttentionPublish + chatAttentionPublish = func(ctx context.Context, _, _, _, _ string, _ []byte, _ string, _ ...stage.NtfyView) (stage.Values, error) { + mu.Lock() + defer mu.Unlock() + sequences = append(sequences, stage.NtfySequence(ctx)) + if len(sequences) == 1 { + return nil, errors.New("ntfy unavailable") + } + return stage.Values{"message_id": "m1"}, nil + } + defer func() { chatAttentionPublish = original }() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + store := newOperatorStore(t) + h := chatAttentionHub(t, "ses_a") + h.settings = store + h.notes = newAppNotifier(store) + h.startChatNotificationOutbox(ctx, store) + form := protocol.ChatForm{ID: "que_1", SessionID: "ses_a", Kind: "question", Title: "Ship it?"} + h.emit(protocol.ChatEventFrame{SessionID: "ses_a", Kind: protocol.ChatEventForm, Form: &form}) + h.attentionWG.Wait() + id := "chat:ses_a:form:que_1" + if status, attempts, err := store.ChatNotificationStatus(ctx, id); err != nil || status != "pending" || attempts != 1 { + t.Fatalf("after a refused attempt: %s/%d %v", status, attempts, err) + } + // The first backoff is 5 s; move the outbox clock past it. + chatOutboxSkew.Store(int64(10 * time.Second)) + defer chatOutboxSkew.Store(0) + waitFor(t, "retried push sent", func() bool { + status, _, _ := store.ChatNotificationStatus(ctx, id) + return status == "sent" + }) + mu.Lock() + defer mu.Unlock() + if len(sequences) != 2 || sequences[0] != chatNtfySequence(id) || sequences[1] != sequences[0] { + t.Fatalf("sequence ids = %v", sequences) + } +} diff --git a/internal/server/chat_queue.go b/internal/server/chat_queue.go index 1a266e7c..f750bed2 100644 --- a/internal/server/chat_queue.go +++ b/internal/server/chat_queue.go @@ -237,9 +237,24 @@ func chatQueueRow(sessionID string, p *chatQueuedPrompt) pipeline.ChatQueuedProm } } +// errChatQueuedPromptInvalid marks a stored prompt that can never be rebuilt +// (unreadable attachment list, an attachment outside the store). Only such a +// row is dropped; any other promptFromRow failure (the attachment directory +// cannot be resolved right now) keeps the row for a later retry. +var errChatQueuedPromptInvalid = errors.New("queued prompt is invalid") + +// chatQueueRecoveryRetry is the first delay before a session whose queued +// prompts could not be restored is tried again; it doubles up to +// chatQueueRecoveryRetryMax. +var ( + chatQueueRecoveryRetry = 30 * time.Second + chatQueueRecoveryRetryMax = 10 * time.Minute +) + // promptFromRow rebuilds a queued prompt read back from the store. Its files // must still name the server's own attachment directory; they are leased again -// so retention cannot collect them before delivery. +// so retention cannot collect them before delivery. A permanent failure wraps +// errChatQueuedPromptInvalid. func promptFromRow(row pipeline.ChatQueuedPrompt) (*chatQueuedPrompt, error) { p := &chatQueuedPrompt{ text: row.Text, @@ -255,7 +270,7 @@ func promptFromRow(row pipeline.ChatQueuedPrompt) (*chatQueuedPrompt, error) { _ = json.Unmarshal([]byte(row.PartsJSON), &p.parts) var stored []chatStoredFile if err := json.Unmarshal([]byte(row.FilesJSON), &stored); err != nil { - return p, fmt.Errorf("queued prompt attachments are unreadable") + return p, fmt.Errorf("%w: queued prompt attachments are unreadable", errChatQueuedPromptInvalid) } if len(stored) == 0 { return p, nil @@ -269,7 +284,7 @@ func promptFromRow(row pipeline.ChatQueuedPrompt) (*chatQueuedPrompt, error) { for _, file := range stored { u, err := url.Parse(file.URI) if err != nil || u.Scheme != "file" || filepath.Dir(u.Path) != dir { - return p, fmt.Errorf("queued prompt attachment %q is outside the attachment store", file.Name) + return p, fmt.Errorf("%w: queued prompt attachment %q is outside the attachment store", errChatQueuedPromptInvalid, file.Name) } chatAttachmentStore.leased[u.Path] = true p.files = append(p.files, opencode.NewPreparedPromptFile(file.URI, file.Name)) @@ -427,49 +442,80 @@ func (h *chatHub) resumeQueued(ctx context.Context, broker chatBroker) { return } for _, sessionID := range sessions { - rows, err := h.queueStore.ChatQueuedPrompts(ctx, sessionID) - if err != nil { - log.Printf("chat queue recovery session=%s: %v", sessionID, err) + h.resumeQueuedSession(ctx, broker, sessionID, chatQueueRecoveryRetry) + } +} + +// resumeQueuedSession restores one session's durable queue. A prompt that can +// never be rebuilt is dropped; a transient failure (the store or the +// attachment directory unavailable) keeps every row, restores nothing for the +// session (so FIFO order is kept) and tries again after retry, backing off. +// A row whose operation the live hub already knows (a retry racing a client +// that queued or delivered it meanwhile) is left to the hub. +func (h *chatHub) resumeQueuedSession(ctx context.Context, broker chatBroker, sessionID string, retry time.Duration) { + if ctx.Err() != nil { + return + } + later := func(err error) { + log.Printf("chat queue recovery session=%s: %v; retrying in %s", sessionID, err, retry) + next := min(2*retry, chatQueueRecoveryRetryMax) + time.AfterFunc(retry, func() { h.resumeQueuedSession(ctx, broker, sessionID, next) }) + } + rows, err := h.queueStore.ChatQueuedPrompts(ctx, sessionID) + if err != nil { + later(err) + return + } + var prompts []*chatQueuedPrompt + for _, row := range rows { + h.mu.Lock() + _, known := h.recentOps[sessionID+"\x00"+row.OperationID] + h.mu.Unlock() + if known && row.OperationID != "" { continue } - var prompts []*chatQueuedPrompt - for _, row := range rows { - p, err := promptFromRow(row) - if err != nil { - releaseChatAttachments(p.files) - log.Printf("chat queue recovery session=%s: %v", sessionID, err) - _, _ = h.queueStore.DeleteChatQueuedPrompt(ctx, sessionID, row.OperationID) - continue - } + p, err := promptFromRow(row) + if err == nil { prompts = append(prompts, p) - } - if len(prompts) == 0 { continue } + releaseChatAttachments(p.files) + if !errors.Is(err, errChatQueuedPromptInvalid) { + for _, kept := range prompts { + releaseChatAttachments(kept.files) + } + later(err) + return + } + log.Printf("chat queue recovery session=%s: dropping %s: %v", sessionID, row.OperationID, err) + _, _ = h.queueStore.DeleteChatQueuedPrompt(ctx, sessionID, row.OperationID) + } + if len(prompts) == 0 { + return + } + h.mu.Lock() + room := h.roomLocked(sessionID) + if room.broker == nil { + room.broker = broker + } + room.notBefore = time.Now().Add(chatQueueRecoverySettle) + for _, p := range prompts { + if !room.holdsOp(p.operationID) { + room.queue = append(room.queue, p) + h.rememberOpLocked(sessionID, p.operationID) + } + } + h.mu.Unlock() + go func(room *chatRoom) { + // Attach the stream first so a turn the harness is still running is + // observed before the settle window lets the runner deliver. + if err := h.ensureObserving(room, broker); err != nil && room.ctx.Err() == nil { + log.Printf("chat queue recovery observe session=%s: %v", room.sessionID, err) + } h.mu.Lock() - room := h.roomLocked(sessionID) - if room.broker == nil { - room.broker = broker - } - room.notBefore = time.Now().Add(chatQueueRecoverySettle) - for _, p := range prompts { - if !room.holdsOp(p.operationID) { - room.queue = append(room.queue, p) - h.rememberOpLocked(sessionID, p.operationID) - } - } + signalWake(room.wake) h.mu.Unlock() - go func(room *chatRoom) { - // Attach the stream first so a turn the harness is still running is - // observed before the settle window lets the runner deliver. - if err := h.ensureObserving(room, broker); err != nil && room.ctx.Err() == nil { - log.Printf("chat queue recovery observe session=%s: %v", room.sessionID, err) - } - h.mu.Lock() - signalWake(room.wake) - h.mu.Unlock() - }(room) - } + }(room) } func (r *chatRoom) holdsOp(operationID string) bool { diff --git a/internal/server/chat_queue_recovery_test.go b/internal/server/chat_queue_recovery_test.go new file mode 100644 index 00000000..6440f2d1 --- /dev/null +++ b/internal/server/chat_queue_recovery_test.go @@ -0,0 +1,74 @@ +package server + +import ( + "context" + "encoding/json" + "net/url" + "path/filepath" + "slices" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/pipeline" +) + +func fastQueueRecovery(t *testing.T) { + t.Helper() + settle, retry, retryMax := chatQueueRecoverySettle, chatQueueRecoveryRetry, chatQueueRecoveryRetryMax + chatQueueRecoverySettle, chatQueueRecoveryRetry, chatQueueRecoveryRetryMax = 10*time.Millisecond, 50*time.Millisecond, 100*time.Millisecond + t.Cleanup(func() { + chatQueueRecoverySettle, chatQueueRecoveryRetry, chatQueueRecoveryRetryMax = settle, retry, retryMax + }) +} + +func queuedPromptWithFile(t *testing.T, store *pipeline.Store, op, text, path string) { + t.Helper() + files, err := json.Marshal([]chatStoredFile{{URI: (&url.URL{Scheme: "file", Path: path}).String(), Name: filepath.Base(path)}}) + if err != nil { + t.Fatal(err) + } + if _, _, err := store.EnqueueChatPrompt(context.Background(), pipeline.ChatQueuedPrompt{SessionID: "ses_1", OperationID: op, MessageID: "msg_" + op, Text: text, FilesJSON: string(files)}, 0); err != nil { + t.Fatal(err) + } +} + +// A queued prompt whose attachment directory cannot be resolved at restart is +// kept and restored on a later retry, not deleted. +func TestChatQueuedPromptKeptOnTransientAttachmentFailure(t *testing.T) { + fastQueueRecovery(t) + dir := t.TempDir() + path := filepath.Join(t.TempDir(), "queue.db") + store := openQueueStore(t, path) + queuedPromptWithFile(t, store, "op-1", "with file", filepath.Join(dir, "a.txt")) + t.Setenv("PIPELINES_CHAT_ATTACHMENT_DIR", "relative/dir") // unresolvable for now + broker := newChannelChat() + startQueueServer(t, broker, store) + time.Sleep(200 * time.Millisecond) + if ops := queuedOps(t, store); !slices.Equal(ops, []string{"op-1"}) { + t.Fatalf("queued prompt dropped on a transient failure: %v", ops) + } + if texts := broker.promptTexts(); len(texts) != 0 { + t.Fatalf("prompt delivered while unrestorable: %v", texts) + } + t.Setenv("PIPELINES_CHAT_ATTACHMENT_DIR", dir) + waitFor(t, "prompt restored on retry", func() bool { return slices.Equal(broker.promptTexts(), []string{"with file"}) }) + waitFor(t, "delivered row deleted", func() bool { return len(queuedOps(t, store)) == 0 }) +} + +// A queued prompt that can never be rebuilt is still dropped, and the rest of +// the session's queue is delivered. +func TestChatQueuedPromptDroppedOnPermanentFailure(t *testing.T) { + fastQueueRecovery(t) + dir := t.TempDir() + t.Setenv("PIPELINES_CHAT_ATTACHMENT_DIR", dir) + path := filepath.Join(t.TempDir(), "queue.db") + store := openQueueStore(t, path) + queuedPromptWithFile(t, store, "op-1", "outside", filepath.Join(t.TempDir(), "elsewhere.txt")) + if _, _, err := store.EnqueueChatPrompt(context.Background(), pipeline.ChatQueuedPrompt{SessionID: "ses_1", OperationID: "op-2", MessageID: "msg_op-2", Text: "plain"}, 0); err != nil { + t.Fatal(err) + } + broker := newChannelChat() + startQueueServer(t, broker, store) + waitFor(t, "valid prompt delivered", func() bool { return slices.Equal(broker.promptTexts(), []string{"plain"}) }) + waitFor(t, "rows cleared", func() bool { return len(queuedOps(t, store)) == 0 }) +} diff --git a/internal/server/chat_unattended.go b/internal/server/chat_unattended.go index 3819ad09..3e5895c1 100644 --- a/internal/server/chat_unattended.go +++ b/internal/server/chat_unattended.go @@ -23,9 +23,11 @@ import ( // is not an idle lease: it remains attached until actual completion or explicit // stop. Its durable journal is independent of bounded replay/room retention. -// chatUnattendedLimit bounds the rooms kept observing with no client attached -// and no queued prompt. -const chatUnattendedLimit = 16 +// chatUnattendedLimit bounds the rooms kept observing with no client attached, +// no queued prompt and no live work of this server's own (see liveWorkLocked): +// a turn this server started, a pending approval or question, or background +// tasks always keep notifying, however many chats are unattended. +const chatUnattendedLimit = 64 // chatRecoverSessionLimit bounds how many recently used open sessions are // probed for a running turn at server start. @@ -84,6 +86,15 @@ func (h *chatHub) keepUnattendedLocked(room *chatRoom, busy, hold bool) bool { return hold && h.clock().Before(room.holdUntil) } +// liveWorkLocked reports whether a room holds work this server knows is real +// and will notify: its own turn in flight, an unanswered approval or question, +// or running background tasks. Such a room is never refused by the idle cap, +// which only bounds observers kept on weaker evidence (a stream-announced or +// harness-reported turn, the start-up settle window). Callers hold h.mu. +func (h *chatHub) liveWorkLocked(room *chatRoom) bool { + return room.running || len(room.pending) > 0 || len(room.forms) > 0 || h.backgroundTasksLocked(room.sessionID) > 0 +} + // unattendedCountLocked counts the rooms kept observing with no client and no // queued prompt, other than except. Callers hold h.mu. func (h *chatHub) unattendedCountLocked(except *chatRoom) int { @@ -109,7 +120,7 @@ func (h *chatHub) leaveUnattendedLocked(room *chatRoom) { h.releaseRoomLocked(room) return } - if !room.watching && h.backgroundTasksLocked(room.sessionID) == 0 && h.unattendedCountLocked(room) >= chatUnattendedLimit { + if !room.watching && !h.liveWorkLocked(room) && h.unattendedCountLocked(room) >= chatUnattendedLimit { log.Printf("chat session %s: %d chats already observed with no client; not keeping this one", room.sessionID, chatUnattendedLimit) h.releaseRoomLocked(room) return diff --git a/internal/server/chat_unattended_test.go b/internal/server/chat_unattended_test.go index 0c5f1fbc..b918aace 100644 --- a/internal/server/chat_unattended_test.go +++ b/internal/server/chat_unattended_test.go @@ -2,6 +2,7 @@ package server import ( "context" + "fmt" "path/filepath" "sync" "testing" @@ -320,7 +321,42 @@ func TestChatStuckUnattendedTurnIsReleased(t *testing.T) { waitFor(t, "stuck observer released", func() bool { active, _ := broker.streams(); return active == 0 }) } -// At most chatUnattendedLimit chats are kept observing with no client. +// A turn this server started keeps notifying however many chats are already +// observed unattended: the idle cap never drops live work. +func TestChatUnattendedRunningTurnsIgnoreTheCap(t *testing.T) { + fastUnattended(t) + h := newChatHub() + defer func() { + h.mu.Lock() + for _, room := range h.rooms { + room.cancel() + } + h.mu.Unlock() + }() + count := chatUnattendedLimit + 3 + kept := 0 + for i := 0; i < count; i++ { + id := fmt.Sprintf("ses_run_%03d", i) + h.mu.Lock() + room := h.roomLocked(id) + room.running = true + sub := &chatSub{hub: h, room: room, clientID: "c", limit: 1, done: make(chan struct{})} + room.subs["c"] = sub + h.mu.Unlock() + h.detach(id, sub) + h.mu.Lock() + if h.rooms[id] == room { + kept++ + } + h.mu.Unlock() + } + if kept != count { + t.Fatalf("kept %d unattended running rooms, want all %d", kept, count) + } +} + +// At most chatUnattendedLimit chats are kept observing with no client on +// weaker evidence than live work (a stream-announced turn). func TestChatUnattendedRoomsAreBounded(t *testing.T) { fastUnattended(t) h := newChatHub() @@ -333,10 +369,10 @@ func TestChatUnattendedRoomsAreBounded(t *testing.T) { }() kept := 0 for i := 0; i < chatUnattendedLimit+3; i++ { - id := "ses_" + string(rune('a'+i)) + id := fmt.Sprintf("ses_obs_%03d", i) h.mu.Lock() room := h.roomLocked(id) - room.running = true + room.observedTurn = true sub := &chatSub{hub: h, room: room, clientID: "c", limit: 1, done: make(chan struct{})} room.subs["c"] = sub h.mu.Unlock() diff --git a/internal/server/legacy_schedule_workspace_test.go b/internal/server/legacy_schedule_workspace_test.go index db8d701a..145008c9 100644 --- a/internal/server/legacy_schedule_workspace_test.go +++ b/internal/server/legacy_schedule_workspace_test.go @@ -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 { diff --git a/internal/server/run_reattach.go b/internal/server/run_reattach.go index f58832f0..33781068 100644 --- a/internal/server/run_reattach.go +++ b/internal/server/run_reattach.go @@ -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. diff --git a/internal/server/runner.go b/internal/server/runner.go index 50e44374..c2b8330a 100644 --- a/internal/server/runner.go +++ b/internal/server/runner.go @@ -41,7 +41,10 @@ type runner struct { artifactsRoot string mu sync.Mutex active map[int64]activeRun - execute func(context.Context, stage.Definition, stage.Values) (stage.Result, error) + // admitting counts admissions creating a run worktree from each source + // workspace outside r.mu; storage maintenance keeps those trees. + admitting map[string]int + execute func(context.Context, stage.Definition, stage.Values) (stage.Result, error) // dirEnv resolves the run workspace's own environment (direnv/mise) at // run start; nil uses workenv.Default. dirEnv *workenv.Resolver @@ -78,6 +81,9 @@ type runner struct { verifyTarget stage.VerificationRunner wg sync.WaitGroup schedulerWG sync.WaitGroup + // scheduleAdmissions tracks schedule-claimed runs still being admitted + // (scheduler.go); the scheduler loop waits for them before it exits. + scheduleAdmissions sync.WaitGroup // attentionMu guards attentionSent, the per-run set of run-attention events // already delivered — by a stage's own notify policy or by the run-level // default — so neither republishes the same genuine event. @@ -183,7 +189,7 @@ func newRunnerReattaching(ctx context.Context, s *pipeline.Store, artifactsRoot active[row.ID] = activeRun{cancel: func() {}, workspace: row.Workspace} } } - r := &runner{ctx: ctx, store: s, artifactsRoot: root, active: active, idents: map[int64]runIdentity{}, attentionSent: map[int64]map[string]bool{}, notifyModes: map[int64]string{}, exportSession: stage.ExportSession, detach: detach, reattach: plans} + r := &runner{ctx: ctx, store: s, artifactsRoot: root, active: active, admitting: map[string]int{}, idents: map[int64]runIdentity{}, attentionSent: map[int64]map[string]bool{}, notifyModes: map[int64]string{}, exportSession: stage.ExportSession, detach: detach, reattach: plans} if err := r.startSessionExportJobs(); err != nil { return nil, err } @@ -334,38 +340,57 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc } r.mu.Lock() - defer r.mu.Unlock() // Another run may have reserved this workspace while the title was // generated, so re-check before reserving it; a race on the request key is // handled by the store's idempotent insert. - if existing == 0 { - if err := r.checkWorkspaceFree(workspace); err != nil { - return nil, err - } - } - // Storage maintenance may have removed a clean inactive tree while an - // admission was generating its title. Refuse that vanished workspace under - // the same lock used by removal instead of launching into a missing tree. - if info, err := os.Stat(workspace); err != nil || !info.IsDir() { - return nil, fmt.Errorf("run workspace is no longer available: %s", workspace) + if err := r.checkAdmissionWorkspace(workspace, existing); err != nil { + r.mu.Unlock() + return nil, err } // A fresh run started from a repository's main checkout gets its own // worktree and branch, so runs never share a tree with each other or with - // the operator's uncommitted work. A retry keeps its run's tree. + // the operator's uncommitted work. A retry keeps its run's tree. Creating + // the worktree can take up to a minute, so it runs without r.mu (listings, + // details and cancellation must not stall behind it); storage maintenance + // keeps the source tree meanwhile (r.admitting), and the reservation is + // re-checked under the lock before the run is recorded. isolated := "" if existing == 0 && request.RetrySource == 0 { + source := workspace + if r.admitting == nil { + r.admitting = map[string]int{} + } + r.admitting[source]++ + r.mu.Unlock() isolateCtx, isolateCancel := context.WithTimeout(r.ctx, time.Minute) - tree, isolateErr := isolateRunWorkspace(isolateCtx, workspace, runTitle.Text) + tree, isolateErr := isolateRunWorkspace(isolateCtx, source, runTitle.Text) isolateCancel() + r.mu.Lock() + if r.admitting[source]--; r.admitting[source] <= 0 { + delete(r.admitting, source) + } if isolateErr != nil { + r.mu.Unlock() return nil, isolateErr } - if tree != workspace { + if tree != source { isolated = tree } workspace = tree request.Input["pwd"] = workspace + recheck := r.ctx.Err() + if recheck == nil { + recheck = r.checkAdmissionWorkspace(workspace, existing) + } + if recheck != nil { + r.mu.Unlock() + if isolated != "" { + discardRunWorktree(isolated) + } + return nil, recheck + } } + defer r.mu.Unlock() id, created, err := r.store.CreateRunTitled(r.ctx, d, request.RequestKey, workspace, request.AllowTools, request.WritePaths, request.Input, pipeline.RunOverrides{Schedule: origin, Model: request.Model, StageModels: request.StageModels, NotifyMode: request.NotifyMode, OutputFormat: request.OutputFormat, StageSkills: stageSkills}, runTitle, retryOf...) if isolated != "" && (err != nil || !created) { // The run was refused or an identical request won the race: the fresh @@ -436,42 +461,100 @@ func (r *runner) launch(id int64, workspace string, fn func(context.Context)) { go func() { defer r.wg.Done() defer cancel() - defer func() { - r.mu.Lock() - defer r.mu.Unlock() - if entry, ok := r.active[id]; !ok || entry.generation != generation { - return // A parked launch must not remove the resumed reservation. - } - check, done := context.WithTimeout(context.Background(), 10*time.Second) - defer done() - detail, err := r.store.GetRun(check, id) - if err != nil || detail.CleanupUnconfirmed { - return // Fail closed: execution/cleanup has not settled durably. - } - if detail.Status == protocol.RunStatusWaiting && detail.CancelRequested { - if err := r.store.CancelWaiting(check, id); err != nil { - return - } - r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: detail.Workspace, Status: protocol.RunStatusCanceled, CancelRequested: true, CurrentStage: detail.CurrentStage, FinishedAt: time.Now().UTC().Format(time.RFC3339)}, true) - } - if detail.FinishedAt != "" || detail.Status == protocol.RunStatusWaiting { - delete(r.active, id) - } - // A landed (or change-free) successful run's own worktree is no - // longer needed; anything unlanded or uncommitted is kept. - if detail.Status == "succeeded" && detail.FinishedAt != "" { - workspace := detail.Workspace - go func() { - if removeLandedRunWorktree(workspace) { - log.Printf("run %d: removed its landed worktree %s", id, workspace) - } - }() - } - }() + defer r.settleLaunch(id, generation) fn(ctx) }() } +// settleLaunch releases a finished launch's reservation once its run has +// settled durably. A failed read is retried with backoff (the lock is not held +// while waiting); a run whose cleanup is unconfirmed, or that cannot be read +// even after the retries, keeps its reservation (fail closed). +func (r *runner) settleLaunch(id int64, generation *byte) { + for attempt := 0; ; attempt++ { + settled, err := r.settleLaunchOnce(id, generation) + if settled { + return + } + if attempt >= len(runSettleBackoff) { + log.Printf("run %d: launch teardown could not read the run; its workspace stays reserved: %v", id, err) + return + } + if !r.sleepSettle(runSettleBackoff[attempt]) { + return + } + } +} + +// settleLaunchOnce is one teardown attempt under r.mu. It reports false only +// when the run could not be read. +func (r *runner) settleLaunchOnce(id int64, generation *byte) (bool, error) { + r.mu.Lock() + defer r.mu.Unlock() + if entry, ok := r.active[id]; !ok || entry.generation != generation { + return true, nil // A parked launch must not remove the resumed reservation. + } + check, done := context.WithTimeout(context.Background(), 10*time.Second) + defer done() + detail, err := runSettleRead(r, check, id) + if err != nil || detail == nil { + return false, err + } + if detail.CleanupUnconfirmed { + return true, nil // Fail closed: execution/cleanup has not settled durably. + } + if detail.Status == protocol.RunStatusWaiting && detail.CancelRequested { + if err := r.store.CancelWaiting(check, id); err != nil { + // A refused transition fails closed; anything else is retried. + return errors.Is(err, pipeline.ErrInvalidRunTransition), err + } + r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: detail.Workspace, Status: protocol.RunStatusCanceled, CancelRequested: true, CurrentStage: detail.CurrentStage, FinishedAt: time.Now().UTC().Format(time.RFC3339)}, true) + } + if detail.FinishedAt != "" || detail.Status == protocol.RunStatusWaiting { + delete(r.active, id) + } + // A landed (or change-free) successful run's own worktree is no longer + // needed; anything unlanded or uncommitted is kept. + if detail.Status == "succeeded" && detail.FinishedAt != "" { + workspace := detail.Workspace + go func() { + if removeLandedRunWorktree(workspace) { + log.Printf("run %d: removed its landed worktree %s", id, workspace) + } + }() + } + return true, nil +} + +// runFinishWrite persists a run's terminal state; tests replace it to inject +// transient store failures. +var runFinishWrite = func(r *runner, ctx context.Context, id int64, status, outcome, diagnostic string, input stage.Values) error { + return r.store.FinishRun(ctx, id, status, outcome, diagnostic, input) +} + +// runSettleRead reads a run for settlement; tests replace it to inject +// transient store failures. +var runSettleRead = func(r *runner, ctx context.Context, id int64) (*protocol.RunDetail, error) { + return r.store.GetRun(ctx, id) +} + +// checkAdmissionWorkspace refuses admitting a fresh run (existing == 0) into a +// workspace another run reserves, and any admission into a vanished workspace: +// storage maintenance may have removed a clean inactive tree while an +// admission was generating its title, so it is checked under the same lock +// removal takes. Callers must hold r.mu. +func (r *runner) checkAdmissionWorkspace(workspace string, existing int64) error { + if existing == 0 { + if err := r.checkWorkspaceFree(workspace); err != nil { + return err + } + } + if info, err := os.Stat(workspace); err != nil || !info.IsDir() { + return fmt.Errorf("run workspace is no longer available: %s", workspace) + } + return nil +} + // checkWorkspaceFree refuses a run when an active or cleanup-unconfirmed run // reserves an overlapping resolved workspace. Callers must hold r.mu. func (r *runner) checkWorkspaceFree(workspace string) error { @@ -535,12 +618,15 @@ func repositoryRoot(dir string) string { } } +// getRun reads one run's detail. The store read runs without r.mu, so a +// detail never waits behind admission or settlement work; only the executing +// overlay reads the active set under the lock. func (r *runner) getRun(id int64) (*protocol.RunDetail, error) { - r.mu.Lock() - defer r.mu.Unlock() d, err := r.store.GetRun(r.ctx, id) if d != nil { + r.mu.Lock() _, d.Executing = r.active[id] + r.mu.Unlock() if d.ExportPendingSequence > 0 { d.Executing = false } @@ -584,28 +670,38 @@ func (r *runner) overlayEffectiveModels(d *protocol.RunDetail) { } } +// listRuns lists every run with its executing overlay. The store reads run +// without r.mu (a listing never waits behind admission or settlement), and a +// failed run whose cleanup agent is still active is found with one query +// rather than a detail read per failed run. func (r *runner) listRuns() ([]protocol.RunSummary, error) { - r.mu.Lock() - defer r.mu.Unlock() items, err := r.store.ListRuns(r.ctx) + if err != nil { + return items, err + } + var agents map[int64]bool + for _, item := range items { + if item.Status == "failed" { + if agents, err = r.store.RunsWithActiveAgents(r.ctx); err != nil { + return nil, err + } + break + } + } + r.mu.Lock() for i := range items { _, items[i].Executing = r.active[items[i].ID] + } + r.mu.Unlock() + for i := range items { if items[i].ExportPendingSequence > 0 { items[i].Executing = false } - if items[i].Status == "failed" && !items[i].Executing { - d, err := r.store.GetRun(r.ctx, items[i].ID) - if err != nil { - return nil, err - } - for _, step := range d.Steps { - if step.AgentActive { - items[i].Executing = true - } - } + if items[i].Status == "failed" && !items[i].Executing && agents[items[i].ID] { + items[i].Executing = true } } - return items, err + return items, nil } type retryCheckpoint struct { @@ -1593,23 +1689,26 @@ func (r *runner) emitRun(frame protocol.RunEventFrame, terminal bool) { } func (r *runner) finishRunState(id int64, name, workspace, status, outcome, diagnostic string, completed, sequence int, currentStage string, input stage.Values) { - r.mu.Lock() + // The deliverable and the size walk touch files only: they run without r.mu, + // so listings and details do not stall behind a large run finishing. The + // run stays in r.active (its workspace reserved) until the launch teardown. c, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() if status == "succeeded" { if err := r.finalizeDeliverable(c, id, sequence, input); err != nil { status, outcome, diagnostic = "failed", "error", "deliverable contract: "+err.Error() } } + cancel() // Measure the run's footprint while it is still recorded as active: its // files are final, and measuring after the terminal status is written would // widen the window in which a client sees the run finished but still owned. // The status write re-marks the cache stale, so the background sizer then // records the exact value including the final output row. size := r.finishedSize(id) - if err := r.store.FinishRun(c, id, status, outcome, diagnostic, input); err != nil { - log.Printf("finish run %d: %v", id, err) - } + r.finishRunWithRetry(id, status, outcome, diagnostic, input) + r.mu.Lock() + c, cancel = context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() // The store atomically makes a stop request win over a late success. detail, getErr := r.store.GetRun(c, id) if getErr != nil || detail == nil { @@ -1645,6 +1744,47 @@ func (r *runner) finishRunState(id int64, name, workspace, status, outcome, diag r.forgetNotifyMode(id) } +// runSettleBackoff is the retry schedule for durable run settlement writes +// (finishing a run, reading it back at launch teardown). A transient store +// failure (a busy or briefly unavailable database) must not leave a run +// "running" with its workspace reserved until restart. +var runSettleBackoff = []time.Duration{250 * time.Millisecond, 500 * time.Millisecond, time.Second, 2 * time.Second, 4 * time.Second, 8 * time.Second, 15 * time.Second} + +// sleepSettle waits out one backoff step; false when the server is stopping. +func (r *runner) sleepSettle(delay time.Duration) bool { + select { + case <-r.ctx.Done(): + return false + case <-time.After(delay): + return true + } +} + +// finishRunWithRetry persists a run's terminal state, retrying a transient +// failure with backoff (each attempt under r.mu, the waits without it). A +// refused transition (an agent still active, cleanup unconfirmed, a run +// already settled) is final and not retried. +func (r *runner) finishRunWithRetry(id int64, status, outcome, diagnostic string, input stage.Values) { + for attempt := 0; ; attempt++ { + r.mu.Lock() + c, cancel := context.WithTimeout(context.Background(), 10*time.Second) + err := runFinishWrite(r, c, id, status, outcome, diagnostic, input) + cancel() + r.mu.Unlock() + if err == nil { + return + } + if errors.Is(err, pipeline.ErrInvalidRunTransition) || attempt >= len(runSettleBackoff) { + log.Printf("finish run %d: %v", id, err) + return + } + log.Printf("finish run %d (attempt %d, retrying): %v", id, attempt+1, err) + if !r.sleepSettle(runSettleBackoff[attempt]) { + return + } + } +} + // completedSteps counts the completed steps of a run detail; resume uses it to // seed the terminal delta without another store read. func completedSteps(steps []protocol.RunStep) int { diff --git a/internal/server/runner_reliability_test.go b/internal/server/runner_reliability_test.go new file mode 100644 index 00000000..4519d69f --- /dev/null +++ b/internal/server/runner_reliability_test.go @@ -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) + }) +} diff --git a/internal/server/schedule_scope_test.go b/internal/server/schedule_scope_test.go index fb53033e..5e501900 100644 --- a/internal/server/schedule_scope_test.go +++ b/internal/server/schedule_scope_test.go @@ -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 { diff --git a/internal/server/scheduler.go b/internal/server/scheduler.go index bdcfc14c..d2165955 100644 --- a/internal/server/scheduler.go +++ b/internal/server/scheduler.go @@ -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) +} diff --git a/internal/server/scheduler_reliability_test.go b/internal/server/scheduler_reliability_test.go new file mode 100644 index 00000000..bd9c7620 --- /dev/null +++ b/internal/server/scheduler_reliability_test.go @@ -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) + } +} diff --git a/internal/server/scheduler_test.go b/internal/server/scheduler_test.go index 3a9e5b28..9a7b5703 100644 --- a/internal/server/scheduler_test.go +++ b/internal/server/scheduler_test.go @@ -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 { diff --git a/internal/server/storage_cleanup.go b/internal/server/storage_cleanup.go index a82eb84f..4355ccbf 100644 --- a/internal/server/storage_cleanup.go +++ b/internal/server/storage_cleanup.go @@ -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 { diff --git a/internal/server/tools_test.go b/internal/server/tools_test.go index 2c200e26..e7678c07 100644 --- a/internal/server/tools_test.go +++ b/internal/server/tools_test.go @@ -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 { diff --git a/internal/server/websocket.go b/internal/server/websocket.go index a1cd26d5..41dfbacc 100644 --- a/internal/server/websocket.go +++ b/internal/server/websocket.go @@ -145,6 +145,7 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin // Prompts queued behind a running turn are durable and owned by their // session; resume delivering any a previous process left queued. hub.queueStore = stores[0] + hub.startChatNotificationOutbox(ctx, stores[0]) hub.liveStore = stores[0] hub.turnDiffStore = stores[0] }