diff --git a/internal/contracts/state/v1/state.pb.go b/internal/contracts/state/v1/state.pb.go index f0adfd016..9744ee35d 100644 --- a/internal/contracts/state/v1/state.pb.go +++ b/internal/contracts/state/v1/state.pb.go @@ -12109,10 +12109,16 @@ func (x *EnqueueBindingTaskResponse) GetTask() *Task { // workflow.call: the caller's grant names the caller; the store derives the // rest from the caller's row (docs/prds/workflow-calls.md). type EnqueueCallTaskRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - CallerTaskId int64 `protobuf:"varint,1,opt,name=caller_task_id,json=callerTaskId,proto3" json:"caller_task_id,omitempty"` - Workflow string `protobuf:"bytes,2,opt,name=workflow,proto3" json:"workflow,omitempty"` - InputsJson string `protobuf:"bytes,3,opt,name=inputs_json,json=inputsJson,proto3" json:"inputs_json,omitempty"` + state protoimpl.MessageState `protogen:"open.v1"` + CallerTaskId int64 `protobuf:"varint,1,opt,name=caller_task_id,json=callerTaskId,proto3" json:"caller_task_id,omitempty"` + Workflow string `protobuf:"bytes,2,opt,name=workflow,proto3" json:"workflow,omitempty"` + InputsJson string `protobuf:"bytes,3,opt,name=inputs_json,json=inputsJson,proto3" json:"inputs_json,omitempty"` + // call_key is the call site's durable identity: the call step's declared + // path within the run. The store stamps it on the child and, when the + // caller already started a child under it, returns that child instead of + // starting a second one. Required: a retry of one call site carries the + // same key, so the retry cannot duplicate the child's work. + CallKey string `protobuf:"bytes,4,opt,name=call_key,json=callKey,proto3" json:"call_key,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -12168,6 +12174,13 @@ func (x *EnqueueCallTaskRequest) GetInputsJson() string { return "" } +func (x *EnqueueCallTaskRequest) GetCallKey() string { + if x != nil { + return x.CallKey + } + return "" +} + type EnqueueCallTaskResponse struct { state protoimpl.MessageState `protogen:"open.v1"` Task *Task `protobuf:"bytes,1,opt,name=task,proto3" json:"task,omitempty"` @@ -15994,12 +16007,13 @@ const file_state_v1_state_proto_rawDesc = "" + "\vinputs_json\x18\t \x01(\tR\n" + "inputsJson\"@\n" + "\x1aEnqueueBindingTaskResponse\x12\"\n" + - "\x04task\x18\x01 \x01(\v2\x0e.state.v1.TaskR\x04task\"{\n" + + "\x04task\x18\x01 \x01(\v2\x0e.state.v1.TaskR\x04task\"\x96\x01\n" + "\x16EnqueueCallTaskRequest\x12$\n" + "\x0ecaller_task_id\x18\x01 \x01(\x03R\fcallerTaskId\x12\x1a\n" + "\bworkflow\x18\x02 \x01(\tR\bworkflow\x12\x1f\n" + "\vinputs_json\x18\x03 \x01(\tR\n" + - "inputsJson\"Y\n" + + "inputsJson\x12\x19\n" + + "\bcall_key\x18\x04 \x01(\tR\acallKey\"Y\n" + "\x17EnqueueCallTaskResponse\x12\"\n" + "\x04task\x18\x01 \x01(\v2\x0e.state.v1.TaskR\x04task\x12\x1a\n" + "\baccepted\x18\x02 \x01(\bR\baccepted\"c\n" + diff --git a/internal/domain/workflow/step_flow.go b/internal/domain/workflow/step_flow.go index 29a3b7b9a..f27b69a50 100644 --- a/internal/domain/workflow/step_flow.go +++ b/internal/domain/workflow/step_flow.go @@ -207,6 +207,14 @@ func wrapStep(step StepRecord, body func(context.Context, *TaskContext) error) S attempts = step.Retry.Attempts } return Stage{Name: name, ContinueOnFailure: step.OnFailure == onFailureContinue, Run: func(ctx context.Context, tc *TaskContext) error { + // The step's path is its name qualified by the branch it runs in and + // by every step above it. A workflow.call below keys its child on it, + // so two runs of one call site agree and two call sites do not. + // Restored on return: a sibling step must not inherit the path of the + // step before it, nor a branch its parent's. + parentPath := tc.stepPath + tc.stepPath = joinStepPath(parentPath, branchStepName(tc.workflowBranch, name)) + defer func() { tc.stepPath = parentPath }() tc.stepResult = StepResult{} tc.skippedWhen = "" if step.When != "" && !when.holds(tc) { @@ -225,6 +233,15 @@ func wrapStep(step StepRecord, body func(context.Context, *TaskContext) error) S }} } +// joinStepPath qualifies a step name with the path of the step that encloses +// it; a top-level step's path is its own name. +func joinStepPath(parent, name string) string { + if parent == "" { + return name + } + return parent + "/" + name +} + func runAttempts(ctx context.Context, tc *TaskContext, name string, attempts int, backoff time.Duration, body func(context.Context, *TaskContext) error) error { var err error for attempt := 1; attempt <= attempts; attempt++ { diff --git a/internal/domain/workflow/task/caller.go b/internal/domain/workflow/task/caller.go index 0c8bf6a79..9416c560c 100644 --- a/internal/domain/workflow/task/caller.go +++ b/internal/domain/workflow/task/caller.go @@ -5,8 +5,11 @@ import "context" // Caller starts a workflow.call callee and reads it back. type Caller interface { // StartCall enqueues the callee for callerTaskID's call step at depth + 1. + // callKey is the call site's durable identity -- the call step's declared + // path within the run -- and is required: the same caller and key return + // the child already started, so a retry of a call site starts one child. // It fails if the caller is not running or the depth limit is exceeded. - StartCall(ctx context.Context, callerTaskID int64, workflow string, inputs map[string]any) (*Task, error) + StartCall(ctx context.Context, callerTaskID int64, callKey, workflow string, inputs map[string]any) (*Task, error) // CallStatus reads one call's callee: its status, latest transition detail // and written outputs. A store only answers for a task whose // call_parent_task_id is callerTaskID, so a caller reads only its own diff --git a/internal/domain/workflow/workflow.go b/internal/domain/workflow/workflow.go index d3e6b2481..e01b471d5 100644 --- a/internal/domain/workflow/workflow.go +++ b/internal/domain/workflow/workflow.go @@ -122,7 +122,12 @@ type TaskContext struct { // body is running: every agent call the stage makes records itself as // this step's child. Zero outside a stage body, which is how the stage // unit tests run their bodies. - StepID int64 + StepID int64 + // stepPath is the running step's declared path within the run: its name, + // qualified by the branch it runs in and by every step above it. It is a + // workflow.call's durable identity, so a retry of one call site starts + // one child. + stepPath string workflowBranch string // BuildSummary is the builder agent's finish summary -- the PR body. BuildSummary string diff --git a/internal/domain/workflow/workflow_call.go b/internal/domain/workflow/workflow_call.go index e10cb6cb7..4025956f6 100644 --- a/internal/domain/workflow/workflow_call.go +++ b/internal/domain/workflow/workflow_call.go @@ -103,6 +103,13 @@ func runWorkflowCall(ctx context.Context, s workflowCallSettings, tc *TaskContex if tc.Calls == nil { return fmt.Errorf("%s: this runner carries no callee capability", WorkflowCallStepName) } + // The key is what makes a retry of this call site return the same child, + // so a call that cannot name itself refuses rather than sharing a key with + // its siblings. + key, err := workflowCallKey(tc) + if err != nil { + return err + } if tc.Task.CallDepth+1 > MaxCallDepth { return fmt.Errorf("%s: call depth %d would pass the limit of %d", WorkflowCallStepName, tc.Task.CallDepth+1, MaxCallDepth) } @@ -110,7 +117,7 @@ func runWorkflowCall(ctx context.Context, s workflowCallSettings, tc *TaskContex if err != nil { return fmt.Errorf("%s: %w", WorkflowCallStepName, err) } - callee, err := tc.Calls.StartCall(ctx, tc.Task.ID, s.Workflow, inputs) + callee, err := tc.Calls.StartCall(ctx, tc.Task.ID, key, s.Workflow, inputs) if err != nil { return fmt.Errorf("%s: start %q: %w", WorkflowCallStepName, s.Workflow, err) } @@ -119,8 +126,9 @@ func runWorkflowCall(ctx context.Context, s workflowCallSettings, tc *TaskContex fmt.Sprintf("started %q as task %d", s.Workflow, callee.ID), started); err != nil { tc.Log.Warn("workflow call start not persisted", "err", err) } - // Record the call as a step holding the callee's execution ID. - callStep, _, err := tc.startCallStep(ctx, callee.ID) + // Record the call as a step holding the callee's execution ID, named for + // the call site so the dashboard shows which call started it. + callStep, _, err := tc.startCallStep(ctx, key, callee.ID) if err != nil { return fmt.Errorf("%s: could not be recorded: %w", WorkflowCallStepName, err) } @@ -162,14 +170,28 @@ func runWorkflowCall(ctx context.Context, s workflowCallSettings, tc *TaskContex return nil } +// workflowCallKey is the running call's durable identity: the step's declared +// path within the run. validateWorkflowCalls refuses a call step with no id at +// save, but a definition pinned before that rule still compiles and runs: its +// path is the bare step type, one key shared by every call site in the run, so +// the second call site would be handed the first's child. A stage run outside +// the step wrapper has no path at all, which is the same failure. +func workflowCallKey(tc *TaskContext) (string, error) { + path := tc.stepPath + if path == "" || path == WorkflowCallStepName || strings.HasSuffix(path, "/"+WorkflowCallStepName) { + return "", fmt.Errorf("%s: the step declares no id, and the step's id is the call's key", WorkflowCallStepName) + } + return path, nil +} + // startCallStep records the call step for a callee this run just started. -func (tc *TaskContext) startCallStep(ctx context.Context, calleeTaskID int64) (int64, events.Event, error) { +func (tc *TaskContext) startCallStep(ctx context.Context, key string, calleeTaskID int64) (int64, events.Event, error) { if tc.Store == nil { return 0, events.Event{}, nil } stepID, event, err := tc.Store.StartStep(ctx, task.StepStart{ ExecutionID: tc.Task.ID, Attempt: tc.Task.Attempt, ParentID: tc.StepID, - Kind: task.StepKindCall, Name: WorkflowCallStepName, CalledExecutionID: calleeTaskID, + Kind: task.StepKindCall, Name: key, CalledExecutionID: calleeTaskID, }) if err != nil { return 0, events.Event{}, err @@ -272,6 +294,12 @@ func validateWorkflowCalls(parsed map[string]YAMLDefinition) error { if step.Type != WorkflowCallStepName { return nil } + // The step's id is the call's key, so a call without one has no way + // to say which call site it is, and two of them in one run would + // share a child. + if step.ID == "" { + return fmt.Errorf("%s: %s declares no id, and the step's id is the call's key", where, WorkflowCallStepName) + } s, err := decodeCallSettings(step) if err != nil { return fmt.Errorf("%s: %w", where, err) diff --git a/internal/domain/workflow/workflow_call_test.go b/internal/domain/workflow/workflow_call_test.go index 29b7d3524..29752d19f 100644 --- a/internal/domain/workflow/workflow_call_test.go +++ b/internal/domain/workflow/workflow_call_test.go @@ -1,14 +1,135 @@ package workflow import ( + "context" + "log/slog" "maps" "slices" "strings" + "sync" "testing" "github.com/samcharles93/archie-core/internal/domain/workflow/task" ) +// callSpy records the key every call site started its child under, and models +// the store's own idempotency: one child per call key. +type callSpy struct { + mu sync.Mutex + keys []string + children map[string]*task.Task +} + +func (c *callSpy) StartCall(_ context.Context, callerTaskID int64, callKey, _ string, _ map[string]any) (*task.Task, error) { + c.mu.Lock() + defer c.mu.Unlock() + c.keys = append(c.keys, callKey) + child, ok := c.children[callKey] + if !ok { + child = &task.Task{ID: int64(len(c.children) + 1), CallParentTaskID: callerTaskID} + c.children[callKey] = child + } + return child, nil +} + +func (c *callSpy) CallStatus(context.Context, int64, int64) (string, string, map[string]any, error) { + return StatusCompleted, "", nil, nil +} + +func (c *callSpy) startedKeys() []string { + c.mu.Lock() + defer c.mu.Unlock() + return slices.Clone(c.keys) +} + +// TestWorkflowCallKeyIsTheDeclaredPath pins the call's durable identity: two +// runs of one call site -- a retry of the stage, a lost EnqueueCallTask reply +// -- key on the same declared path and start one child, and two call sites in +// one run key on different paths so neither returns the other's child. +func TestWorkflowCallKeyIsTheDeclaredPath(t *testing.T) { + registry := StepRegistry{WorkflowCallStepName: newWorkflowCallStage} + tests := []struct { + name string + def string + wantKeys []string + wantErr string + }{ + { + name: "a call step keys on its declared id", + def: `id: caller +repository: none +steps: + - {id: check, type: workflow.call, settings: {workflow: callee}} +`, + wantKeys: []string{"check"}, + }, + { + name: "a call in a parallel branch keys on its path within the run", + def: `id: caller +repository: none +steps: + - id: fanout + parallel: + a: [{id: check, type: workflow.call, settings: {workflow: callee}}] + b: [{id: verify, type: workflow.call, settings: {workflow: callee}}] +`, + wantKeys: []string{"fanout/a/check", "fanout/b/verify"}, + }, + { + // A definition pinned before the rule that a call declares an id + // compiles and runs: were its path the bare step type, every call + // site in the run would share one key and the second would return + // the first's child. + name: "a call step with no id is refused, not keyed on its type", + def: `id: caller +repository: none +steps: + - type: workflow.call + settings: {workflow: callee} +`, + wantErr: "declares no id", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + wf, err := ParseAndCompile(tt.def, registry) + if err != nil { + t.Fatalf("compile: %v", err) + } + spy := &callSpy{children: map[string]*task.Task{}} + tc := &TaskContext{Task: &task.Task{ID: 7}, Calls: spy, Log: slog.Default()} + stage := wf.Stages[0] + // The same stage twice: a requeued attempt re-runs the call site. + for range 2 { + if err := stage.Run(context.Background(), tc); err != nil { + if tt.wantErr == "" || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("err = %v, want %q", err, tt.wantErr) + } + if keys := spy.startedKeys(); len(keys) != 0 { + t.Fatalf("started %q, want no call", keys) + } + return + } + if tt.wantErr != "" { + t.Fatalf("err = nil, want %q", tt.wantErr) + } + } + keys := spy.startedKeys() + first, second := keys[:len(keys)/2], keys[len(keys)/2:] + // Branches finish in whatever order; the keys a run used, not their + // order, are the behaviour. + slices.Sort(first) + slices.Sort(second) + if !slices.Equal(first, tt.wantKeys) || !slices.Equal(second, tt.wantKeys) { + t.Fatalf("keys = %q then %q, want %q both times", first, second, tt.wantKeys) + } + if len(spy.children) != len(tt.wantKeys) { + t.Fatalf("started %d children, want %d", len(spy.children), len(tt.wantKeys)) + } + }) + } +} + func TestValidateWorkflowCallsWalksBranches(t *testing.T) { registry := StepRegistry{ AgentRunStepName: newAgentRunStage, @@ -27,7 +148,7 @@ func TestValidateWorkflowCallsWalksBranches(t *testing.T) { repository: none steps: - parallel: - a: [{type: workflow.call, settings: {workflow: callee}}] + a: [{id: check, type: workflow.call, settings: {workflow: callee}}] b: [{type: agent.run, settings: {mission: m, read_only: true}}] `, "callee": `id: callee @@ -44,12 +165,28 @@ steps: repository: none steps: - parallel: - a: [{type: workflow.call, settings: {workflow: missing}}] + a: [{id: check, type: workflow.call, settings: {workflow: missing}}] b: [{type: agent.run, settings: {mission: m, read_only: true}}] `, }, wantErr: `workflow "caller" step 1 branch "a" step 1 calls "missing", which is not defined`, }, + { + name: "a call step with no id is refused naming the step", + defs: map[string]string{ + "caller": `id: caller +repository: none +steps: + - {type: workflow.call, settings: {workflow: callee}} +`, + "callee": `id: callee +repository: none +steps: + - type: workflow.finish +`, + }, + wantErr: `workflow "caller" step 1: workflow.call declares no id`, + }, { name: "a cycle through branch calls is refused", defs: map[string]string{ @@ -57,13 +194,14 @@ steps: repository: none steps: - parallel: - x: [{type: workflow.call, settings: {workflow: b}}] + x: [{id: check, type: workflow.call, settings: {workflow: b}}] y: [{type: agent.run, settings: {mission: m, read_only: true}}] `, "b": `id: b repository: none steps: - - type: workflow.call + - id: call-back + type: workflow.call settings: {workflow: a} `, }, diff --git a/internal/infrastructure/agenttransport/nats/transport.go b/internal/infrastructure/agenttransport/nats/transport.go index 49ac09ee3..164839b5b 100644 --- a/internal/infrastructure/agenttransport/nats/transport.go +++ b/internal/infrastructure/agenttransport/nats/transport.go @@ -166,10 +166,10 @@ func (d deadlineCaller) withDeadline(ctx context.Context) (context.Context, cont return context.WithTimeout(ctx, d.timeout) } -func (d deadlineCaller) StartCall(ctx context.Context, callerTaskID int64, wf string, inputs map[string]any) (*task.Task, error) { +func (d deadlineCaller) StartCall(ctx context.Context, callerTaskID int64, callKey, wf string, inputs map[string]any) (*task.Task, error) { ctx, cancel := d.withDeadline(ctx) defer cancel() - return d.Caller.StartCall(ctx, callerTaskID, wf, inputs) + return d.Caller.StartCall(ctx, callerTaskID, callKey, wf, inputs) } func (d deadlineCaller) CallStatus(ctx context.Context, callerTaskID, callTaskID int64) (string, string, map[string]any, error) { diff --git a/internal/infrastructure/postgres/migrations/0038_workflow_call_key.sql b/internal/infrastructure/postgres/migrations/0038_workflow_call_key.sql new file mode 100644 index 000000000..46c647ba7 --- /dev/null +++ b/internal/infrastructure/postgres/migrations/0038_workflow_call_key.sql @@ -0,0 +1,16 @@ +-- tasks.call_key is a workflow.call call site's durable identity: the call +-- step's declared path within the calling run. With the parent it is the key +-- EnqueueCallTask upserts on, so a retry of one call site -- a lost +-- EnqueueCallTask reply, a failed step record, a requeued attempt -- returns +-- the child already started instead of starting a second one. The index is +-- partial: every task that is not a workflow.call callee carries the empty key. + +-- +goose Up + +ALTER TABLE tasks ADD COLUMN call_key text NOT NULL DEFAULT ''; +CREATE UNIQUE INDEX idx_tasks_call_key ON tasks (call_parent_task_id, call_key) WHERE call_key <> ''; + +-- +goose Down + +DROP INDEX idx_tasks_call_key; +ALTER TABLE tasks DROP COLUMN call_key; diff --git a/internal/infrastructure/postgres/postgresdb/call_tasks.sql.go b/internal/infrastructure/postgres/postgresdb/call_tasks.sql.go index 99cb27c35..6cfb82386 100644 --- a/internal/infrastructure/postgres/postgresdb/call_tasks.sql.go +++ b/internal/infrastructure/postgres/postgresdb/call_tasks.sql.go @@ -24,9 +24,9 @@ func (q *Queries) CallStatusDetail(ctx context.Context, taskID int64) (string, e const enqueueCallTask = `-- name: EnqueueCallTask :one WITH caller AS ( - SELECT t.id, t.owner, t.repo, t.issue_number, t.title, t.body, t.labels, t.status, t.workflow, t.branch, t.plan, t.notes, t.pr_number, t.tokens_used, t.iterations, t.attempt, t.park_reason, t.watch_comment_id, t.park_class, t.remediation_rounds, t.retry_count, t.source, t.identity, t.binding_id, t.binding_version, t.review_payload, t.workflow_definition_version, t.workflow_definition_digest, t.workflow_definition_yaml, t.created_at, t.updated_at, t.review_cursor, t.inputs, t.org_id, t.workspace_id, t.call_parent_task_id, t.call_depth, t.outputs, t.review_gate, t.rereview_rounds, t.retry_mode, t.resume_from, t.resume_results, t.pending_reviews, t.origin FROM tasks t WHERE t.id = $1 FOR UPDATE + SELECT t.id, t.owner, t.repo, t.issue_number, t.title, t.body, t.labels, t.status, t.workflow, t.branch, t.plan, t.notes, t.pr_number, t.tokens_used, t.iterations, t.attempt, t.park_reason, t.watch_comment_id, t.park_class, t.remediation_rounds, t.retry_count, t.source, t.identity, t.binding_id, t.binding_version, t.review_payload, t.workflow_definition_version, t.workflow_definition_digest, t.workflow_definition_yaml, t.created_at, t.updated_at, t.review_cursor, t.inputs, t.org_id, t.workspace_id, t.call_parent_task_id, t.call_depth, t.outputs, t.review_gate, t.rereview_rounds, t.retry_mode, t.resume_from, t.resume_results, t.pending_reviews, t.origin, t.call_key FROM tasks t WHERE t.id = $1 FOR UPDATE ) -INSERT INTO tasks (owner, repo, issue_number, title, body, labels, workflow, source, identity, org_id, workspace_id, inputs, call_parent_task_id, call_depth) +INSERT INTO tasks (owner, repo, issue_number, title, body, labels, workflow, source, identity, org_id, workspace_id, inputs, call_parent_task_id, call_depth, call_key) SELECT caller.owner, caller.repo, @@ -38,10 +38,11 @@ SELECT ), $2::bigint) + 1, $3, $4, 'chat', $5, 'chat', caller.identity, caller.org_id, caller.workspace_id, $6, - caller.id, caller.call_depth + 1 + caller.id, caller.call_depth + 1, $7 FROM caller -WHERE caller.status = 'running' AND caller.call_depth + 1 <= $7::int -RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin +WHERE caller.status = 'running' AND caller.call_depth + 1 <= $8::int +ON CONFLICT (call_parent_task_id, call_key) WHERE call_key <> '' DO UPDATE SET call_key = EXCLUDED.call_key +RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key ` type EnqueueCallTaskParams struct { @@ -51,10 +52,17 @@ type EnqueueCallTaskParams struct { Body string Workflow string Inputs string + CallKey string MaxDepth int32 } // The callee of a workflow.call step (docs/prds/workflow-calls.md) +// +// The call key makes this the one write that can be retried: a call site that +// already started its child gets that child back rather than a second one. The +// upsert only fires for a keyed callee, and the WHERE below still decides +// whether the caller may call at all -- a caller that is missing, not running +// or past the depth limit inserts nothing and returns no row, conflict or not. func (q *Queries) EnqueueCallTask(ctx context.Context, arg EnqueueCallTaskParams) (Task, error) { row := q.db.QueryRow(ctx, enqueueCallTask, arg.ID, @@ -63,6 +71,7 @@ func (q *Queries) EnqueueCallTask(ctx context.Context, arg EnqueueCallTaskParams arg.Body, arg.Workflow, arg.Inputs, + arg.CallKey, arg.MaxDepth, ) var i Task @@ -112,6 +121,7 @@ func (q *Queries) EnqueueCallTask(ctx context.Context, arg EnqueueCallTaskParams &i.ResumeResults, &i.PendingReviews, &i.Origin, + &i.CallKey, ) return i, err } diff --git a/internal/infrastructure/postgres/postgresdb/models.go b/internal/infrastructure/postgres/postgresdb/models.go index f5eda6995..288a4bf3e 100644 --- a/internal/infrastructure/postgres/postgresdb/models.go +++ b/internal/infrastructure/postgres/postgresdb/models.go @@ -429,6 +429,7 @@ type Task struct { ResumeResults []byte PendingReviews []byte Origin string + CallKey string } type ToolCall struct { diff --git a/internal/infrastructure/postgres/postgresdb/tasks.sql.go b/internal/infrastructure/postgres/postgresdb/tasks.sql.go index b7ff8471a..8b4e40f66 100644 --- a/internal/infrastructure/postgres/postgresdb/tasks.sql.go +++ b/internal/infrastructure/postgres/postgresdb/tasks.sql.go @@ -13,7 +13,7 @@ import ( ) const activeTasksByOrigin = `-- name: ActiveTasksByOrigin :many -SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin FROM tasks +SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key FROM tasks WHERE origin = $1 AND origin <> '' AND status IN ('queued', 'running') ORDER BY id ` @@ -74,6 +74,7 @@ func (q *Queries) ActiveTasksByOrigin(ctx context.Context, origin string) ([]Tas &i.ResumeResults, &i.PendingReviews, &i.Origin, + &i.CallKey, ); err != nil { return nil, err } @@ -153,7 +154,7 @@ func (q *Queries) BeginRemediationTask(ctx context.Context, arg BeginRemediation const claimByIssue = `-- name: ClaimByIssue :one UPDATE tasks SET status = 'running', attempt = attempt + 1, outputs = '', updated_at = now() WHERE owner = $1 AND repo = $2 AND issue_number = $3 AND status = 'queued' -RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin +RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key ` type ClaimByIssueParams struct { @@ -213,6 +214,7 @@ func (q *Queries) ClaimByIssue(ctx context.Context, arg ClaimByIssueParams) (Tas &i.ResumeResults, &i.PendingReviews, &i.Origin, + &i.CallKey, ) return i, err } @@ -227,7 +229,7 @@ WHERE id = ( FOR UPDATE SKIP LOCKED LIMIT 1 ) -RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin +RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key ` // FOR UPDATE SKIP LOCKED replaces the SQLite single-writer assumption: two @@ -285,6 +287,7 @@ func (q *Queries) ClaimNextTask(ctx context.Context) (Task, error) { &i.ResumeResults, &i.PendingReviews, &i.Origin, + &i.CallKey, ) return i, err } @@ -396,7 +399,7 @@ VALUES ( $8, $9 ) -RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin +RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key ` type InsertChatTaskParams struct { @@ -477,6 +480,7 @@ func (q *Queries) InsertChatTask(ctx context.Context, arg InsertChatTaskParams) &i.ResumeResults, &i.PendingReviews, &i.Origin, + &i.CallKey, ) return i, err } @@ -915,7 +919,7 @@ func (q *Queries) StampTaskBinding(ctx context.Context, arg StampTaskBindingPara } const taskByID = `-- name: TaskByID :one -SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin FROM tasks WHERE id = $1 +SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key FROM tasks WHERE id = $1 ` func (q *Queries) TaskByID(ctx context.Context, id int64) (Task, error) { @@ -967,12 +971,13 @@ func (q *Queries) TaskByID(ctx context.Context, id int64) (Task, error) { &i.ResumeResults, &i.PendingReviews, &i.Origin, + &i.CallKey, ) return i, err } const taskByIssue = `-- name: TaskByIssue :one -SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin FROM tasks WHERE owner = $1 AND repo = $2 AND issue_number = $3 +SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key FROM tasks WHERE owner = $1 AND repo = $2 AND issue_number = $3 ` type TaskByIssueParams struct { @@ -1030,12 +1035,13 @@ func (q *Queries) TaskByIssue(ctx context.Context, arg TaskByIssueParams) (Task, &i.ResumeResults, &i.PendingReviews, &i.Origin, + &i.CallKey, ) return i, err } const taskByPR = `-- name: TaskByPR :one -SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin FROM tasks WHERE owner = $1 AND repo = $2 AND pr_number = $3 AND status = $4 +SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key FROM tasks WHERE owner = $1 AND repo = $2 AND pr_number = $3 AND status = $4 ` type TaskByPRParams struct { @@ -1102,6 +1108,7 @@ func (q *Queries) TaskByPR(ctx context.Context, arg TaskByPRParams) (Task, error &i.ResumeResults, &i.PendingReviews, &i.Origin, + &i.CallKey, ) return i, err } diff --git a/internal/infrastructure/postgres/queries/call_tasks.sql b/internal/infrastructure/postgres/queries/call_tasks.sql index 0fd63eb24..d0203c211 100644 --- a/internal/infrastructure/postgres/queries/call_tasks.sql +++ b/internal/infrastructure/postgres/queries/call_tasks.sql @@ -1,9 +1,15 @@ -- name: EnqueueCallTask :one -- The callee of a workflow.call step (docs/prds/workflow-calls.md) +-- +-- The call key makes this the one write that can be retried: a call site that +-- already started its child gets that child back rather than a second one. The +-- upsert only fires for a keyed callee, and the WHERE below still decides +-- whether the caller may call at all -- a caller that is missing, not running +-- or past the depth limit inserts nothing and returns no row, conflict or not. WITH caller AS ( SELECT t.* FROM tasks t WHERE t.id = $1 FOR UPDATE ) -INSERT INTO tasks (owner, repo, issue_number, title, body, labels, workflow, source, identity, org_id, workspace_id, inputs, call_parent_task_id, call_depth) +INSERT INTO tasks (owner, repo, issue_number, title, body, labels, workflow, source, identity, org_id, workspace_id, inputs, call_parent_task_id, call_depth, call_key) SELECT caller.owner, caller.repo, @@ -15,9 +21,10 @@ SELECT ), sqlc.arg('fallback_issue_number')::bigint) + 1, sqlc.arg(title), sqlc.arg(body), 'chat', sqlc.arg(workflow), 'chat', caller.identity, caller.org_id, caller.workspace_id, sqlc.arg(inputs), - caller.id, caller.call_depth + 1 + caller.id, caller.call_depth + 1, sqlc.arg('call_key') FROM caller WHERE caller.status = 'running' AND caller.call_depth + 1 <= sqlc.arg('max_depth')::int +ON CONFLICT (call_parent_task_id, call_key) WHERE call_key <> '' DO UPDATE SET call_key = EXCLUDED.call_key RETURNING *; -- name: CallStatusDetail :one diff --git a/internal/infrastructure/postgres/store.go b/internal/infrastructure/postgres/store.go index cd8f6efae..1409cc9ca 100644 --- a/internal/infrastructure/postgres/store.go +++ b/internal/infrastructure/postgres/store.go @@ -782,9 +782,10 @@ func (s *Store) TaskByID(ctx context.Context, taskID int64) (*workflow.Task, err } // StartCall enqueues a workflow.call callee inheriting the caller's org, -// workspace, identity and repo. The caller must be running and within -// workflow.MaxCallDepth. -func (s *Store) StartCall(ctx context.Context, callerTaskID int64, wf string, inputs map[string]any) (*workflow.Task, error) { +// workspace, identity and repo, and returns the callee already started under +// callerTaskID and callKey when there is one. The caller must be running and +// within workflow.MaxCallDepth. +func (s *Store) StartCall(ctx context.Context, callerTaskID int64, callKey string, wf string, inputs map[string]any) (*workflow.Task, error) { encoded, err := task.EncodeInputs(inputs) if err != nil { return nil, err @@ -796,6 +797,7 @@ func (s *Store) StartCall(ctx context.Context, callerTaskID int64, wf string, in Body: fmt.Sprintf("Started by a workflow.call step from task %d (workflow %q); the call's inputs travel with the task.", callerTaskID, wf), Workflow: wf, Inputs: encoded, + CallKey: callKey, MaxDepth: int32(workflow.MaxCallDepth), }) if errors.Is(err, pgx.ErrNoRows) { diff --git a/internal/infrastructure/postgres/workflow_call_test.go b/internal/infrastructure/postgres/workflow_call_test.go new file mode 100644 index 000000000..eb224cad7 --- /dev/null +++ b/internal/infrastructure/postgres/workflow_call_test.go @@ -0,0 +1,51 @@ +package postgres_test + +import ( + "testing" + + "github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore" +) + +// StartCall is idempotent per call site: the same caller and call key return +// the child already started, so a retry of a lost EnqueueCallTask reply, or of +// the stage that made the call, does not start a second child and run its work +// twice. A different call site in the same run still gets its own child. +func TestStartCallReturnsOneChildPerCallKey(t *testing.T) { + ctx := t.Context() + db := pgstore.Open(t) + if _, err := db.EnqueueChatTask(ctx, "", "", "caller", "", "tdd", "", "", nil); err != nil { + t.Fatal(err) + } + caller, err := db.ClaimNext(ctx) + if err != nil || caller == nil { + t.Fatalf("claim: %v", err) + } + + first, err := db.StartCall(ctx, caller.ID, "check", "callee", nil) + if err != nil { + t.Fatal(err) + } + retry, err := db.StartCall(ctx, caller.ID, "check", "callee", nil) + if err != nil { + t.Fatal(err) + } + if retry.ID != first.ID { + t.Fatalf("the retry started task %d, want the child already started, %d", retry.ID, first.ID) + } + other, err := db.StartCall(ctx, caller.ID, "verify", "callee", nil) + if err != nil { + t.Fatal(err) + } + if other.ID == first.ID { + t.Fatalf("a different call key returned the first child, %d", first.ID) + } + + var rows int + if err := db.Pool.QueryRow(ctx, + `SELECT count(*) FROM tasks WHERE call_parent_task_id = $1`, caller.ID).Scan(&rows); err != nil { + t.Fatal(err) + } + if rows != 2 { + t.Fatalf("the caller started %d children, want one per call key (2)", rows) + } +} diff --git a/internal/infrastructure/staterpc/client.go b/internal/infrastructure/staterpc/client.go index 1f3085d27..22f83f42c 100644 --- a/internal/infrastructure/staterpc/client.go +++ b/internal/infrastructure/staterpc/client.go @@ -756,12 +756,12 @@ func (c *Client) EnqueueBindingTask(ctx context.Context, owner, repo, title, bod // rehydrates the sentinels the server maps, so a caller's errors.Is(err, // storecontract.ErrCallNotYours) works across the wire. -func (c *Client) StartCall(ctx context.Context, callerTaskID int64, wf string, inputs map[string]any) (*task.Task, error) { +func (c *Client) StartCall(ctx context.Context, callerTaskID int64, callKey, wf string, inputs map[string]any) (*task.Task, error) { encoded, err := task.EncodeInputs(inputs) if err != nil { return nil, err } - r, err := c.client.EnqueueCallTask(ctx, &pb.EnqueueCallTaskRequest{CallerTaskId: callerTaskID, Workflow: wf, InputsJson: encoded}) + r, err := c.client.EnqueueCallTask(ctx, &pb.EnqueueCallTaskRequest{CallerTaskId: callerTaskID, CallKey: callKey, Workflow: wf, InputsJson: encoded}) if err != nil { return nil, unmapError(err) } diff --git a/internal/infrastructure/staterpc/server.go b/internal/infrastructure/staterpc/server.go index 8bc8f5c75..2556e8aae 100644 --- a/internal/infrastructure/staterpc/server.go +++ b/internal/infrastructure/staterpc/server.go @@ -1123,11 +1123,16 @@ func (s *server) EnqueueCallTask(ctx context.Context, r *pb.EnqueueCallTaskReque if r.CallerTaskId <= 0 { return nil, status.Error(codes.InvalidArgument, "caller task id is required") } + // A call is identified by its key: without one the store would have to + // guess, and two calls of one caller would collide or duplicate. + if r.CallKey == "" { + return nil, status.Error(codes.InvalidArgument, "call key is required") + } inputs, err := task.DecodeInputs(r.InputsJson) if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } - t, err := s.deps.WorkflowCalls.StartCall(ctx, r.CallerTaskId, r.Workflow, inputs) + t, err := s.deps.WorkflowCalls.StartCall(ctx, r.CallerTaskId, r.CallKey, r.Workflow, inputs) if err != nil { return nil, s.logErr("EnqueueCallTask", err) } diff --git a/proto/state/v1/state.proto b/proto/state/v1/state.proto index a9b5c4800..0ee587a49 100644 --- a/proto/state/v1/state.proto +++ b/proto/state/v1/state.proto @@ -1260,6 +1260,12 @@ message EnqueueCallTaskRequest { int64 caller_task_id = 1; string workflow = 2; string inputs_json = 3; + // call_key is the call site's durable identity: the call step's declared + // path within the run. The store stamps it on the child and, when the + // caller already started a child under it, returns that child instead of + // starting a second one. Required: a retry of one call site carries the + // same key, so the retry cannot duplicate the child's work. + string call_key = 4; } message EnqueueCallTaskResponse { Task task = 1;