fix: persist and retry run alerts and honor notification modes
This commit is contained in:
@@ -621,6 +621,7 @@ func (s *Store) removeRetentionRuns(ctx context.Context, policy RetentionPolicy,
|
||||
func deleteRetentionRows(ctx context.Context, tx *sql.Tx, ids []int64) error {
|
||||
for _, table := range []struct{ name, column string }{
|
||||
{"step_notifications", "run_id"},
|
||||
{"run_notifications", "run_id"},
|
||||
{"step_file_changes", "run_id"},
|
||||
{"step_control", "run_id"},
|
||||
{"step_artifacts", "run_id"},
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// RunNotification is durable publisher evidence, not proof of device reception.
|
||||
// A sending lease permits restart recovery; a crash after publish but before
|
||||
// acknowledgement can repeat a message. Attempts are bounded, not guaranteed.
|
||||
type RunNotification struct {
|
||||
RunID int64
|
||||
Sequence int
|
||||
Event, Channel, Title, Body, Click, Status, Diagnostic, MessageID string
|
||||
Attempts int
|
||||
}
|
||||
|
||||
func (s *Store) initRunNotifications() error {
|
||||
_, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS run_notifications (
|
||||
run_id INTEGER NOT NULL, sequence INTEGER NOT NULL, event TEXT NOT NULL, channel TEXT NOT NULL,
|
||||
title TEXT NOT NULL, body TEXT NOT NULL, click TEXT NOT NULL,
|
||||
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 '',
|
||||
PRIMARY KEY(run_id,sequence,event,channel));
|
||||
CREATE INDEX IF NOT EXISTS run_notifications_due ON run_notifications(status,next_attempt);`)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) EnqueueRunNotification(ctx context.Context, n RunNotification) error {
|
||||
_, err := s.db.ExecContext(ctx, `INSERT OR IGNORE INTO run_notifications
|
||||
(run_id,sequence,event,channel,title,body,click) VALUES (?,?,?,?,?,?,?)`, n.RunID, n.Sequence, n.Event, n.Channel, n.Title, n.Body, n.Click)
|
||||
return err
|
||||
}
|
||||
|
||||
// ClaimRunNotification atomically leases one due attempt for 60 seconds. Three
|
||||
// attempts total bound both transient failures and crash/restart loops.
|
||||
func (s *Store) ClaimRunNotification(ctx context.Context, now int64) (*RunNotification, error) {
|
||||
if _, err := s.db.ExecContext(ctx, `UPDATE run_notifications SET status='failed',diagnostic='publisher acknowledgement unknown after final lease expired' WHERE status='sending' AND attempts>=3 AND next_attempt<=?`, now); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n := new(RunNotification)
|
||||
err := s.db.QueryRowContext(ctx, `UPDATE run_notifications SET status='sending', attempts=attempts+1, next_attempt=?
|
||||
WHERE rowid=(SELECT rowid FROM run_notifications WHERE status IN ('pending','sending') AND attempts<3 AND next_attempt<=? ORDER BY next_attempt,rowid LIMIT 1)
|
||||
RETURNING run_id,sequence,event,channel,title,body,click,status,attempts`, now+60, now).Scan(&n.RunID, &n.Sequence, &n.Event, &n.Channel, &n.Title, &n.Body, &n.Click, &n.Status, &n.Attempts)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
// CoverRunNotification records a successful stage publication covering the same
|
||||
// run event, without publishing a second final alert.
|
||||
func (s *Store) CoverRunNotification(ctx context.Context, id int64, sequence int, event string) error {
|
||||
_, err := s.db.ExecContext(ctx, `INSERT OR IGNORE INTO run_notifications(run_id,sequence,event,channel,title,body,click,status) VALUES (?,?,?,'system','','','','covered')`, id, sequence, event)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) FinishRunNotification(ctx context.Context, n RunNotification, now int64, messageID string, failure error) error {
|
||||
status, diagnostic := "sent", ""
|
||||
if failure != nil {
|
||||
status, diagnostic = "pending", failure.Error()
|
||||
if n.Attempts >= 3 {
|
||||
status = "failed"
|
||||
}
|
||||
}
|
||||
_, err := s.db.ExecContext(ctx, `UPDATE run_notifications SET status=?,diagnostic=?,message_id=?,next_attempt=?
|
||||
WHERE run_id=? AND sequence=? AND event=? AND channel=? AND status='sending' AND attempts=?`, status, diagnostic, messageID, now+int64(n.Attempts*5), n.RunID, n.Sequence, n.Event, n.Channel, n.Attempts)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) RunNotifications(ctx context.Context, id int64) ([]RunNotification, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT run_id,sequence,event,channel,status,attempts,diagnostic,message_id FROM run_notifications WHERE run_id=? ORDER BY sequence,event,channel`, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
result := []RunNotification{}
|
||||
for rows.Next() {
|
||||
var n RunNotification
|
||||
if err := rows.Scan(&n.RunID, &n.Sequence, &n.Event, &n.Channel, &n.Status, &n.Attempts, &n.Diagnostic, &n.MessageID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, n)
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRunNotificationPersistenceLeasesAndBound(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
path := filepath.Join(t.TempDir(), "outbox.db")
|
||||
s, err := Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
n := RunNotification{RunID: 7, Sequence: 2, Event: "failed", Channel: "system", Title: "Failed", Body: "Run #7", Click: "pipelines://run/7"}
|
||||
if err := s.EnqueueRunNotification(ctx, n); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.EnqueueRunNotification(ctx, n); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first, err := s.ClaimRunNotification(ctx, 100)
|
||||
if err != nil || first == nil || first.Attempts != 1 {
|
||||
t.Fatalf("first claim: %+v %v", first, err)
|
||||
}
|
||||
if other, err := s.ClaimRunNotification(ctx, 100); err != nil || other != nil {
|
||||
t.Fatalf("lease double claim: %+v %v", other, err)
|
||||
}
|
||||
// Reopen an already-existing schema, preserving an in-flight lease.
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err = Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
second, err := s.ClaimRunNotification(ctx, 161)
|
||||
if err != nil || second == nil || second.Attempts != 2 || second.Body != n.Body {
|
||||
t.Fatalf("recovery: %+v %v", second, err)
|
||||
}
|
||||
if err := s.FinishRunNotification(ctx, *second, 161, "", errors.New("publisher unavailable")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if other, err := s.ClaimRunNotification(ctx, 170); err != nil || other != nil {
|
||||
t.Fatalf("backoff ignored: %+v %v", other, err)
|
||||
}
|
||||
third, err := s.ClaimRunNotification(ctx, 171)
|
||||
if err != nil || third == nil || third.Attempts != 3 {
|
||||
t.Fatalf("third claim: %+v %v", third, err)
|
||||
}
|
||||
// Final attempt crashes: its expired lease must become failed, not retry forever.
|
||||
if other, err := s.ClaimRunNotification(ctx, 232); err != nil || other != nil {
|
||||
t.Fatalf("retry bound ignored: %+v %v", other, err)
|
||||
}
|
||||
got, err := s.RunNotifications(ctx, 7)
|
||||
if err != nil || len(got) != 1 || got[0].Status != "failed" || got[0].Attempts != 3 {
|
||||
t.Fatalf("audit: %+v %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunNotificationStageCoverageSurvivesReopen(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
path := filepath.Join(t.TempDir(), "coverage.db")
|
||||
s, err := Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.CoverRunNotification(ctx, 7, 1, "succeeded"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err = Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
if err := s.EnqueueRunNotification(ctx, RunNotification{RunID: 7, Sequence: 1, Event: "succeeded", Channel: "system"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, err := s.ClaimRunNotification(ctx, 100); err != nil || got != nil {
|
||||
t.Fatalf("covered stage repeated: %+v %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunNotificationMigrationPreservesExistingRun(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
path := filepath.Join(t.TempDir(), "existing.db")
|
||||
s, err := Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Submit(ctx, "existing", Template([]string{"one"}, true)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, err := s.List(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d, err := s.Get(ctx, items[0].ID, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id, _, err := s.CreateRun(ctx, d, "existing-key", "workspace", false, nil, map[string]any{"prompt": "preserve me"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Simulate the immediately preceding schema, which has no run outbox.
|
||||
if _, err := s.db.ExecContext(ctx, "DROP TABLE run_notifications"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err = Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
got, err := s.GetRun(ctx, id)
|
||||
if err != nil || got.Input["prompt"] != "preserve me" || got.Status != "queued" || got.NotifyMode != "auto" || len(got.Notifications) != 0 {
|
||||
t.Fatalf("migration changed run: %+v %v", got, err)
|
||||
}
|
||||
if err := s.EnqueueRunNotification(ctx, RunNotification{RunID: id, Sequence: 1, Event: "failed", Channel: "system"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -21,12 +21,12 @@ const runStamps = `strftime('%Y-%m-%dT%H:%M:%SZ',r.created_at),COALESCE(strftime
|
||||
const runSelect = `SELECT r.id,r.pipeline_id,p.name,r.version,v.content_hash,r.status,r.outcome,r.current_stage,
|
||||
` + runStamps + `,r.diagnostic,
|
||||
CASE WHEN r.status='succeeded' THEN r.output_json ELSE COALESCE((SELECT output_json FROM run_steps WHERE run_id=r.id AND status='completed' ORDER BY sequence DESC LIMIT 1),'{}') END,
|
||||
(SELECT COUNT(*) FROM run_steps WHERE run_id=r.id AND status='completed'),r.workspace,r.title,r.model,r.stage_models
|
||||
(SELECT COUNT(*) FROM run_steps WHERE run_id=r.id AND status='completed'),r.workspace,r.title,r.model,r.stage_models,r.notify_mode
|
||||
` + runFrom + ` JOIN pipeline_versions v ON v.pipeline_id=r.pipeline_id AND v.version=r.version`
|
||||
|
||||
func scanRun(row interface{ Scan(...any) error }, r *protocol.RunSummary) error {
|
||||
var output, stageModels string
|
||||
if err := row.Scan(&r.ID, &r.PipelineID, &r.Name, &r.Version, &r.ContentHash, &r.Status, &r.Outcome, &r.CurrentStage, &r.CreatedAt, &r.FinishedAt, &r.Diagnostic, &output, &r.CompletedSteps, &r.Workspace, &r.Title, &r.Model, &stageModels); err != nil {
|
||||
if err := row.Scan(&r.ID, &r.PipelineID, &r.Name, &r.Version, &r.ContentHash, &r.Status, &r.Outcome, &r.CurrentStage, &r.CreatedAt, &r.FinishedAt, &r.Diagnostic, &output, &r.CompletedSteps, &r.Workspace, &r.Title, &r.Model, &stageModels, &r.NotifyMode); err != nil {
|
||||
return err
|
||||
}
|
||||
if stageModels != "" && stageModels != "{}" {
|
||||
@@ -201,6 +201,23 @@ strftime('%Y-%m-%dT%H:%M:%SZ',started_at),COALESCE(strftime('%Y-%m-%dT%H:%M:%SZ'
|
||||
// The run total is one pass over the steps already loaded above: it adds no
|
||||
// query and no transcript parse.
|
||||
r.Usage = protocol.TotalUsage(r.Steps)
|
||||
alerts, err := tx.QueryContext(ctx, `SELECT sequence,event,channel,status,attempts,diagnostic,message_id FROM run_notifications WHERE run_id=? ORDER BY sequence,event,channel`, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for alerts.Next() {
|
||||
var receipt protocol.RunNotificationReceipt
|
||||
if err := alerts.Scan(&receipt.Sequence, &receipt.Event, &receipt.Channel, &receipt.Status, &receipt.Attempts, &receipt.Diagnostic, &receipt.MessageID); err != nil {
|
||||
alerts.Close()
|
||||
return nil, err
|
||||
}
|
||||
r.Notifications = append(r.Notifications, receipt)
|
||||
}
|
||||
err = alerts.Err()
|
||||
alerts.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -54,6 +54,10 @@ CREATE TABLE IF NOT EXISTS submissions (id INTEGER PRIMARY KEY, name TEXT NOT NU
|
||||
db.Close()
|
||||
return nil, err
|
||||
}
|
||||
if err := s.initRunNotifications(); err != nil {
|
||||
db.Close()
|
||||
return nil, err
|
||||
}
|
||||
if err := s.initSchedules(); err != nil {
|
||||
db.Close()
|
||||
return nil, err
|
||||
|
||||
Reference in New Issue
Block a user