refactor: testing from the beginning. a journey in 150k lines of tests to none
This commit is contained in:
651 files changed
-146443
No files matched your search
@@ -1,31 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestAgentStatusSnapshotBeforeObserveIsUnverified(t *testing.T) {
|
||||
var s AgentStatus
|
||||
if version, installType, ok := s.Snapshot(); ok || version != "" || installType != "" {
|
||||
t.Fatalf("Snapshot() = (%q, %q, %v), want zero values and ok=false before any Observe", version, installType, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAgentStatusObserveThenSnapshot(t *testing.T) {
|
||||
var s AgentStatus
|
||||
s.Observe("1.9.11", "container")
|
||||
|
||||
version, installType, ok := s.Snapshot()
|
||||
if !ok || version != "1.9.11" || installType != "container" {
|
||||
t.Fatalf("Snapshot() = (%q, %q, %v), want (\"1.9.11\", \"container\", true)", version, installType, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAgentStatusObserveOverwritesPrevious(t *testing.T) {
|
||||
var s AgentStatus
|
||||
s.Observe("1.9.10", "container")
|
||||
s.Observe("1.9.11", "container")
|
||||
|
||||
version, _, _ := s.Snapshot()
|
||||
if version != "1.9.11" {
|
||||
t.Fatalf("Snapshot() version = %q, want the most recent observation %q", version, "1.9.11")
|
||||
}
|
||||
}
|
||||
@@ -1,171 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const workflowImportPath = "github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
|
||||
// Autonomous workflow execution belongs exclusively to the task-scoped
|
||||
// archie-agent worker. A local workflow.Run call in daemon silently restores
|
||||
// the host-authority fallback this boundary exists to remove.
|
||||
func TestDaemonNeverExecutesWorkflowLocally(t *testing.T) {
|
||||
files, err := filepath.Glob("*.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fileset := token.NewFileSet()
|
||||
for _, path := range files {
|
||||
if strings.HasSuffix(path, "_test.go") {
|
||||
continue
|
||||
}
|
||||
file, parseErr := parser.ParseFile(fileset, path, nil, 0)
|
||||
if parseErr != nil {
|
||||
t.Errorf("parse %s: %v", path, parseErr)
|
||||
continue
|
||||
}
|
||||
workflowNames := make(map[string]bool)
|
||||
dotImport := false
|
||||
for _, spec := range file.Imports {
|
||||
importPath, unquoteErr := strconv.Unquote(spec.Path.Value)
|
||||
if unquoteErr != nil || importPath != workflowImportPath {
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case spec.Name == nil:
|
||||
workflowNames["workflow"] = true
|
||||
case spec.Name.Name == ".":
|
||||
dotImport = true
|
||||
case spec.Name.Name != "_":
|
||||
workflowNames[spec.Name.Name] = true
|
||||
}
|
||||
}
|
||||
ast.Inspect(file, func(node ast.Node) bool {
|
||||
call, ok := node.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
if dotImport {
|
||||
if ident, ok := call.Fun.(*ast.Ident); ok && ident.Name == "Run" {
|
||||
reportLocalWorkflowRun(t, fileset, call)
|
||||
}
|
||||
}
|
||||
selector, ok := call.Fun.(*ast.SelectorExpr)
|
||||
if !ok || selector.Sel.Name != "Run" {
|
||||
return true
|
||||
}
|
||||
pkg, ok := selector.X.(*ast.Ident)
|
||||
if ok && workflowNames[pkg.Name] {
|
||||
reportLocalWorkflowRun(t, fileset, call)
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func reportLocalWorkflowRun(t *testing.T, fileset *token.FileSet, call *ast.CallExpr) {
|
||||
t.Helper()
|
||||
position := fileset.Position(call.Pos())
|
||||
t.Errorf("%s calls workflow.Run; autonomous workflows must use the full-task worker handoff", position)
|
||||
}
|
||||
|
||||
// Daemon and IdentityRunner carry routing and authority state only. Keeping a
|
||||
// stage runner or workflow registry on either type makes a host execution path
|
||||
// one call away from returning.
|
||||
func TestDaemonCarriesNoLocalWorkflowExecutionState(t *testing.T) {
|
||||
file, err := parser.ParseFile(token.NewFileSet(), "daemon.go", nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
forbiddenExecution := map[string]bool{"Agent": true, "Workflows": true, "CustomStages": true}
|
||||
// Composition handles the daemon must not carry. Each was an exported field
|
||||
// the composition root assigned and nothing read: the curator
|
||||
// registry/runtime is boot-owned (the curator isolation invariant keeps it
|
||||
// off the agent loop), the capability host is lifecycle-owned by the
|
||||
// composition root and consumed by the control plane, and the tool registry
|
||||
// is consumed by chat/curator/MCP wiring. A re-add is decorative wiring.
|
||||
forbiddenHandles := map[string]bool{"Curators": true, "CapabilityHost": true, "ToolRegistry": true}
|
||||
for _, declaration := range file.Decls {
|
||||
gen, ok := declaration.(*ast.GenDecl)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
for _, spec := range gen.Specs {
|
||||
typeSpec, ok := spec.(*ast.TypeSpec)
|
||||
if !ok || (typeSpec.Name.Name != "Daemon" && typeSpec.Name.Name != "IdentityRunner") {
|
||||
continue
|
||||
}
|
||||
structure, ok := typeSpec.Type.(*ast.StructType)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
for _, field := range structure.Fields.List {
|
||||
for _, name := range field.Names {
|
||||
if forbiddenExecution[name.Name] {
|
||||
t.Errorf("%s carries local workflow execution field %s", typeSpec.Name.Name, name.Name)
|
||||
}
|
||||
if forbiddenHandles[name.Name] {
|
||||
t.Errorf("%s carries unread composition handle %s; the composition root owns it", typeSpec.Name.Name, name.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A repository's base branch has exactly one default and Repo.BaseBranch() is
|
||||
// where it lives: an empty base means "main". Handing the raw field to the
|
||||
// worktree manager skips that mapping, so a repository stored with no base
|
||||
// reaches git with "" and the branch is never cut from main
|
||||
// (archie-core-lwzd).
|
||||
//
|
||||
// This is a wiring invariant rather than a behaviour test because the value is
|
||||
// an argument: the worktree manager's own tests cover what it does with a base,
|
||||
// and a daemon-level test would need a real clone to reach the call.
|
||||
func TestDaemonPreparesWorktreesFromTheMappedBaseBranch(t *testing.T) {
|
||||
files, err := filepath.Glob("*.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fileset := token.NewFileSet()
|
||||
checked := 0
|
||||
for _, path := range files {
|
||||
if strings.HasSuffix(path, "_test.go") {
|
||||
continue
|
||||
}
|
||||
file, parseErr := parser.ParseFile(fileset, path, nil, 0)
|
||||
if parseErr != nil {
|
||||
t.Errorf("parse %s: %v", path, parseErr)
|
||||
continue
|
||||
}
|
||||
ast.Inspect(file, func(node ast.Node) bool {
|
||||
call, ok := node.(*ast.CallExpr)
|
||||
// Prepare carries owner, repo, base, issue, title, body, labels and
|
||||
// the daemon's prepare target: nine arguments.
|
||||
if !ok || len(call.Args) != 9 {
|
||||
return true
|
||||
}
|
||||
selector, ok := call.Fun.(*ast.SelectorExpr)
|
||||
if !ok || selector.Sel.Name != "Prepare" {
|
||||
return true
|
||||
}
|
||||
checked++
|
||||
base, ok := call.Args[3].(*ast.SelectorExpr)
|
||||
if ok && base.Sel.Name == "Base" {
|
||||
t.Errorf("%s: worktree.Prepare receives the raw base field; pass BaseBranch() so an empty base means main",
|
||||
fileset.Position(call.Pos()))
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
// A rename or a move must not leave this passing without having looked.
|
||||
if checked == 0 {
|
||||
t.Error("no worktree.Prepare call found, so the base-branch invariant went unchecked")
|
||||
}
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
dockercontainer "github.com/moby/moby/api/types/container"
|
||||
"github.com/moby/moby/client"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
archiecontainer "github.com/samcharles93/archie-core/internal/container"
|
||||
)
|
||||
|
||||
// This pins the last handoff seam, not just its two halves: the runtime NATS
|
||||
// endpoint frozen in Daemon becomes the environment on a container created on
|
||||
// the same Docker network whose gateway embedded NATS binds.
|
||||
func TestConnectedNATSEndpointReachesManagedContainerCreate(t *testing.T) {
|
||||
const (
|
||||
networkName = "workers"
|
||||
gateway = "172.31.0.1"
|
||||
containerID = "12345678901234567890123456789012"
|
||||
token = "runtime-only-token"
|
||||
)
|
||||
var createRequest dockercontainer.CreateRequest
|
||||
dockerAPI := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case strings.HasSuffix(r.URL.Path, "/networks/"+networkName):
|
||||
writeContainerDockerJSON(t, w, map[string]any{
|
||||
"Name": networkName,
|
||||
"Driver": "bridge",
|
||||
"Scope": "local",
|
||||
"IPAM": map[string]any{
|
||||
"Config": []map[string]string{{
|
||||
"Subnet": "172.31.0.0/16",
|
||||
"Gateway": gateway,
|
||||
}},
|
||||
},
|
||||
})
|
||||
case strings.HasSuffix(r.URL.Path, "/containers/create"):
|
||||
if err := json.NewDecoder(r.Body).Decode(&createRequest); err != nil {
|
||||
t.Errorf("decode container create request: %v", err)
|
||||
}
|
||||
writeContainerDockerJSON(t, w, dockercontainer.CreateResponse{ID: containerID})
|
||||
case strings.HasSuffix(r.URL.Path, "/containers/"+containerID+"/start"):
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
case strings.HasSuffix(r.URL.Path, "/containers/json"):
|
||||
writeContainerDockerJSON(t, w, []any{})
|
||||
default:
|
||||
http.Error(w, fmt.Sprintf("unexpected Docker API path %s", r.URL.Path), http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(dockerAPI.Close)
|
||||
|
||||
dockerClient, err := client.New(client.WithHost(dockerAPI.URL), client.WithAPIVersion("1.55"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = dockerClient.Close() })
|
||||
|
||||
pool, err := archiecontainer.NewPool(t.Context(), archiecontainer.Config{
|
||||
Image: "archie-agent:test",
|
||||
Network: networkName,
|
||||
DockerClient: dockerClient,
|
||||
RequireHostGateway: true,
|
||||
}, nil, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatalf("container.NewPool = %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = pool.Close() })
|
||||
|
||||
d := &Daemon{
|
||||
Cfg: config.NewHolder(config.Config{}),
|
||||
ConnectedNATS: NATSEndpoint{
|
||||
URL: "nats://" + gateway + ":4222",
|
||||
Token: token,
|
||||
},
|
||||
}
|
||||
if _, err := pool.Acquire(t.Context(), "", nil, d.containerEnv(nil, "")); err != nil {
|
||||
t.Fatalf("Pool.Acquire = %v", err)
|
||||
}
|
||||
|
||||
if createRequest.HostConfig == nil || string(createRequest.HostConfig.NetworkMode) != networkName {
|
||||
t.Fatalf("container network = %v, want %q", createRequest.HostConfig, networkName)
|
||||
}
|
||||
for _, want := range []string{
|
||||
"NATS_URL=nats://" + gateway + ":4222",
|
||||
"NATS_TOKEN=" + token,
|
||||
} {
|
||||
if !slices.Contains(createRequest.Env, want) {
|
||||
t.Errorf("container env = %q, want %q", createRequest.Env, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func writeContainerDockerJSON(t *testing.T, w http.ResponseWriter, value any) {
|
||||
t.Helper()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if err := json.NewEncoder(w).Encode(value); err != nil {
|
||||
t.Errorf("encode Docker response: %v", err)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,458 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
// Test 30: an armed binding + an authenticated capture creates a task
|
||||
// whose provenance points back at the binding (and its version), and
|
||||
// records a dispatch row in the dedup ledger.
|
||||
func TestDispatchBindingsCreatesTaskFromArmedCapture(t *testing.T) {
|
||||
s := openDispatchTestStore(t)
|
||||
mappingID := seedMapping(t, s, "sentry", mapping.Field{Name: "title", Path: "title", Type: mapping.TypeString, Required: true})
|
||||
bindingID, bindingVersion := seedArmedBinding(t, s, "sentry", mappingID)
|
||||
seedCapture(t, s, "sentry", true, `{"title":"hello"}`)
|
||||
|
||||
d := newDispatchDaemon(t, s)
|
||||
d.dispatchBindings(t.Context())
|
||||
|
||||
tasks, err := s.Tasks(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("Tasks: %v", err)
|
||||
}
|
||||
if len(tasks) != 1 {
|
||||
t.Fatalf("Tasks len = %d, want 1", len(tasks))
|
||||
}
|
||||
got := tasks[0]
|
||||
if got.BindingID != bindingID {
|
||||
t.Errorf("task.BindingID = %q, want %q", got.BindingID, bindingID)
|
||||
}
|
||||
if got.BindingVersion != bindingVersion {
|
||||
t.Errorf("task.BindingVersion = %d, want %d", got.BindingVersion, bindingVersion)
|
||||
}
|
||||
if got.Source != workflow.SourceChat {
|
||||
t.Errorf("task.Source = %q, want %q", got.Source, workflow.SourceChat)
|
||||
}
|
||||
if got.Status != workflow.StatusQueued {
|
||||
t.Errorf("task.Status = %q, want %q", got.Status, workflow.StatusQueued)
|
||||
}
|
||||
|
||||
assertDispatchRecorded(t, s, bindingID)
|
||||
}
|
||||
|
||||
// TestDispatchBindingsUsesBindingRepoPinWithMultipleConfiguredRepos is the
|
||||
// multi-repo fix: a binding that pins Owner/Repo dispatches to that
|
||||
// target even when the daemon has zero or several [[repos]] configured,
|
||||
// where resolveBindingRepo's old single-repo-only fallback would have
|
||||
// refused entirely.
|
||||
func TestDispatchBindingsUsesBindingRepoPinWithMultipleConfiguredRepos(t *testing.T) {
|
||||
s := openDispatchTestStore(t)
|
||||
mappingID := seedMapping(t, s, "sentry", mapping.Field{Name: "title", Path: "title", Type: mapping.TypeString, Required: true})
|
||||
bindingID, _ := seedArmedBindingWithRepo(t, s, "sentry", mappingID, "acme", "widget")
|
||||
seedCapture(t, s, "sentry", true, `{"title":"hello"}`)
|
||||
|
||||
d := newDispatchDaemonWithRepos(t, s, []config.Repo{
|
||||
{Owner: "acme", Name: "widget"},
|
||||
{Owner: "other-org", Name: "other-repo"},
|
||||
})
|
||||
d.dispatchBindings(t.Context())
|
||||
|
||||
tasks, err := s.Tasks(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("Tasks: %v", err)
|
||||
}
|
||||
if len(tasks) != 1 {
|
||||
t.Fatalf("Tasks len = %d, want 1 (pinned binding must dispatch despite 2 configured repos)", len(tasks))
|
||||
}
|
||||
if tasks[0].Owner != "acme" || tasks[0].Repo != "widget" {
|
||||
t.Fatalf("task owner/repo = %s/%s, want acme/widget (the binding's own pin, not a guess)", tasks[0].Owner, tasks[0].Repo)
|
||||
}
|
||||
assertDispatchRecorded(t, s, bindingID)
|
||||
}
|
||||
|
||||
// TestDispatchBindingsRefusesUnpinnedBindingWithMultipleConfiguredRepos
|
||||
// pins the existing safety behaviour: a binding with no Owner/Repo pin
|
||||
// must still refuse to dispatch when the target repo is ambiguous,
|
||||
// exactly as it did before this field existed.
|
||||
func TestDispatchBindingsRefusesUnpinnedBindingWithMultipleConfiguredRepos(t *testing.T) {
|
||||
s := openDispatchTestStore(t)
|
||||
mappingID := seedMapping(t, s, "sentry", mapping.Field{Name: "title", Path: "title", Type: mapping.TypeString, Required: true})
|
||||
seedArmedBinding(t, s, "sentry", mappingID) // no owner/repo pin
|
||||
seedCapture(t, s, "sentry", true, `{"title":"hello"}`)
|
||||
|
||||
d := newDispatchDaemonWithRepos(t, s, []config.Repo{
|
||||
{Owner: "acme", Name: "widget"},
|
||||
{Owner: "other-org", Name: "other-repo"},
|
||||
})
|
||||
d.dispatchBindings(t.Context())
|
||||
|
||||
tasks, err := s.Tasks(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("Tasks: %v", err)
|
||||
}
|
||||
if len(tasks) != 0 {
|
||||
t.Fatalf("Tasks len = %d, want 0 (an unpinned binding must still refuse an ambiguous target)", len(tasks))
|
||||
}
|
||||
}
|
||||
|
||||
// Test 31: the binding_dispatches ledger is the at-most-once
|
||||
// guarantee across cycles -- running dispatchBindings twice must
|
||||
// yield exactly one task even though the undispatched-captures query
|
||||
// keeps finding the capture on the second pass.
|
||||
func TestDispatchBindingsDoesNotDoubleDispatch(t *testing.T) {
|
||||
s := openDispatchTestStore(t)
|
||||
mappingID := seedMapping(t, s, "sentry", mapping.Field{Name: "title", Path: "title", Type: mapping.TypeString})
|
||||
seedArmedBinding(t, s, "sentry", mappingID)
|
||||
seedCapture(t, s, "sentry", true, `{"title":"hello"}`)
|
||||
|
||||
d := newDispatchDaemon(t, s)
|
||||
d.dispatchBindings(t.Context())
|
||||
d.dispatchBindings(t.Context())
|
||||
|
||||
tasks, err := s.Tasks(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("Tasks: %v", err)
|
||||
}
|
||||
if len(tasks) != 1 {
|
||||
t.Fatalf("after two cycles, Tasks len = %d, want 1 (ledger dedup)", len(tasks))
|
||||
}
|
||||
}
|
||||
|
||||
// Test 32: an unauthenticated capture can never spawn a task -- the
|
||||
// matcher refuses it regardless of source match (binding.Matcher.Matches
|
||||
// gates on authenticated, see docs/prds/webhook-intake-security.md).
|
||||
func TestDispatchBindingsSkipsUnauthenticatedCaptures(t *testing.T) {
|
||||
s := openDispatchTestStore(t)
|
||||
mappingID := seedMapping(t, s, "sentry", mapping.Field{Name: "title", Path: "title", Type: mapping.TypeString})
|
||||
seedArmedBinding(t, s, "sentry", mappingID)
|
||||
seedCapture(t, s, "sentry", false, `{"title":"hello"}`)
|
||||
|
||||
d := newDispatchDaemon(t, s)
|
||||
d.dispatchBindings(t.Context())
|
||||
|
||||
tasks, err := s.Tasks(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("Tasks: %v", err)
|
||||
}
|
||||
if len(tasks) != 0 {
|
||||
t.Fatalf("unauthenticated capture spawned %d task(s), want 0", len(tasks))
|
||||
}
|
||||
}
|
||||
|
||||
// markUnsigned reports every undispatched capture as taken on an approved
|
||||
// unsigned source, which the legacy capture store cannot persist.
|
||||
type markUnsigned struct {
|
||||
storecontract.BindingDispatcher
|
||||
}
|
||||
|
||||
func (m markUnsigned) ListUndispatchedCaptures(ctx context.Context, sources []string, limit int) ([]storecontract.CapturedEvent, error) {
|
||||
cs, err := m.BindingDispatcher.ListUndispatchedCaptures(ctx, sources, limit)
|
||||
for i := range cs {
|
||||
cs[i].Unsigned = true
|
||||
}
|
||||
return cs, err
|
||||
}
|
||||
|
||||
// An event on an approved unsigned source dispatches without a signature,
|
||||
// and the task it starts carries an unsigned_event on its timeline.
|
||||
func TestDispatchBindingsDispatchesUnsignedCaptureAndMarksTimeline(t *testing.T) {
|
||||
s := openDispatchTestStore(t)
|
||||
mappingID := seedMapping(t, s, "fw", mapping.Field{Name: "title", Path: "title", Type: mapping.TypeString})
|
||||
seedArmedBinding(t, s, "fw", mappingID)
|
||||
seedCapture(t, s, "fw", false, `{"title":"blocked"}`)
|
||||
|
||||
d := newDispatchDaemon(t, s)
|
||||
d.BindingDispatcher = markUnsigned{d.BindingDispatcher}
|
||||
d.dispatchBindings(t.Context())
|
||||
|
||||
tasks, err := s.Tasks(t.Context(), 10)
|
||||
if err != nil || len(tasks) != 1 {
|
||||
t.Fatalf("Tasks = %d (err %v), want 1", len(tasks), err)
|
||||
}
|
||||
evs, err := s.TaskEvents(t.Context(), tasks[0].ID)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskEvents: %v", err)
|
||||
}
|
||||
for _, e := range evs {
|
||||
if e.Kind == events.KindUnsignedEvent {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatalf("task timeline has no %s event: %+v", events.KindUnsignedEvent, evs)
|
||||
}
|
||||
|
||||
// Test 33: a required field whose path is missing in the capture body
|
||||
// blocks the dispatch -- the failure path emits a
|
||||
// binding_dispatch_failure event and creates no task.
|
||||
func TestDispatchBindingsSkipsWhenResolveFails(t *testing.T) {
|
||||
s := openDispatchTestStore(t)
|
||||
mappingID := seedMapping(t, s, "sentry",
|
||||
mapping.Field{Name: "title", Path: "title", Type: mapping.TypeString, Required: true})
|
||||
seedArmedBinding(t, s, "sentry", mappingID)
|
||||
// Body is missing the required "title" path.
|
||||
seedCapture(t, s, "sentry", true, `{"other":"value"}`)
|
||||
|
||||
d := newDispatchDaemon(t, s)
|
||||
d.dispatchBindings(t.Context())
|
||||
|
||||
tasks, err := s.Tasks(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("Tasks: %v", err)
|
||||
}
|
||||
if len(tasks) != 0 {
|
||||
t.Fatalf("required-field failure spawned %d task(s), want 0", len(tasks))
|
||||
}
|
||||
events, err := s.EventsSince(t.Context(), "", 100)
|
||||
if err != nil {
|
||||
t.Fatalf("EventsSince: %v", err)
|
||||
}
|
||||
found := false
|
||||
for _, e := range events {
|
||||
if e.Kind == "binding_dispatch_failure" {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("binding_dispatch_failure event not published; got %d events", len(events))
|
||||
}
|
||||
}
|
||||
|
||||
// Test 34: with no armed bindings the loop is a no-op -- even with
|
||||
// authenticated captures sitting in the table.
|
||||
func TestDispatchBindingsNoOpWhenNoArmedBindings(t *testing.T) {
|
||||
s := openDispatchTestStore(t)
|
||||
// Capture is present, but no binding rows exist.
|
||||
seedCapture(t, s, "sentry", true, `{"title":"hello"}`)
|
||||
|
||||
d := newDispatchDaemon(t, s)
|
||||
d.dispatchBindings(t.Context())
|
||||
|
||||
tasks, err := s.Tasks(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("Tasks: %v", err)
|
||||
}
|
||||
if len(tasks) != 0 {
|
||||
t.Fatalf("no-armed-bindings loop spawned %d task(s), want 0", len(tasks))
|
||||
}
|
||||
}
|
||||
|
||||
// Test: dispatchBindings is a no-op when Bindings is nil -- the loop
|
||||
// must degrade silently rather than panic in legacy compositions.
|
||||
func TestDispatchBindingsNilBindingsIsNoOp(t *testing.T) {
|
||||
d := &Daemon{
|
||||
Cfg: config.NewHolder(config.Config{}),
|
||||
Log: slog.New(slog.NewTextHandler(os.Stderr, nil)),
|
||||
}
|
||||
// Should not panic.
|
||||
d.dispatchBindings(t.Context())
|
||||
}
|
||||
|
||||
// TestDispatchBindingsNilDispatcherIsNoOp exercises the composition
|
||||
// gap the daemon field comments claim is safe: Bindings is set (so an
|
||||
// armed binding + a matching capture exist) but BindingDispatcher is
|
||||
// nil. Both fields are documented "optional: nil disables the
|
||||
// dispatch loop", so this must degrade silently rather than panic on
|
||||
// the nil-interface call to ListUndispatchedCaptures.
|
||||
func TestDispatchBindingsNilDispatcherIsNoOp(t *testing.T) {
|
||||
s := openDispatchTestStore(t)
|
||||
mappingID := seedMapping(t, s, "sentry", mapping.Field{Name: "title", Path: "title", Type: mapping.TypeString})
|
||||
seedArmedBinding(t, s, "sentry", mappingID)
|
||||
seedCapture(t, s, "sentry", true, `{"title":"hello"}`)
|
||||
|
||||
d := &Daemon{
|
||||
Cfg: config.NewHolder(config.Config{Repos: []config.Repo{{Owner: "acme", Name: "widget"}}}),
|
||||
Store: s.Store,
|
||||
Mappings: s.EdaStore,
|
||||
Bindings: s.EdaStore,
|
||||
// BindingDispatcher and BindingTaskCreator intentionally nil.
|
||||
Log: slog.New(slog.NewTextHandler(os.Stderr, nil)),
|
||||
}
|
||||
// Should not panic.
|
||||
d.dispatchBindings(t.Context())
|
||||
}
|
||||
|
||||
// ── helpers ──────────────────────────────────────────────────────
|
||||
|
||||
// dispatchStores pairs the two stores the dispatcher spans: the task store and
|
||||
// the event-capture store, so a seed helper reads as one handle.
|
||||
type dispatchStores struct {
|
||||
*pgstore.TaskDB
|
||||
EdaStore *postgres.EDA
|
||||
edaPool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func openDispatchTestStore(t *testing.T) *dispatchStores {
|
||||
t.Helper()
|
||||
s := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
pool := pgstore.Pool(t)
|
||||
return &dispatchStores{TaskDB: s, EdaStore: postgres.NewEDA(pool, nil), edaPool: pool}
|
||||
}
|
||||
|
||||
// seedMapping inserts a mapping with the given fields and returns its id.
|
||||
// The mapping belongs to a catch-all event type on sourceHint, so every
|
||||
// capture later inserted on that source is identified as its type and
|
||||
// dispatches.
|
||||
func seedMapping(t *testing.T, s *dispatchStores, sourceHint string, fields ...mapping.Field) string {
|
||||
t.Helper()
|
||||
eventTypeID, err := s.EdaStore.InsertEventType(t.Context(), eventtype.EventType{Source: sourceHint, Name: "any"})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertEventType: %v", err)
|
||||
}
|
||||
id, err := s.EdaStore.InsertMapping(t.Context(), mapping.Mapping{
|
||||
Name: sourceHint + "-mapping",
|
||||
SourceHint: sourceHint,
|
||||
EventTypeID: eventTypeID,
|
||||
Fields: fields,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertMapping: %v", err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// seedArmedBinding inserts a binding and approves it, matching the operator
|
||||
// flow an Approve button on the dashboard drives: InsertBinding stores
|
||||
// pending_approval and the only sanctioned armed transition is
|
||||
// ApproveBinding.
|
||||
func seedArmedBinding(t *testing.T, s *dispatchStores, source, mappingID string) (string, int) {
|
||||
t.Helper()
|
||||
return seedArmedBindingWithRepo(t, s, source, mappingID, "", "")
|
||||
}
|
||||
|
||||
// seedArmedBindingWithRepo is seedArmedBinding with an explicit
|
||||
// owner/repo pin (pass "", "" for the unpinned case seedArmedBinding
|
||||
// covers).
|
||||
func seedArmedBindingWithRepo(t *testing.T, s *dispatchStores, source, mappingID, owner, repo string) (string, int) {
|
||||
t.Helper()
|
||||
id, err := s.EdaStore.InsertBinding(t.Context(), binding.Binding{
|
||||
Name: "test " + source,
|
||||
Matcher: binding.Matcher{Source: source},
|
||||
MappingID: mappingID,
|
||||
Workflow: "implement",
|
||||
Owner: owner,
|
||||
Repo: repo,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertBinding: %v", err)
|
||||
}
|
||||
if err := s.EdaStore.ApproveBinding(t.Context(), id); err != nil {
|
||||
t.Fatalf("ApproveBinding: %v", err)
|
||||
}
|
||||
got, err := s.EdaStore.GetBinding(t.Context(), id)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("GetBinding after approve: %+v, %v", got, err)
|
||||
}
|
||||
return id, got.Version
|
||||
}
|
||||
|
||||
// seedCapture inserts an inbound capture event with the given source,
|
||||
// authenticated flag, and body. retention=0, maxEvents=0 disable
|
||||
// the per-insert pruning the production path uses, so a test that
|
||||
// only needs a single row in the table is not at the mercy of
|
||||
// maxEvents=0's "no cap" reading.
|
||||
func seedCapture(t *testing.T, s *dispatchStores, source string, authenticated bool, body string) {
|
||||
t.Helper()
|
||||
_, err := s.EdaStore.InsertCapture(t.Context(), storecontract.CapturedEvent{
|
||||
Source: source,
|
||||
Body: body,
|
||||
Authenticated: authenticated,
|
||||
ReceivedAt: time.Now().UTC(),
|
||||
}, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("InsertCapture: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// newDispatchDaemon builds a Daemon whose store-related handles all
|
||||
// point at the same *pgstore.TaskDB so dispatchBindings can resolve
|
||||
// captures through the dispatcher handles and mappings through
|
||||
// d.Mappings. Exactly one repo is configured so resolveBindingRepo's
|
||||
// single-repo fallback accepts the dispatch; with zero or many
|
||||
// configured repos the loop would log and skip, masking the test's
|
||||
// positive assertions.
|
||||
func newDispatchDaemon(t *testing.T, s *dispatchStores) *Daemon {
|
||||
t.Helper()
|
||||
return newDispatchDaemonWithRepos(t, s, []config.Repo{{Owner: "acme", Name: "widget"}})
|
||||
}
|
||||
|
||||
// newDispatchDaemonWithRepos is newDispatchDaemon with an explicit repo
|
||||
// list, for tests exercising resolveBindingRepo's owner/repo-pin path
|
||||
// against zero, one, or several configured repos.
|
||||
func newDispatchDaemonWithRepos(t *testing.T, s *dispatchStores, repos []config.Repo) *Daemon {
|
||||
t.Helper()
|
||||
cfg := config.Config{Repos: repos}
|
||||
return &Daemon{
|
||||
Cfg: config.NewHolder(cfg),
|
||||
Store: s.Store,
|
||||
Mappings: s.EdaStore,
|
||||
Bindings: s.EdaStore,
|
||||
BindingDispatcher: s.EdaStore,
|
||||
BindingTaskCreator: s.Store,
|
||||
Log: slog.New(slog.NewTextHandler(os.Stderr, nil)),
|
||||
}
|
||||
}
|
||||
|
||||
// assertDispatchRecorded reads the dedup ledger directly: the (binding,
|
||||
// capture) unique index is what guarantees no double dispatch. The dispatch
|
||||
// is claimed before its task exists, so the row carries no task id.
|
||||
func assertDispatchRecorded(t *testing.T, s *dispatchStores, bindingID string) {
|
||||
t.Helper()
|
||||
var gotBindingID string
|
||||
if err := s.edaPool.QueryRow(t.Context(),
|
||||
"SELECT binding FROM binding_dispatches WHERE binding = $1", bindingID).
|
||||
Scan(&gotBindingID); err != nil {
|
||||
t.Fatalf("binding_dispatches row missing: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
type staticEnablement struct {
|
||||
value workflowtask.WorkflowEnablement
|
||||
}
|
||||
|
||||
func (e staticEnablement) WorkflowEnablement(context.Context) (workflowtask.WorkflowEnablement, error) {
|
||||
return e.value, nil
|
||||
}
|
||||
|
||||
// A binding whose org disabled its workflow does not dispatch, and the capture
|
||||
// waits: re-enabling the workflow dispatches it on the next cycle.
|
||||
func TestDispatchBindingsSkipsWorkflowItsOrgDisabled(t *testing.T) {
|
||||
s := openDispatchTestStore(t)
|
||||
mappingID := seedMapping(t, s, "sentry", mapping.Field{Name: "title", Path: "title", Type: mapping.TypeString, Required: true})
|
||||
bindingID, _ := seedArmedBinding(t, s, "sentry", mappingID)
|
||||
seedCapture(t, s, "sentry", true, `{"title":"hello"}`)
|
||||
stored, err := s.EdaStore.GetBinding(t.Context(), bindingID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetBinding: %v", err)
|
||||
}
|
||||
|
||||
d := newDispatchDaemon(t, s)
|
||||
var enablement workflowtask.WorkflowEnablement
|
||||
d.WorkflowEnablement = staticEnablement{enablement.SetEnabled(stored.OrgID, stored.Workflow, false)}
|
||||
d.dispatchBindings(t.Context())
|
||||
if tasks, _ := s.Tasks(t.Context(), 10); len(tasks) != 0 {
|
||||
t.Fatalf("Tasks len = %d, want 0 while the workflow is disabled", len(tasks))
|
||||
}
|
||||
|
||||
d.WorkflowEnablement = staticEnablement{enablement.SetEnabled(stored.OrgID, stored.Workflow, true)}
|
||||
d.dispatchBindings(t.Context())
|
||||
assertDispatchRecorded(t, s, bindingID)
|
||||
}
|
||||
@@ -1,171 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
// fakeEDA serves bindings, mappings and one capture from memory, and records
|
||||
// dispatches and mapping matches the way the store's unique keys do.
|
||||
type fakeEDA struct {
|
||||
bindings []binding.Binding
|
||||
mappings map[string]mapping.Mapping
|
||||
captures []storecontract.CapturedEvent
|
||||
dispatched map[[2]string]bool
|
||||
matches map[[2]string]bool
|
||||
}
|
||||
|
||||
func (f *fakeEDA) InsertMapping(context.Context, mapping.Mapping) (string, error) { return "", nil }
|
||||
func (f *fakeEDA) GetMapping(_ context.Context, id string) (*mapping.Mapping, error) {
|
||||
m, ok := f.mappings[id]
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
return &m, nil
|
||||
}
|
||||
func (f *fakeEDA) ListMappings(context.Context) ([]mapping.Mapping, error) { return nil, nil }
|
||||
func (f *fakeEDA) UpdateMapping(context.Context, mapping.Mapping) error { return nil }
|
||||
func (f *fakeEDA) DeleteMapping(context.Context, string) error { return nil }
|
||||
|
||||
func (f *fakeEDA) InsertBinding(context.Context, binding.Binding) (string, error) { return "", nil }
|
||||
func (f *fakeEDA) GetBinding(context.Context, string) (*binding.Binding, error) { return nil, nil }
|
||||
|
||||
func (f *fakeEDA) ListBindings(context.Context) ([]binding.Binding, error) { return f.bindings, nil }
|
||||
func (f *fakeEDA) UpdateBinding(context.Context, binding.Binding) error { return nil }
|
||||
func (f *fakeEDA) DeleteBinding(context.Context, string) error { return nil }
|
||||
func (f *fakeEDA) ApproveBinding(context.Context, string) error { return nil }
|
||||
|
||||
func (f *fakeEDA) ArmedBindingsForSource(_ context.Context, source string) ([]binding.Binding, error) {
|
||||
var out []binding.Binding
|
||||
for _, b := range f.bindings {
|
||||
if b.Status == binding.StatusArmed && b.Matcher.Source == source {
|
||||
out = append(out, b)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (f *fakeEDA) RecordDispatch(_ context.Context, bindingID string, _ int64, captureID string, _ int64) error {
|
||||
key := [2]string{bindingID, captureID}
|
||||
if f.dispatched[key] {
|
||||
return storecontract.ErrAlreadyDispatched
|
||||
}
|
||||
f.dispatched[key] = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeEDA) ListUndispatchedCaptures(context.Context, []string, int) ([]storecontract.CapturedEvent, error) {
|
||||
return f.captures, nil
|
||||
}
|
||||
|
||||
func (f *fakeEDA) RecordMappingMatch(_ context.Context, mappingID, captureID string) error {
|
||||
f.matches[[2]string{mappingID, captureID}] = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func armed(id, mappingID, filter string) binding.Binding {
|
||||
return binding.Binding{
|
||||
ID: id, Name: id, Matcher: binding.Matcher{Source: "fw"}, MappingID: mappingID,
|
||||
Filter: filter, Workflow: "implement", Status: binding.StatusArmed, Version: 1,
|
||||
}
|
||||
}
|
||||
|
||||
func severityMapping(id, eventType string) mapping.Mapping {
|
||||
return mapping.Mapping{
|
||||
ID: id, Name: id, EventTypeID: eventType,
|
||||
Fields: []mapping.Field{{Name: "severity", Path: "severity", Type: mapping.TypeString, Required: true}},
|
||||
}
|
||||
}
|
||||
|
||||
func TestDispatchPerBindingByEventTypeAndFilter(t *testing.T) {
|
||||
capture := storecontract.CapturedEvent{
|
||||
ID: "c1", Source: "fw", EventType: "blocked", Authenticated: true, Body: `{"severity":"high"}`,
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
bindings []binding.Binding
|
||||
mappings []mapping.Mapping
|
||||
wantTasks []string
|
||||
wantMatches [][2]string
|
||||
}{
|
||||
{
|
||||
name: "several bindings on one source each dispatch once",
|
||||
bindings: []binding.Binding{armed("a", "m", ""), armed("b", "m", "")},
|
||||
mappings: []mapping.Mapping{severityMapping("m", "blocked")},
|
||||
wantTasks: []string{"a", "b"},
|
||||
wantMatches: [][2]string{{"m", "c1"}},
|
||||
},
|
||||
{
|
||||
name: "a binding for another event type does not dispatch",
|
||||
bindings: []binding.Binding{armed("a", "m", "")},
|
||||
mappings: []mapping.Mapping{severityMapping("m", "allowed")},
|
||||
},
|
||||
{
|
||||
name: "a filter that excludes the event does not dispatch it",
|
||||
bindings: []binding.Binding{armed("a", "m", `severity == "low"`), armed("b", "m", `severity in ["high", "critical"]`)},
|
||||
mappings: []mapping.Mapping{severityMapping("m", "blocked")},
|
||||
wantTasks: []string{"b"},
|
||||
wantMatches: [][2]string{{"m", "c1"}},
|
||||
},
|
||||
{
|
||||
name: "a filter that does not compile does not dispatch",
|
||||
bindings: []binding.Binding{armed("a", "m", `nope ==`)},
|
||||
mappings: []mapping.Mapping{severityMapping("m", "blocked")},
|
||||
// The mapping still resolved the event.
|
||||
wantMatches: [][2]string{{"m", "c1"}},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
st := pgstore.Open(t)
|
||||
eda := &fakeEDA{
|
||||
bindings: tt.bindings, mappings: map[string]mapping.Mapping{},
|
||||
captures: []storecontract.CapturedEvent{capture},
|
||||
dispatched: map[[2]string]bool{}, matches: map[[2]string]bool{},
|
||||
}
|
||||
for _, m := range tt.mappings {
|
||||
eda.mappings[m.ID] = m
|
||||
}
|
||||
d := &Daemon{
|
||||
Cfg: config.NewHolder(config.Config{Repos: []config.Repo{{Owner: "acme", Name: "widget"}}}),
|
||||
Store: st, Mappings: eda, Bindings: eda, BindingDispatcher: eda, MappingMatches: eda,
|
||||
BindingTaskCreator: st,
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
}
|
||||
d.dispatchBindings(t.Context())
|
||||
d.dispatchBindings(t.Context())
|
||||
|
||||
tasks, err := st.Tasks(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("Tasks: %v", err)
|
||||
}
|
||||
got := map[string]int{}
|
||||
for _, task := range tasks {
|
||||
got[task.BindingID]++
|
||||
}
|
||||
if len(tasks) != len(tt.wantTasks) {
|
||||
t.Fatalf("tasks by binding = %v, want one each for %v", got, tt.wantTasks)
|
||||
}
|
||||
for _, id := range tt.wantTasks {
|
||||
if got[id] != 1 {
|
||||
t.Fatalf("tasks by binding = %v, want one each for %v", got, tt.wantTasks)
|
||||
}
|
||||
}
|
||||
if len(eda.matches) != len(tt.wantMatches) {
|
||||
t.Fatalf("mapping matches = %v, want %v", eda.matches, tt.wantMatches)
|
||||
}
|
||||
for _, key := range tt.wantMatches {
|
||||
if !eda.matches[key] {
|
||||
t.Fatalf("mapping matches = %v, want %v", eda.matches, tt.wantMatches)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
)
|
||||
|
||||
const (
|
||||
investigateYAML = "id: investigate\nrepository: none\ninputs:\n src_ip: {type: string, required: true}\n severity: {type: string}\nsteps:\n - type: agent.run\n settings:\n mission: look\n"
|
||||
reviewYAML = "id: review\nrepository: required\nsteps:\n - type: implement.prepare\n"
|
||||
)
|
||||
|
||||
func eventDefinitions() *workflowDefinitionsStub {
|
||||
return &workflowDefinitionsStub{collection: workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{
|
||||
{ID: "investigate", YAML: investigateYAML},
|
||||
{ID: "review", YAML: reviewYAML},
|
||||
}}, version: 1}
|
||||
}
|
||||
|
||||
// armBinding saves and approves b on source, returning its id.
|
||||
func armBinding(t *testing.T, s *dispatchStores, b binding.Binding) string {
|
||||
t.Helper()
|
||||
id, err := s.EdaStore.InsertBinding(t.Context(), b)
|
||||
if err != nil {
|
||||
t.Fatalf("InsertBinding: %v", err)
|
||||
}
|
||||
if err := s.EdaStore.ApproveBinding(t.Context(), id); err != nil {
|
||||
t.Fatalf("ApproveBinding: %v", err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func dispatchFailures(t *testing.T, s *dispatchStores) []string {
|
||||
t.Helper()
|
||||
events, err := s.EventsSince(t.Context(), "", 100)
|
||||
if err != nil {
|
||||
t.Fatalf("EventsSince: %v", err)
|
||||
}
|
||||
var out []string
|
||||
for _, e := range events {
|
||||
if e.Kind == "binding_dispatch_failure" {
|
||||
out = append(out, e.Detail)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestDispatchBindingTargetsTheWorkflowInterface(t *testing.T) {
|
||||
fields := []mapping.Field{
|
||||
{Name: "ip", Path: "ip", Type: mapping.TypeString},
|
||||
{Name: "sev", Path: "sev", Type: mapping.TypeString},
|
||||
{Name: "full", Path: "repository.full_name", Type: mapping.TypeString},
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
binding binding.Binding
|
||||
body string
|
||||
wantOwner string
|
||||
wantRepo string
|
||||
wantInputs map[string]any
|
||||
wantFailure string
|
||||
}{
|
||||
{
|
||||
name: "no-repository workflow gets structured inputs and no repo",
|
||||
binding: binding.Binding{Workflow: "investigate", Inputs: map[string]binding.InputSource{
|
||||
"src_ip": {Param: "ip"}, "severity": {Value: "high"},
|
||||
}},
|
||||
body: `{"ip":"10.0.0.9"}`,
|
||||
wantInputs: map[string]any{"src_ip": "10.0.0.9", "severity": "high"},
|
||||
},
|
||||
{
|
||||
name: "a required input that did not resolve is refused",
|
||||
binding: binding.Binding{Workflow: "investigate", Inputs: map[string]binding.InputSource{"src_ip": {Param: "ip"}}},
|
||||
body: `{"sev":"low"}`,
|
||||
wantFailure: `input "src_ip" is required`,
|
||||
},
|
||||
{
|
||||
name: "repository from the payload",
|
||||
binding: binding.Binding{Workflow: "review", RepoParam: "full"},
|
||||
body: `{"repository":{"full_name":"acme/api"}}`,
|
||||
wantOwner: "acme", wantRepo: "api",
|
||||
},
|
||||
{
|
||||
name: "repository from the payload must be configured",
|
||||
binding: binding.Binding{Workflow: "review", RepoParam: "full"},
|
||||
body: `{"repository":{"full_name":"evil/elsewhere"}}`,
|
||||
wantFailure: "evil/elsewhere from the event is not a configured repository",
|
||||
},
|
||||
{
|
||||
name: "undefined workflow is refused",
|
||||
binding: binding.Binding{Workflow: "gone"},
|
||||
body: `{}`,
|
||||
wantFailure: `workflow "gone" is not defined`,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := openDispatchTestStore(t)
|
||||
mappingID := seedMapping(t, s, "fw", fields...)
|
||||
b := tt.binding
|
||||
b.Name, b.Matcher, b.MappingID = "b", binding.Matcher{Source: "fw"}, mappingID
|
||||
armBinding(t, s, b)
|
||||
seedCapture(t, s, "fw", true, tt.body)
|
||||
|
||||
d := newDispatchDaemonWithRepos(t, s, []config.Repo{{Owner: "acme", Name: "api"}, {Owner: "acme", Name: "web"}})
|
||||
d.WorkflowDefinitions = eventDefinitions()
|
||||
d.dispatchBindings(t.Context())
|
||||
|
||||
tasks, err := s.Tasks(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("Tasks: %v", err)
|
||||
}
|
||||
failures := dispatchFailures(t, s)
|
||||
if tt.wantFailure != "" {
|
||||
if len(tasks) != 0 {
|
||||
t.Fatalf("dispatched %d task(s), want none", len(tasks))
|
||||
}
|
||||
if len(failures) == 0 || !strings.Contains(failures[0], tt.wantFailure) {
|
||||
t.Fatalf("failures = %q, want one containing %q", failures, tt.wantFailure)
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(tasks) != 1 {
|
||||
t.Fatalf("dispatched %d task(s), want 1 (failures %q)", len(tasks), failures)
|
||||
}
|
||||
got, err := s.TaskByID(t.Context(), tasks[0].ID)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskByID: %v", err)
|
||||
}
|
||||
if got.Owner != tt.wantOwner || got.Repo != tt.wantRepo {
|
||||
t.Errorf("task repo = %q/%q, want %q/%q", got.Owner, got.Repo, tt.wantOwner, tt.wantRepo)
|
||||
}
|
||||
if len(got.Inputs) != len(tt.wantInputs) {
|
||||
t.Fatalf("inputs = %v, want %v", got.Inputs, tt.wantInputs)
|
||||
}
|
||||
for k, v := range tt.wantInputs {
|
||||
if got.Inputs[k] != v {
|
||||
t.Errorf("input %s = %v, want %v", k, got.Inputs[k], v)
|
||||
}
|
||||
}
|
||||
if len(tt.wantInputs) > 0 && strings.Contains(got.Body, "10.0.0.9") {
|
||||
t.Errorf("body %q repeats the inputs as text", got.Body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,163 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workintake"
|
||||
"github.com/samcharles93/archie-core/internal/eventbus"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/worktree"
|
||||
)
|
||||
|
||||
// fakeMessage is a minimal eventbus.Message for driving processNATSTask
|
||||
// without standing up a broker.
|
||||
type fakeMessage struct {
|
||||
data []byte
|
||||
subject string
|
||||
acked bool
|
||||
naked bool
|
||||
}
|
||||
|
||||
func (m *fakeMessage) Data() []byte { return m.data }
|
||||
func (m *fakeMessage) Subject() string { return m.subject }
|
||||
func (m *fakeMessage) Ack() error { m.acked = true; return nil }
|
||||
func (m *fakeMessage) Nak() error { m.naked = true; return nil }
|
||||
|
||||
var _ eventbus.Message = (*fakeMessage)(nil)
|
||||
|
||||
// TestProcessNATSTaskRejectsUnresolvableIdentity pins the intake half of the
|
||||
// fail-closed relation: a task envelope naming an identity this daemon does
|
||||
// not know must not be written to the store at all. Today it is enqueued and
|
||||
// only fails open later, when forgeFor/repoFor fall back to the root forge.
|
||||
func TestProcessNATSTaskRejectsUnresolvableIdentity(t *testing.T) {
|
||||
s := pgstore.Open(t)
|
||||
d := &Daemon{
|
||||
Store: s,
|
||||
Cfg: config.NewHolder(config.Config{}),
|
||||
Trees: &worktree.Manager{},
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
}
|
||||
|
||||
data, err := workintake.TaskEnvelope{
|
||||
Owner: "acme", Repo: "widget", Number: 1, Title: "ghost task",
|
||||
Identity: "ghost",
|
||||
}.Encode()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
msg := &fakeMessage{data: data, subject: workintake.SubjectTaskDefault}
|
||||
|
||||
d.processNATSTask(t.Context(), msg)
|
||||
|
||||
if msg.naked {
|
||||
t.Fatal("unresolvable identity intake was nacked; a redelivery can never resolve it")
|
||||
}
|
||||
if !msg.acked {
|
||||
t.Fatal("unresolvable identity intake was not dropped (acked)")
|
||||
}
|
||||
task, err := s.TaskByIssue(t.Context(), "acme", "widget", 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if task != nil {
|
||||
t.Fatalf("task %d was created with an unresolvable identity %q", task.ID, task.Identity)
|
||||
}
|
||||
}
|
||||
|
||||
// TestProcessParksTaskWhoseIdentityNoLongerResolves pins the dispatch half of
|
||||
// the fail-closed relation: a task whose non-empty identity no longer has a
|
||||
// configured runner must park, never fall back to the root forge's credential.
|
||||
func TestProcessParksTaskWhoseIdentityNoLongerResolves(t *testing.T) {
|
||||
d, s, rootFg, _, _ := twoIdentityDaemon(t)
|
||||
d.Log = slog.New(slog.DiscardHandler)
|
||||
ctx := context.Background()
|
||||
|
||||
if _, err := s.EnqueueIssue(ctx, "acme", "shared", 42, "t", "b", "", "ghost"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := s.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("ClaimNext = (%+v, %v)", task, err)
|
||||
}
|
||||
|
||||
d.process(ctx, task)
|
||||
|
||||
got, err := s.TaskByID(ctx, task.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID = (%+v, %v)", got, err)
|
||||
}
|
||||
if got.Status != workflow.StatusParked {
|
||||
t.Fatalf("status = %q, want parked", got.Status)
|
||||
}
|
||||
if !strings.Contains(got.ParkReason, "no longer resolves") {
|
||||
t.Errorf("ParkReason = %q, want it to name the unresolvable identity", got.ParkReason)
|
||||
}
|
||||
// The root forge must not have been touched for this task: parking on an
|
||||
// identity that no longer resolves is the fail-closed outcome, not a
|
||||
// fallback to root credentials.
|
||||
if calls := len(rootFg.stateLabels) + len(rootFg.closedIssues) + len(rootFg.comments); calls != 0 {
|
||||
t.Errorf("root forge was called %d time(s) for a task with an unresolvable identity", calls)
|
||||
}
|
||||
}
|
||||
|
||||
// TestProcessParksRetiredIdentity pins the lifecycle half: an identity that
|
||||
// still has a runner but has been retired may not act, so its tasks park
|
||||
// rather than running under a credential the control plane has retired.
|
||||
func TestProcessParksRetiredIdentity(t *testing.T) {
|
||||
s := pgstore.Open(t)
|
||||
ctx := context.Background()
|
||||
log := slog.New(slog.DiscardHandler)
|
||||
|
||||
id := identity.StableID("worker")
|
||||
created, err := identity.New(id, identity.KindBot, "worker")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
created, err = s.Create(ctx, created, identity.Audit{ActorID: identity.SystemID, Source: "test", RequestID: "create"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Apply(ctx, created.ID, created.Version, identity.Command{Type: identity.CommandRetire}, identity.Audit{ActorID: identity.SystemID, Source: "test", RequestID: "retire"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
repo := config.Repo{Owner: "acme", Name: "widget"}
|
||||
d := &Daemon{
|
||||
Cfg: config.NewHolder(config.Config{Repos: []config.Repo{repo}}),
|
||||
Store: s,
|
||||
Log: log,
|
||||
IdentityRepository: s,
|
||||
Identities: []*IdentityRunner{{
|
||||
Name: "worker", ID: id,
|
||||
Forge: &testForge{}, Trees: &worktree.Manager{},
|
||||
Repos: []config.Repo{repo}, Cfg: config.IdentityConfig{Name: "worker"}, Log: log,
|
||||
}},
|
||||
}
|
||||
|
||||
if _, err := s.EnqueueIssue(ctx, "acme", "widget", 7, "t", "b", "", string(id)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := s.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("ClaimNext = (%+v, %v)", task, err)
|
||||
}
|
||||
|
||||
d.process(ctx, task)
|
||||
|
||||
got, err := s.TaskByID(ctx, task.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID = (%+v, %v)", got, err)
|
||||
}
|
||||
if got.Status != workflow.StatusParked {
|
||||
t.Fatalf("status = %q, want parked", got.Status)
|
||||
}
|
||||
if !strings.Contains(got.ParkReason, "may not act") {
|
||||
t.Errorf("ParkReason = %q, want it to name the retired identity", got.ParkReason)
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) { os.Exit(pgtest.Main(m)) }
|
||||
@@ -1,78 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
// parkClassRecorder captures the class of the one park a test drives, without
|
||||
// a live store. The embedded TaskStore is nil: only ParkTask is reachable from
|
||||
// the code under test, and any other store call panics loudly rather than
|
||||
// silently succeeding.
|
||||
type parkClassRecorder struct {
|
||||
storecontract.TaskStore
|
||||
class taskstate.ParkClass
|
||||
}
|
||||
|
||||
func (r *parkClassRecorder) ParkTask(_ context.Context, _ int64, _, _, class string) error {
|
||||
r.class = class
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestDurablePinDefectIsNotParkedTransient pins the classification of a pin the
|
||||
// task itself carries wrong. A stored definition whose YAML does not hash to
|
||||
// the digest recorded beside it is a durable defect: the same row fails the
|
||||
// same way on every requeue until an operator repairs it, so ParkTransient --
|
||||
// whose own contract says "a requeue can succeed" -- would hand a future retry
|
||||
// pass an endless loop.
|
||||
func TestDurablePinDefectIsNotParkedTransient(t *testing.T) {
|
||||
store := &parkClassRecorder{}
|
||||
d := &Daemon{Store: store, Log: slog.New(slog.DiscardHandler)}
|
||||
task := &workflow.Task{
|
||||
ID: 1,
|
||||
Workflow: "implement",
|
||||
WorkflowDefinitionYAML: "id: implement\nsteps:\n - type: implement.prepare\n",
|
||||
WorkflowDefinitionDigest: workflow.DigestDefinition("id: implement\nsteps:\n - type: implement.build\n"),
|
||||
}
|
||||
if _, ok := d.pinTaskProfile(context.Background(), task); ok {
|
||||
t.Fatal("pinTaskProfile accepted a tampered pin")
|
||||
}
|
||||
if store.class == "" {
|
||||
t.Fatal("a durable pin defect was not parked at all")
|
||||
}
|
||||
if store.class == taskstate.ParkTransient {
|
||||
t.Fatalf("durable pin defect parked as %q: a requeue recurs on the same defect, so a retry pass cannot make progress", store.class)
|
||||
}
|
||||
}
|
||||
|
||||
// failingWorkflowDefinitions stands in for a State Store read failure.
|
||||
type failingWorkflowDefinitions struct{ err error }
|
||||
|
||||
func (f failingWorkflowDefinitions) WorkflowDefinitions(context.Context) (workflow.WorkflowDefinitionCollection, int64, error) {
|
||||
return workflow.WorkflowDefinitionCollection{}, 0, f.err
|
||||
}
|
||||
|
||||
// TestTransientPinFailureStaysTransient keeps the other half of the cause-based
|
||||
// rule: a State Store read failure is environmental, so it must still park
|
||||
// transient rather than being folded in with the durable defects.
|
||||
func TestTransientPinFailureStaysTransient(t *testing.T) {
|
||||
store := &parkClassRecorder{}
|
||||
d := &Daemon{
|
||||
Store: store,
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
WorkflowDefinitions: failingWorkflowDefinitions{err: errors.New("state store unavailable")},
|
||||
}
|
||||
task := &workflow.Task{ID: 1, Workflow: "implement"}
|
||||
if _, ok := d.pinTaskProfile(context.Background(), task); ok {
|
||||
t.Fatal("pinTaskProfile succeeded despite a definition read failure")
|
||||
}
|
||||
if store.class != taskstate.ParkTransient {
|
||||
t.Fatalf("pin class = %q, want %q for a State Store read failure", store.class, taskstate.ParkTransient)
|
||||
}
|
||||
}
|
||||
@@ -1,254 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eda/module"
|
||||
"github.com/samcharles93/archie-core/internal/domain/eda/playbook"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
// playbookStore loads a single playbook document from a temp directory, so
|
||||
// these tests exercise the real loader rather than a hand-built store.
|
||||
func playbookStore(t *testing.T, document string) *playbook.Store {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "pb.yaml"), []byte(document), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
loaded, err := playbook.Load(dir, module.New())
|
||||
if err != nil {
|
||||
t.Fatalf("load playbook: %v", err)
|
||||
}
|
||||
return loaded
|
||||
}
|
||||
|
||||
// routableDefinitions is the definition collection these tests pin against:
|
||||
// two real ids so a playbook's choice is distinguishable from the choice the
|
||||
// kind bindings would have made for the same labels.
|
||||
func routableDefinitions() *workflowDefinitionsStub {
|
||||
return &workflowDefinitionsStub{
|
||||
collection: workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{
|
||||
{ID: "tdd", YAML: "id: tdd\nsteps:\n - type: bootstrap.apply\n"},
|
||||
{ID: "feasibility", YAML: "id: feasibility\nsteps:\n - type: bootstrap.prepare\n"},
|
||||
}},
|
||||
version: 1,
|
||||
}
|
||||
}
|
||||
|
||||
// forgeTask enqueues a labelled forge-sourced task and returns its row.
|
||||
func forgeTask(t *testing.T, resources *pgstore.TaskDB, labels string) *workflow.Task {
|
||||
t.Helper()
|
||||
if _, err := resources.EnqueueIssue(t.Context(), "acme", "widget", 7, "title", "body", labels, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := resources.TaskByIssue(t.Context(), "acme", "widget", 7)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return task
|
||||
}
|
||||
|
||||
// TestPinWorkflowDefinitionPrefersMatchingPlaybook is the coordinator's
|
||||
// production wiring: a forge task whose labels match a loaded playbook pins
|
||||
// the workflow that playbook names, not the one the kind bindings would have
|
||||
// chosen for the same labels. Bypassing the coordinator pins "tdd" (the
|
||||
// default binding for kind bug) and fails this test.
|
||||
func TestPinWorkflowDefinitionPrefersMatchingPlaybook(t *testing.T) {
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
task := forgeTask(t, resources, "bug")
|
||||
|
||||
d := &Daemon{
|
||||
Store: resources,
|
||||
WorkflowDefinitions: routableDefinitions(),
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Playbooks: playbookStore(t, `
|
||||
trigger:
|
||||
kind: bug
|
||||
actions:
|
||||
- position: workflow
|
||||
workflow: feasibility
|
||||
`),
|
||||
}
|
||||
if err := d.pinWorkflowDefinition(t.Context(), task); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if task.Workflow != "feasibility" {
|
||||
t.Fatalf("pinned workflow = %q, want feasibility (the playbook's choice, not the kind binding's)", task.Workflow)
|
||||
}
|
||||
stored, err := resources.TaskByID(t.Context(), task.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stored.Workflow != "feasibility" {
|
||||
t.Fatalf("persisted workflow = %q, want feasibility", stored.Workflow)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPinWorkflowDefinitionFallsBackWhenNoPlaybookMatches: the coordinator is
|
||||
// an additional routing source, not a replacement. A non-matching playbook
|
||||
// set leaves the existing kind/label bindings in charge.
|
||||
func TestPinWorkflowDefinitionFallsBackWhenNoPlaybookMatches(t *testing.T) {
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
task := forgeTask(t, resources, "bug")
|
||||
|
||||
d := &Daemon{
|
||||
Store: resources,
|
||||
WorkflowDefinitions: routableDefinitions(),
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Playbooks: playbookStore(t, `
|
||||
trigger:
|
||||
kind: bootstrap
|
||||
actions:
|
||||
- position: workflow
|
||||
workflow: feasibility
|
||||
`),
|
||||
}
|
||||
if err := d.pinWorkflowDefinition(t.Context(), task); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if task.Workflow != "tdd" {
|
||||
t.Fatalf("pinned workflow = %q, want tdd (kind binding for bug)", task.Workflow)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPinWorkflowDefinitionPlaybookWorkflowMustExist: an operator who binds a
|
||||
// trigger to a workflow that is not defined gets a reported failure, the same
|
||||
// shape ResolveWorkflowID gives a task pre-assigned an undefined workflow.
|
||||
// Silently running the kind binding's choice instead would run the wrong
|
||||
// workflow under a rule the operator wrote.
|
||||
func TestPinWorkflowDefinitionPlaybookWorkflowMustExist(t *testing.T) {
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
task := forgeTask(t, resources, "bug")
|
||||
|
||||
d := &Daemon{
|
||||
Store: resources,
|
||||
WorkflowDefinitions: routableDefinitions(),
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Playbooks: playbookStore(t, `
|
||||
trigger:
|
||||
kind: bug
|
||||
actions:
|
||||
- position: workflow
|
||||
workflow: nonesuch
|
||||
`),
|
||||
}
|
||||
err := d.pinWorkflowDefinition(t.Context(), task)
|
||||
if err == nil {
|
||||
t.Fatal("pin succeeded, want an error naming the undefined workflow")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "nonesuch") || !strings.Contains(err.Error(), "pb.yaml") {
|
||||
t.Fatalf("error = %v, want it to name both the workflow and the playbook", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPinWorkflowDefinitionPreAssignedWorkflowBeatsPlaybook: a task carrying
|
||||
// an explicit workflow is the waiting_human -> approved requeue handoff. That
|
||||
// assignment is a decision already made about this task and must not be
|
||||
// re-routed by a playbook trigger that still matches its labels.
|
||||
func TestPinWorkflowDefinitionPreAssignedWorkflowBeatsPlaybook(t *testing.T) {
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
task := forgeTask(t, resources, "bug")
|
||||
task.Workflow = "tdd"
|
||||
|
||||
d := &Daemon{
|
||||
Store: resources,
|
||||
WorkflowDefinitions: routableDefinitions(),
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Playbooks: playbookStore(t, `
|
||||
trigger:
|
||||
kind: bug
|
||||
actions:
|
||||
- position: workflow
|
||||
workflow: feasibility
|
||||
`),
|
||||
}
|
||||
if err := d.pinWorkflowDefinition(t.Context(), task); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if task.Workflow != "tdd" {
|
||||
t.Fatalf("pinned workflow = %q, want the pre-assigned tdd", task.Workflow)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPinWorkflowDefinitionEvaluatesConditionAgainstIntakeEvent: a `when`
|
||||
// condition reads the event surface the daemon really builds from the task
|
||||
// row. This is the field-name contract between playbookInput and every
|
||||
// operator-written condition, including the shipped example's -- a rename on
|
||||
// either side makes conditions silently evaluate false, which this catches.
|
||||
func TestPinWorkflowDefinitionEvaluatesConditionAgainstIntakeEvent(t *testing.T) {
|
||||
document := `
|
||||
trigger:
|
||||
kind: bug
|
||||
actions:
|
||||
- position: workflow
|
||||
workflow: feasibility
|
||||
when: '"regression" in event.labels && event.repo == "widget"'
|
||||
`
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
labels string
|
||||
want string
|
||||
}{
|
||||
{name: "condition true selects the playbook's workflow", labels: "bug,regression", want: "feasibility"},
|
||||
{name: "condition false leaves the kind binding in charge", labels: "bug", want: "tdd"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
task := forgeTask(t, resources, tc.labels)
|
||||
d := &Daemon{
|
||||
Store: resources,
|
||||
WorkflowDefinitions: routableDefinitions(),
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Playbooks: playbookStore(t, document),
|
||||
}
|
||||
if err := d.pinWorkflowDefinition(t.Context(), task); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if task.Workflow != tc.want {
|
||||
t.Fatalf("pinned workflow = %q, want %q", task.Workflow, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestPinWorkflowDefinitionTriggersOnInstanceDefinedLabel: the trigger's kind
|
||||
// axis is the closed workintake vocabulary (it addresses the task subjects),
|
||||
// so the label axis is what an instance defines for itself. A label no kind
|
||||
// recognises still triggers a playbook, which is the only way an operator can
|
||||
// bind a workflow to their own taxonomy without a code change.
|
||||
func TestPinWorkflowDefinitionTriggersOnInstanceDefinedLabel(t *testing.T) {
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
task := forgeTask(t, resources, "ops::security-review,needs-triage")
|
||||
|
||||
d := &Daemon{
|
||||
Store: resources,
|
||||
WorkflowDefinitions: routableDefinitions(),
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Playbooks: playbookStore(t, `
|
||||
trigger:
|
||||
labels:
|
||||
- ops::security-review
|
||||
actions:
|
||||
- position: workflow
|
||||
workflow: feasibility
|
||||
`),
|
||||
}
|
||||
if err := d.pinWorkflowDefinition(t.Context(), task); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if task.Workflow != "feasibility" {
|
||||
t.Fatalf("pinned workflow = %q, want feasibility (triggered by an instance-defined label)", task.Workflow)
|
||||
}
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eda/playbook"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
// runRecorder is a playbook set that matches no workflow playbook and records
|
||||
// each action-playbook run, failing it when err is set.
|
||||
type runRecorder struct {
|
||||
runs []playbook.DispatchInput
|
||||
err error
|
||||
}
|
||||
|
||||
func (r *runRecorder) Dispatch(playbook.DispatchInput) (playbook.Decision, bool) {
|
||||
return playbook.Decision{}, false
|
||||
}
|
||||
|
||||
func (r *runRecorder) Run(_ context.Context, _ storecontract.PlaybookDispatcher, _ *slog.Logger, input playbook.DispatchInput) error {
|
||||
r.runs = append(r.runs, input)
|
||||
return r.err
|
||||
}
|
||||
|
||||
type nopPlaybookLedger struct{}
|
||||
|
||||
func (nopPlaybookLedger) RecordPlaybookDispatch(context.Context, string, string, string, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (nopPlaybookLedger) DeletePlaybookDispatches(context.Context, string) error { return nil }
|
||||
|
||||
func TestPinWorkflowDefinitionRunsActionPlaybooks(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ledger storecontract.PlaybookDispatcher
|
||||
workflow string
|
||||
runErr error
|
||||
wantRuns int
|
||||
}{
|
||||
{name: "runs once with a ledger", ledger: nopPlaybookLedger{}, wantRuns: 1},
|
||||
{name: "a failed run leaves routing alone", ledger: nopPlaybookLedger{}, runErr: errors.New("boom"), wantRuns: 1},
|
||||
{name: "never runs without a ledger", wantRuns: 0},
|
||||
{name: "skips a task that already names a workflow", ledger: nopPlaybookLedger{}, workflow: "tdd", wantRuns: 0},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
task := forgeTask(t, resources, "bug")
|
||||
task.Workflow = tt.workflow
|
||||
recorder := &runRecorder{err: tt.runErr}
|
||||
d := &Daemon{
|
||||
Store: resources,
|
||||
WorkflowDefinitions: routableDefinitions(),
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Playbooks: recorder,
|
||||
PlaybookLedger: tt.ledger,
|
||||
}
|
||||
if err := d.pinWorkflowDefinition(t.Context(), task); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A second pin reuses the stored definition and must not run again.
|
||||
if err := d.pinWorkflowDefinition(t.Context(), task); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(recorder.runs) != tt.wantRuns {
|
||||
t.Fatalf("runs = %d, want %d", len(recorder.runs), tt.wantRuns)
|
||||
}
|
||||
if task.Workflow != "tdd" {
|
||||
t.Fatalf("pinned workflow = %q, want tdd (the kind binding, untouched by the run)", task.Workflow)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
)
|
||||
|
||||
// TestPollPassStampsLastPollAt pins the "is the poller still running" fact
|
||||
// /status reports: the daemon stamps the moment a poll pass begins, so a
|
||||
// missing or stale timestamp is what tells an operator the poll loop has
|
||||
// stopped or is stuck inside a pass.
|
||||
//
|
||||
// Both poll paths are covered because they are separate goroutines with
|
||||
// separate entry points: Run's single-identity loop drives poll, while
|
||||
// runIdentities drives one pollForIdentity per identity. A stamp on only one
|
||||
// of them leaves /status permanently reporting "never" for the other
|
||||
// deployment shape.
|
||||
func TestPollPassStampsLastPollAt(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := config.Repo{Owner: "acme", Name: "widget"}
|
||||
|
||||
pollPaths := []struct {
|
||||
name string
|
||||
poll func(context.Context, *Daemon)
|
||||
}{
|
||||
{
|
||||
name: "single-identity poll",
|
||||
poll: func(ctx context.Context, d *Daemon) { d.poll(ctx) },
|
||||
},
|
||||
{
|
||||
name: "per-identity poll",
|
||||
poll: func(ctx context.Context, d *Daemon) {
|
||||
d.pollForIdentity(ctx, &IdentityRunner{
|
||||
Name: "main",
|
||||
Forge: d.Forge,
|
||||
Repos: d.Cfg.Get().Repos,
|
||||
Log: d.Log,
|
||||
})
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, path := range pollPaths {
|
||||
t.Run(path.name, func(t *testing.T) {
|
||||
d := &Daemon{
|
||||
Cfg: config.NewHolder(config.Config{
|
||||
BotUser: "archie",
|
||||
Repos: []config.Repo{repo},
|
||||
Dispatch: config.Dispatch{Trigger: "assignee"},
|
||||
}),
|
||||
Forge: &pollingForge{},
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
}
|
||||
|
||||
if got := d.LastPollAt(); !got.IsZero() {
|
||||
t.Fatalf("LastPollAt() before any poll pass = %v, want the zero time", got)
|
||||
}
|
||||
|
||||
before := time.Now()
|
||||
path.poll(ctx, d)
|
||||
after := time.Now()
|
||||
|
||||
got := d.LastPollAt()
|
||||
if got.IsZero() {
|
||||
t.Fatal("LastPollAt() after a poll pass = zero, want the pass's start time")
|
||||
}
|
||||
if got.Before(before) || got.After(after) {
|
||||
t.Errorf("LastPollAt() = %v, want a time within [%v, %v]", got, before, after)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/prsource"
|
||||
)
|
||||
|
||||
// buildTestArchive builds a gzipped tar containing files, each wrapped under
|
||||
// a synthetic top-level directory the way a forge's repo-archive endpoint
|
||||
// does, so prefetchPRReview exercises the same extraction path production
|
||||
// traffic does.
|
||||
func buildTestArchive(t *testing.T, files map[string]string) []byte {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
gz := gzip.NewWriter(&buf)
|
||||
tw := tar.NewWriter(gz)
|
||||
for name, content := range files {
|
||||
hdr := &tar.Header{
|
||||
Name: "repo-abc123/" + name,
|
||||
Mode: 0o644,
|
||||
Size: int64(len(content)),
|
||||
}
|
||||
if err := tw.WriteHeader(hdr); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := tw.Write([]byte(content)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := tw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := gz.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
type fakePRForge struct {
|
||||
pr forge.PullRequest
|
||||
diff string
|
||||
archive []byte
|
||||
pullErr error
|
||||
diffErr error
|
||||
archErr error
|
||||
archCalls int
|
||||
}
|
||||
|
||||
func (f *fakePRForge) GetPullRequest(context.Context, string, string, int) (forge.PullRequest, error) {
|
||||
return f.pr, f.pullErr
|
||||
}
|
||||
|
||||
func (f *fakePRForge) GetPullRequestDiff(context.Context, string, string, int) (string, error) {
|
||||
return f.diff, f.diffErr
|
||||
}
|
||||
|
||||
func (f *fakePRForge) GetRepoArchive(context.Context, string, string, string) (io.ReadCloser, error) {
|
||||
f.archCalls++
|
||||
if f.archErr != nil {
|
||||
return nil, f.archErr
|
||||
}
|
||||
return io.NopCloser(strings.NewReader(string(f.archive))), nil
|
||||
}
|
||||
|
||||
func TestPrefetchPRReviewWritesMetadataDiffAndSnapshot(t *testing.T) {
|
||||
archive := buildTestArchive(t, map[string]string{"a.go": "package a\n"})
|
||||
f := &fakePRForge{
|
||||
pr: forge.PullRequest{Title: "t", Body: "b", HeadSHA: "abc123"},
|
||||
diff: "diff --git a/x b/x\n",
|
||||
archive: archive,
|
||||
}
|
||||
workDir := t.TempDir()
|
||||
|
||||
if err := prefetchPRReview(context.Background(), f, "acme", "widget", 7, workDir); err != nil {
|
||||
t.Fatalf("prefetchPRReview: %v", err)
|
||||
}
|
||||
|
||||
base := filepath.Join(workDir, prsource.PrefetchDirName)
|
||||
meta, err := os.ReadFile(filepath.Join(base, "metadata.json"))
|
||||
if err != nil {
|
||||
t.Fatalf("read metadata.json: %v", err)
|
||||
}
|
||||
if !strings.Contains(string(meta), "abc123") || !strings.Contains(string(meta), `"t"`) {
|
||||
t.Fatalf("metadata.json = %s, want title and head_sha", meta)
|
||||
}
|
||||
diff, err := os.ReadFile(filepath.Join(base, "diff.patch"))
|
||||
if err != nil {
|
||||
t.Fatalf("read diff.patch: %v", err)
|
||||
}
|
||||
if string(diff) != "diff --git a/x b/x\n" {
|
||||
t.Fatalf("diff.patch = %q", diff)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(base, "snapshot", "a.go")); err != nil {
|
||||
t.Fatalf("snapshot not extracted: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrefetchPRReviewFailsWhenForgeCannotReadPullRequests(t *testing.T) {
|
||||
workDir := t.TempDir()
|
||||
if err := prefetchPRReview(context.Background(), noPRCapability{}, "acme", "widget", 7, workDir); err == nil {
|
||||
t.Fatal("want an error when the forge cannot read pull requests")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrefetchPRReviewPropagatesForgeError(t *testing.T) {
|
||||
f := &fakePRForge{pullErr: errors.New("boom")}
|
||||
workDir := t.TempDir()
|
||||
if err := prefetchPRReview(context.Background(), f, "acme", "widget", 7, workDir); err == nil {
|
||||
t.Fatal("want the forge error surfaced")
|
||||
}
|
||||
}
|
||||
|
||||
// noPRCapability satisfies forge.Forge's method set with none of
|
||||
// PullRequestReader/PullRequestDiffReader/RepoArchiveReader -- like the noop
|
||||
// forge, or a forge configured without PR-reading support.
|
||||
type noPRCapability struct{}
|
||||
@@ -1,276 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/go-git/go-git/v6"
|
||||
"github.com/go-git/go-git/v6/plumbing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
"github.com/samcharles93/archie-core/internal/worktree"
|
||||
)
|
||||
|
||||
// pushedImplementRun models what a remediation task starts from: the implement
|
||||
// run prepared the clone, committed, and pushed its branch, so origin/<branch>
|
||||
// holds work base does not. title is the issue title the implement run saw,
|
||||
// which a later rename can move past the branch the PR actually lives on.
|
||||
func pushedImplementRun(t *testing.T, trees *worktree.Manager, title string) (dir, branch string, tip plumbing.Hash) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
dir, branch, err := trees.Prepare(ctx, "acme", "widget", "main", 7, title, "", "bug", worktree.Fresh)
|
||||
if err != nil {
|
||||
t.Fatalf("Prepare() error = %v", err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "widget.go"), []byte("package widget\n"), 0o600); err != nil {
|
||||
t.Fatalf("write widget.go: %v", err)
|
||||
}
|
||||
changed, err := trees.CommitAll(ctx, dir, "fix: the PR work")
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("CommitAll() = (%v, %v), want (true, nil)", changed, err)
|
||||
}
|
||||
if err := trees.Push(ctx, dir, branch); err != nil {
|
||||
t.Fatalf("Push() error = %v", err)
|
||||
}
|
||||
return dir, branch, headOf(t, dir)
|
||||
}
|
||||
|
||||
// claimedTask returns the running row a dispatch leaves behind, carrying the
|
||||
// workflow, branch and retry mode prepareWorkspace must route on. The row is
|
||||
// read back from the store, so the test drives prepareWorkspace from persisted
|
||||
// state rather than from a struct the test assembled.
|
||||
func claimedTask(t *testing.T, st *pgstore.TaskDB, title, workflowName, branch string, retryMode taskstate.RetryMode) *workflow.Task {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
if _, err := st.EnqueueIssue(ctx, "acme", "widget", 7, title, "body", "bug", ""); err != nil {
|
||||
t.Fatalf("EnqueueIssue: %v", err)
|
||||
}
|
||||
task, err := st.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("ClaimNext = (%+v, %v)", task, err)
|
||||
}
|
||||
task.Workflow, task.Branch = workflowName, branch
|
||||
task.RetryMode = string(retryMode)
|
||||
if err := st.Update(ctx, task); err != nil {
|
||||
t.Fatalf("persist task fields: %v", err)
|
||||
}
|
||||
|
||||
persisted, err := st.TaskByID(ctx, task.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskByID: %v", err)
|
||||
}
|
||||
if persisted.Workflow != workflowName || persisted.Branch != branch || persisted.RetryMode != string(retryMode) {
|
||||
t.Fatalf("persisted row = (workflow %q, branch %q, retry mode %q), want (%q, %q, %q)",
|
||||
persisted.Workflow, persisted.Branch, persisted.RetryMode, workflowName, branch, retryMode)
|
||||
}
|
||||
return persisted
|
||||
}
|
||||
|
||||
func headOf(t *testing.T, dir string) plumbing.Hash {
|
||||
t.Helper()
|
||||
r, err := git.PlainOpen(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("PlainOpen(%s): %v", dir, err)
|
||||
}
|
||||
ref, err := r.Head()
|
||||
if err != nil {
|
||||
t.Fatalf("Head(%s): %v", dir, err)
|
||||
}
|
||||
return ref.Hash()
|
||||
}
|
||||
|
||||
// TestPrepareWorkspaceResumesThePersistedBranchForARemediation pins the defect
|
||||
// a remediation run used to hit: prepareWorkspace always called Manager.Prepare,
|
||||
// whose refresh resets the worktree onto origin/<base>, so a task continuing an
|
||||
// open PR branch lost that branch's commits before its container started and
|
||||
// the agent worked from base. It must instead resume the branch persisted on
|
||||
// the task row -- here a branch the task's current title would no longer name,
|
||||
// so a recomputed branch name cannot masquerade as the right answer.
|
||||
func TestPrepareWorkspaceResumesThePersistedBranchForARemediation(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
trees := newTestTrees(t, newLocalRemote(t, "acme", "widget"))
|
||||
|
||||
// The implement run pushed its PR work on the branch its then-title named.
|
||||
dir, branch, tip := pushedImplementRun(t, trees, "fix: original issue")
|
||||
|
||||
d, st, _ := testDaemon(t, 3, 0)
|
||||
// The issue was retitled since; the PR's branch is still the pushed one.
|
||||
task := claimedTask(t, st, "fix: retitled issue", "remediate", branch, taskstate.RetryContinuePushedWork)
|
||||
|
||||
gotDir, ok := d.prepareWorkspace(ctx, task, trees, config.Repo{Owner: "acme", Name: "widget", Base: "main"})
|
||||
if !ok {
|
||||
t.Fatal("prepareWorkspace() = false, want the remediation prepared on its PR branch")
|
||||
}
|
||||
if gotDir != dir {
|
||||
t.Errorf("prepareWorkspace() dir = %q, want the task's worktree %q", gotDir, dir)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(gotDir, "widget.go")); err != nil {
|
||||
t.Fatalf("widget.go missing after prepare: %v (the worktree was reset to base, discarding the PR branch's commits)", err)
|
||||
}
|
||||
if got := headOf(t, gotDir); got != tip {
|
||||
t.Errorf("worktree HEAD = %s, want the PR branch tip %s", got, tip)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPrepareWorkspaceResumesAPRBranchAfterTheWorktreeWasRemoved pins the
|
||||
// retry failure archie-core-866m reports. Manager.Resume opens an
|
||||
// already-prepared worktree, so a remediation whose local clone is gone -- a
|
||||
// first run on this host, an expired volume, a worktree the terminal cleanup
|
||||
// removed before a retry -- can never be resumed, and the retry path offers
|
||||
// only fresh-from-base or that unrunnable resume. Preparing a resume must
|
||||
// clone when the worktree is missing, exactly as a fresh prepare does, and
|
||||
// land on the PR branch tip rather than base.
|
||||
func TestPrepareWorkspaceResumesAPRBranchAfterTheWorktreeWasRemoved(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
trees := newTestTrees(t, newLocalRemote(t, "acme", "widget"))
|
||||
dir, branch, tip := pushedImplementRun(t, trees, "fix: original issue")
|
||||
|
||||
// The clone is gone before the retry reaches prepareWorkspace.
|
||||
if err := os.RemoveAll(dir); err != nil {
|
||||
t.Fatalf("remove worktree: %v", err)
|
||||
}
|
||||
|
||||
d, st, _ := testDaemon(t, 3, 0)
|
||||
task := claimedTask(t, st, "fix: original issue", "remediate", branch, taskstate.RetryContinuePushedWork)
|
||||
|
||||
gotDir, ok := d.prepareWorkspace(ctx, task, trees, config.Repo{Owner: "acme", Name: "widget", Base: "main"})
|
||||
if !ok {
|
||||
t.Fatal("prepareWorkspace() = false, want the remediation prepared on its PR branch after the worktree was removed")
|
||||
}
|
||||
if gotDir != dir {
|
||||
t.Errorf("prepareWorkspace() dir = %q, want the task's worktree %q", gotDir, dir)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(gotDir, "widget.go")); err != nil {
|
||||
t.Fatalf("widget.go missing after prepare: %v (the PR branch's work was not restored)", err)
|
||||
}
|
||||
if got := headOf(t, gotDir); got != tip {
|
||||
t.Errorf("worktree HEAD = %s, want the PR branch tip %s", got, tip)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPrepareWorkspaceFailsClosedWhenTheRemediationBranchIsGone pins the other
|
||||
// half of the same routing: a remediation whose branch is not on the remote
|
||||
// must park, not quietly fall back to preparing base -- the fallback is exactly
|
||||
// the state the fix removes, and a remediation run that cannot see its PR
|
||||
// branch has nothing correct to do.
|
||||
func TestPrepareWorkspaceFailsClosedWhenTheRemediationBranchIsGone(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
trees := newTestTrees(t, newLocalRemote(t, "acme", "widget"))
|
||||
|
||||
// The implement run's clone exists and holds its work, but the branch the
|
||||
// task row names was never pushed (a row pointing at the wrong branch is
|
||||
// the dispatch bug this guards).
|
||||
dir, _, tip := pushedImplementRun(t, trees, "fix: original issue")
|
||||
|
||||
d, st, _ := testDaemon(t, 3, 0)
|
||||
task := claimedTask(t, st, "fix: original issue", "remediate", "fix/7-never-pushed", taskstate.RetryContinuePushedWork)
|
||||
|
||||
gotDir, ok := d.prepareWorkspace(ctx, task, trees, config.Repo{Owner: "acme", Name: "widget", Base: "main"})
|
||||
if ok {
|
||||
t.Errorf("prepareWorkspace() = true (dir %q), want a fail-closed park: a missing PR branch must not be replaced by a base checkout", gotDir)
|
||||
}
|
||||
if gotDir != "" {
|
||||
t.Errorf("prepareWorkspace() dir = %q, want empty on failure", gotDir)
|
||||
}
|
||||
|
||||
persisted, err := st.TaskByID(ctx, task.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskByID: %v", err)
|
||||
}
|
||||
if persisted.Status != workflow.StatusParked {
|
||||
t.Errorf("task status = %q, want parked", persisted.Status)
|
||||
}
|
||||
if !strings.Contains(persisted.ParkReason, "resume") {
|
||||
t.Errorf("park reason = %q, want it to name the failed resume", persisted.ParkReason)
|
||||
}
|
||||
if got := headOf(t, dir); got != tip {
|
||||
t.Errorf("worktree HEAD = %s, want it left on the PR branch tip %s", got, tip)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPrepareWorkspaceStartsBaseForANonRemediationTask keeps the resume route
|
||||
// from widening: a task that is not a remediation starts fresh on the branch
|
||||
// its current title names, even when its row carries a branch from an earlier
|
||||
// lifecycle (the row an operator requeue leaves behind).
|
||||
func TestPrepareWorkspaceStartsBaseForANonRemediationTask(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
trees := newTestTrees(t, newLocalRemote(t, "acme", "widget"))
|
||||
|
||||
_, pushedBranch, tip := pushedImplementRun(t, trees, "fix: original issue")
|
||||
|
||||
d, st, _ := testDaemon(t, 3, 0)
|
||||
task := claimedTask(t, st, "fix: retitled issue", "implement", pushedBranch, taskstate.RetryRefreshOntoBase)
|
||||
|
||||
gotDir, ok := d.prepareWorkspace(ctx, task, trees, config.Repo{Owner: "acme", Name: "widget", Base: "main"})
|
||||
if !ok {
|
||||
t.Fatal("prepareWorkspace() = false, want a fresh preparation")
|
||||
}
|
||||
if got := headOf(t, gotDir); got == tip {
|
||||
t.Errorf("worktree HEAD = %s, want base rather than the persisted branch's tip: only a remediation resumes a branch", got)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(gotDir, "widget.go")); !os.IsNotExist(err) {
|
||||
t.Errorf("widget.go present after a non-remediation prepare (stat err = %v), want a fresh base checkout", err)
|
||||
}
|
||||
if task.Branch == pushedBranch {
|
||||
t.Errorf("task branch = %q, want the branch recomputed for fresh work rather than the persisted PR branch", task.Branch)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPrepareWorkspaceContinuesPushedWorkWhenTheOperatorChoseIt is the
|
||||
// operator-mode half of the retry routing: a task whose persisted retry_mode
|
||||
// is continue_pushed_work resumes the branch it already pushed, even though
|
||||
// its workflow -- implement -- is not one that resumes by default. The
|
||||
// worktree must land on the pushed tip, not reset over it.
|
||||
func TestPrepareWorkspaceContinuesPushedWorkWhenTheOperatorChoseIt(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
trees := newTestTrees(t, newLocalRemote(t, "acme", "widget"))
|
||||
dir, branch, tip := pushedImplementRun(t, trees, "fix: original issue")
|
||||
|
||||
d, st, _ := testDaemon(t, 3, 0)
|
||||
task := claimedTask(t, st, "fix: retitled issue", "implement", branch, taskstate.RetryContinuePushedWork)
|
||||
|
||||
gotDir, ok := d.prepareWorkspace(ctx, task, trees, config.Repo{Owner: "acme", Name: "widget", Base: "main"})
|
||||
if !ok {
|
||||
t.Fatal("prepareWorkspace() = false, want the retry prepared on the branch the operator chose to continue")
|
||||
}
|
||||
if gotDir != dir {
|
||||
t.Errorf("prepareWorkspace() dir = %q, want the task's worktree %q", gotDir, dir)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(gotDir, "widget.go")); err != nil {
|
||||
t.Fatalf("widget.go missing after prepare: %v (the pushed work was discarded despite continue_pushed_work)", err)
|
||||
}
|
||||
if got := headOf(t, gotDir); got != tip {
|
||||
t.Errorf("worktree HEAD = %s, want the pushed branch tip %s", got, tip)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPrepareWorkspaceRefreshesOntoBaseWhenTheOperatorChoseIt pins that the
|
||||
// persisted mode decides, not the workflow: a task whose workflow would resume
|
||||
// (remediate) but whose retry_mode is refresh_onto_base must land on base. The
|
||||
// daemon must not re-derive the choice from the workflow, which is the silent
|
||||
// default this bead exists to remove.
|
||||
func TestPrepareWorkspaceRefreshesOntoBaseWhenTheOperatorChoseIt(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
trees := newTestTrees(t, newLocalRemote(t, "acme", "widget"))
|
||||
_, branch, tip := pushedImplementRun(t, trees, "fix: original issue")
|
||||
|
||||
d, st, _ := testDaemon(t, 3, 0)
|
||||
task := claimedTask(t, st, "fix: original issue", "remediate", branch, taskstate.RetryRefreshOntoBase)
|
||||
|
||||
gotDir, ok := d.prepareWorkspace(ctx, task, trees, config.Repo{Owner: "acme", Name: "widget", Base: "main"})
|
||||
if !ok {
|
||||
t.Fatal("prepareWorkspace() = false, want a fresh base preparation for refresh_onto_base")
|
||||
}
|
||||
if got := headOf(t, gotDir); got == tip {
|
||||
t.Errorf("worktree HEAD = %s, want base rather than the pushed branch tip: refresh_onto_base must win over the workflow", got)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(gotDir, "widget.go")); !os.IsNotExist(err) {
|
||||
t.Errorf("widget.go present after refresh_onto_base (stat err = %v), want a fresh base checkout", err)
|
||||
}
|
||||
}
|
||||
@@ -1,247 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workintake"
|
||||
"github.com/samcharles93/archie-core/internal/eventbus"
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
)
|
||||
|
||||
// captureBus is a TaskBus that records the one published envelope, so a test
|
||||
// can assert the org the producer resolved before encoding.
|
||||
type captureBus struct {
|
||||
subject string
|
||||
key string
|
||||
payload []byte
|
||||
publish int
|
||||
pubErr error
|
||||
fetchErr error
|
||||
}
|
||||
|
||||
func (b *captureBus) PublishUnique(_ context.Context, subject, key string, payload []byte) error {
|
||||
if b.pubErr != nil {
|
||||
return b.pubErr
|
||||
}
|
||||
b.subject, b.key, b.payload = subject, key, payload
|
||||
b.publish++
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *captureBus) Fetch(context.Context) (eventbus.Message, error) {
|
||||
if b.fetchErr != nil {
|
||||
return nil, b.fetchErr
|
||||
}
|
||||
return nil, eventbus.ErrNoMessage
|
||||
}
|
||||
|
||||
func (b *captureBus) Request(context.Context, string, []byte) ([]byte, error) {
|
||||
return nil, errors.New("captureBus: Request is not part of this test")
|
||||
}
|
||||
|
||||
// stubPrincipals is the access.PrincipalSource the producer resolves against,
|
||||
// keyed by identity so a test can make each identity serve a distinct org.
|
||||
type stubPrincipals struct {
|
||||
orgs map[identity.IdentityID]org.OrgID
|
||||
err error
|
||||
}
|
||||
|
||||
func (s stubPrincipals) PrincipalFor(_ context.Context, id identity.IdentityID) (access.Principal, error) {
|
||||
if s.err != nil {
|
||||
return access.Principal{}, s.err
|
||||
}
|
||||
return access.Principal{IdentityID: id, Org: s.orgs[id]}, nil
|
||||
}
|
||||
|
||||
func decodedTask(t *testing.T, payload []byte) workintake.TaskEnvelope {
|
||||
t.Helper()
|
||||
var got workintake.TaskEnvelope
|
||||
if err := json.Unmarshal(payload, &got); err != nil {
|
||||
t.Fatalf("decode published task: %v", err)
|
||||
}
|
||||
return got
|
||||
}
|
||||
|
||||
// TestPublishTaskStampsTheResolvedIdentityOrg is the core scbe assertion: the
|
||||
// poller's envelope must carry the org the identity serves, not the default,
|
||||
// so the idempotency key is org/identity/owner/repo/number for a multi-org
|
||||
// install (docs/prds/orgs-and-access.md, "Events and task identity").
|
||||
func TestPublishTaskStampsTheResolvedIdentityOrg(t *testing.T) {
|
||||
id := identity.StableID("worker")
|
||||
bus := &captureBus{}
|
||||
d := &Daemon{
|
||||
Tasks: bus,
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Identities: []*IdentityRunner{{ID: id, Name: "worker"}},
|
||||
Principals: stubPrincipals{orgs: map[identity.IdentityID]org.OrgID{id: "soc"}},
|
||||
}
|
||||
|
||||
err := d.PublishTask(t.Context(), workintake.TaskEnvelope{
|
||||
Owner: "acme", Repo: "widget", Number: 1, Identity: string(id),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("PublishTask: %v", err)
|
||||
}
|
||||
|
||||
got := decodedTask(t, bus.payload)
|
||||
if got.Org != "soc" {
|
||||
t.Errorf("published org = %q, want the identity's org %q", got.Org, "soc")
|
||||
}
|
||||
if want := "soc/" + string(id) + "/acme/widget/1"; !strings.Contains(bus.key, want) {
|
||||
t.Errorf("idempotency key = %q, want it to contain %q", bus.key, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublishTaskUsesTheRootOrgForASingleIdentityEnvelope pins the webhook
|
||||
// producer's shape: an empty identity is the root identity of a
|
||||
// single-operator install, so its org is the org the key must carry.
|
||||
func TestPublishTaskUsesTheRootOrgForASingleIdentityEnvelope(t *testing.T) {
|
||||
root := identity.StableID("root")
|
||||
bus := &captureBus{}
|
||||
d := &Daemon{
|
||||
Tasks: bus,
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
RootIdentityID: root,
|
||||
Principals: stubPrincipals{orgs: map[identity.IdentityID]org.OrgID{root: "soc"}},
|
||||
}
|
||||
|
||||
if err := d.PublishTask(t.Context(), workintake.TaskEnvelope{
|
||||
Owner: "acme", Repo: "widget", Number: 2,
|
||||
}); err != nil {
|
||||
t.Fatalf("PublishTask: %v", err)
|
||||
}
|
||||
|
||||
if got := decodedTask(t, bus.payload).Org; got != "soc" {
|
||||
t.Errorf("published org = %q, want the root identity's org %q", got, "soc")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublishTaskFailsClosedWhenTheOrgCannotBeResolved: publishing under a
|
||||
// guessed org would let the same issue key differently across deliveries, so
|
||||
// an org-RPC failure must stop the publish rather than fall back to default.
|
||||
func TestPublishTaskFailsClosedWhenTheOrgCannotBeResolved(t *testing.T) {
|
||||
id := identity.StableID("worker")
|
||||
bus := &captureBus{}
|
||||
d := &Daemon{
|
||||
Tasks: bus,
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Identities: []*IdentityRunner{{ID: id, Name: "worker"}},
|
||||
Principals: stubPrincipals{err: errors.New("state store unavailable")},
|
||||
}
|
||||
|
||||
err := d.PublishTask(t.Context(), workintake.TaskEnvelope{
|
||||
Owner: "acme", Repo: "widget", Number: 3, Identity: string(id),
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("PublishTask succeeded with an unresolved org; it must fail closed")
|
||||
}
|
||||
if bus.publish != 0 {
|
||||
t.Fatalf("published %d envelope(s) after an org resolve failure, want 0", bus.publish)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublishTaskDefaultsToTheDefaultOrgWithoutAPrincipalSource: an install
|
||||
// with no State Store has no org surface, so the default org remains correct.
|
||||
func TestPublishTaskDefaultsToTheDefaultOrgWithoutAPrincipalSource(t *testing.T) {
|
||||
bus := &captureBus{}
|
||||
d := &Daemon{Tasks: bus, Log: slog.New(slog.DiscardHandler)}
|
||||
|
||||
if err := d.PublishTask(t.Context(), workintake.TaskEnvelope{
|
||||
Owner: "acme", Repo: "widget", Number: 4,
|
||||
}); err != nil {
|
||||
t.Fatalf("PublishTask: %v", err)
|
||||
}
|
||||
|
||||
if got := decodedTask(t, bus.payload).Org; got != org.DefaultOrgID {
|
||||
t.Errorf("published org = %q, want %q", got, org.DefaultOrgID)
|
||||
}
|
||||
}
|
||||
|
||||
// TestScanPRReviewReactionsCarriesTheTaskOrg: the review scan already holds
|
||||
// the task, so the org it resolved for the PR is the org its reactions must
|
||||
// key on -- no second lookup and no cross-org drift between the two producers.
|
||||
func TestScanPRReviewReactionsCarriesTheTaskOrg(t *testing.T) {
|
||||
reader := &fakeReviewReader{
|
||||
reviews: []forge.Review{{ID: 7, Author: "alice", State: "requested_changes", Body: "fix"}},
|
||||
}
|
||||
publisher := &recordingPublisher{}
|
||||
task := openTask(42, 0, 0)
|
||||
task.Org = "soc"
|
||||
|
||||
if _, _, err := scanPRReviewReactions(
|
||||
t.Context(), reader, task, "archie-bot", 0, 0, publisher.publish); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(publisher.reactions) != 1 {
|
||||
t.Fatalf("published = %d, want 1", len(publisher.reactions))
|
||||
}
|
||||
if got := publisher.reactions[0].Org; got != "soc" {
|
||||
t.Errorf("reaction org = %q, want the task's org %q", got, "soc")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublishReactionStampsTheRootOrgWhenTheProducerCouldNot: the webhook
|
||||
// producer has no owned task to read an org from, so the reaction write path
|
||||
// resolves the root identity's org -- the same org the poll's scan stamps --
|
||||
// or the two deliveries of one review key differently.
|
||||
func TestPublishReactionStampsTheRootOrgWhenTheProducerCouldNot(t *testing.T) {
|
||||
root := identity.StableID("root")
|
||||
bus := &captureBus{}
|
||||
d := &Daemon{
|
||||
Tasks: bus,
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
RootIdentityID: root,
|
||||
Principals: stubPrincipals{orgs: map[identity.IdentityID]org.OrgID{root: "soc"}},
|
||||
}
|
||||
|
||||
err := d.PublishReaction(t.Context(), workintake.ReviewCommentEnvelope{
|
||||
Owner: "acme", Repo: "widget", PRNumber: 1,
|
||||
Kind: workintake.ReviewReactionReview, ReviewID: 5, Author: "alice",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("PublishReaction: %v", err)
|
||||
}
|
||||
|
||||
var got workintake.ReviewCommentEnvelope
|
||||
if err := json.Unmarshal(bus.payload, &got); err != nil {
|
||||
t.Fatalf("decode published reaction: %v", err)
|
||||
}
|
||||
if got.Org != "soc" {
|
||||
t.Errorf("published org = %q, want the root identity's org %q", got.Org, "soc")
|
||||
}
|
||||
if want := "review/soc/acme/widget/1/review/5"; !strings.Contains(bus.key, want) {
|
||||
t.Errorf("idempotency key = %q, want it to contain %q", bus.key, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublishReactionKeepsTheScansResolvedOrg: a reaction the scan already
|
||||
// resolved from its task must not be re-resolved to the root org, or a
|
||||
// multi-identity install would collapse every org's reactions onto one key.
|
||||
func TestPublishReactionKeepsTheScansResolvedOrg(t *testing.T) {
|
||||
bus := &captureBus{}
|
||||
d := &Daemon{Tasks: bus, Log: slog.New(slog.DiscardHandler)}
|
||||
|
||||
err := d.PublishReaction(t.Context(), workintake.ReviewCommentEnvelope{
|
||||
Owner: "acme", Repo: "widget", PRNumber: 1,
|
||||
Kind: workintake.ReviewReactionReview, ReviewID: 5, Org: "soc",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("PublishReaction: %v", err)
|
||||
}
|
||||
|
||||
var got workintake.ReviewCommentEnvelope
|
||||
if err := json.Unmarshal(bus.payload, &got); err != nil {
|
||||
t.Fatalf("decode published reaction: %v", err)
|
||||
}
|
||||
if got.Org != "soc" {
|
||||
t.Errorf("published org = %q, want the scan's org %q", got.Org, "soc")
|
||||
}
|
||||
}
|
||||
@@ -1,371 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workintake"
|
||||
"github.com/samcharles93/archie-core/internal/eventbus"
|
||||
)
|
||||
|
||||
// ---- fakes ----
|
||||
|
||||
type fakeReactionSource struct {
|
||||
mu sync.Mutex
|
||||
pending []eventbus.Message
|
||||
fetchErr error
|
||||
}
|
||||
|
||||
func (f *fakeReactionSource) Fetch(ctx context.Context) (eventbus.Message, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.fetchErr != nil {
|
||||
return nil, f.fetchErr
|
||||
}
|
||||
if len(f.pending) == 0 {
|
||||
return nil, eventbus.ErrNoMessage
|
||||
}
|
||||
m := f.pending[0]
|
||||
f.pending = f.pending[1:]
|
||||
return m, nil
|
||||
}
|
||||
|
||||
type fakeReactionMessage struct {
|
||||
data []byte
|
||||
subject string
|
||||
mu sync.Mutex
|
||||
acked bool
|
||||
nakked bool
|
||||
}
|
||||
|
||||
func (m *fakeReactionMessage) Data() []byte { return m.data }
|
||||
func (m *fakeReactionMessage) Subject() string { return m.subject }
|
||||
func (m *fakeReactionMessage) Ack() error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.acked = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *fakeReactionMessage) Nak() error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.nakked = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *fakeReactionMessage) wasAcked() bool {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return m.acked
|
||||
}
|
||||
|
||||
func (m *fakeReactionMessage) wasNakked() bool {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return m.nakked
|
||||
}
|
||||
|
||||
type fakeRemediations struct {
|
||||
begun []string // payloads handed to BeginRemediation, in order
|
||||
updated []string
|
||||
beginErr error
|
||||
}
|
||||
|
||||
func (f *fakeRemediations) BeginRemediation(ctx context.Context, taskID int64, payload string) error {
|
||||
if f.beginErr != nil {
|
||||
return f.beginErr
|
||||
}
|
||||
f.begun = append(f.begun, payload)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeRemediations) UpdateReviewPayload(ctx context.Context, taskID int64, payload string) error {
|
||||
f.updated = append(f.updated, payload)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeRemediations) SetReviewCursors(ctx context.Context, taskID, reviewCursor, commentCursor int64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type fakeReviewLookup struct {
|
||||
task *workflowtask.Task
|
||||
err error
|
||||
// sequence, when set, is consulted before task, so a test can model the
|
||||
// store's fresh read per message (e.g. a unit that queued between two
|
||||
// reactions).
|
||||
sequence func(call int) (*workflowtask.Task, error)
|
||||
calls int
|
||||
}
|
||||
|
||||
func (f *fakeReviewLookup) OpenTaskByPR(ctx context.Context, owner, repo string, number int) (*workflowtask.Task, error) {
|
||||
f.calls++
|
||||
if f.sequence != nil {
|
||||
return f.sequence(f.calls)
|
||||
}
|
||||
return f.task, f.err
|
||||
}
|
||||
|
||||
// ---- helpers ----
|
||||
|
||||
func reviewEnvelopeJSON(kind string, reviewID, commentID int64, author, state, body string) []byte {
|
||||
e := workintake.ReviewCommentEnvelope{
|
||||
Owner: "acme", Repo: "widgets", PRNumber: 42,
|
||||
Kind: workintake.ReviewReactionKind(kind),
|
||||
ReviewID: reviewID, CommentID: commentID,
|
||||
Author: author, State: state, Body: body,
|
||||
}
|
||||
data, err := e.Encode()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
func ownedTask(status, workflowName, payload string) *workflowtask.Task {
|
||||
t := &workflowtask.Task{
|
||||
ID: 7, Owner: "acme", Repo: "widgets", PRNumber: 42,
|
||||
Status: status, Workflow: workflowName, ReviewPayload: payload,
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
func newConsumer(task *workflowtask.Task, remediations *fakeRemediations) *reactionConsumer {
|
||||
return newReactionConsumer(
|
||||
&fakeReviewLookup{task: task},
|
||||
remediations,
|
||||
func(*workflowtask.Task) string { return "archie-bot" },
|
||||
slog.New(slog.DiscardHandler),
|
||||
)
|
||||
}
|
||||
|
||||
// ---- tests ----
|
||||
|
||||
func TestReactionConsumerReviewEventStartsARemediation(t *testing.T) {
|
||||
remediations := &fakeRemediations{}
|
||||
c := newConsumer(ownedTask(workflowtask.StatusPROpen, "implement", ""), remediations)
|
||||
msg := &fakeReactionMessage{data: reviewEnvelopeJSON("review", 7, 0, "alice", "requested_changes", "please fix x")}
|
||||
|
||||
c.handle(context.Background(), msg)
|
||||
|
||||
if len(remediations.begun) != 1 {
|
||||
t.Fatalf("BeginRemediation calls = %d, want 1", len(remediations.begun))
|
||||
}
|
||||
unit, err := workflow.DecodeReviewUnit(remediations.begun[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if unit.ReviewID != 7 || unit.State != "requested_changes" || unit.Body != "please fix x" {
|
||||
t.Errorf("unit = %+v, want the review's own coordinates", unit)
|
||||
}
|
||||
if !msg.wasAcked() {
|
||||
t.Error("message was not acked")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReactionConsumerApprovedReviewDoesNotRemediate(t *testing.T) {
|
||||
remediations := &fakeRemediations{}
|
||||
c := newConsumer(ownedTask(workflowtask.StatusPROpen, "implement", ""), remediations)
|
||||
msg := &fakeReactionMessage{data: reviewEnvelopeJSON("review", 7, 0, "alice", "approved", "lgtm")}
|
||||
|
||||
c.handle(context.Background(), msg)
|
||||
|
||||
if len(remediations.begun) != 0 {
|
||||
t.Errorf("BeginRemediation called for an approved review")
|
||||
}
|
||||
if !msg.wasAcked() {
|
||||
t.Error("message was not acked")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReactionConsumerOwnCommentNeverRetriggers(t *testing.T) {
|
||||
remediations := &fakeRemediations{}
|
||||
c := newConsumer(ownedTask(workflowtask.StatusPROpen, "implement", ""), remediations)
|
||||
msg := &fakeReactionMessage{data: reviewEnvelopeJSON("comment", 0, 9, "archie-bot", "", "my own reply")}
|
||||
|
||||
c.handle(context.Background(), msg)
|
||||
|
||||
if len(remediations.begun) != 0 || len(remediations.updated) != 0 {
|
||||
t.Errorf("own comment triggered work: begun=%d updated=%d", len(remediations.begun), len(remediations.updated))
|
||||
}
|
||||
if !msg.wasAcked() {
|
||||
t.Error("message was not acked")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReactionConsumerCommentAppendsToThePendingUnitOfItsReview(t *testing.T) {
|
||||
remediations := &fakeRemediations{}
|
||||
pending := ownedTask(workflowtask.StatusQueued, "remediate", `{"review_id":7,"state":"requested_changes"}`)
|
||||
c := newConsumer(pending, remediations)
|
||||
msg := &fakeReactionMessage{data: reviewEnvelopeJSON("comment", 7, 9, "alice", "", "fix the loop")}
|
||||
|
||||
c.handle(context.Background(), msg)
|
||||
|
||||
if len(remediations.updated) != 1 {
|
||||
t.Fatalf("UpdateReviewPayload calls = %d, want 1", len(remediations.updated))
|
||||
}
|
||||
unit, err := workflow.DecodeReviewUnit(remediations.updated[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if unit.ReviewID != 7 || len(unit.Comments) != 1 || unit.Comments[0].CommentID != 9 {
|
||||
t.Errorf("appended unit = %+v, want comment 9 under review 7", unit)
|
||||
}
|
||||
// The parent review's summary survives the append.
|
||||
if unit.State != "requested_changes" {
|
||||
t.Errorf("unit state = %q, want the parent review's state preserved", unit.State)
|
||||
}
|
||||
if !msg.wasAcked() {
|
||||
t.Error("message was not acked")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReactionConsumerDuplicateCommentIsNotAppendedTwice(t *testing.T) {
|
||||
remediations := &fakeRemediations{}
|
||||
pending := ownedTask(workflowtask.StatusQueued, "remediate", `{"review_id":7,"comments":[{"comment_id":9,"body":"fix the loop"}]}`)
|
||||
c := newConsumer(pending, remediations)
|
||||
msg := &fakeReactionMessage{data: reviewEnvelopeJSON("comment", 7, 9, "alice", "", "fix the loop")}
|
||||
|
||||
c.handle(context.Background(), msg)
|
||||
|
||||
if len(remediations.updated) != 0 {
|
||||
t.Errorf("UpdateReviewPayload called for a comment the unit already carries")
|
||||
}
|
||||
if !msg.wasAcked() {
|
||||
t.Error("message was not acked")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReactionConsumerLateCommentAfterDispatchIsDropped(t *testing.T) {
|
||||
remediations := &fakeRemediations{}
|
||||
c := newConsumer(ownedTask(workflowtask.StatusPROpen, "implement", ""), remediations)
|
||||
// A comment carrying a parent review id, but the task is not a queued
|
||||
// remediation for it: the unit already dispatched.
|
||||
msg := &fakeReactionMessage{data: reviewEnvelopeJSON("comment", 7, 9, "alice", "", "late comment")}
|
||||
|
||||
c.handle(context.Background(), msg)
|
||||
|
||||
if len(remediations.begun) != 0 || len(remediations.updated) != 0 {
|
||||
t.Errorf("late comment mutated store state: begun=%d updated=%d", len(remediations.begun), len(remediations.updated))
|
||||
}
|
||||
if !msg.wasAcked() {
|
||||
t.Error("message was not acked")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReactionConsumerStandaloneCommentIsItsOwnUnit(t *testing.T) {
|
||||
remediations := &fakeRemediations{}
|
||||
c := newConsumer(ownedTask(workflowtask.StatusPROpen, "implement", ""), remediations)
|
||||
msg := &fakeReactionMessage{data: reviewEnvelopeJSON("comment", 0, 12, "alice", "", "nit: rename")}
|
||||
|
||||
c.handle(context.Background(), msg)
|
||||
|
||||
if len(remediations.begun) != 1 {
|
||||
t.Fatalf("BeginRemediation calls = %d, want 1", len(remediations.begun))
|
||||
}
|
||||
unit, err := workflow.DecodeReviewUnit(remediations.begun[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(unit.Comments) != 1 || unit.Comments[0].CommentID != 12 {
|
||||
t.Errorf("unit = %+v, want one standalone comment", unit)
|
||||
}
|
||||
if !msg.wasAcked() {
|
||||
t.Error("message was not acked")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReactionConsumerUnresolvablePRIsDropped(t *testing.T) {
|
||||
remediations := &fakeRemediations{}
|
||||
// nil task: the PR does not belong to an archie-owned task.
|
||||
c := newConsumer(nil, remediations)
|
||||
msg := &fakeReactionMessage{data: reviewEnvelopeJSON("review", 7, 0, "alice", "requested_changes", "unrelated")}
|
||||
|
||||
c.handle(context.Background(), msg)
|
||||
|
||||
if len(remediations.begun) != 0 {
|
||||
t.Errorf("reaction for a foreign PR started work")
|
||||
}
|
||||
if !msg.wasAcked() {
|
||||
t.Error("message was not acked")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReactionConsumerInvalidEnvelopeIsAckedNotRedelivered(t *testing.T) {
|
||||
remediations := &fakeRemediations{}
|
||||
c := newConsumer(ownedTask(workflowtask.StatusPROpen, "implement", ""), remediations)
|
||||
msg := &fakeReactionMessage{data: []byte(`{"owner":"acme"}`)} // no kind, no ids
|
||||
|
||||
c.handle(context.Background(), msg)
|
||||
|
||||
if len(remediations.begun) != 0 {
|
||||
t.Errorf("invalid envelope started work")
|
||||
}
|
||||
if !msg.wasAcked() {
|
||||
t.Error("message was not acked")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReactionConsumerTransientStoreErrorNaks(t *testing.T) {
|
||||
remediations := &fakeRemediations{beginErr: errors.New("db unavailable")}
|
||||
c := newConsumer(ownedTask(workflowtask.StatusPROpen, "implement", ""), remediations)
|
||||
msg := &fakeReactionMessage{data: reviewEnvelopeJSON("review", 7, 0, "alice", "requested_changes", "please fix x")}
|
||||
|
||||
c.handle(context.Background(), msg)
|
||||
|
||||
if !msg.wasNakked() {
|
||||
t.Error("transient failure was not nakked for redelivery")
|
||||
}
|
||||
if msg.wasAcked() {
|
||||
t.Error("transient failure was acked")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReactionConsumerDrainsUntilIdle(t *testing.T) {
|
||||
remediations := &fakeRemediations{}
|
||||
// The lookup reads the row fresh per message: the review event queues the
|
||||
// remediation, so the comment event resolves against the queued unit.
|
||||
lookup := &fakeReviewLookup{sequence: func(call int) (*workflowtask.Task, error) {
|
||||
if call == 1 {
|
||||
return ownedTask(workflowtask.StatusPROpen, "implement", ""), nil
|
||||
}
|
||||
return ownedTask(workflowtask.StatusQueued, "remediate", `{"review_id":7,"state":"requested_changes","body":"one"}`), nil
|
||||
}}
|
||||
c := newReactionConsumer(lookup, remediations, func(*workflowtask.Task) string { return "archie-bot" }, slog.New(slog.DiscardHandler))
|
||||
src := &fakeReactionSource{pending: []eventbus.Message{
|
||||
&fakeReactionMessage{data: reviewEnvelopeJSON("review", 7, 0, "alice", "requested_changes", "one")},
|
||||
&fakeReactionMessage{data: reviewEnvelopeJSON("comment", 7, 8, "alice", "", "one-a")},
|
||||
}}
|
||||
|
||||
n, err := c.drain(context.Background(), src, 8)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n != 2 {
|
||||
t.Errorf("handled = %d, want 2", n)
|
||||
}
|
||||
// The review queued the unit; the comment appended to it.
|
||||
if len(remediations.begun) != 1 || len(remediations.updated) != 1 {
|
||||
t.Errorf("begun=%d updated=%d, want 1/1", len(remediations.begun), len(remediations.updated))
|
||||
}
|
||||
unit, err := workflow.DecodeReviewUnit(remediations.updated[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(unit.Comments) != 1 || unit.Comments[0].CommentID != 8 {
|
||||
t.Errorf("appended unit = %+v, want comment 8 collected under review 7", unit)
|
||||
}
|
||||
}
|
||||
|
||||
// compile-time interface checks
|
||||
var (
|
||||
_ workintake.ReviewTaskLookup = (*fakeReviewLookup)(nil)
|
||||
_ storecontract.RemediationStarter = (*fakeRemediations)(nil)
|
||||
)
|
||||
@@ -1,138 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workintake"
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
)
|
||||
|
||||
type fakeReviewReader struct {
|
||||
reviews []forge.Review
|
||||
comments []forge.ReviewComment
|
||||
listErr error
|
||||
}
|
||||
|
||||
func (f *fakeReviewReader) ListReviews(ctx context.Context, owner, repo string, number int, sinceID int64) ([]forge.Review, error) {
|
||||
// The real implementations filter on the forge; the fake models the
|
||||
// contract so "records at or below the cursor never come back" is
|
||||
// actually exercised.
|
||||
var out []forge.Review
|
||||
for _, r := range f.reviews {
|
||||
if r.ID > sinceID {
|
||||
out = append(out, r)
|
||||
}
|
||||
}
|
||||
return out, f.listErr
|
||||
}
|
||||
|
||||
func (f *fakeReviewReader) ListReviewComments(ctx context.Context, owner, repo string, number int, sinceID int64) ([]forge.ReviewComment, error) {
|
||||
var out []forge.ReviewComment
|
||||
for _, c := range f.comments {
|
||||
if c.ID > sinceID {
|
||||
out = append(out, c)
|
||||
}
|
||||
}
|
||||
return out, f.listErr
|
||||
}
|
||||
|
||||
func (f *fakeReviewReader) ReplyToReview(ctx context.Context, owner, repo string, number int, inReplyTo int64, body string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type recordingPublisher struct {
|
||||
reactions []workintake.ReviewCommentEnvelope
|
||||
err error
|
||||
}
|
||||
|
||||
func (p *recordingPublisher) publish(ctx context.Context, e workintake.ReviewCommentEnvelope) error {
|
||||
if p.err != nil {
|
||||
return p.err
|
||||
}
|
||||
p.reactions = append(p.reactions, e)
|
||||
return nil
|
||||
}
|
||||
|
||||
func openTask(prNumber int, reviewCursor, commentCursor int64) *workflowtask.Task {
|
||||
return &workflowtask.Task{ID: 7, Owner: "acme", Repo: "widgets", PRNumber: prNumber, Status: "pr_open", ReviewCursor: reviewCursor, WatchCommentID: commentCursor}
|
||||
}
|
||||
|
||||
func TestScanPRReviewReactionsPublishesNewRecordsAndSkipsOwn(t *testing.T) {
|
||||
reader := &fakeReviewReader{
|
||||
reviews: []forge.Review{
|
||||
{ID: 5, Author: "archie-bot", State: "requested_changes", Body: "mine"},
|
||||
{ID: 7, Author: "alice", State: "requested_changes", Body: "please fix"},
|
||||
},
|
||||
comments: []forge.ReviewComment{
|
||||
{ID: 9, ReviewID: 7, Author: "archie-bot", Body: "my reply"},
|
||||
{ID: 11, ReviewID: 7, Author: "bob", Body: "also this", Path: "x.go", Line: 3},
|
||||
},
|
||||
}
|
||||
publisher := &recordingPublisher{}
|
||||
task := openTask(42, 0, 0)
|
||||
|
||||
reviewCursor, commentCursor, err := scanPRReviewReactions(
|
||||
context.Background(), reader, task, "archie-bot", 0, 0, publisher.publish)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// The own review and own reply are excluded; alice's review and bob's
|
||||
// comment are the two actionable records.
|
||||
if len(publisher.reactions) != 2 {
|
||||
t.Fatalf("published = %d, want 2", len(publisher.reactions))
|
||||
}
|
||||
if publisher.reactions[0].Kind != workintake.ReviewReactionReview || publisher.reactions[0].ReviewID != 7 {
|
||||
t.Errorf("first reaction = %+v, want alice's review 7", publisher.reactions[0])
|
||||
}
|
||||
if publisher.reactions[1].Kind != workintake.ReviewReactionComment || publisher.reactions[1].CommentID != 11 {
|
||||
t.Errorf("second reaction = %+v, want bob's comment 11", publisher.reactions[1])
|
||||
}
|
||||
if publisher.reactions[1].ReviewID != 7 {
|
||||
t.Errorf("comment reaction ReviewID = %d, want 7 (collected under its review)", publisher.reactions[1].ReviewID)
|
||||
}
|
||||
if publisher.reactions[1].Body != "also this" || publisher.reactions[1].Path != "x.go" || publisher.reactions[1].Line != 3 {
|
||||
t.Errorf("comment payload = %+v, want the comment's own content", publisher.reactions[1])
|
||||
}
|
||||
// Cursors advance past every record seen, own or not: a cursor that
|
||||
// stalls on a skipped record would re-list it every scan forever.
|
||||
if reviewCursor != 7 || commentCursor != 11 {
|
||||
t.Errorf("cursors = (%d, %d), want (7, 11)", reviewCursor, commentCursor)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScanPRReviewReactionsSkipRecordsAtOrBelowTheCursors(t *testing.T) {
|
||||
reader := &fakeReviewReader{
|
||||
reviews: []forge.Review{{ID: 5, Author: "alice", State: "requested_changes", Body: "old"}},
|
||||
comments: []forge.ReviewComment{{ID: 6, ReviewID: 5, Author: "bob", Body: "old comment"}},
|
||||
}
|
||||
publisher := &recordingPublisher{}
|
||||
|
||||
reviewCursor, commentCursor, err := scanPRReviewReactions(
|
||||
context.Background(), reader, openTask(42, 5, 6), "archie-bot", 5, 6, publisher.publish)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(publisher.reactions) != 0 {
|
||||
t.Errorf("published %d reactions for records at or below the cursors", len(publisher.reactions))
|
||||
}
|
||||
if reviewCursor != 5 || commentCursor != 6 {
|
||||
t.Errorf("cursors = (%d, %d), want unchanged (5, 6)", reviewCursor, commentCursor)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScanPRReviewReactionsKeepsCursorsOnPublishFailure(t *testing.T) {
|
||||
reader := &fakeReviewReader{
|
||||
reviews: []forge.Review{{ID: 7, Author: "alice", State: "requested_changes", Body: "fix"}},
|
||||
}
|
||||
publisher := &recordingPublisher{err: errors.New("bus unavailable")}
|
||||
|
||||
_, _, err := scanPRReviewReactions(
|
||||
context.Background(), reader, openTask(42, 0, 0), "archie-bot", 0, 0, publisher.publish)
|
||||
if err == nil {
|
||||
t.Fatal("publish error was swallowed; the cursors must not advance past unpublished records")
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestRunningTaskIsInterruptible is the guarantee /stop rests on for
|
||||
// agents. Cancelling a task must reach the work in flight, not merely
|
||||
// record an intention in the store.
|
||||
func TestRunningTaskIsInterruptible(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var r runningTasks
|
||||
started := make(chan struct{})
|
||||
observed := make(chan error, 1)
|
||||
|
||||
go func() {
|
||||
taskCtx, finished := r.begin(context.Background(), 7, "archie")
|
||||
defer finished()
|
||||
close(started)
|
||||
<-taskCtx.Done()
|
||||
observed <- taskCtx.Err()
|
||||
}()
|
||||
<-started
|
||||
|
||||
if !r.stop(7) {
|
||||
t.Fatal("stop reported that task 7 was not running")
|
||||
}
|
||||
select {
|
||||
case err := <-observed:
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Errorf("task context error = %v, want context.Canceled", err)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("the task never observed cancellation")
|
||||
}
|
||||
}
|
||||
|
||||
// TestStopUnknownTaskIsReported keeps a stale store row distinguishable
|
||||
// from a live task: the caller has to be able to tell the difference to
|
||||
// decide whether recording a terminal state is safe.
|
||||
func TestStopUnknownTaskIsReported(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var r runningTasks
|
||||
if r.stop(99) {
|
||||
t.Error("stop claimed to cancel a task that was never running")
|
||||
}
|
||||
}
|
||||
|
||||
// TestFinishedTaskIsNotCancellable guards the retirement in begin's
|
||||
// cleanup. A stale entry would let a later /stop report success against a
|
||||
// task that had already completed.
|
||||
func TestFinishedTaskIsNotCancellable(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var r runningTasks
|
||||
_, finished := r.begin(context.Background(), 3, "archie")
|
||||
finished()
|
||||
|
||||
if r.stop(3) {
|
||||
t.Error("a completed task was reported as stopped")
|
||||
}
|
||||
if got := r.list(); len(got) != 0 {
|
||||
t.Errorf("list() = %v, want empty after the task finished", got)
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/worktree"
|
||||
)
|
||||
|
||||
// A task with no repository gets an empty scratch workspace, no publication
|
||||
// grant, and is not serialized behind other repository-less tasks.
|
||||
func TestNoRepositoryTaskRunsInScratch(t *testing.T) {
|
||||
d := &Daemon{Cfg: config.NewHolder(config.Config{}), Log: slog.New(slog.DiscardHandler)}
|
||||
task := &workflow.Task{ID: 12}
|
||||
trees := &worktree.Manager{WorkDir: t.TempDir()}
|
||||
|
||||
dir, ok := d.prepareWorkspace(t.Context(), task, trees, config.Repo{})
|
||||
if !ok || dir != trees.ScratchDir(12) {
|
||||
t.Fatalf("prepareWorkspace() = %q, %v; want the task's scratch dir", dir, ok)
|
||||
}
|
||||
if info, err := os.Stat(dir); err != nil || !info.IsDir() {
|
||||
t.Fatalf("scratch dir not created: %v", err)
|
||||
}
|
||||
grant, revoke, ok := d.publicationGrant(t.Context(), task)
|
||||
if !ok || grant != "" || revoke == nil {
|
||||
t.Fatalf("publicationGrant() = %q, %v; want no grant and a no-op revoke", grant, ok)
|
||||
}
|
||||
revoke()
|
||||
if !d.allowConcurrentForTask(task) {
|
||||
t.Error("repository-less tasks are serialized on an empty repo key")
|
||||
}
|
||||
}
|
||||
|
||||
// runPinnedViaAgent pins the task's workflow and profile, then hands it to the
|
||||
// agent, the order process uses.
|
||||
func runPinnedViaAgent(ctx context.Context, d *Daemon, task *workflow.Task, repo config.Repo) {
|
||||
profile, ok := d.pinTaskProfile(ctx, task)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
d.runViaAgent(ctx, task, repo, profile, nil)
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
)
|
||||
|
||||
// fakeStateStoreGrants issues a fixed, task-scoped token and records revoke
|
||||
// calls, standing in for staterpc.GrantIssuer in daemon-level tests.
|
||||
type fakeStateStoreGrants struct {
|
||||
token string
|
||||
err error
|
||||
revoked int
|
||||
}
|
||||
|
||||
func (f *fakeStateStoreGrants) Issue(*workflow.Task) (string, func(), error) {
|
||||
if f.err != nil {
|
||||
return "", nil, f.err
|
||||
}
|
||||
return f.token, func() { f.revoked++ }, nil
|
||||
}
|
||||
|
||||
func TestContainerEnvNeverExposesStateStoreAdminToken(t *testing.T) {
|
||||
d := &Daemon{Cfg: config.NewHolder(config.Config{}), ConnectedStateStore: StateStoreEndpoint{URL: "127.0.0.1:9090", Token: "admin-secret"}}
|
||||
for _, entry := range d.containerEnv(&workflow.Task{ID: 42}, "task-scoped-token") {
|
||||
if strings.Contains(entry, "admin-secret") {
|
||||
t.Fatalf("container receives administrative credential: %s", entry)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestContainerEnvCarriesTaskScopedStateStoreToken(t *testing.T) {
|
||||
d := &Daemon{Cfg: config.NewHolder(config.Config{}), ConnectedStateStore: StateStoreEndpoint{URL: "127.0.0.1:9090", Token: "admin-secret"}}
|
||||
got := d.containerEnv(&workflow.Task{ID: 42}, "task-scoped-token")
|
||||
if !slices.Contains(got, "STATE_STORE_TOKEN=task-scoped-token") {
|
||||
t.Fatalf("containerEnv() = %q, want STATE_STORE_TOKEN=task-scoped-token", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStateStoreGrantTokenIssuesFromWiredGrants(t *testing.T) {
|
||||
grants := &fakeStateStoreGrants{token: "task-scoped-token"}
|
||||
d := &Daemon{ConnectedStateStore: StateStoreEndpoint{URL: "127.0.0.1:9090"}, StateStoreGrants: grants}
|
||||
|
||||
token, revoke, err := d.stateStoreGrantToken(&workflow.Task{ID: 42})
|
||||
if err != nil {
|
||||
t.Fatalf("stateStoreGrantToken: %v", err)
|
||||
}
|
||||
if token != "task-scoped-token" {
|
||||
t.Fatalf("token = %q, want %q", token, "task-scoped-token")
|
||||
}
|
||||
revoke()
|
||||
if grants.revoked != 1 {
|
||||
t.Fatalf("revoked = %d, want 1", grants.revoked)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStateStoreGrantTokenFailsClosedWithoutIssuer(t *testing.T) {
|
||||
d := &Daemon{ConnectedStateStore: StateStoreEndpoint{URL: "127.0.0.1:9090"}}
|
||||
|
||||
if _, _, err := d.stateStoreGrantToken(&workflow.Task{ID: 42}); err == nil {
|
||||
t.Fatal("stateStoreGrantToken: want error when State Store is configured but no grant issuer is wired")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStateStoreGrantTokenNoOpWhenStateStoreUnconfigured(t *testing.T) {
|
||||
d := &Daemon{}
|
||||
|
||||
token, revoke, err := d.stateStoreGrantToken(&workflow.Task{ID: 42})
|
||||
if err != nil || token != "" || revoke == nil {
|
||||
t.Fatalf("stateStoreGrantToken = (%q, revoke==nil:%v, %v), want (\"\", false, nil)", token, revoke == nil, err)
|
||||
}
|
||||
revoke() // must not panic
|
||||
}
|
||||
@@ -1,543 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
dockercontainer "github.com/moby/moby/api/types/container"
|
||||
"github.com/moby/moby/client"
|
||||
natsio "github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
archiecontainer "github.com/samcharles93/archie-core/internal/container"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
agentnats "github.com/samcharles93/archie-core/internal/infrastructure/agenttransport/nats"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/storage"
|
||||
"github.com/samcharles93/archie-core/internal/taskrun"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate/taskstatetest"
|
||||
"github.com/samcharles93/archie-core/internal/worktree"
|
||||
)
|
||||
|
||||
type logBuffer struct {
|
||||
mu sync.Mutex
|
||||
buf bytes.Buffer
|
||||
}
|
||||
|
||||
func (l *logBuffer) Write(p []byte) (n int, err error) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return l.buf.Write(p)
|
||||
}
|
||||
|
||||
func (l *logBuffer) String() string {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return l.buf.String()
|
||||
}
|
||||
|
||||
type errGrantIssuer struct{}
|
||||
|
||||
func (errGrantIssuer) Issue(*workflow.Task) (string, func(), error) {
|
||||
return "", nil, errors.New("simulated grant issue error")
|
||||
}
|
||||
|
||||
type errStorage struct {
|
||||
setupErr error
|
||||
}
|
||||
|
||||
func (s *errStorage) Setup(context.Context, storage.TaskRef) ([]storage.Mount, error) {
|
||||
if s.setupErr != nil {
|
||||
return nil, s.setupErr
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *errStorage) Teardown(context.Context, storage.TaskRef) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *errStorage) CleanupExpired(context.Context, time.Duration) (int, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func TestCancelledTaskTransitionsToParked(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
cancelBefore bool
|
||||
cancelDuring bool
|
||||
nilGrants bool
|
||||
errGrants bool
|
||||
decodeErr bool
|
||||
agentErr string
|
||||
wantStatus string
|
||||
wantParkSubstr string
|
||||
}{
|
||||
{
|
||||
name: "task cancelled during requestTaskRun",
|
||||
cancelDuring: true,
|
||||
wantStatus: workflow.StatusParked,
|
||||
wantParkSubstr: "context canceled",
|
||||
},
|
||||
{
|
||||
name: "task cancelled before runViaAgent",
|
||||
cancelBefore: true,
|
||||
wantStatus: workflow.StatusParked,
|
||||
wantParkSubstr: "context canceled",
|
||||
},
|
||||
{
|
||||
name: "worktree grants unavailable",
|
||||
nilGrants: true,
|
||||
wantStatus: workflow.StatusParked,
|
||||
wantParkSubstr: "worktree publication grants are unavailable",
|
||||
},
|
||||
{
|
||||
name: "worktree grant issue failed",
|
||||
errGrants: true,
|
||||
wantStatus: workflow.StatusParked,
|
||||
wantParkSubstr: "worktree publication grant failed",
|
||||
},
|
||||
{
|
||||
name: "taskrun decode response failed",
|
||||
decodeErr: true,
|
||||
wantStatus: workflow.StatusParked,
|
||||
wantParkSubstr: "taskrun decode response failed",
|
||||
},
|
||||
{
|
||||
name: "taskrun agent returned error",
|
||||
agentErr: "simulated agent execution failure",
|
||||
wantStatus: workflow.StatusParked,
|
||||
wantParkSubstr: "taskrun run failed: simulated agent execution failure",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
d, s, busClient := daemonWithNATS(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
|
||||
if _, err := s.EnqueueIssue(context.Background(), "acme", "widget", 1, "task", "body", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := s.ClaimNext(context.Background())
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("ClaimNext: (%v, %v)", task, err)
|
||||
}
|
||||
|
||||
if tt.nilGrants {
|
||||
d.WorktreeGrants = nil
|
||||
}
|
||||
if tt.errGrants {
|
||||
d.WorktreeGrants = errGrantIssuer{}
|
||||
}
|
||||
|
||||
if tt.cancelBefore {
|
||||
cancel()
|
||||
}
|
||||
|
||||
if tt.cancelDuring {
|
||||
sub, err := mustCoreConn(t, busClient).Subscribe(agentnats.SubjectForTask(task.ID), func(msg *natsio.Msg) {
|
||||
cancel()
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sub.Unsubscribe() })
|
||||
}
|
||||
|
||||
if tt.decodeErr {
|
||||
sub, err := mustCoreConn(t, busClient).Subscribe(agentnats.SubjectForTask(task.ID), func(msg *natsio.Msg) {
|
||||
_ = msg.Respond([]byte("invalid json response"))
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sub.Unsubscribe() })
|
||||
}
|
||||
|
||||
if tt.agentErr != "" {
|
||||
sub, err := mustCoreConn(t, busClient).Subscribe(agentnats.SubjectForTask(task.ID), func(msg *natsio.Msg) {
|
||||
resp, _ := json.Marshal(taskrun.Response{Error: tt.agentErr})
|
||||
_ = msg.Respond(resp)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sub.Unsubscribe() })
|
||||
}
|
||||
|
||||
d.TaskRunReadyTimeout = 100 * time.Millisecond
|
||||
d.TaskRunRetryBackoff = 10 * time.Millisecond
|
||||
|
||||
runPinnedViaAgent(ctx, d, task, config.Repo{Owner: "acme", Name: "widget"})
|
||||
|
||||
got, err := s.TaskByID(context.Background(), task.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskByID: %v", err)
|
||||
}
|
||||
if got.Status != tt.wantStatus {
|
||||
t.Fatalf("task status = %q, want %q", got.Status, tt.wantStatus)
|
||||
}
|
||||
if !strings.Contains(got.ParkReason, tt.wantParkSubstr) {
|
||||
t.Errorf("park reason = %q, want substring %q", got.ParkReason, tt.wantParkSubstr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanupTerminalTaskWorktreeWithCancelledContext(t *testing.T) {
|
||||
host := newLocalRemote(t, "acme", "widget")
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
taskStatus string
|
||||
prNumber int
|
||||
wantTreeExists bool
|
||||
}{
|
||||
{
|
||||
name: "merged task with cancelled context cleans worktree",
|
||||
taskStatus: workflow.StatusMerged,
|
||||
prNumber: 0,
|
||||
wantTreeExists: false,
|
||||
},
|
||||
{
|
||||
name: "rejected task with cancelled context cleans worktree",
|
||||
taskStatus: workflow.StatusRejected,
|
||||
prNumber: 0,
|
||||
wantTreeExists: false,
|
||||
},
|
||||
{
|
||||
name: "closed wont do task with cancelled context cleans worktree",
|
||||
taskStatus: workflow.StatusClosedWontDo,
|
||||
prNumber: 0,
|
||||
wantTreeExists: false,
|
||||
},
|
||||
{
|
||||
name: "parked task with cancelled context preserves worktree",
|
||||
taskStatus: workflow.StatusParked,
|
||||
prNumber: 0,
|
||||
wantTreeExists: true,
|
||||
},
|
||||
{
|
||||
name: "open PR task with cancelled context preserves worktree",
|
||||
taskStatus: workflow.StatusPROpen,
|
||||
prNumber: 12,
|
||||
wantTreeExists: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel() // cancel context before calling cleanup
|
||||
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
trees := newTestTrees(t, host)
|
||||
log := slog.New(slog.DiscardHandler)
|
||||
d := &Daemon{
|
||||
Store: st,
|
||||
Trees: trees,
|
||||
Log: log,
|
||||
}
|
||||
|
||||
if _, err := st.EnqueueIssue(context.Background(), "acme", "widget", 101, "task", "body", "bug", ""); err != nil {
|
||||
t.Fatalf("EnqueueIssue: %v", err)
|
||||
}
|
||||
task, err := st.ClaimNext(context.Background())
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("ClaimNext: (%v, %v)", task, err)
|
||||
}
|
||||
|
||||
// Seeded along the table's legal edges: a merge and a rejection
|
||||
// are both observed on an open pull request.
|
||||
taskstatetest.Seed(t.Context(), t, st, task.ID, task.Status, tt.taskStatus, "setup")
|
||||
if tt.prNumber > 0 {
|
||||
task.PRNumber = tt.prNumber
|
||||
if err := st.Update(context.Background(), task); err != nil {
|
||||
t.Fatalf("Update: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
workDir := trees.Dir(task.Owner, task.Repo, task.IssueNumber)
|
||||
// A prepared clone: the cancelled context is the thing under test,
|
||||
// so the worktree itself is readied with a live one.
|
||||
if _, _, err := trees.Prepare(context.Background(), task.Owner, task.Repo, "main",
|
||||
task.IssueNumber, task.Title, task.Body, task.Labels, worktree.Fresh); err != nil {
|
||||
t.Fatalf("prepare worktree: %v", err)
|
||||
}
|
||||
|
||||
d.cleanupTerminalTaskWorktree(ctx, task, trees)
|
||||
|
||||
_, statErr := os.Stat(workDir)
|
||||
treeExists := statErr == nil
|
||||
if treeExists != tt.wantTreeExists {
|
||||
t.Errorf("worktree exists = %v, want %v (path: %s)", treeExists, tt.wantTreeExists, workDir)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessStopRunningTransitionsToParked(t *testing.T) {
|
||||
host := newLocalRemote(t, "acme", "widget")
|
||||
d, s, busClient := daemonWithNATS(t)
|
||||
ctx := context.Background()
|
||||
|
||||
rootTrees := &worktree.Manager{
|
||||
WorkDir: t.TempDir(),
|
||||
Token: "unused",
|
||||
BotUser: "archie-bot",
|
||||
BotEmail: "archie-bot@example.com",
|
||||
BaseURL: "file://" + host,
|
||||
}
|
||||
d.Trees = rootTrees
|
||||
|
||||
repo := config.Repo{Owner: "acme", Name: "widget", Base: "main"}
|
||||
d.Cfg.Set(config.Config{
|
||||
Repos: []config.Repo{repo},
|
||||
})
|
||||
|
||||
// Mock Docker API server for ContainerPool
|
||||
dockerAPI := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case strings.HasSuffix(r.URL.Path, "/containers/create"):
|
||||
writeContainerDockerJSON(t, w, dockercontainer.CreateResponse{ID: "test-container-id"})
|
||||
case strings.Contains(r.URL.Path, "/containers/test-container-id"):
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
case strings.HasSuffix(r.URL.Path, "/containers/json"):
|
||||
writeContainerDockerJSON(t, w, []any{})
|
||||
default:
|
||||
http.Error(w, "unexpected Docker API path "+r.URL.Path, http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(dockerAPI.Close)
|
||||
|
||||
dockerClient, err := client.New(client.WithHost(dockerAPI.URL), client.WithAPIVersion("1.55"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = dockerClient.Close() })
|
||||
|
||||
pool, err := archiecontainer.NewPool(ctx, archiecontainer.Config{
|
||||
Image: "archie-agent:test",
|
||||
DockerClient: dockerClient,
|
||||
}, nil, d.Log)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d.ContainerPool = pool
|
||||
d.Storage = &noopStorage{}
|
||||
|
||||
if _, err := s.EnqueueIssue(ctx, "acme", "widget", 42, "issue to stop", "body", "bug", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := s.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("ClaimNext: (%v, %v)", task, err)
|
||||
}
|
||||
|
||||
// When agent request is received, stop the running task via d.CancelTask(task.ID)
|
||||
sub, err := mustCoreConn(t, busClient).Subscribe(agentnats.SubjectForTask(task.ID), func(msg *natsio.Msg) {
|
||||
stopped := d.CancelTask(task.ID)
|
||||
if !stopped {
|
||||
t.Errorf("CancelTask(%d) = false, want true", task.ID)
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sub.Unsubscribe() })
|
||||
|
||||
d.TaskRunReadyTimeout = 100 * time.Millisecond
|
||||
d.TaskRunRetryBackoff = 10 * time.Millisecond
|
||||
|
||||
d.process(ctx, task)
|
||||
|
||||
got, err := s.TaskByID(ctx, task.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskByID: %v", err)
|
||||
}
|
||||
if got.Status != workflow.StatusParked {
|
||||
t.Fatalf("stopped task status = %q, want %q", got.Status, workflow.StatusParked)
|
||||
}
|
||||
if !strings.Contains(got.ParkReason, "context canceled") {
|
||||
t.Errorf("park reason = %q, want substring 'context canceled'", got.ParkReason)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParkRunningTaskGuardedAndLogging(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
initialStatus string
|
||||
workerStatus string
|
||||
closeStore bool
|
||||
cancelContext bool
|
||||
wantStatus string
|
||||
wantWarning bool
|
||||
wantLogSubstr string
|
||||
}{
|
||||
{
|
||||
name: "successful park on cancelled context transitions row to parked without warning",
|
||||
initialStatus: workflow.StatusRunning,
|
||||
cancelContext: true,
|
||||
wantStatus: workflow.StatusParked,
|
||||
wantWarning: false,
|
||||
},
|
||||
{
|
||||
name: "stale transition preserves worker status and logs no warning",
|
||||
initialStatus: workflow.StatusRunning,
|
||||
workerStatus: workflow.StatusMerged,
|
||||
cancelContext: true,
|
||||
wantStatus: workflow.StatusMerged,
|
||||
wantWarning: false,
|
||||
},
|
||||
{
|
||||
name: "store write failure logs warning",
|
||||
initialStatus: workflow.StatusRunning,
|
||||
closeStore: true,
|
||||
wantWarning: true,
|
||||
wantLogSubstr: "terminal park transition failed",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
|
||||
var buf logBuffer
|
||||
log := slog.New(slog.NewTextHandler(&buf, nil))
|
||||
|
||||
d := &Daemon{
|
||||
Store: s,
|
||||
Log: log,
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
if _, err := s.EnqueueIssue(ctx, "acme", "widget", 55, "task", "body", "bug", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := s.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("ClaimNext: (%v, %v)", task, err)
|
||||
}
|
||||
|
||||
if tt.workerStatus != "" {
|
||||
taskstatetest.Seed(ctx, t, s, task.ID, task.Status, tt.workerStatus, "worker completion")
|
||||
}
|
||||
|
||||
callCtx := ctx
|
||||
if tt.cancelContext {
|
||||
cctx, cancel := context.WithCancel(ctx)
|
||||
cancel()
|
||||
callCtx = cctx
|
||||
}
|
||||
|
||||
if tt.closeStore {
|
||||
s.Pool.Close()
|
||||
}
|
||||
|
||||
d.parkRunningTask(callCtx, task.ID, "simulated park reason", taskstate.ParkTransient)
|
||||
|
||||
logOutput := buf.String()
|
||||
if tt.wantWarning {
|
||||
if !strings.Contains(logOutput, tt.wantLogSubstr) {
|
||||
t.Errorf("log output = %q, want substring %q", logOutput, tt.wantLogSubstr)
|
||||
}
|
||||
if !strings.Contains(logOutput, "level=WARN") {
|
||||
t.Errorf("log output = %q, want level=WARN", logOutput)
|
||||
}
|
||||
} else if strings.Contains(logOutput, "terminal park transition failed") {
|
||||
t.Errorf("unexpected warning in log output: %q", logOutput)
|
||||
}
|
||||
|
||||
if !tt.closeStore {
|
||||
got, err := s.TaskByID(ctx, task.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskByID: %v", err)
|
||||
}
|
||||
if got.Status != tt.wantStatus {
|
||||
t.Errorf("task status = %q, want %q", got.Status, tt.wantStatus)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAcquireTaskContainerFailureParksTaskOnCancelledContext(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
nilStorage bool
|
||||
setupErr error
|
||||
wantParkSubstr string
|
||||
}{
|
||||
{
|
||||
name: "storage backend not configured",
|
||||
nilStorage: true,
|
||||
wantParkSubstr: "storage backend not configured",
|
||||
},
|
||||
{
|
||||
name: "storage setup failed",
|
||||
setupErr: errors.New("simulated setup error"),
|
||||
wantParkSubstr: "storage setup failed",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
|
||||
d := &Daemon{
|
||||
Store: s,
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel() // cancelled context
|
||||
|
||||
if _, err := s.EnqueueIssue(context.Background(), "acme", "widget", 88, "task", "body", "bug", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := s.ClaimNext(context.Background())
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("ClaimNext: (%v, %v)", task, err)
|
||||
}
|
||||
|
||||
workDir := t.TempDir()
|
||||
|
||||
if !tt.nilStorage {
|
||||
d.Storage = &errStorage{setupErr: tt.setupErr}
|
||||
}
|
||||
|
||||
ctr, revoke, ok := d.acquireTaskContainer(ctx, task, config.Repo{Owner: "acme", Name: "widget"}, workDir, "")
|
||||
if ok || ctr != nil || revoke != nil {
|
||||
t.Fatalf("acquireTaskContainer ok = %v, ctr = %v, revoke==nil:%v; want false, nil, true", ok, ctr, revoke == nil)
|
||||
}
|
||||
|
||||
got, err := s.TaskByID(context.Background(), task.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskByID: %v", err)
|
||||
}
|
||||
if got.Status != workflow.StatusParked {
|
||||
t.Fatalf("task status = %q, want %q", got.Status, workflow.StatusParked)
|
||||
}
|
||||
if !strings.Contains(got.ParkReason, tt.wantParkSubstr) {
|
||||
t.Errorf("park reason = %q, want substring %q", got.ParkReason, tt.wantParkSubstr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
)
|
||||
|
||||
// TestDaemonResizeTaskDispatcherTracksConfig pins the daemon's live-apply
|
||||
// wrapper: the dispatcher is built from the running config and a later resize
|
||||
// reaches it without rebuilding the daemon.
|
||||
func TestDaemonResizeTaskDispatcherTracksConfig(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
d := &Daemon{
|
||||
Cfg: config.NewHolder(config.Config{Containers: config.ContainerConfig{MaxConcurrency: 2}}),
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
}
|
||||
dispatcher := d.taskDispatcher()
|
||||
dispatcher.mu.Lock()
|
||||
booted := dispatcher.limit
|
||||
dispatcher.mu.Unlock()
|
||||
if booted != 2 {
|
||||
t.Fatalf("dispatcher limit = %d, want the running config's 2", booted)
|
||||
}
|
||||
|
||||
d.ResizeTaskDispatcher(5)
|
||||
dispatcher.mu.Lock()
|
||||
resized := dispatcher.limit
|
||||
dispatcher.mu.Unlock()
|
||||
if resized != 5 {
|
||||
t.Fatalf("dispatcher limit after resize = %d, want 5", resized)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTaskDispatcherResizesWithoutRestart pins the live half of
|
||||
// archie-core-zfb0.2: the running dispatcher accepts a new
|
||||
// containers.max_concurrency. Raising the limit admits queued work
|
||||
// immediately; lowering it leaves running tasks holding their slots and
|
||||
// admits new work only as they finish.
|
||||
func TestTaskDispatcherResizesWithoutRestart(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dispatcher := newTaskDispatcher(1, nil)
|
||||
|
||||
releaseA := make(chan struct{})
|
||||
aStarted := make(chan struct{})
|
||||
bStarted := make(chan struct{})
|
||||
releaseB := make(chan struct{})
|
||||
cStarted := make(chan struct{})
|
||||
|
||||
dispatcher.Submit(context.Background(), &workflow.Task{Owner: "acme", Repo: "a"}, func(context.Context, *workflow.Task) {
|
||||
close(aStarted)
|
||||
<-releaseA
|
||||
})
|
||||
<-aStarted
|
||||
|
||||
dispatcher.Submit(context.Background(), &workflow.Task{Owner: "acme", Repo: "b"}, func(context.Context, *workflow.Task) {
|
||||
close(bStarted)
|
||||
<-releaseB
|
||||
})
|
||||
select {
|
||||
case <-bStarted:
|
||||
t.Fatal("second task started above max_concurrency 1")
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
}
|
||||
|
||||
// Raising the limit must admit the queued task without a restart.
|
||||
dispatcher.SetMaxConcurrency(2)
|
||||
select {
|
||||
case <-bStarted:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("raising the limit did not admit the queued task")
|
||||
}
|
||||
|
||||
// Lowering the limit applies as running tasks finish: a new task waits
|
||||
// while two tasks hold slots, and starts only once they have drained
|
||||
// below the new limit.
|
||||
dispatcher.SetMaxConcurrency(1)
|
||||
dispatcher.Submit(context.Background(), &workflow.Task{Owner: "acme", Repo: "c"}, func(context.Context, *workflow.Task) {
|
||||
close(cStarted)
|
||||
})
|
||||
|
||||
close(releaseA)
|
||||
select {
|
||||
case <-cStarted:
|
||||
t.Fatal("a task started while two tasks still held slots under a lowered limit")
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
}
|
||||
|
||||
close(releaseB)
|
||||
select {
|
||||
case <-cStarted:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("lowered limit did not admit new work as running tasks finished")
|
||||
}
|
||||
|
||||
dispatcher.Wait()
|
||||
}
|
||||
@@ -1,424 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-git/go-git/v6"
|
||||
gitconfig "github.com/go-git/go-git/v6/config"
|
||||
"github.com/go-git/go-git/v6/plumbing"
|
||||
"github.com/go-git/go-git/v6/plumbing/object"
|
||||
dockercontainer "github.com/moby/moby/api/types/container"
|
||||
"github.com/moby/moby/client"
|
||||
natsio "github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
archiecontainer "github.com/samcharles93/archie-core/internal/container"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
agentnats "github.com/samcharles93/archie-core/internal/infrastructure/agenttransport/nats"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/storage"
|
||||
"github.com/samcharles93/archie-core/internal/taskrun"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate/taskstatetest"
|
||||
"github.com/samcharles93/archie-core/internal/worktree"
|
||||
)
|
||||
|
||||
type noopStorage struct{}
|
||||
|
||||
func (s *noopStorage) Setup(context.Context, storage.TaskRef) ([]storage.Mount, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *noopStorage) Teardown(context.Context, storage.TaskRef) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *noopStorage) CleanupExpired(context.Context, time.Duration) (int, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func newLocalRemote(t *testing.T, owner, repo string) string {
|
||||
t.Helper()
|
||||
host := t.TempDir()
|
||||
bare := filepath.Join(host, owner, repo+".git")
|
||||
mainRef := plumbing.NewBranchReferenceName("main")
|
||||
|
||||
if _, err := git.PlainInit(bare, true, git.WithDefaultBranch(mainRef)); err != nil {
|
||||
t.Fatalf("init bare remote: %v", err)
|
||||
}
|
||||
|
||||
seed := filepath.Join(t.TempDir(), "seed")
|
||||
sr, err := git.PlainInit(seed, false, git.WithDefaultBranch(mainRef))
|
||||
if err != nil {
|
||||
t.Fatalf("init seed repo: %v", err)
|
||||
}
|
||||
cfg, err := sr.Config()
|
||||
if err != nil {
|
||||
t.Fatalf("read seed config: %v", err)
|
||||
}
|
||||
cfg.Raw.Section("commit").SetOption("gpgsign", "false")
|
||||
if err := sr.SetConfig(cfg); err != nil {
|
||||
t.Fatalf("write seed config: %v", err)
|
||||
}
|
||||
|
||||
if err := os.WriteFile(filepath.Join(seed, "README.md"), []byte("seed\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wt, err := sr.Worktree()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := wt.Add("README.md"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sig := &object.Signature{Name: "test", Email: "test@test", When: time.Now()}
|
||||
h, err := wt.Commit("seed", &git.CommitOptions{Author: sig, Committer: sig})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := sr.CreateRemote(&gitconfig.RemoteConfig{
|
||||
Name: git.DefaultRemoteName,
|
||||
URLs: []string{bare},
|
||||
}); err != nil {
|
||||
t.Fatalf("create remote: %v", err)
|
||||
}
|
||||
if err := sr.PushContext(t.Context(), &git.PushOptions{
|
||||
RemoteName: git.DefaultRemoteName,
|
||||
RefSpecs: []gitconfig.RefSpec{gitconfig.RefSpec(mainRef + ":" + mainRef)},
|
||||
}); err != nil {
|
||||
t.Fatalf("push seed to bare remote: %v", err)
|
||||
}
|
||||
_ = h
|
||||
return host
|
||||
}
|
||||
|
||||
// newTestTrees returns a worktree manager whose clones come from the local
|
||||
// bare remote at host, so a fixture can prepare the clone the daemon would.
|
||||
func newTestTrees(t *testing.T, host string) *worktree.Manager {
|
||||
t.Helper()
|
||||
return &worktree.Manager{
|
||||
WorkDir: t.TempDir(),
|
||||
Token: "unused",
|
||||
BotUser: "archie-bot",
|
||||
BotEmail: "archie-bot@example.com",
|
||||
BaseURL: "file://" + host,
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanupTerminalTaskWorktreeLifecycle(t *testing.T) {
|
||||
host := newLocalRemote(t, "acme", "widget")
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
taskIdentity string
|
||||
setupStatus string
|
||||
prNumber int
|
||||
uncommitted bool
|
||||
wantTreeExists bool
|
||||
}{
|
||||
{
|
||||
name: "root no-change merged task cleans worktree",
|
||||
taskIdentity: "",
|
||||
setupStatus: workflow.StatusMerged,
|
||||
prNumber: 0,
|
||||
wantTreeExists: false,
|
||||
},
|
||||
{
|
||||
name: "multi-identity no-change merged task cleans identity worktree",
|
||||
taskIdentity: "winter",
|
||||
setupStatus: workflow.StatusMerged,
|
||||
prNumber: 0,
|
||||
wantTreeExists: false,
|
||||
},
|
||||
{
|
||||
name: "root no-change completed task cleans worktree",
|
||||
taskIdentity: "",
|
||||
setupStatus: workflow.StatusCompleted,
|
||||
prNumber: 0,
|
||||
wantTreeExists: false,
|
||||
},
|
||||
{
|
||||
name: "multi-identity no-change completed task cleans identity worktree",
|
||||
taskIdentity: "winter",
|
||||
setupStatus: workflow.StatusCompleted,
|
||||
prNumber: 0,
|
||||
wantTreeExists: false,
|
||||
},
|
||||
{
|
||||
// agent.run ends a task completed with its deliverable still
|
||||
// uncommitted in the clone. Deleting that worktree deletes the
|
||||
// work: nothing else anywhere holds those edits.
|
||||
name: "completed task keeps a worktree that holds uncommitted work",
|
||||
taskIdentity: "",
|
||||
setupStatus: workflow.StatusCompleted,
|
||||
prNumber: 0,
|
||||
uncommitted: true,
|
||||
wantTreeExists: true,
|
||||
},
|
||||
{
|
||||
name: "merged task keeps a worktree that holds uncommitted work",
|
||||
taskIdentity: "",
|
||||
setupStatus: workflow.StatusMerged,
|
||||
prNumber: 0,
|
||||
uncommitted: true,
|
||||
wantTreeExists: true,
|
||||
},
|
||||
{
|
||||
name: "parked task preserves worktree for post-mortem",
|
||||
taskIdentity: "",
|
||||
setupStatus: workflow.StatusParked,
|
||||
prNumber: 0,
|
||||
wantTreeExists: true,
|
||||
},
|
||||
{
|
||||
name: "open PR task preserves worktree for PR reconciliation",
|
||||
taskIdentity: "",
|
||||
setupStatus: workflow.StatusPROpen,
|
||||
prNumber: 42,
|
||||
wantTreeExists: true,
|
||||
},
|
||||
{
|
||||
name: "waiting human task preserves worktree",
|
||||
taskIdentity: "",
|
||||
setupStatus: workflow.StatusWaitingHuman,
|
||||
prNumber: 0,
|
||||
wantTreeExists: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
rootTrees := newTestTrees(t, host)
|
||||
winterTrees := newTestTrees(t, host)
|
||||
|
||||
log := slog.New(slog.DiscardHandler)
|
||||
d := &Daemon{
|
||||
Store: st,
|
||||
Trees: rootTrees,
|
||||
Identities: []*IdentityRunner{
|
||||
{
|
||||
Name: "winter",
|
||||
Trees: winterTrees,
|
||||
Forge: &testForge{},
|
||||
Repos: []config.Repo{{Owner: "acme", Name: "widget"}},
|
||||
Cfg: config.IdentityConfig{Name: "winter"},
|
||||
Log: log,
|
||||
},
|
||||
},
|
||||
Log: log,
|
||||
}
|
||||
|
||||
issueNum := 101
|
||||
if _, err := st.EnqueueIssue(ctx, "acme", "widget", issueNum, "test task", "body", "bug", tt.taskIdentity); err != nil {
|
||||
t.Fatalf("EnqueueIssue: %v", err)
|
||||
}
|
||||
|
||||
claimed, err := st.ClaimNext(ctx)
|
||||
if err != nil || claimed == nil {
|
||||
t.Fatalf("ClaimNext: (%v, %v)", claimed, err)
|
||||
}
|
||||
|
||||
// Seeded along the table's legal edges: a merged task reached
|
||||
// `merged` through an open pull request, never from running.
|
||||
taskstatetest.Seed(ctx, t, st, claimed.ID, claimed.Status, tt.setupStatus, "status update")
|
||||
|
||||
if tt.prNumber > 0 {
|
||||
claimed.PRNumber = tt.prNumber
|
||||
if err := st.Update(ctx, claimed); err != nil {
|
||||
t.Fatalf("Update PRNumber: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
targetTrees := d.treesFor(claimed)
|
||||
workDir := targetTrees.Dir(claimed.Owner, claimed.Repo, claimed.IssueNumber)
|
||||
// A prepared clone, the only shape the daemon ever cleans up.
|
||||
if _, _, err := targetTrees.Prepare(ctx, claimed.Owner, claimed.Repo, "main",
|
||||
claimed.IssueNumber, claimed.Title, claimed.Body, claimed.Labels, worktree.Fresh); err != nil {
|
||||
t.Fatalf("prepare worktree: %v", err)
|
||||
}
|
||||
if tt.uncommitted {
|
||||
if err := os.WriteFile(filepath.Join(workDir, "deliverable.md"), []byte("uncommitted work\n"), 0o600); err != nil {
|
||||
t.Fatalf("write uncommitted work: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
d.cleanupTerminalTaskWorktree(ctx, claimed, targetTrees)
|
||||
|
||||
_, statErr := os.Stat(workDir)
|
||||
treeExists := statErr == nil
|
||||
if treeExists != tt.wantTreeExists {
|
||||
t.Errorf("worktree exists = %v, want %v (path: %s)", treeExists, tt.wantTreeExists, workDir)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessCleansWorktreeOnTerminalNoChange(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
workerStatus string
|
||||
taskIdentity string
|
||||
wantTreeExists bool
|
||||
}{
|
||||
{
|
||||
name: "process removes worktree when worker completes without a PR",
|
||||
workerStatus: workflow.StatusCompleted,
|
||||
taskIdentity: "",
|
||||
wantTreeExists: false,
|
||||
},
|
||||
{
|
||||
name: "process removes identity worktree when worker completes without a PR",
|
||||
workerStatus: workflow.StatusCompleted,
|
||||
taskIdentity: "winter",
|
||||
wantTreeExists: false,
|
||||
},
|
||||
{
|
||||
name: "process keeps worktree when worker parks task",
|
||||
workerStatus: workflow.StatusParked,
|
||||
taskIdentity: "",
|
||||
wantTreeExists: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
host := newLocalRemote(t, "acme", "widget")
|
||||
d, s, busClient := daemonWithNATS(t)
|
||||
ctx := context.Background()
|
||||
|
||||
rootTrees := &worktree.Manager{
|
||||
WorkDir: t.TempDir(),
|
||||
Token: "unused",
|
||||
BotUser: "archie-bot",
|
||||
BotEmail: "archie-bot@example.com",
|
||||
BaseURL: "file://" + host,
|
||||
}
|
||||
winterTrees := &worktree.Manager{
|
||||
WorkDir: t.TempDir(),
|
||||
Token: "unused",
|
||||
BotUser: "winter-bot",
|
||||
BotEmail: "winter-bot@example.com",
|
||||
BaseURL: "file://" + host,
|
||||
}
|
||||
d.Trees = rootTrees
|
||||
|
||||
repo := config.Repo{Owner: "acme", Name: "widget", Base: "main"}
|
||||
d.Cfg.Set(config.Config{
|
||||
Repos: []config.Repo{repo},
|
||||
})
|
||||
|
||||
d.Identities = []*IdentityRunner{
|
||||
{
|
||||
Name: "winter",
|
||||
Trees: winterTrees,
|
||||
Forge: &testForge{},
|
||||
Repos: []config.Repo{repo},
|
||||
Cfg: config.IdentityConfig{Name: "winter"},
|
||||
Log: d.Log,
|
||||
},
|
||||
}
|
||||
|
||||
// Mock Docker API server for ContainerPool
|
||||
dockerAPI := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case strings.HasSuffix(r.URL.Path, "/containers/create"):
|
||||
writeContainerDockerJSON(t, w, dockercontainer.CreateResponse{ID: "test-container-id"})
|
||||
case strings.Contains(r.URL.Path, "/containers/test-container-id"):
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
case strings.HasSuffix(r.URL.Path, "/containers/json"):
|
||||
writeContainerDockerJSON(t, w, []any{})
|
||||
default:
|
||||
http.Error(w, "unexpected Docker API path "+r.URL.Path, http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(dockerAPI.Close)
|
||||
|
||||
dockerClient, err := client.New(client.WithHost(dockerAPI.URL), client.WithAPIVersion("1.55"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = dockerClient.Close() })
|
||||
|
||||
pool, err := archiecontainer.NewPool(ctx, archiecontainer.Config{
|
||||
Image: "archie-agent:test",
|
||||
DockerClient: dockerClient,
|
||||
}, nil, d.Log)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d.ContainerPool = pool
|
||||
d.Storage = &noopStorage{}
|
||||
|
||||
if _, err := s.EnqueueIssue(ctx, "acme", "widget", 77, "no-op issue", "body", "bug", tt.taskIdentity); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := s.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("ClaimNext: (%v, %v)", task, err)
|
||||
}
|
||||
|
||||
targetTrees := d.treesFor(task)
|
||||
workDir := targetTrees.Dir(task.Owner, task.Repo, task.IssueNumber)
|
||||
|
||||
sub, err := mustCoreConn(t, busClient).Subscribe(agentnats.SubjectForTask(task.ID), func(msg *natsio.Msg) {
|
||||
// Transition task in store as archie-agent would do over the gRPC State Store
|
||||
_ = s.Transition(ctx, task.ID, workflow.StatusRunning, tt.workerStatus, "worker completion")
|
||||
resp, _ := json.Marshal(taskrun.Response{
|
||||
Status: tt.workerStatus,
|
||||
})
|
||||
_ = msg.Respond(resp)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sub.Unsubscribe() })
|
||||
|
||||
d.process(ctx, task)
|
||||
|
||||
_, statErr := os.Stat(workDir)
|
||||
treeExists := statErr == nil
|
||||
if treeExists != tt.wantTreeExists {
|
||||
t.Errorf("worktree exists = %v, want %v (path: %s)", treeExists, tt.wantTreeExists, workDir)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestRemoveWorktreeReapsTheOwningIdentitysClone is the operator's reap path
|
||||
// for a worktree terminal cleanup kept: archiving removes the clone under the
|
||||
// trees of the identity that owns the task, and only that clone.
|
||||
func TestRemoveWorktreeReapsTheOwningIdentitysClone(t *testing.T) {
|
||||
root := &worktree.Manager{WorkDir: t.TempDir()}
|
||||
winter := &worktree.Manager{WorkDir: t.TempDir()}
|
||||
d := &Daemon{Trees: root, Identities: []*IdentityRunner{{Name: "winter", Trees: winter}}}
|
||||
for _, m := range []*worktree.Manager{root, winter} {
|
||||
if err := os.MkdirAll(m.Dir("acme", "widget", 7), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := d.RemoveWorktree("acme", "widget", "winter", 7); err != nil {
|
||||
t.Fatalf("RemoveWorktree: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(winter.Dir("acme", "widget", 7)); !errors.Is(err, fs.ErrNotExist) {
|
||||
t.Errorf("identity worktree still on disk: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(root.Dir("acme", "widget", 7)); err != nil {
|
||||
t.Errorf("root worktree removed: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -1,294 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
type workflowDefinitionsStub struct {
|
||||
collection workflow.WorkflowDefinitionCollection
|
||||
version int64
|
||||
}
|
||||
|
||||
func (s *workflowDefinitionsStub) WorkflowDefinitions(context.Context) (workflow.WorkflowDefinitionCollection, int64, error) {
|
||||
return s.collection, s.version, nil
|
||||
}
|
||||
|
||||
func TestWorkflowDefinitionPinSurvivesActiveOverride(t *testing.T) {
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
task, err := resources.EnqueueChatTask(t.Context(), "acme", "widget", "custom", "", "custom", "operator", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first := "id: custom\nsteps:\n - type: bootstrap.apply\n"
|
||||
provider := &workflowDefinitionsStub{collection: workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{{ID: "custom", YAML: first}}}, version: 4}
|
||||
d := &Daemon{Store: resources, WorkflowDefinitions: provider}
|
||||
if err := d.pinWorkflowDefinition(t.Context(), task); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
provider.collection.Definitions[0].YAML = "id: custom\nsteps:\n - type: bootstrap.prepare\n"
|
||||
provider.version = 5
|
||||
if err := d.pinWorkflowDefinition(t.Context(), task); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if task.WorkflowDefinitionYAML != first || task.WorkflowDefinitionVersion != 4 {
|
||||
t.Fatalf("pin changed after override: version=%d yaml=%q", task.WorkflowDefinitionVersion, task.WorkflowDefinitionYAML)
|
||||
}
|
||||
stored, err := resources.TaskByID(t.Context(), task.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stored.WorkflowDefinitionDigest != workflow.DigestDefinition(first) {
|
||||
t.Fatal("persisted workflow digest does not identify the pinned YAML")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPinWorkflowDefinitionRepinsWhenTheTaskNamesAnotherWorkflow covers the
|
||||
// waiting_human -> approved requeue: RequeueTask writes the new workflow name
|
||||
// and leaves the previous run's definition pinned, so the requeued row carries
|
||||
// a workflow column and a stored definition that disagree.
|
||||
//
|
||||
// Those two are what the worker's compile refuses at dispatch
|
||||
// (agentworker.CompilePinnedWorkflow: "pinned workflow definition does not
|
||||
// match task identity"), so a pin that names a different workflow than the
|
||||
// task is a dispatch that can never run, and the daemon -- the producer that
|
||||
// wrote the pin -- re-pins it from the collection the task's workflow is
|
||||
// resolved out of. A pin that is present, digest-valid AND id-consistent stays
|
||||
// a strict no-op, so an operator's newer active definition does not overwrite
|
||||
// a task's existing pin on the next dispatch.
|
||||
func TestPinWorkflowDefinitionRepinsWhenTheTaskNamesAnotherWorkflow(t *testing.T) {
|
||||
const (
|
||||
pinnedVersion = 4
|
||||
activeVersion = 9
|
||||
)
|
||||
feasibilityPin := "id: feasibility\nsteps:\n - type: feasibility.assess\n"
|
||||
customPin := "id: custom\nsteps:\n - type: bootstrap.apply\n"
|
||||
// The active collection is the one the daemon resolves a named workflow
|
||||
// out of. Its "custom" entry is deliberately different YAML from customPin:
|
||||
// that is the operator's newer active definition, and the only way to tell
|
||||
// a reuse from a re-pin is that a reused pin keeps the older YAML.
|
||||
active := &workflowDefinitionsStub{
|
||||
collection: workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{
|
||||
{ID: "feasibility", YAML: feasibilityPin},
|
||||
{ID: "implement", YAML: "id: implement\nsteps:\n - type: implement.prepare\n"},
|
||||
{ID: "custom", YAML: "id: custom\nsteps:\n - type: bootstrap.prepare\n"},
|
||||
}},
|
||||
version: activeVersion,
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
// taskWorkflow is the row's workflow column: what the requeue wrote,
|
||||
// and the workflow the pinned definition must end up naming.
|
||||
taskWorkflow string
|
||||
// pinnedYAML is the definition the row carries into the dispatch --
|
||||
// for a requeue, the workflow the task ran before its workflow column
|
||||
// changed.
|
||||
pinnedYAML string
|
||||
// shipped pins from the shipped definitions, the way a daemon with no
|
||||
// definitions provider does.
|
||||
shipped bool
|
||||
wantWorkflow string
|
||||
wantYAML string
|
||||
wantVersion int64
|
||||
}{
|
||||
{
|
||||
name: "a requeue onto another workflow is re-pinned from the active collection",
|
||||
taskWorkflow: "implement",
|
||||
pinnedYAML: feasibilityPin,
|
||||
wantWorkflow: "implement",
|
||||
wantYAML: "id: implement\nsteps:\n - type: implement.prepare\n",
|
||||
wantVersion: activeVersion,
|
||||
},
|
||||
{
|
||||
name: "a daemon with no definitions provider re-pins from the shipped set",
|
||||
taskWorkflow: "implement",
|
||||
pinnedYAML: feasibilityPin,
|
||||
shipped: true,
|
||||
wantWorkflow: "implement",
|
||||
wantVersion: 0,
|
||||
},
|
||||
{
|
||||
name: "an id-consistent pin is reused, so an active override does not displace it",
|
||||
taskWorkflow: "custom",
|
||||
pinnedYAML: customPin,
|
||||
wantWorkflow: "custom",
|
||||
wantYAML: customPin,
|
||||
wantVersion: pinnedVersion,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
wantYAML := tt.wantYAML
|
||||
if tt.shipped {
|
||||
entry, ok := workflow.ShippedDefinitions().DefinitionByID(tt.wantWorkflow)
|
||||
if !ok {
|
||||
t.Fatalf("shipped definitions have no %q", tt.wantWorkflow)
|
||||
}
|
||||
wantYAML = entry.YAML
|
||||
}
|
||||
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
task, err := resources.EnqueueChatTask(t.Context(), "acme", "widget", tt.name, "", tt.taskWorkflow, "operator", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// RequeueTask sets status, workflow and park_reason, and never
|
||||
// touches the workflow_definition_* columns, so this is the row a
|
||||
// requeue hands to the next dispatch: the new workflow name over
|
||||
// the previous run's definition.
|
||||
task.WorkflowDefinitionYAML = tt.pinnedYAML
|
||||
task.WorkflowDefinitionDigest = workflow.DigestDefinition(tt.pinnedYAML)
|
||||
task.WorkflowDefinitionVersion = pinnedVersion
|
||||
if err := resources.Update(t.Context(), task); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
d := &Daemon{Store: resources, Log: slog.New(slog.DiscardHandler)}
|
||||
if !tt.shipped {
|
||||
d.WorkflowDefinitions = active
|
||||
}
|
||||
if err := d.pinWorkflowDefinition(t.Context(), task); err != nil {
|
||||
t.Fatalf("pinWorkflowDefinition: %v", err)
|
||||
}
|
||||
if task.Workflow != tt.wantWorkflow || task.WorkflowDefinitionYAML != wantYAML || task.WorkflowDefinitionVersion != tt.wantVersion {
|
||||
t.Fatalf("pin = (%q, version %d, %q),\nwant (%q, version %d, %q)",
|
||||
task.Workflow, task.WorkflowDefinitionVersion, task.WorkflowDefinitionYAML,
|
||||
tt.wantWorkflow, tt.wantVersion, wantYAML)
|
||||
}
|
||||
|
||||
stored, err := resources.TaskByID(t.Context(), task.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stored.Workflow != tt.wantWorkflow || stored.WorkflowDefinitionYAML != wantYAML || stored.WorkflowDefinitionVersion != tt.wantVersion {
|
||||
t.Fatalf("persisted pin = (%q, version %d, %q),\nwant (%q, version %d, %q)",
|
||||
stored.Workflow, stored.WorkflowDefinitionVersion, stored.WorkflowDefinitionYAML,
|
||||
tt.wantWorkflow, tt.wantVersion, wantYAML)
|
||||
}
|
||||
requirePinMatchesTaskIdentity(t, stored)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestApproveRequeueRepinsTheWorkflowDefinition reproduces the operator-visible
|
||||
// defect end to end through the real store writes: a task runs feasibility,
|
||||
// parks waiting_human with the feasibility definition pinned, and the approval
|
||||
// requeue moves it to the implement workflow. RequeueTask sets status, workflow
|
||||
// and park_reason and leaves the workflow_definition_* columns, so the next
|
||||
// dispatch met an id mismatch and the worker's compile parked the task again --
|
||||
// identically on every further approval, leaving decline the only working
|
||||
// action.
|
||||
//
|
||||
// What the task row must satisfy before that dispatch is the worker's own
|
||||
// precondition (agentworker.CompilePinnedWorkflow), asserted here through
|
||||
// requirePinMatchesTaskIdentity.
|
||||
func TestApproveRequeueRepinsTheWorkflowDefinition(t *testing.T) {
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
if _, err := resources.EnqueueChatTask(t.Context(), "acme", "widget", "feature request", "", "feasibility", "operator", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
claim, err := resources.ClaimNext(t.Context())
|
||||
if err != nil || claim == nil {
|
||||
t.Fatalf("claim: (%v, %v)", claim, err)
|
||||
}
|
||||
|
||||
// The run pins the feasibility definition and parks for the human decision.
|
||||
provider := &workflowDefinitionsStub{collection: workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{
|
||||
{ID: "feasibility", YAML: "id: feasibility\nsteps:\n - type: feasibility.assess\n"},
|
||||
{ID: "implement", YAML: "id: implement\nsteps:\n - type: implement.prepare\n"},
|
||||
}}, version: 2}
|
||||
d := &Daemon{Store: resources, Log: slog.New(slog.DiscardHandler), WorkflowDefinitions: provider}
|
||||
if err := d.pinWorkflowDefinition(t.Context(), claim); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := resources.Transition(t.Context(), claim.ID, "running", "waiting_human", "PRD delivered, awaiting go/no-go"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// The operator approves: the same write taskactions.Service.apply performs.
|
||||
if err := resources.Requeue(t.Context(), claim.ID, "waiting_human", "implement"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
requeued, err := resources.TaskByID(t.Context(), claim.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if requeued.Workflow != "implement" {
|
||||
t.Fatalf("requeued workflow = %q, want implement", requeued.Workflow)
|
||||
}
|
||||
if got, err := workflow.DefinitionID(requeued.WorkflowDefinitionYAML); err != nil || got != "feasibility" {
|
||||
t.Fatalf("the requeue changed the stored pin to (%q, %v); this test only means anything while the pin is still the previous workflow's", got, err)
|
||||
}
|
||||
|
||||
// The next dispatch re-pins before the worker's compile sees the row.
|
||||
if err := d.pinWorkflowDefinition(t.Context(), requeued); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stored, err := resources.TaskByID(t.Context(), requeued.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
requirePinMatchesTaskIdentity(t, stored)
|
||||
}
|
||||
|
||||
// TestPinWorkflowDefinitionRefusesATamperedPin keeps the digest half of the
|
||||
// guard intact: a stored definition that does not hash to the digest recorded
|
||||
// with it is a corrupt row, and repairing it here would silently run a
|
||||
// definition nobody wrote. It is refused, and the row is left for an operator.
|
||||
func TestPinWorkflowDefinitionRefusesATamperedPin(t *testing.T) {
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
task, err := resources.EnqueueChatTask(t.Context(), "acme", "widget", "tampered", "", "implement", "operator", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task.WorkflowDefinitionYAML = "id: implement\nsteps:\n - type: implement.prepare\n"
|
||||
task.WorkflowDefinitionDigest = workflow.DigestDefinition("id: implement\nsteps:\n - type: implement.build\n")
|
||||
if err := resources.Update(t.Context(), task); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
d := &Daemon{Store: resources, Log: slog.New(slog.DiscardHandler), WorkflowDefinitions: &workflowDefinitionsStub{
|
||||
collection: workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{
|
||||
{ID: "implement", YAML: "id: implement\nsteps:\n - type: implement.prepare\n"},
|
||||
}},
|
||||
version: 3,
|
||||
}}
|
||||
err = d.pinWorkflowDefinition(t.Context(), task)
|
||||
if err == nil || !strings.Contains(err.Error(), "digest mismatch") {
|
||||
t.Fatalf("pinWorkflowDefinition error = %v, want a digest mismatch refusal", err)
|
||||
}
|
||||
if task.WorkflowDefinitionVersion != 0 {
|
||||
t.Fatalf("refused pin wrote version %d; a refused pin must leave the row alone", task.WorkflowDefinitionVersion)
|
||||
}
|
||||
}
|
||||
|
||||
// requirePinMatchesTaskIdentity holds a persisted pin to the invariant the
|
||||
// worker's compile enforces before it runs a dispatch
|
||||
// (agentworker.CompilePinnedWorkflow): the pinned definition compiles against
|
||||
// the process vocabulary, names the workflow the task row names, and hashes to
|
||||
// the digest stored beside it. A producer that leaves a pin failing this is
|
||||
// the defect that parks a requeued task forever.
|
||||
func requirePinMatchesTaskIdentity(t *testing.T, stored *workflow.Task) {
|
||||
t.Helper()
|
||||
compiled, err := workflow.ParseAndCompile(stored.WorkflowDefinitionYAML, workflow.BuiltinStepRegistry())
|
||||
if err != nil {
|
||||
t.Fatalf("pinned definition does not compile: %v", err)
|
||||
}
|
||||
if compiled.Name != stored.Workflow {
|
||||
t.Fatalf("pinned definition names %q, the task row names %q: the worker's compile refuses this pair", compiled.Name, stored.Workflow)
|
||||
}
|
||||
if got := workflow.DigestDefinition(stored.WorkflowDefinitionYAML); got != stored.WorkflowDefinitionDigest {
|
||||
t.Fatalf("pinned definition digest = %s, the row records %s", got, stored.WorkflowDefinitionDigest)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user