fix: commit run notification intents with state transitions
This commit is contained in:
@@ -35,6 +35,23 @@ func (r *runner) notifyStep(id int64, name, workspace string, policy *protocol.N
|
||||
if !enabled {
|
||||
return
|
||||
}
|
||||
var lease *pipeline.RunNotification
|
||||
runEvent := stageAttentionEvent(event)
|
||||
if event == "success" && step.Target == protocol.SuccessEnd {
|
||||
runEvent = "succeeded"
|
||||
}
|
||||
if event == protocol.NotifyWaiting || step.Target == protocol.SuccessEnd || step.Target == protocol.FailureEnd {
|
||||
var allowed bool
|
||||
var err error
|
||||
lease, allowed, err = r.store.ClaimStageRunNotification(r.ctx, id, step.Sequence, runEvent, time.Now().Unix())
|
||||
if err != nil {
|
||||
log.Printf("claim stage notification run=%d: %v", id, err)
|
||||
return
|
||||
}
|
||||
if !allowed {
|
||||
return
|
||||
}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
summary := fmt.Sprintf("%s · run #%d · stage %s · %s (%s)", name, id, step.Stage, event, step.Outcome)
|
||||
@@ -134,7 +151,36 @@ func (r *runner) notifyStep(id int64, name, workspace string, policy *protocol.N
|
||||
covered = "succeeded"
|
||||
}
|
||||
r.markAttentionSent(id, step.Sequence, covered)
|
||||
break
|
||||
return
|
||||
}
|
||||
}
|
||||
if lease != nil {
|
||||
diagnostic := "stage notification publication failed"
|
||||
if len(receipts) > 0 && receipts[0].Diagnostic != "" {
|
||||
diagnostic = receipts[0].Diagnostic
|
||||
}
|
||||
if err := r.store.FinishRunNotification(r.ctx, *lease, time.Now().Unix(), "", fmt.Errorf("%s", diagnostic)); err != nil {
|
||||
log.Printf("release stage notification run=%d: %v", id, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Terminal hooks run only after FinishRun commits. They arbitrate against the
|
||||
// durable intent just like waiting hooks, never publishing a proposed success.
|
||||
func (r *runner) notifyTerminalStep(id int64, status string) {
|
||||
detail, err := r.store.GetRun(r.ctx, id)
|
||||
if err != nil || len(detail.Steps) == 0 {
|
||||
return
|
||||
}
|
||||
step := detail.Steps[len(detail.Steps)-1]
|
||||
stepStatus, _, _, terminal := terminalFinish(step.Target, step.Stage, step.Outcome, step.Diagnostic)
|
||||
if !terminal || stepStatus != status {
|
||||
return
|
||||
}
|
||||
for _, definition := range detail.Graph.Stages {
|
||||
if definition.Key == step.Stage {
|
||||
r.notifyStep(id, detail.Name, detail.Workspace, definition.Notify, step)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
"git.a-wan.net/alan/pipelines/internal/summarise"
|
||||
)
|
||||
|
||||
func TestRunNotificationPublisherFailureRetriesAfterReopen(t *testing.T) {
|
||||
@@ -58,6 +59,128 @@ func TestRunNotificationPublisherFailureRetriesAfterReopen(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestFinishRunPersistenceFailureDoesNotAnnounceSuccess(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
s, err := pipeline.Open(filepath.Join(t.TempDir(), "not-finished.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
source := strings.Replace(pipeline.Template([]string{"one"}, true), "# stage one", "# stage one\n```notify\non=success\n```", 1)
|
||||
if _, err := s.Submit(ctx, "test", source); 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.CreateRunTitled(ctx, d, "not-finished", "workspace", false, nil, nil, pipeline.RunOverrides{NotifyMode: "on"}, summarise.Title{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var calls atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"id": "wrong-success", "event": "message"})
|
||||
}))
|
||||
defer server.Close()
|
||||
t.Setenv("PIPELINES_NTFY_URL", server.URL+"/fake")
|
||||
t.Setenv("PIPELINES_NTFY_TOKEN", "")
|
||||
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
|
||||
r := &runner{ctx: ctx, store: s, events: newRunEventHub()}
|
||||
if err := s.BeginStep(ctx, id, 1, "one", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state := &runState{memory: map[string]memoryValue{}}
|
||||
if _, _, _, _, err := r.finishStage(id, "test", "workspace", d.Graph.Stages[0], state, protocol.RunStep{Sequence: 1, Stage: "one", Status: "completed", Outcome: "success", Target: protocol.SuccessEnd, Output: map[string]any{"markdown": "result"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls.Load() != 0 {
|
||||
t.Fatal("terminal stage success published before FinishRun")
|
||||
}
|
||||
sub := r.events.subscribe("test", "workspace", nil, func(protocol.Message) error { return nil })
|
||||
defer sub.close()
|
||||
// Marshal failure occurs before FinishRun can commit its proposed success.
|
||||
r.finishRunState(id, "test", "workspace", "succeeded", "success", "", 0, 0, "", stage.Values{"invalid": make(chan int)})
|
||||
got, err := s.GetRun(ctx, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Status != "running" || len(got.Notifications) != 0 || calls.Load() != 0 {
|
||||
t.Fatalf("unpersisted success announced: %+v calls=%d", got, calls.Load())
|
||||
}
|
||||
sub.mu.Lock()
|
||||
defer sub.mu.Unlock()
|
||||
if len(sub.pending) != 0 {
|
||||
t.Fatalf("unpersisted terminal event emitted: %+v", sub.pending)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitingHookSharesTransactionalRunIntent(t *testing.T) {
|
||||
for _, failFirst := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "covered", true: "retry"}[failFirst], func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
s, err := pipeline.Open(filepath.Join(t.TempDir(), "waiting-hook.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
var calls atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if calls.Add(1) == 1 && failFirst {
|
||||
http.Error(w, "transient", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"id": "waiting-ack", "event": "message"})
|
||||
}))
|
||||
defer server.Close()
|
||||
t.Setenv("PIPELINES_NTFY_URL", server.URL+"/fake")
|
||||
t.Setenv("PIPELINES_NTFY_TOKEN", "")
|
||||
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
|
||||
source := strings.Replace(humanPipelineSource, "# stage gate", "# stage gate\n```notify\non=waiting\n```", 1)
|
||||
if _, err := s.Submit(ctx, "waiting", source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, err := s.List(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err := newRunner(ctx, s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { cancel(); r.schedulerWG.Wait() }()
|
||||
run, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "waiting-hook", Workspace: t.TempDir(), Input: map[string]any{"prompt": "task"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
r.deliverRunNotifications(time.Now().Add(time.Minute))
|
||||
detail, err := s.GetRun(ctx, run.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wantCalls := int32(1)
|
||||
if failFirst {
|
||||
wantCalls = 2
|
||||
}
|
||||
if calls.Load() != wantCalls || detail.Status != "waiting" || len(detail.Notifications) != 1 {
|
||||
t.Fatalf("waiting hook duplicated/lost: calls=%d detail=%+v", calls.Load(), detail)
|
||||
}
|
||||
status := detail.Notifications[0].Status
|
||||
if status != "sent" && status != "covered" {
|
||||
t.Fatalf("missing acknowledgement: %+v", detail.Notifications)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunNotificationModesAndFinalStageDedupe(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -1332,7 +1332,10 @@ func (r *runner) finishRunState(id int64, name, workspace, status, outcome, diag
|
||||
CompletedSteps: completed,
|
||||
FinishedAt: detail.FinishedAt,
|
||||
}, true)
|
||||
r.notifyRun(id, name, status, sequence, currentStage, diagnostic)
|
||||
if status != protocol.RunStatusCanceled {
|
||||
r.notifyTerminalStep(id, status)
|
||||
}
|
||||
r.deliverRunNotificationBatch(time.Now(), 1)
|
||||
// The run is terminal: nothing more can notify for it.
|
||||
r.forgetAttention(id)
|
||||
r.forgetNotifyMode(id)
|
||||
@@ -1422,9 +1425,11 @@ func (r *runner) finishStage(id int64, name, workspace string, selected protocol
|
||||
}
|
||||
state.memory[step.Stage] = memoryValue{output: values, sequence: step.Sequence}
|
||||
}
|
||||
r.notifyStep(id, name, workspace, selected.Notify, step)
|
||||
state.input = stage.Values(step.Output)
|
||||
status, outcome, diagnostic, terminal = terminalFinish(step.Target, step.Stage, step.Outcome, step.Diagnostic)
|
||||
if !terminal {
|
||||
r.notifyStep(id, name, workspace, selected.Notify, step)
|
||||
}
|
||||
return status, outcome, diagnostic, terminal, nil
|
||||
}
|
||||
|
||||
@@ -1588,7 +1593,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
Step: &protocol.RunStepDelta{Sequence: sequence, Stage: key, Status: protocol.StepStatusWaiting},
|
||||
}, false)
|
||||
r.notifyStep(id, name, workspace, selected.Notify, waitStep)
|
||||
r.notifyRun(id, name, protocol.RunStatusWaiting, sequence, key, "")
|
||||
r.deliverRunNotificationBatch(time.Now(), 1)
|
||||
return
|
||||
}
|
||||
// A stage that declares a `skipped` route is short-circuited when the run
|
||||
|
||||
Reference in New Issue
Block a user