From 629404a5091a0abbf8e450ecd704a4f7f4b73284 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Thu, 8 Oct 2026 22:28:53 +1100 Subject: [PATCH] fix(daemon): let a run waiting on a callee release its capacity A wait:true workflow.call run held its global slot and its repo's place for the callee's whole life, and the drain pass waited for its own tasks, so a callee queued by that pass was never claimed. With containers.max_concurrency saturated, or a repo that does not allow concurrency, the wait could not end. A drain pass now returns once the stream and the claim fallback are empty, and shutdown waits for in-flight work once. Suspend/Resume give a run's slot and repo place back while it waits on a callee, driven by the workflow call events on the daemon's bus; a hold records one slot and one place, so a second re-acquire gives back what it took. --- internal/daemon/call_waits.go | 53 +++ internal/daemon/daemon.go | 261 +++++++++++--- internal/daemon/dispatcher_test.go | 544 +++++++++++++++++++++++++++++ internal/daemon/update_test.go | 2 +- 4 files changed, 818 insertions(+), 42 deletions(-) create mode 100644 internal/daemon/call_waits.go create mode 100644 internal/daemon/dispatcher_test.go diff --git a/internal/daemon/call_waits.go b/internal/daemon/call_waits.go new file mode 100644 index 000000000..b61554508 --- /dev/null +++ b/internal/daemon/call_waits.go @@ -0,0 +1,53 @@ +package daemon + +import ( + "context" + + "github.com/samcharles93/archie-core/internal/events" +) + +// callWaitBuffer is the watcher's subscription buffer. The bus carries the +// whole agent-event stream and drops for a subscriber whose buffer is full, so +// this has to absorb a burst rather than overflow on one. +const callWaitBuffer = 1024 + +// watchCallWaits gives a run's execution capacity back while it waits on a +// callee, and takes it again when the wait ends. The events arrive on the +// daemon's own bus, republished from the container running the workflow, and +// carry the caller's task id. +func (d *Daemon) watchCallWaits(ctx context.Context) { + if d.Bus == nil { + return + } + sub := d.Bus.Subscribe(callWaitBuffer) + dispatcher := d.taskDispatcher() + go func() { + defer sub.Close() + for { + select { + case <-ctx.Done(): + return + case e, ok := <-sub.C: + if !ok { + return + } + applyCallWait(dispatcher, e) + } + } + }() +} + +// applyCallWait suspends the run a call start names and resumes it when the +// call finishes. It stays non-blocking: a full subscriber buffer drops events, +// and a dropped start leaves a waiting run holding the capacity its callee +// needs, so this must never wait on anything. +func applyCallWait(dispatcher *taskDispatcher, e events.Event) { + switch e.Kind { + case events.KindWorkflowCallStarted: + if waiting, _ := e.Data["wait"].(bool); waiting { + dispatcher.Suspend(e.TaskID) + } + case events.KindWorkflowCallFinished: + dispatcher.Resume(e.TaskID) + } +} diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index 2b95a89dc..e0bb2c95a 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -170,7 +170,7 @@ type Daemon struct { // dispatcher bounds task execution globally across poll passes. Built once, // on first use, so ResizeTaskDispatcher can apply a live // containers.max_concurrency change without a restart; drainNATS submits - // each pass through it and waits for that pass. + // each pass through it and leaves its tasks running. dispatcherOnce sync.Once dispatcher *taskDispatcher // Storage is the pluggable storage backend for container mounts. @@ -345,6 +345,10 @@ func (d *Daemon) Run(ctx context.Context) error { if len(d.Identities) > 0 { return d.runIdentities(ctx) } + // A pass no longer waits for the tasks it submitted, so the run does, once + // the ctx is cancelled. + defer d.WaitForTasks() + d.watchCallWaits(ctx) interval := d.Cfg.Get().PollInterval.Std() ticker := time.NewTicker(interval) defer ticker.Stop() @@ -370,6 +374,7 @@ func (d *Daemon) Run(ctx context.Context) error { func (d *Daemon) runIdentities(ctx context.Context) error { ctx, cancel := context.WithCancel(ctx) defer cancel() + d.watchCallWaits(ctx) var wg sync.WaitGroup @@ -428,6 +433,7 @@ func (d *Daemon) runIdentities(ctx context.Context) error { }) wg.Wait() + d.WaitForTasks() return ctx.Err() } @@ -923,7 +929,10 @@ func (d *Daemon) botUserForTask(task *workflowtask.Task) string { // drainNATS processes tasks from NATS, falling back to the task store's ClaimNext for // requeued tasks (waiting_human approval, retry-parked) that didn't come -// through a NATS publish. +// through a NATS publish. It returns once the stream and the claim fallback +// are both empty: in-flight tasks keep running, so a task waiting on a callee +// does not hold up the pass that would claim it. Shutdown waits for them +// through WaitForTasks. func (d *Daemon) drainNATS(ctx context.Context) { dispatcher := d.taskDispatcher() for ctx.Err() == nil { @@ -951,13 +960,11 @@ func (d *Daemon) drainNATS(ctx context.Context) { } dispatcher.Submit(ctx, task, d.process) } - dispatcher.Wait() } // taskDispatcher returns the daemon's long-lived global dispatcher, building // it from the running config on first use. It outlives a single drain pass so -// ResizeTaskDispatcher can resize the running dispatcher; drainNATS still -// waits for each pass's work before returning. +// ResizeTaskDispatcher can resize the running dispatcher. func (d *Daemon) taskDispatcher() *taskDispatcher { d.dispatcherOnce.Do(func() { d.dispatcher = newTaskDispatcher(d.Cfg.Get().Containers.MaxConcurrency, d.allowConcurrentForTask) @@ -965,6 +972,13 @@ func (d *Daemon) taskDispatcher() *taskDispatcher { return d.dispatcher } +// WaitForTasks blocks until every submitted task's process has returned. A +// drain pass no longer waits for its own tasks, so shutdown is where in-flight +// work is waited for. +func (d *Daemon) WaitForTasks() { + d.taskDispatcher().Wait() +} + // ResizeTaskDispatcher applies a new containers.max_concurrency to the // running global task dispatcher without a restart. Running tasks keep their // slots; a lowered limit is honoured as they finish, and a raised limit @@ -984,8 +998,8 @@ func (d *Daemon) submitNATSTask(ctx context.Context, dispatcher *taskDispatcher, return } task := &workflow.Task{Owner: envelope.Owner, Repo: envelope.Repo, Identity: envelope.Identity} - dispatcher.Submit(ctx, task, func(ctx context.Context, _ *workflow.Task) { - d.processNATSTask(ctx, msg) + dispatcher.Submit(ctx, task, func(ctx context.Context, _ *workflow.Task, hold *taskHold) { + d.processNATSTask(ctx, msg, hold) }) } @@ -1000,6 +1014,47 @@ type taskDispatcher struct { slotsFree *sync.Cond repoTail map[string]chan struct{} pending int + // holds maps a task id to the capacity its run holds, so a run waiting on + // a callee can give that capacity back and take it again by task id. + holds map[int64]*taskHold +} + +// taskHold is one submitted task's claim on execution capacity: its slot under +// the global limit, and its place at the tail of its repo's chain, which the +// next task for that repo is blocked on. A run that waits on a callee gives +// both back so the callee can run, and takes them again when the wait ends. +type taskHold struct { + dispatcher *taskDispatcher + repo string + // chain is true when the repo runs one task at a time, so the run holds a + // place in that repo's chain. + chain bool + // baton is the run's place in its repo's chain, closed when it gives that + // place up; nil while it holds none. + baton chan struct{} + // slot is true while the run counts against the global limit. + slot bool + // waits counts the callees the run is waiting on: the first Suspend gives + // capacity back and the last Resume takes it again. + waits int + // finished is true once the run's process returned. + finished bool + // id is the task this hold belongs to, named by the run once it knows the + // task's id. + id int64 +} + +// name records which task's capacity this hold is, so a wait on a callee can +// give it back by task id. Zero names nothing: a task arriving on the NATS +// stream has no id until the store claims its row inside the run. +func (h *taskHold) name(id int64) { + if id == 0 { + return + } + h.dispatcher.mu.Lock() + h.id = id + h.dispatcher.holds[id] = h + h.dispatcher.mu.Unlock() } // SetMaxConcurrency accepts a new global limit without a restart. Running @@ -1020,42 +1075,176 @@ func newTaskDispatcher(maxConcurrency int, allowConcurrent func(task *workflow.T limit: maxConcurrency, allowConcurrent: allowConcurrent, repoTail: make(map[string]chan struct{}), + holds: make(map[int64]*taskHold), } d.slotsFree = sync.NewCond(&d.mu) return d } -// acquireSlot blocks until the global limit has room and returns the release -// function. limit <= 0 means unlimited. The limit is re-read on every wake, so +// joinRepoLocked appends baton to the tail of repo's chain and returns the +// baton ahead of it, which the joining task is blocked on. Callers hold d.mu. +func (d *taskDispatcher) joinRepoLocked(repo string, baton chan struct{}) chan struct{} { + previous := d.repoTail[repo] + d.repoTail[repo] = baton + return previous +} + +// takeSlotLocked blocks until the global limit has room, then counts the run +// in. limit <= 0 means unlimited. The limit is re-read on every wake, so // SetMaxConcurrency reaches waiting tasks without recreating the dispatcher. -func (d *taskDispatcher) acquireSlot() func() { - d.mu.Lock() - defer d.mu.Unlock() +// Callers hold d.mu. +func (d *taskDispatcher) takeSlotLocked() { for d.limit > 0 && d.active >= d.limit { d.slotsFree.Wait() } d.active++ - return func() { - d.mu.Lock() +} + +// giveBackLocked gives back everything the run holds: its slot under the +// global limit, and its place in its repo's chain, which releases the task +// queued behind it. Callers hold d.mu. +func (d *taskDispatcher) giveBackLocked(hold *taskHold) { + if hold.slot { + d.active-- + hold.slot = false + } + if hold.baton == nil { + return + } + close(hold.baton) + if d.repoTail[hold.repo] == hold.baton { + delete(d.repoTail, hold.repo) + } + hold.baton = nil +} + +// finishRun retires a returned run: it holds no capacity any more, and no +// Resume may take any for it. Whatever an in-flight resume takes later is +// given back by reacquire, which sees finished. +func (d *taskDispatcher) finishRun(hold *taskHold) { + d.mu.Lock() + hold.finished = true + if hold.id != 0 && d.holds[hold.id] == hold { + delete(d.holds, hold.id) + } + d.giveBackLocked(hold) + d.pending-- + d.mu.Unlock() + d.slotsFree.Broadcast() +} + +// Suspend gives a run's capacity back while it waits on a callee, so the +// callee can start. Calls are refcounted per task: a run waiting on callees +// from parallel branches releases once. An unknown task, or one whose run has +// already returned, is a no-op. +func (d *taskDispatcher) Suspend(id int64) { + d.mu.Lock() + hold := d.holds[id] + if hold == nil || hold.finished { + d.mu.Unlock() + return + } + hold.waits++ + if hold.waits == 1 { + d.giveBackLocked(hold) + } + d.mu.Unlock() + d.slotsFree.Broadcast() +} + +// Resume takes a run's capacity back when one of its waits ends. Only the last +// wait does: a run waiting on callees from parallel branches keeps nothing +// until all of them are done. An unknown task, one whose run has returned, and +// one that never suspended are all no-ops. +func (d *taskDispatcher) Resume(id int64) { + d.mu.Lock() + hold := d.holds[id] + if hold == nil || hold.finished || hold.waits == 0 { + d.mu.Unlock() + return + } + hold.waits-- + if hold.waits > 0 { + d.mu.Unlock() + return + } + d.mu.Unlock() + // The two waits below can block, and neither may hold up the bus + // subscriber calling this or the resumed run, which is already executing + // inside its container: the execution cap can be exceeded by at most the + // number of simultaneous resumes, and re-converges as tasks finish. + go d.reacquire(hold) +} + +// reacquire returns a resumed run's capacity: its place in its repo's chain +// and a slot under the global limit. The run keeps executing meanwhile -- a +// wait on a callee is not a pause. A hold records one slot and one place, so a +// re-acquire queued while another is still waiting gives back whichever of the +// two it finds already recorded instead of taking a second. +func (d *taskDispatcher) reacquire(hold *taskHold) { + d.mu.Lock() + if hold.finished || hold.waits > 0 { + // The run returned, or started waiting again, after the Resume that + // queued this: it needs no capacity. + d.mu.Unlock() + return + } + var previous chan struct{} + // A place another re-acquire already queued is the run's one place; joining + // behind it would queue a second, which the task behind it would wait on + // forever. + if hold.chain && hold.baton == nil { + hold.baton = make(chan struct{}) + previous = d.joinRepoLocked(hold.repo, hold.baton) + } + d.mu.Unlock() + + if previous != nil { + <-previous + } + + d.mu.Lock() + d.takeSlotLocked() + if hold.slot { + // Another re-acquire took the run's one slot while this waited: give + // back the slot this one just took. The place is the other's, so it is + // left alone. d.active-- d.mu.Unlock() d.slotsFree.Broadcast() + return } + hold.slot = true + if hold.finished || hold.waits > 0 { + // The run ended, or started waiting again, while this was queued for + // capacity: give back what it took, so no slot or place in the repo + // chain leaks. + d.giveBackLocked(hold) + d.mu.Unlock() + d.slotsFree.Broadcast() + return + } + d.mu.Unlock() } +// Submit queues a task's process behind the global limit and, unless the repo +// allows concurrency, behind the task already holding that repo. process is +// handed the run's capacity so it can name it once it knows the task's id and +// give it back while it waits on a callee. func (d *taskDispatcher) Submit( ctx context.Context, task *workflow.Task, - process func(context.Context, *workflow.Task), + process func(context.Context, *workflow.Task, *taskHold), ) { repo := task.Owner + "/" + task.Repo + hold := &taskHold{dispatcher: d, repo: repo} - var previous, done chan struct{} + var previous chan struct{} if !d.allowConcurrent(task) { - done = make(chan struct{}) + hold.chain = true + hold.baton = make(chan struct{}) d.mu.Lock() - previous = d.repoTail[repo] - d.repoTail[repo] = done + previous = d.joinRepoLocked(repo, hold.baton) d.mu.Unlock() } @@ -1063,28 +1252,15 @@ func (d *taskDispatcher) Submit( d.pending++ d.mu.Unlock() go func() { - defer func() { - d.mu.Lock() - d.pending-- - d.mu.Unlock() - d.slotsFree.Broadcast() - }() + defer d.finishRun(hold) if previous != nil { <-previous } - releaseSlot := d.acquireSlot() - defer releaseSlot() - if done != nil { - defer func() { - close(done) - d.mu.Lock() - if d.repoTail[repo] == done { - delete(d.repoTail, repo) - } - d.mu.Unlock() - }() - } - process(ctx, task) + d.mu.Lock() + d.takeSlotLocked() + hold.slot = true + d.mu.Unlock() + process(ctx, task, hold) }() } @@ -1298,7 +1474,7 @@ func (d *Daemon) acknowledge(ctx context.Context, fg forge.Forge, cfg config.Con // processNATSTask decodes a NATS message, writes it to SQLite, claims it, // and runs the workflow. The message is ack'd on terminal (park is a valid // outcome). Nak on transient errors so NATS redelivers. -func (d *Daemon) processNATSTask(ctx context.Context, msg eventbus.Message) { +func (d *Daemon) processNATSTask(ctx context.Context, msg eventbus.Message, hold *taskHold) { tm, err := workintake.DecodeTask(msg.Data()) if err != nil { d.Log.Error("nats decode failed", "err", err) @@ -1349,7 +1525,7 @@ func (d *Daemon) processNATSTask(ctx context.Context, msg eventbus.Message) { return } - d.process(ctx, task) + d.process(ctx, task, hold) if err := msg.Ack(); err != nil { d.Log.Warn("ack failed", "err", err) } @@ -1422,7 +1598,10 @@ func (d *Daemon) reconcilePRs(ctx context.Context) { } } -func (d *Daemon) process(ctx context.Context, task *workflow.Task) { +func (d *Daemon) process(ctx context.Context, task *workflow.Task, hold *taskHold) { + // A task off the NATS stream only has an id once the store has claimed its + // row, inside this call, so its capacity is named here. + hold.name(task.ID) // The workflow may name the identity the run acts as, which everything // below is chosen by, so it is settled before anything else. if !d.adoptWorkflowIdentity(ctx, task) { diff --git a/internal/daemon/dispatcher_test.go b/internal/daemon/dispatcher_test.go new file mode 100644 index 000000000..297247c82 --- /dev/null +++ b/internal/daemon/dispatcher_test.go @@ -0,0 +1,544 @@ +package daemon + +import ( + "context" + "encoding/json" + "log/slog" + "runtime" + "sync" + "testing" + "time" + + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/domain/storecontract" + "github.com/samcharles93/archie-core/internal/domain/workflow" + "github.com/samcharles93/archie-core/internal/eventbus" + "github.com/samcharles93/archie-core/internal/events" +) + +// runDeadline bounds a wait for something that must happen. Only a broken +// dispatcher ever reaches it, so it is generous rather than tight. +const runDeadline = 5 * time.Second + +// startWindow is the window a test gives the dispatcher to show that something +// does not happen. The window only ever fails a broken dispatcher: a run that +// was going to take capacity does it within microseconds of the event that +// wakes it. +const startWindow = 100 * time.Millisecond + +// awaitStart waits for a task's process to report that it started. +func awaitStart(t *testing.T, started <-chan int64, want int64) { + t.Helper() + select { + case got := <-started: + if got != want { + t.Fatalf("task %d started, want %d", got, want) + } + case <-time.After(runDeadline): + t.Fatalf("task %d did not start", want) + } +} + +// awaitNoStart fails if any task starts within startWindow. +func awaitNoStart(t *testing.T, started <-chan int64, why string) { + t.Helper() + select { + case got := <-started: + t.Fatalf("task %d started %s", got, why) + case <-time.After(startWindow): + } +} + +// awaitState waits until want holds. Taking capacity back is asynchronous by +// design -- it must not block the bus subscriber that resumed the run, and the +// resumed run keeps executing meanwhile -- so there is no channel to wait on. +func awaitState(t *testing.T, why string, want func() bool) { + t.Helper() + deadline := time.Now().Add(runDeadline) + for { + if want() { + return + } + if time.Now().After(deadline) { + t.Fatal(why) + } + runtime.Gosched() + } +} + +// awaitNoState fails if want becomes true within startWindow. An assertion that +// something stays false needs a window: state that never changes signals on +// nothing. +func awaitNoState(t *testing.T, why string, want func() bool) { + t.Helper() + deadline := time.Now().Add(startWindow) + for time.Now().Before(deadline) { + if want() { + t.Fatal(why) + } + runtime.Gosched() + } +} + +// capacity reads one task's execution capacity under the dispatcher's lock: +// slot is true while it counts against the global limit, place while it holds +// its repo's chain, and known is false once the run has retired. +func capacity(d *taskDispatcher, id int64) (slot, place, known bool) { + d.mu.Lock() + defer d.mu.Unlock() + hold := d.holds[id] + if hold == nil { + return false, false, false + } + return hold.slot, hold.baton != nil, true +} + +// holdsCapacity reports whether a task's run holds both its slot and its place. +func holdsCapacity(d *taskDispatcher, id int64) bool { + slot, place, _ := capacity(d, id) + return slot && place +} + +// activeRuns counts the runs held against the global limit. +func activeRuns(d *taskDispatcher) int { + d.mu.Lock() + defer d.mu.Unlock() + return d.active +} + +// taskHoldOf reads the capacity record for a task. +func taskHoldOf(d *taskDispatcher, id int64) *taskHold { + d.mu.Lock() + defer d.mu.Unlock() + return d.holds[id] +} + +// placeClaim reads the place the run holds in its repo's chain, as the +// dispatcher records it. +func placeClaim(d *taskDispatcher, id int64) chan struct{} { + d.mu.Lock() + defer d.mu.Unlock() + if hold := d.holds[id]; hold != nil { + return hold.baton + } + return nil +} + +// slotHolders counts the runs the dispatcher knows that record a slot. Every +// run a test submits is named before its process starts, and no test submits +// while it checks this, so the two counts describe the same set of runs. +func slotHolders(d *taskDispatcher) int { + d.mu.Lock() + defer d.mu.Unlock() + held := 0 + for _, hold := range d.holds { + if hold.slot { + held++ + } + } + return held +} + +// submitRun queues a task whose process reports its start on started and then +// blocks until released. Naming the run's capacity is what the daemon's own +// process does, where the task's id first exists. +func submitRun(d *taskDispatcher, id int64, repo string, started chan<- int64, released <-chan struct{}) { + d.Submit(context.Background(), &workflow.Task{ID: id, Owner: "acme", Repo: repo}, func(_ context.Context, task *workflow.Task, hold *taskHold) { + hold.name(task.ID) + started <- task.ID + <-released + }) +} + +// A run waiting on a callee holds no capacity: the task next in its repo, and +// behind it in the chain, runs while the wait lasts, and the run takes its slot +// and its place back once the wait ends. +func TestSuspendReleasesCapacityForTheTaskBehindIt(t *testing.T) { + d := newTaskDispatcher(1, nil) + started := make(chan int64, 4) + a, b, c := make(chan struct{}), make(chan struct{}), make(chan struct{}) + + submitRun(d, 1, "app", started, a) + awaitStart(t, started, 1) + + submitRun(d, 2, "app", started, b) + awaitNoStart(t, started, "while the waiting run held the only slot and the repo's place") + + d.Suspend(1) + awaitStart(t, started, 2) + close(b) + + d.Resume(1) + awaitState(t, "task 1 did not take its slot and its place back", func() bool { return holdsCapacity(d, 1) }) + + submitRun(d, 3, "app", started, c) + awaitNoStart(t, started, "while the resumed run held the only slot and the repo's place") + + close(a) + awaitStart(t, started, 3) + close(c) + d.Wait() +} + +// A resumed run keeps its repo's place, not just its slot: with slots to spare, +// a task queued behind it still waits. +func TestResumedRunKeepsItsPlaceInTheReposChain(t *testing.T) { + d := newTaskDispatcher(3, nil) + started := make(chan int64, 4) + a, b, c := make(chan struct{}), make(chan struct{}), make(chan struct{}) + + submitRun(d, 1, "app", started, a) + awaitStart(t, started, 1) + + submitRun(d, 2, "app", started, b) + awaitNoStart(t, started, "while the repo's place was another run's") + + d.Suspend(1) + awaitStart(t, started, 2) + close(b) + + d.Resume(1) + awaitState(t, "task 1 did not take its slot and its place back", func() bool { return holdsCapacity(d, 1) }) + submitRun(d, 3, "app", started, c) + awaitNoStart(t, started, "while the resumed run held the repo's place, with slots free") + + close(a) + awaitStart(t, started, 3) + close(c) + d.Wait() +} + +// A run waiting on callees from parallel branches gives its capacity back once, +// and takes none of it again until the last wait ends. +func TestResumeTakesCapacityBackOnlyAfterTheLastWait(t *testing.T) { + d := newTaskDispatcher(1, nil) + started := make(chan int64, 4) + a, b := make(chan struct{}), make(chan struct{}) + + submitRun(d, 1, "app", started, a) + awaitStart(t, started, 1) + d.Suspend(1) + d.Suspend(1) + + // The callee queued behind it runs, and returns. + submitRun(d, 2, "app", started, b) + awaitStart(t, started, 2) + close(b) + awaitState(t, "the callee's slot was not given back", func() bool { return activeRuns(d) == 0 }) + + // One wait outstanding: the run keeps no capacity while its other callee + // runs. + d.Resume(1) + awaitNoState(t, "task 1 took capacity back with a callee still running", func() bool { return holdsCapacity(d, 1) }) + + // With the last wait done it takes capacity back. + d.Resume(1) + awaitState(t, "task 1 did not take its capacity back", func() bool { return holdsCapacity(d, 1) }) + + close(a) + d.Wait() +} + +// A hold records one slot and one place in its repo's chain, in whatever order +// the re-acquires a run queues take them: a second taker gives back the slot it +// took, and a re-acquire that finds a place already queued does not queue a +// second. Otherwise each occurrence permanently over-counts the global limit +// and the dispatcher throttles harder than containers.max_concurrency says. +func TestResumeTwiceDoesNotCountASecondSlot(t *testing.T) { + // Two slots: the task holding the repo's place must be able to take one + // while the run's second re-acquire takes another. + d := newTaskDispatcher(2, nil) + started := make(chan int64, 4) + a, x, z := make(chan struct{}), make(chan struct{}), make(chan struct{}) + + submitRun(d, 1, "app", started, a) + awaitStart(t, started, 1) + d.Suspend(1) + + // X takes the repo's place while A waits on its callee, so A's first + // re-acquire queues its next place behind X. + submitRun(d, 2, "app", started, x) + awaitStart(t, started, 2) + d.Resume(1) + awaitState(t, "task 1 did not queue its place back", func() bool { + _, place, _ := capacity(d, 1) + return place + }) + + // That callee ends and the run starts its next call at once: the place the + // first re-acquire claimed is given back with it, and the second re-acquire + // takes a slot immediately. + d.Suspend(1) + d.Resume(1) + awaitState(t, "task 1 did not take its slot back", func() bool { return holdsCapacity(d, 1) }) + + // X leaves, so the first re-acquire can take a slot as well. + close(x) + awaitState(t, "task 2 did not retire", func() bool { + _, _, known := capacity(d, 2) + return !known + }) + + // Nothing may be counted against the limit that no run records. + awaitNoState(t, "the dispatcher counts a slot no run holds", func() bool { + return activeRuns(d) != slotHolders(d) + }) + + close(a) + awaitState(t, "task 1 did not retire", func() bool { + _, _, known := capacity(d, 1) + return !known + }) + awaitState(t, "a slot is still counted with no run in flight", func() bool { return activeRuns(d) == 0 }) + + // A later task for another repo still gets a slot at the configured limit. + submitRun(d, 3, "other", started, z) + awaitStart(t, started, 3) + close(z) + d.Wait() +} + +// A re-acquire that finds the run's place already queued leaves it at one: a +// second place in the same repo's chain is a claim nothing closes, and the +// re-acquire waiting on it is parked for good. +func TestSecondReacquireDoesNotQueueASecondPlace(t *testing.T) { + d := newTaskDispatcher(2, nil) + started := make(chan int64, 4) + a, x, z := make(chan struct{}), make(chan struct{}), make(chan struct{}) + + submitRun(d, 1, "app", started, a) + awaitStart(t, started, 1) + d.Suspend(1) + + // X holds the repo's place, so the run's re-acquire queues behind it and + // stays there. + submitRun(d, 2, "app", started, x) + awaitStart(t, started, 2) + d.Resume(1) + awaitState(t, "task 1 did not queue its place back", func() bool { + _, place, _ := capacity(d, 1) + return place + }) + queued := placeClaim(d, 1) + + // A second re-acquire for the same run, with the first still waiting. A + // Resume cannot queue this one: queueing two takes a Suspend between them, + // and that Suspend would clear the place queued above. + go d.reacquire(taskHoldOf(d, 1)) + + awaitNoState(t, "a second place was queued for the run", func() bool { return placeClaim(d, 1) != queued }) + awaitState(t, "task 1 did not take its slot back", func() bool { return holdsCapacity(d, 1) }) + + // X leaves: the first re-acquire takes a slot as well, and gives it back, + // because the hold records one. + close(x) + awaitState(t, "task 2 did not retire", func() bool { + _, _, known := capacity(d, 2) + return !known + }) + awaitNoState(t, "the dispatcher counts a slot no run holds", func() bool { + return activeRuns(d) != slotHolders(d) + }) + + close(a) + awaitState(t, "task 1 did not retire", func() bool { + _, _, known := capacity(d, 1) + return !known + }) + awaitState(t, "a slot is still counted with no run in flight", func() bool { return activeRuns(d) == 0 }) + + submitRun(d, 3, "other", started, z) + awaitStart(t, started, 3) + close(z) + d.Wait() +} + +// A run that returns while the resume it queued is still waiting for capacity +// leaves nothing behind: a later task still gets a slot, a Resume arriving +// afterwards is a no-op, and shutdown's wait returns. +func TestResumeAfterTheRunReturnedLeavesNoCapacity(t *testing.T) { + d := newTaskDispatcher(1, nil) + started := make(chan int64, 4) + a, b, c := make(chan struct{}), make(chan struct{}), make(chan struct{}) + + submitRun(d, 1, "app", started, a) + awaitStart(t, started, 1) + d.Suspend(1) + + submitRun(d, 2, "app", started, b) + awaitStart(t, started, 2) + + // The resume is queued for a slot and a place in the chain, and overtaken by + // the run returning before either comes free. + d.Resume(1) + awaitState(t, "task 1 did not take its place in the chain back", func() bool { + _, place, _ := capacity(d, 1) + return place + }) + close(a) + awaitState(t, "task 1 did not retire", func() bool { + _, _, known := capacity(d, 1) + return !known + }) + close(b) + awaitState(t, "task 2 did not retire", func() bool { + _, _, known := capacity(d, 2) + return !known + }) + + // Neither the returned run nor the resume it queued took the slot: it is + // free for the task queued behind it. + awaitNoState(t, "a returned run's slot was taken", func() bool { return activeRuns(d) > 0 }) + submitRun(d, 3, "app", started, c) + awaitStart(t, started, 3) + close(c) + + // A Resume arriving after the run returned is a no-op. + d.Resume(1) + d.Wait() +} + +// callEvent builds one call step's event as the daemon receives it: the event +// the container's workflow engine published, JSON-encoded and decoded again by +// the agent-event bridge, so the wait flag arrives as a decoded bool. +func callEvent(t *testing.T, kind string, taskID int64, wait bool) events.Event { + t.Helper() + raw, err := json.Marshal(events.Event{Kind: kind, TaskID: taskID, Data: map[string]any{"wait": wait}}) + if err != nil { + t.Fatal(err) + } + var e events.Event + if err := json.Unmarshal(raw, &e); err != nil { + t.Fatal(err) + } + return e +} + +// Only a call the caller waits on releases its capacity, and the call +// finishing takes it back. +func TestCallWaitEventsReleaseCapacity(t *testing.T) { + d := newTaskDispatcher(1, nil) + started := make(chan int64, 4) + a, b := make(chan struct{}), make(chan struct{}) + + submitRun(d, 1, "app", started, a) + awaitStart(t, started, 1) + submitRun(d, 2, "app", started, b) + + // A call that does not wait is not waited on: nothing is released. + applyCallWait(d, callEvent(t, events.KindWorkflowCallStarted, 1, false)) + awaitNoStart(t, started, "while the call that started does not wait") + + applyCallWait(d, callEvent(t, events.KindWorkflowCallStarted, 1, true)) + awaitStart(t, started, 2) + close(b) + + applyCallWait(d, callEvent(t, events.KindWorkflowCallFinished, 1, false)) + awaitState(t, "task 1 did not take its capacity back", func() bool { return holdsCapacity(d, 1) }) + + close(a) + d.Wait() +} + +// A daemon with no bus still starts and stops: the watcher is optional. +func TestCallWaitsWithoutABus(t *testing.T) { + d := &Daemon{Cfg: config.NewHolder(config.Config{}), Log: slog.New(slog.DiscardHandler)} + d.watchCallWaits(t.Context()) + d.WaitForTasks() +} + +// stubTasks is a task bus with an empty stream, so a drain pass falls through +// to the store's ClaimNext. +type stubTasks struct{} + +func (stubTasks) PublishUnique(context.Context, string, string, []byte) error { return nil } +func (stubTasks) Fetch(context.Context) (eventbus.Message, error) { + return nil, eventbus.ErrNoMessage +} +func (stubTasks) Request(context.Context, string, []byte) ([]byte, error) { return nil, nil } + +// stubStore hands out one claimed task, then nothing, and blocks in ParkTask +// for as long as the test wants a task held in flight. Every path a task takes +// through the daemon without a container parks, so ParkTask is where a test +// task waits. +type stubStore struct { + storecontract.TaskStore + claim *workflow.Task + park func() +} + +func (s *stubStore) ClaimNext(context.Context) (*workflow.Task, error) { + task := s.claim + s.claim = nil + return task, nil +} + +func (s *stubStore) Update(context.Context, *workflow.Task) error { return nil } + +func (s *stubStore) ParkTask(context.Context, int64, string, string, string) error { + s.park() + return nil +} + +// A drain pass returns as soon as the stream and the store's claim fallback are +// both empty; its tasks keep running, and shutdown waits for them. A pass that +// waits for them blocks every later pass, so a run waiting on a callee whose +// callee is queued by that same pass would never be released. +func TestDrainPassDoesNotWaitForItsTasks(t *testing.T) { + inFlight := make(chan struct{}, 1) + release := make(chan struct{}) + var unblockOnce sync.Once + unblock := func() { unblockOnce.Do(func() { close(release) }) } + defer unblock() + store := &stubStore{ + claim: &workflow.Task{ID: 7, Owner: "acme", Repo: "app"}, + park: func() { + select { + case inFlight <- struct{}{}: + default: + } + <-release + }, + } + d := &Daemon{ + Cfg: config.NewHolder(config.Config{}), + Log: slog.New(slog.DiscardHandler), + Store: store, + Tasks: stubTasks{}, + } + + drained := make(chan struct{}) + go func() { + d.drainNATS(context.Background()) + close(drained) + }() + + select { + case <-inFlight: + case <-time.After(runDeadline): + t.Fatal("no task reached execution") + } + select { + case <-drained: + case <-time.After(runDeadline): + t.Fatal("the drain pass waited for a task still in flight") + } + + // Shutdown is where that wait now lives. + waited := make(chan struct{}) + go func() { + d.WaitForTasks() + close(waited) + }() + select { + case <-waited: + t.Fatal("WaitForTasks returned with a task still in flight") + default: + } + unblock() + select { + case <-waited: + case <-time.After(runDeadline): + t.Fatal("WaitForTasks did not return after the task finished") + } +} diff --git a/internal/daemon/update_test.go b/internal/daemon/update_test.go index d5cf7fc70..01b3e863d 100644 --- a/internal/daemon/update_test.go +++ b/internal/daemon/update_test.go @@ -14,7 +14,7 @@ func TestDispatcherWaitIncludesQueuedWork(t *testing.T) { release := make(chan struct{}) process := func() { started <- struct{}{}; <-release } for range 2 { - dispatcher.Submit(t.Context(), &workflow.Task{Owner: "o", Repo: "r"}, func(_ context.Context, _ *workflow.Task) { process() }) + dispatcher.Submit(t.Context(), &workflow.Task{Owner: "o", Repo: "r"}, func(_ context.Context, _ *workflow.Task, _ *taskHold) { process() }) } <-started dispatcher.mu.Lock()