Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7933: fix(wakeups): drain inputs and due checks in one pass (#9202)
Multica Eve9310690e0a6d
diff --git a/server/internal/service/issue_wakeup.go b/server/internal/service/issue_wakeup.goindex 840c905eb6..3dda35fea5 100644--- a/server/internal/service/issue_wakeup.go+++ b/server/internal/service/issue_wakeup.go@@ -5,6 +5,7 @@ import ("encoding/json""errors""fmt"+ "log/slog""slices""strings""time"@@ -659,46 +660,303 @@ func (s *IssueWakeupService) TickWorkspaces(ctx context.Context, workspaceIDs ..return s.tick(ctx, workspaceIDs)}+// Scheduler pass limits. A pass used to visit a single batch of 100 rules, so+// with more ready rules than that a status change waited several passes+// (minutes) behind condition checks that had nothing new (MUL-7933, #9139).+// A pass now keeps taking batches until both lanes are drained or a limit is+// hit. The scheduler runs its jobs one after another, so the pass stops well+// inside the job's 45s run timeout and leaves the rest of the 30s scheduler+// tick to the other jobs; one dispatch is itself capped at 2s.+const (+ wakeupTickBatch = 100+ // At most this many rules of a batch come from the input lane; the due+ // lane fetches the rest.+ wakeupTickInputShare = 50+ wakeupTickBudget = 15 * time.Second+ // While the due lane still has work, the input lane may spend at most+ // this much of the pass, so slow inputs cannot starve schedules,+ // deadlines and condition checks. Either lane uses the whole budget once+ // the other is drained.+ wakeupTickInputBudget = wakeupTickBudget / 2+ wakeupTickMaxRules = 1500+ // A pending input the scheduler could act on that is older than this is+ // logged as a warning. Inputs a run holds are reported separately.+ wakeupPendingWarnAge = 2 * time.Minute+)++// tickLimits are a pass's limits; zero fields take the defaults above. Tests+// shrink them, and beforeDispatch lets a test make a dispatch slow.+type tickLimits struct {+ budget, inputBudget time.Duration+ beforeDispatch func(db.IssueWakeup)+}+// tick dispatches ready wakeups; nil workspaceIDs means every workspace.+//+// Two lanes feed the pass: rules with unprocessed inputs (an event, a+// condition hint, "wake now") and rules whose schedule, deadline or condition+// check is due. Dispatches alternate between the lanes, and the input lane's+// time is capped while due work remains. Each rule is visited at most once.func (s *IssueWakeupService) tick(ctx context.Context, workspaceIDs []pgtype.UUID) error {+ return s.tickWith(ctx, workspaceIDs, tickLimits{})+}++func (s *IssueWakeupService) tickWith(ctx context.Context, workspaceIDs []pgtype.UUID, lim tickLimits) error {+ if lim.budget <= 0 {+ lim.budget = wakeupTickBudget+ }+ if lim.inputBudget <= 0 {+ lim.inputBudget = wakeupTickInputBudget+ }+ start := time.Now()// Receipts are operational evidence, not the run history. Match the existing// event telemetry's seven-day retention; never expire unprocessed inputs.cleanupCtx, cleanupCancel := context.WithTimeout(ctx, 2*time.Second)_, cleanupErr := s.Tasks.Queries.DeleteExpiredWakeupReceipts(cleanupCtx, pgtype.Timestamptz{Time: time.Now().Add(-7 * 24 * time.Hour), Valid: true})cleanupCancel()- rows, err := s.Tasks.Queries.ListReadyWakeups(ctx, workspaceIDs)- if err != nil {- return err- }var errs []errorif cleanupErr != nil {errs = append(errs, fmt.Errorf("expire wakeup receipts: %w", cleanupErr))}- for _, w := range rows {+ // claimed holds every rule visited or queued in this pass. Never nil:+ // "id = ANY(NULL)" is NULL and would exclude every rule.+ claimed := []pgtype.UUID{}+ var inputQ, dueQ []db.IssueWakeup+ inputDrained, dueDrained := false, false+ var inputSpent time.Duration+ inputs, due := 0, 0+ stop := "drained"+ inputTurn := true+ for {if ctx.Err() != nil {return errors.Join(append(errs, ctx.Err())...)}- // Outcome writes must not turn a busy rule row into another batch-wide- // wait. Use the batch context, not dispatch's expired per-rule context.- dispatch := s.dispatch- if w.SystemRule.Valid {- dispatch = s.dispatchSystem+ if time.Since(start) >= lim.budget {+ stop = "time_budget"+ break}- if err = dispatch(ctx, w); err != nil {- errs = append(errs, fmt.Errorf("wakeup %s: %w", util.UUIDToString(w.ID), err))- outcomeCtx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)- _ = s.Tasks.Queries.NoteWakeupFailure(outcomeCtx, db.NoteWakeupFailureParams{ID: w.ID, LastError: pgtype.Text{String: truncateForSummary(err.Error(), 500), Valid: true}})- cancel()+ if inputs+due >= wakeupTickMaxRules {+ stop = "rule_cap"+ break}- outcomeCtx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)- if touchErr := s.Tasks.Queries.TouchWakeupDispatch(outcomeCtx, w.ID); touchErr != nil {- errs = append(errs, touchErr)+ room := wakeupTickMaxRules - len(claimed)+ if len(inputQ) == 0 && !inputDrained && room > 0 {+ limit := min(wakeupTickInputShare, room)+ rows, err := s.Tasks.Queries.ListInputWakeups(ctx, db.ListInputWakeupsParams{WorkspaceIds: workspaceIDs, SkipIds: claimed, RowLimit: int32(limit)})+ if err != nil {+ return errors.Join(append(errs, err)...)+ }+ inputDrained = len(rows) < limit+ inputQ = rows+ for _, w := range rows {+ claimed = append(claimed, w.ID)+ }+ room -= len(rows)}- cancel()+ if len(dueQ) == 0 && !dueDrained && room > 0 {+ limit := min(wakeupTickBatch-len(inputQ), room)+ rows, err := s.Tasks.Queries.ListDueWakeups(ctx, db.ListDueWakeupsParams{WorkspaceIds: workspaceIDs, SkipIds: claimed, RowLimit: int32(limit)})+ if err != nil {+ return errors.Join(append(errs, err)...)+ }+ dueDrained = len(rows) < limit+ dueQ = rows+ for _, w := range rows {+ claimed = append(claimed, w.ID)+ }+ }+ // Due work is left while the lane has queued rules or can still fetch.+ dueLeft := len(dueQ) > 0 || (!dueDrained && wakeupTickMaxRules > len(claimed))+ inputAllowed := len(inputQ) > 0 && (inputSpent < lim.inputBudget || !dueLeft)+ var w db.IssueWakeup+ fromInput := false+ switch {+ case inputAllowed && (inputTurn || len(dueQ) == 0):+ w, inputQ, fromInput = inputQ[0], inputQ[1:], true+ case len(dueQ) > 0:+ w, dueQ = dueQ[0], dueQ[1:]+ default:+ // Both lanes are empty: drained, or out of room under the cap.+ if !inputDrained || !dueDrained {+ stop = "rule_cap"+ }+ return s.finishTick(ctx, workspaceIDs, start, inputs, due, stop, errs)+ }+ inputTurn = !fromInput+ began := time.Now()+ if lim.beforeDispatch != nil {+ lim.beforeDispatch(w)+ }+ errs = append(errs, s.dispatchFromTick(ctx, w)...)+ if fromInput {+ inputs+++ inputSpent += time.Since(began)+ } else {+ due+++ }+ }+ return s.finishTick(ctx, workspaceIDs, start, inputs, due, stop, errs)+}++// finishTick logs a global pass and returns its errors.+func (s *IssueWakeupService) finishTick(ctx context.Context, workspaceIDs []pgtype.UUID, start time.Time, inputs, due int, stop string, errs []error) error {+ if workspaceIDs == nil {+ s.logTick(ctx, start, inputs, due, stop, len(errs))}return errors.Join(errs...)}+// dispatchFromTick dispatches one rule for a scheduler pass and records the+// outcome on the rule.+func (s *IssueWakeupService) dispatchFromTick(ctx context.Context, w db.IssueWakeup) []error {+ var errs []error+ // Outcome writes must not turn a busy rule row into another batch-wide+ // wait. Use the batch context, not dispatch's expired per-rule context.+ dispatch := s.dispatch+ if w.SystemRule.Valid {+ dispatch = s.dispatchSystem+ }+ if err := dispatch(ctx, w); err != nil {+ errs = append(errs, fmt.Errorf("wakeup %s: %w", util.UUIDToString(w.ID), err))+ outcomeCtx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)+ _ = s.Tasks.Queries.NoteWakeupFailure(outcomeCtx, db.NoteWakeupFailureParams{ID: w.ID, LastError: pgtype.Text{String: truncateForSummary(err.Error(), 500), Valid: true}})+ cancel()+ }+ // Move the rule to the back of its lane so one noisy issue cannot+ // monopolize the batches. Only scan order depends on this write: dispatch+ // already committed the rule's outcome, and an unfinished rule stays a+ // candidate either way. A pass now visits many more rules than one batch,+ // so under load this bounded write can time out without anything being+ // wrong; that is logged, not reported as a failed pass.+ outcomeCtx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)+ if touchErr := s.Tasks.Queries.TouchWakeupDispatch(outcomeCtx, w.ID); touchErr != nil && ctx.Err() == nil {+ slog.DebugContext(ctx, "issue wakeup: scan-order touch skipped", "wakeup_id", util.UUIDToString(w.ID), "error", touchErr)+ }+ cancel()+ return errs+}++// logTick reports one global pass: how many rules each lane visited, how long+// the pass took and why it stopped, plus the age of the oldest input the+// scheduler could act on and how many inputs a run is holding. It logs at+// warn level when a limit cut the pass short, a dispatch failed, an+// actionable input has waited longer than wakeupPendingWarnAge, or the+// pending scan could not finish (pending_scan=incomplete: the age may be+// missing or too young, so silence must not be read as "no backlog").+// Held inputs never warn on their own.+func (s *IssueWakeupService) logTick(ctx context.Context, start time.Time, inputs, due int, stop string, failures int) {+ attrs := []any{"input_rules", inputs, "due_rules", due, "duration_ms", time.Since(start).Milliseconds(), "stopped", stop, "failures", failures}+ level := slog.LevelInfo+ if stop != "drained" || failures > 0 {+ level = slog.LevelWarn+ }+ pendingCtx, cancel := context.WithTimeout(ctx, wakeupPendingScanBudget)+ pending, err := s.pendingInputs(pendingCtx, nil, wakeupPendingScanPage)+ cancel()+ attrs = append(attrs, "held_inputs", pending.Held)+ if err != nil {+ attrs = append(attrs, "pending_scan", "incomplete", "pending_scan_error", err.Error())+ level = slog.LevelWarn+ } else {+ attrs = append(attrs, "pending_scan", "complete")+ }+ if age, ok := pending.age(time.Now()); ok {+ attrs = append(attrs, "oldest_ready_input_age_s", int64(age.Seconds()))+ if age > wakeupPendingWarnAge {+ level = slog.LevelWarn+ }+ }+ slog.Log(ctx, level, "issue wakeup dispatch pass", attrs...)+}++// The pending scan reads every group of unprocessed inputs, a page at a time,+// within this budget. A scan that runs out of it reports itself incomplete.+const (+ wakeupPendingScanBudget = 3 * time.Second+ wakeupPendingScanPage = 1000+)++// pendingInputSummary splits unprocessed inputs into those a run is holding+// on purpose and the backlog the scheduler could act on.+type pendingInputSummary struct {+ OldestReady pgtype.Timestamptz+ Held int+}++// age is how long the oldest actionable input has waited, if there is one.+func (p pendingInputSummary) age(now time.Time) (time.Duration, bool) {+ if !p.OldestReady.Valid {+ return 0, false+ }+ return now.Sub(p.OldestReady.Time), true+}++// pendingInputs classifies every unprocessed input the way dispatch treats+// it (see ListPendingWakeupInputGroups), paging until the groups run out. For+// a platform rule an input is held only while a run of the issue's current+// target agent, run as the person the platform rule's run would run as, waits+// to start: the same check dispatchSystem makes before keeping its inputs.+//+// On an error, including ctx running out, it returns what it read so far+// with the error: the summary is then a lower bound, not the answer.+func (s *IssueWakeupService) pendingInputs(ctx context.Context, workspaceIDs []pgtype.UUID, pageSize int) (pendingInputSummary, error) {+ var out pendingInputSummary+ q := s.Tasks.Queries+ systemWaiting := map[pgtype.UUID]bool{}+ params := db.ListPendingWakeupInputGroupsParams{WorkspaceIds: workspaceIDs, PageSize: int32(pageSize)}+ for {+ groups, err := q.ListPendingWakeupInputGroups(ctx, params)+ if err != nil {+ return out, fmt.Errorf("list pending wakeup inputs: %w", err)+ }+ for _, g := range groups {+ held := g.Reserved || g.OwnClaimed || g.UserWaiting+ if !held && g.SystemRule {+ waiting, known := systemWaiting[g.IssueID]+ if !known {+ if waiting, err = s.systemRuleRunWaiting(ctx, q, g.IssueID); err != nil {+ return out, fmt.Errorf("resolve platform rule target: %w", err)+ }+ systemWaiting[g.IssueID] = waiting+ }+ held = waiting+ }+ switch {+ case held:+ out.Held += int(g.Inputs)+ case !out.OldestReady.Valid || g.Oldest.Time.Before(out.OldestReady.Time):+ out.OldestReady = g.Oldest+ }+ }+ if len(groups) < pageSize {+ return out, nil+ }+ last := groups[len(groups)-1]+ params.AfterOldest, params.AfterWakeupID, params.AfterReserved = last.Oldest, last.WakeupID, last.Reserved+ }+}++// systemRuleRunWaiting reports whether a platform rule on the issue would+// keep its inputs for a run waiting to start (dispatchSystem's hasWaitingRun).+func (s *IssueWakeupService) systemRuleRunWaiting(ctx context.Context, q *db.Queries, issueID pgtype.UUID) (bool, error) {+ issue, err := q.GetIssue(ctx, issueID)+ if errors.Is(err, pgx.ErrNoRows) {+ return false, nil+ }+ if err != nil {+ return false, err+ }+ target, err := resolveWakeTarget(ctx, q, issue)+ if err != nil || !target.Agent.ID.Valid {+ return false, err+ }+ runAs, err := s.childDoneRunAs(ctx, issue, target.Agent)+ if err != nil {+ return false, err+ }+ return hasWaitingRun(ctx, q, issue.ID, target.Agent.ID, runAs.UserID)+}+func (s *IssueWakeupService) dispatch(ctx context.Context, prev db.IssueWakeup) error {// A rule gets at most two seconds including credentials and SQL. Lock waits// below are shorter: even 100 contended rules consume only ~5s of the 45sdiff --git a/server/internal/service/issue_wakeup_expiry_test.go b/server/internal/service/issue_wakeup_expiry_test.goindex 7de4dfa77e..adc88016a5 100644--- a/server/internal/service/issue_wakeup_expiry_test.go+++ b/server/internal/service/issue_wakeup_expiry_test.go@@ -58,7 +58,7 @@ func TestIssueWakeupTimeoutWakesOnceAndEnds(t *testing.T) {t.Fatal("dispatched before the deadline")}f.Exec(t, "UPDATE issue_wakeup SET expires_at=now()-interval '1 second' WHERE id=$1", w.ID)- ready, err := f.q.ListReadyWakeups(ctx, []pgtype.UUID{parseTestUUID(t, f.WorkspaceID)})+ ready, err := f.q.ListDueWakeups(ctx, db.ListDueWakeupsParams{WorkspaceIds: []pgtype.UUID{parseTestUUID(t, f.WorkspaceID)}, SkipIds: []pgtype.UUID{}, RowLimit: 100})if err != nil {t.Fatal(err)}diff --git a/server/internal/service/issue_wakeup_tick_test.go b/server/internal/service/issue_wakeup_tick_test.gonew file mode 100644index 0000000000..ea897c7c11--- /dev/null+++ b/server/internal/service/issue_wakeup_tick_test.go@@ -0,0 +1,353 @@+package service++import (+ "context"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/dbid"+)++// drainTick runs one pass over the workspace with room to finish: these tests+// pin which rules a pass reaches, not how fast a loaded CI machine runs them.+func drainTick(t *testing.T, s *IssueWakeupService, ws pgtype.UUID) {+ t.Helper()+ if err := s.tickWith(context.Background(), []pgtype.UUID{ws}, tickLimits{budget: 5 * time.Minute, inputBudget: 5 * time.Minute}); err != nil {+ t.Fatal(err)+ }+}++// idleConditionRules adds n enabled condition rules whose condition never+// holds, all due and ordered ahead of everything else, the way a busy+// production scan looks to a freshly hinted rule. They are spread over issues+// to stay under the per-issue limit and carry the instruction "never".+func idleConditionRules(t *testing.T, f principalFixture, s *IssueWakeupService, agent string, n int) {+ t.Helper()+ const perIssue = 30+ for made := 0; made < n; made += perIssue {+ idleIssue := parseTestUUID(t, f.Issue(t, "Idle conditions"))+ f.Cleanup(t, "DELETE FROM issue_wakeup WHERE issue_id=$1", idleIssue)+ f.Cleanup(t, "DELETE FROM issue_wakeup_receipt WHERE wakeup_id IN (SELECT id FROM issue_wakeup WHERE issue_id=$1)", idleIssue)+ f.Cleanup(t, "DELETE FROM activity_log WHERE issue_id=$1", idleIssue)+ seed := wakeCreate(t, f, s, idleIssue, WakeupInput{AgentID: agent, Kind: "event", Instruction: "never",+ Condition: condition(t, map[string]any{"type": "issue_field", "field": "status", "value": "blocked"})})+ cloneWakeup(t, f, seed.ID, min(perIssue, n-made)-1, false)+ }+ f.Exec(t, "UPDATE issue_wakeup SET next_fire_at=now()-interval '1 second', updated_at=now()-interval '1 hour' WHERE workspace_id=$1 AND instruction='never'", f.WorkspaceID)+}++// cloneWakeup copies a rule n times, optionally as turned-off rules.+func cloneWakeup(t *testing.T, f principalFixture, id pgtype.UUID, n int, off bool) {+ t.Helper()+ if n <= 0 {+ return+ }+ f.Exec(t, `INSERT INTO issue_wakeup+ SELECT (jsonb_populate_record(w, jsonb_build_object('id', gen_random_uuid())+ || CASE WHEN $3 THEN jsonb_build_object('enabled', false, 'disabled_at', now()) ELSE '{}'::jsonb END)).*+ FROM issue_wakeup w, generate_series(1, $2::int) WHERE w.id=$1`, id, n, off)+}++// MUL-7933 / #9139: a status change behind more due condition checks than one+// batch used to wait several scheduler passes (minutes). The hinted rule must+// fire in the first pass, exactly once, after the coder's run has already+// ended, and the due checks must all still be visited in that pass.+func TestWakeupTickFiresStatusHintBehindManyDueChecks(t *testing.T) {+ f, s, issue, reviewer := conditionFixture(t)+ ctx := context.Background()+ ws := parseTestUUID(t, f.WorkspaceID)+ idleConditionRules(t, f, s, reviewer, 2*wakeupTickBatch+30)++ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: reviewer, Kind: "event", Instruction: "Review it",+ Condition: condition(t, map[string]any{"type": "issue_field", "field": "status", "value": "in_review"})})+ // Not due by time and last in scan order: only its hint can reach it.+ f.Exec(t, "UPDATE issue_wakeup SET next_fire_at=now()+interval '1 hour', updated_at=now() WHERE id=$1", w.ID)++ // The coder sets in_review from its run, and the run ends before any pass.+ var owner string+ f.QueryRow(t, "SELECT owner_id::text FROM agent WHERE id=$1", reviewer).Scan(&owner)+ coder := f.privateAgentOwnedBy(t, owner, "coder")+ run := f.Task(t, coder, testutil.Cols{"issue_id": issue, "status": "running", "started_at": testutil.Raw("now()"),+ "runtime_id": testutil.Raw("(SELECT runtime_id FROM agent WHERE id='" + coder + "')")})+ if _, err := f.q.UpdateIssueStatus(ctx, db.UpdateIssueStatusParams{ID: issue, Status: "in_review", WorkspaceID: ws, SourceTaskID: parseTestUUID(t, run)}); err != nil {+ t.Fatal(err)+ }+ if n := f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1 AND processed_at IS NULL AND event_type='issue.status_changed'", w.ID); n != 1 {+ t.Fatalf("pending status hints = %d, want 1", n)+ }+ f.Exec(t, "UPDATE agent_task_queue SET status='completed', completed_at=now() WHERE id=$1", run)++ drainTick(t, s, ws)+ if n := wakeRuns(t, f, w.ID); n != 1 {+ t.Fatalf("reviewer runs after one pass = %d, want 1", n)+ }+ // Every due check was visited in the same pass, across several batches.+ if n := f.Count(t, "SELECT count(*) FROM issue_wakeup WHERE workspace_id=$1 AND instruction='never' AND next_fire_at<=now()", f.WorkspaceID); n != 0 {+ t.Fatalf("%d due condition checks were left for a later pass", n)+ }+ if n := f.Count(t, "SELECT count(*) FROM agent_task_queue t JOIN issue_wakeup w ON t.context->>'wakeup_id'=w.id::text WHERE w.workspace_id=$1 AND w.instruction='never'", f.WorkspaceID); n != 0 {+ t.Fatalf("unmet conditions started %d runs", n)+ }+ // Later passes do not fire the once rule again.+ f.Exec(t, "UPDATE issue_wakeup SET next_fire_at=now()-interval '1 second' WHERE id=$1 AND next_fire_at IS NOT NULL", w.ID)+ drainTick(t, s, ws)+ if n := wakeRuns(t, f, w.ID); n != 1 {+ t.Fatalf("reviewer runs after two passes = %d, want 1", n)+ }+}++// More rules with pending inputs than a whole batch and a full batch of due+// checks both drain in one pass: the input lane takes at most its share of+// each batch, the due lane the rest, and each rule is visited once.+func TestWakeupTickDrainsBothLanesInOnePass(t *testing.T) {+ f, s, issue, agent := conditionFixture(t)+ ctx := context.Background()+ ws := parseTestUUID(t, f.WorkspaceID)+ idleConditionRules(t, f, s, agent, wakeupTickBatch)++ // More turned-off rules with pending inputs than a whole batch: dispatch+ // only drops their inputs. The lane still lists rules that are not+ // enabled, as it must for a stopped once rule's captured inputs.+ seed := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous", EventTypes: []string{"comment.created"}, Instruction: "noisy"})+ f.Exec(t, "UPDATE issue_wakeup SET enabled=false, disabled_at=now() WHERE id=$1", seed.ID)+ cloneWakeup(t, f, seed.ID, wakeupTickBatch+20-1, true)+ f.Exec(t, `INSERT INTO issue_wakeup_receipt(id,wakeup_id,revision,event_key,event_type,payload)+ SELECT gen_random_uuid(),id,revision,'k','comment.created','{}' FROM issue_wakeup WHERE issue_id=$1`, issue)++ inputs, err := f.q.ListInputWakeups(ctx, db.ListInputWakeupsParams{WorkspaceIds: []pgtype.UUID{ws}, SkipIds: []pgtype.UUID{}, RowLimit: 1000})+ if err != nil {+ t.Fatal(err)+ }+ if len(inputs) != wakeupTickBatch+20 {+ t.Fatalf("input lane lists %d rules, want %d (disabled rules with inputs included)", len(inputs), wakeupTickBatch+20)+ }+ drainTick(t, s, ws)+ if n := f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt r JOIN issue_wakeup w ON w.id=r.wakeup_id WHERE w.issue_id=$1 AND r.processed_at IS NULL", issue); n != 0 {+ t.Fatalf("%d inputs left pending after one pass", n)+ }+ if n := f.Count(t, "SELECT count(*) FROM issue_wakeup WHERE workspace_id=$1 AND instruction='never' AND next_fire_at<=now()", f.WorkspaceID); n != 0 {+ t.Fatalf("%d due checks were crowded out", n)+ }+}++// Slow inputs must not starve due checks (PR #9202 review): dispatches+// alternate between the lanes, and while due work remains the input lane+// stops at its share of the pass budget. Checked by dispatch order, so a slow+// machine cannot change the outcome.+func TestWakeupTickSlowInputsLeaveTimeForDueChecks(t *testing.T) {+ f, s, issue, agent := conditionFixture(t)+ ctx := context.Background()+ ws := parseTestUUID(t, f.WorkspaceID)+ const dueRules, slowInputs = 40, 10+ idleConditionRules(t, f, s, agent, dueRules)+ seed := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous", EventTypes: []string{"comment.created"}, Instruction: "noisy"})+ f.Exec(t, "UPDATE issue_wakeup SET enabled=false, disabled_at=now() WHERE id=$1", seed.ID)+ cloneWakeup(t, f, seed.ID, slowInputs-1, true)+ f.Exec(t, `INSERT INTO issue_wakeup_receipt(id,wakeup_id,revision,event_key,event_type,payload)+ SELECT gen_random_uuid(),id,revision,'k','comment.created','{}' FROM issue_wakeup WHERE issue_id=$1`, issue)++ // Each input takes at least 300ms; the input lane gets 500ms while due+ // checks remain, so at most two inputs may run before the last due check.+ var order []string+ err := s.tickWith(ctx, []pgtype.UUID{ws}, tickLimits{budget: 5 * time.Minute, inputBudget: 500 * time.Millisecond,+ beforeDispatch: func(w db.IssueWakeup) {+ order = append(order, w.Instruction)+ if w.Instruction == "noisy" {+ time.Sleep(300 * time.Millisecond)+ }+ }})+ if err != nil {+ t.Fatal(err)+ }+ lastDue, inputsBefore, inputs := -1, 0, 0+ for i, kind := range order {+ if kind == "never" {+ lastDue = i+ }+ }+ for i, kind := range order {+ if kind == "noisy" {+ inputs+++ if i < lastDue {+ inputsBefore+++ }+ }+ }+ if inputsBefore < 1 || inputsBefore > 2 {+ t.Fatalf("%d slow inputs ran before the last due check, want 1-2 (the input lane's share): %v", inputsBefore, order)+ }+ if order[0] != "noisy" || order[1] != "never" {+ t.Fatalf("lanes did not alternate: %v", order[:2])+ }+ // Once the due lane drained, the inputs used the rest of the pass.+ if inputs != slowInputs || len(order) != dueRules+slowInputs {+ t.Fatalf("dispatched %d inputs of %d and %d rules of %d", inputs, slowInputs, len(order), dueRules+slowInputs)+ }+ if n := f.Count(t, "SELECT count(*) FROM issue_wakeup WHERE workspace_id=$1 AND instruction='never' AND next_fire_at<=now()", f.WorkspaceID); n != 0 {+ t.Fatalf("%d due checks were left behind", n)+ }+}++// Inputs a run holds on purpose are reported as held, not as backlog, so a+// long-waiting run does not make every pass warn (PR #9202 review). Inputs no+// run can take any more stay backlog, so a stalled wakeup still warns.+func TestPendingWakeupInputsSeparatesHeldFromBacklog(t *testing.T) {+ f, s, issue, agent := conditionFixture(t)+ ctx := context.Background()+ ws := []pgtype.UUID{parseTestUUID(t, f.WorkspaceID)}+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous", EventTypes: []string{"comment.created"}, Instruction: "follow up"})+ f.Comment(t, issue.String(), "hello")+ f.Exec(t, "UPDATE issue_wakeup_receipt SET created_at=now()-interval '10 minutes' WHERE wakeup_id=$1", w.ID)+ read := func() pendingInputSummary {+ t.Helper()+ p, err := s.pendingInputs(ctx, ws, wakeupPendingScanPage)+ if err != nil {+ t.Fatal(err)+ }+ return p+ }+ backlog := func(why string) {+ t.Helper()+ p := read()+ if age, ok := p.age(time.Now()); !ok || age < 9*time.Minute || p.Held != 0 {+ t.Fatalf("%s: age=%v ok=%v held=%d, want ~10m backlog", why, age, ok, p.Held)+ }+ }+ held := func(why string) {+ t.Helper()+ if p := read(); p.OldestReady.Valid || p.Held != 1 {+ t.Fatalf("%s: %+v, want held", why, p)+ }+ }+ backlog("unhandled input")+ // A queued run of the agent for the rule's creator will take the input.+ run := f.Task(t, agent, testutil.Cols{"issue_id": issue.String(), "originator_user_id": f.UserID, "accountable_user_id": f.UserID,+ "runtime_id": testutil.Raw("(SELECT runtime_id FROM agent WHERE id='" + agent + "')")})+ held("input waiting for a queued run")+ // A claim reserved the input for that run, which has not started yet.+ f.Exec(t, "UPDATE agent_task_queue SET status='dispatched' WHERE id=$1", run)+ f.Exec(t, "UPDATE issue_wakeup_receipt SET task_id=$2 WHERE wakeup_id=$1", w.ID, run)+ held("input reserved by a claimed run")+ // The run ended without starting: dispatch releases the input, so nobody+ // holds it any more.+ f.Exec(t, "UPDATE agent_task_queue SET status='cancelled', completed_at=now() WHERE id=$1", run)+ backlog("input reserved by a run cancelled before it started")+ f.Exec(t, "UPDATE agent_task_queue SET status='failed', completed_at=now() WHERE id=$1", run)+ backlog("input reserved by a run that failed before it started")+ // The run started: the next dispatch consumes the input.+ f.Exec(t, "UPDATE agent_task_queue SET status='running', started_at=now(), completed_at=NULL WHERE id=$1", run)+ backlog("input of a run that already started")+}++// A platform rule's input is held only by a run waiting for the issue's+// current target, run as that rule's run would be, not by any queued run on+// the issue (PR #9202 review).+func TestPendingWakeupInputsSystemRuleHeldOnlyByItsTarget(t *testing.T) {+ f, s, issue, target := conditionFixture(t)+ ctx := context.Background()+ ws := []pgtype.UUID{parseTestUUID(t, f.WorkspaceID)}+ var owner string+ f.QueryRow(t, "SELECT owner_id::text FROM agent WHERE id=$1", target).Scan(&owner)+ other := f.privateAgentOwnedBy(t, owner, "other")+ f.Exec(t, "UPDATE issue SET assignee_type='agent', assignee_id=$2 WHERE id=$1", issue, target)+ rule, err := f.q.CreateSystemWakeup(ctx, db.CreateSystemWakeupParams{ID: dbid.NewV7(), WorkspaceID: ws[0], IssueID: issue,+ EventTypes: []string{"issue.status_changed"}, Condition: childDoneCondition, Enabled: true, SystemRule: systemRuleText(SystemRuleChildDone)})+ if err != nil {+ t.Fatal(err)+ }+ f.Exec(t, `INSERT INTO issue_wakeup_receipt(id,wakeup_id,revision,event_key,event_type,payload,created_at)+ VALUES(gen_random_uuid(),$1,$2,'k','condition.met','{}',now()-interval '10 minutes')`, rule.ID, rule.Revision)+ read := func() pendingInputSummary {+ t.Helper()+ p, err := s.pendingInputs(ctx, ws, wakeupPendingScanPage)+ if err != nil {+ t.Fatal(err)+ }+ return p+ }+ queued := func(agent, runAs string) string {+ t.Helper()+ return f.Task(t, agent, testutil.Cols{"issue_id": issue.String(), "originator_user_id": runAs, "accountable_user_id": runAs,+ "runtime_id": testutil.Raw("(SELECT runtime_id FROM agent WHERE id='" + agent + "')")})+ }+ issueRow, err := f.q.GetIssue(ctx, issue)+ if err != nil {+ t.Fatal(err)+ }+ targetAgent, err := f.q.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{ID: parseTestUUID(t, target), WorkspaceID: ws[0]})+ if err != nil {+ t.Fatal(err)+ }+ runAs, err := s.childDoneRunAs(ctx, issueRow, targetAgent)+ if err != nil || !runAs.UserID.Valid {+ t.Fatalf("run-as for the target: %+v %v", runAs, err)+ }+ // Another agent's queued run cannot take a platform rule's input.+ queued(other, runAs.UserID.String())+ if p := read(); !p.OldestReady.Valid || p.Held != 0 {+ t.Fatalf("input with only another agent's run queued: %+v, want backlog", p)+ }+ // Nor can the target's run as somebody else.+ stranger := queued(target, f.member(t, "someone-else"))+ if p := read(); !p.OldestReady.Valid || p.Held != 0 {+ t.Fatalf("input with the target's run as another person: %+v, want backlog", p)+ }+ f.Exec(t, "UPDATE agent_task_queue SET status='cancelled', completed_at=now() WHERE id=$1", stranger)+ queued(target, runAs.UserID.String())+ if p := read(); p.OldestReady.Valid || p.Held != 1 {+ t.Fatalf("input with the target's run queued: %+v, want held", p)+ }+}++// More held groups than one page must not hide the ready input behind them+// (PR #9202 review): the scan pages until the groups run out.+func TestPendingWakeupInputsScansPastAFullPageOfHeldGroups(t *testing.T) {+ f, s, issue, agent := conditionFixture(t)+ ctx := context.Background()+ ws := []pgtype.UUID{parseTestUUID(t, f.WorkspaceID)}+ // A page of turned-off rules whose inputs a queued run will take along.+ seed := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous", EventTypes: []string{"comment.created"}, Instruction: "held"})+ f.Exec(t, "UPDATE issue_wakeup SET enabled=false, disabled_at=now() WHERE id=$1", seed.ID)+ cloneWakeup(t, f, seed.ID, wakeupPendingScanPage-1, true)+ f.Exec(t, `INSERT INTO issue_wakeup_receipt(id,wakeup_id,revision,event_key,event_type,payload,created_at)+ SELECT gen_random_uuid(),id,revision,'k','comment.created','{}',now()-interval '20 minutes' FROM issue_wakeup WHERE issue_id=$1`, issue)+ f.Task(t, agent, testutil.Cols{"issue_id": issue.String(), "originator_user_id": f.UserID, "accountable_user_id": f.UserID,+ "runtime_id": testutil.Raw("(SELECT runtime_id FROM agent WHERE id='" + agent + "')")})+ // One ready input, younger than every held one, on another issue.+ other := parseTestUUID(t, f.Issue(t, "Ready input"))+ f.Cleanup(t, "DELETE FROM issue_wakeup WHERE issue_id=$1", other)+ f.Cleanup(t, "DELETE FROM issue_wakeup_receipt WHERE wakeup_id IN (SELECT id FROM issue_wakeup WHERE issue_id=$1)", other)+ f.Cleanup(t, "DELETE FROM activity_log WHERE issue_id=$1", other)+ ready := wakeCreate(t, f, s, other, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous", EventTypes: []string{"comment.created"}, Instruction: "ready"})+ f.Exec(t, `INSERT INTO issue_wakeup_receipt(id,wakeup_id,revision,event_key,event_type,payload,created_at)+ VALUES(gen_random_uuid(),$1,$2,'k','comment.created','{}',now()-interval '10 minutes')`, ready.ID, ready.Revision)++ for _, page := range []int{wakeupPendingScanPage, 7} {+ p, err := s.pendingInputs(ctx, ws, page)+ if err != nil {+ t.Fatal(err)+ }+ if p.Held != wakeupPendingScanPage {+ t.Fatalf("page %d: held = %d, want %d", page, p.Held, wakeupPendingScanPage)+ }+ if age, ok := p.age(time.Now()); !ok || age < 9*time.Minute || age > 15*time.Minute {+ t.Fatalf("page %d: ready input behind the held page: age=%v ok=%v", page, age, ok)+ }+ }+}++// A scan that cannot finish says so instead of returning a silent summary.+func TestPendingWakeupInputsReportsAnIncompleteScan(t *testing.T) {+ f, s, issue, agent := conditionFixture(t)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous", EventTypes: []string{"comment.created"}, Instruction: "follow up"})+ f.Exec(t, `INSERT INTO issue_wakeup_receipt(id,wakeup_id,revision,event_key,event_type,payload)+ VALUES(gen_random_uuid(),$1,$2,'k','comment.created','{}')`, w.ID, w.Revision)+ ctx, cancel := context.WithCancel(context.Background())+ cancel()+ if _, err := s.pendingInputs(ctx, []pgtype.UUID{parseTestUUID(t, f.WorkspaceID)}, wakeupPendingScanPage); err == nil {+ t.Fatal("a scan whose context ended reported a complete result")+ }+}diff --git a/server/pkg/db/generated/wakeup.sql.go b/server/pkg/db/generated/wakeup.sql.goindex 7a1c6f3503..dc5e5503d1 100644--- a/server/pkg/db/generated/wakeup.sql.go+++ b/server/pkg/db/generated/wakeup.sql.go@@ -750,6 +750,163 @@ func (q *Queries) GetIssueWakeup(ctx context.Context, arg GetIssueWakeupParams)return i, err}+const listDueWakeups = `-- name: ListDueWakeups :many+WITH candidates AS (+ SELECT id FROM issue_wakeup WHERE enabled AND kind<>'event' AND next_fire_at<=now()+ UNION+ SELECT id FROM issue_wakeup WHERE enabled AND expires_at<=now()+ UNION+ SELECT id FROM issue_wakeup WHERE enabled AND condition IS NOT NULL AND next_fire_at<=now()+)+SELECT w.id, w.workspace_id, w.issue_id, w.agent_id, w.created_by, w.source_task_id, w.parent_comment_id, w.instruction, w.kind, w.mode, w.event_types, w.filter_agent_id, w.filter_task_id, w.interval_seconds, w.cron_expression, w.timezone, w.next_fire_at, w.enabled, w.disabled_at, w.revision, w.last_task_id, w.last_error, w.created_at, w.updated_at, w.filter_actor_type, w.filter_actor_id, w.expires_at, w.expiry_seconds, w.on_timeout, w.timed_out_at, w.system_rule, w.customized_at, w.condition, w.condition_state, w.max_fires, w.fire_count, w.paused_reason FROM candidates c JOIN issue_wakeup w ON w.id=c.id+WHERE ($1::uuid[] IS NULL OR w.workspace_id = ANY($1::uuid[]))+ AND NOT (w.id = ANY($2::uuid[]))+ORDER BY w.updated_at,w.id LIMIT $3+`++type ListDueWakeupsParams struct {+ WorkspaceIds []pgtype.UUID `json:"workspace_ids"`+ SkipIds []pgtype.UUID `json:"skip_ids"`+ RowLimit int32 `json:"row_limit"`+}++// Scheduler lane 2: schedules, deadlines and condition checks that are due.+// Rules already visited in this pass are skipped.+func (q *Queries) ListDueWakeups(ctx context.Context, arg ListDueWakeupsParams) ([]IssueWakeup, error) {+ rows, err := q.db.Query(ctx, listDueWakeups, arg.WorkspaceIds, arg.SkipIds, arg.RowLimit)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []IssueWakeup{}+ for rows.Next() {+ var i IssueWakeup+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.AgentID,+ &i.CreatedBy,+ &i.SourceTaskID,+ &i.ParentCommentID,+ &i.Instruction,+ &i.Kind,+ &i.Mode,+ &i.EventTypes,+ &i.FilterAgentID,+ &i.FilterTaskID,+ &i.IntervalSeconds,+ &i.CronExpression,+ &i.Timezone,+ &i.NextFireAt,+ &i.Enabled,+ &i.DisabledAt,+ &i.Revision,+ &i.LastTaskID,+ &i.LastError,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.FilterActorType,+ &i.FilterActorID,+ &i.ExpiresAt,+ &i.ExpirySeconds,+ &i.OnTimeout,+ &i.TimedOutAt,+ &i.SystemRule,+ &i.CustomizedAt,+ &i.Condition,+ &i.ConditionState,+ &i.MaxFires,+ &i.FireCount,+ &i.PausedReason,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listInputWakeups = `-- name: ListInputWakeups :many+SELECT w.id, w.workspace_id, w.issue_id, w.agent_id, w.created_by, w.source_task_id, w.parent_comment_id, w.instruction, w.kind, w.mode, w.event_types, w.filter_agent_id, w.filter_task_id, w.interval_seconds, w.cron_expression, w.timezone, w.next_fire_at, w.enabled, w.disabled_at, w.revision, w.last_task_id, w.last_error, w.created_at, w.updated_at, w.filter_actor_type, w.filter_actor_id, w.expires_at, w.expiry_seconds, w.on_timeout, w.timed_out_at, w.system_rule, w.customized_at, w.condition, w.condition_state, w.max_fires, w.fire_count, w.paused_reason FROM issue_wakeup w+WHERE w.id IN (SELECT r.wakeup_id FROM issue_wakeup_receipt r WHERE r.processed_at IS NULL)+ AND ($1::uuid[] IS NULL OR w.workspace_id = ANY($1::uuid[]))+ AND NOT (w.id = ANY($2::uuid[]))+ORDER BY w.updated_at,w.id LIMIT $3+`++type ListInputWakeupsParams struct {+ WorkspaceIds []pgtype.UUID `json:"workspace_ids"`+ SkipIds []pgtype.UUID `json:"skip_ids"`+ RowLimit int32 `json:"row_limit"`+}++// Scheduler lane 1: rules with unprocessed inputs (subscribed events,+// condition hints, "wake now"). Deliberately not filtered by enabled: a once+// rule that stopped still delivers the inputs it captured before stopping.+// The subquery reads only pending rows (issue_wakeup_receipt_pending_idx).+// Rules already visited in this pass are skipped.+func (q *Queries) ListInputWakeups(ctx context.Context, arg ListInputWakeupsParams) ([]IssueWakeup, error) {+ rows, err := q.db.Query(ctx, listInputWakeups, arg.WorkspaceIds, arg.SkipIds, arg.RowLimit)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []IssueWakeup{}+ for rows.Next() {+ var i IssueWakeup+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.AgentID,+ &i.CreatedBy,+ &i.SourceTaskID,+ &i.ParentCommentID,+ &i.Instruction,+ &i.Kind,+ &i.Mode,+ &i.EventTypes,+ &i.FilterAgentID,+ &i.FilterTaskID,+ &i.IntervalSeconds,+ &i.CronExpression,+ &i.Timezone,+ &i.NextFireAt,+ &i.Enabled,+ &i.DisabledAt,+ &i.Revision,+ &i.LastTaskID,+ &i.LastError,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.FilterActorType,+ &i.FilterActorID,+ &i.ExpiresAt,+ &i.ExpirySeconds,+ &i.OnTimeout,+ &i.TimedOutAt,+ &i.SystemRule,+ &i.CustomizedAt,+ &i.Condition,+ &i.ConditionState,+ &i.MaxFires,+ &i.FireCount,+ &i.PausedReason,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listIssueWakeups = `-- name: ListIssueWakeups :manySELECT w.id,w.workspace_id,w.issue_id,w.agent_id,w.created_by,w.source_task_id,w.parent_comment_id,w.instruction,w.kind,w.mode,w.event_types,w.filter_actor_type,@@ -933,35 +1090,85 @@ func (q *Queries) ListPausedWakeupIssues(ctx context.Context, workspaceID pgtypereturn items, nil}-const listPendingWakeupReceipts = `-- name: ListPendingWakeupReceipts :many-SELECT id, wakeup_id, revision, event_key, event_type, payload, task_id, processed_at, created_at, coalesce_key FROM issue_wakeup_receipt WHERE wakeup_id= $1 AND revision= $2 AND processed_at IS NULL ORDER BY created_at,id LIMIT 100 FOR UPDATE+const listPendingWakeupInputGroups = `-- name: ListPendingWakeupInputGroups :many+WITH groups AS (+ SELECT w.id AS wakeup_id, w.issue_id, (w.system_rule IS NOT NULL)::bool AS system_rule,+ (r.task_id IS NOT NULL AND EXISTS (SELECT 1 FROM agent_task_queue t WHERE t.id=r.task_id+ AND t.started_at IS NULL AND t.status NOT IN ('running','completed','failed','cancelled')))::bool AS reserved,+ EXISTS (SELECT 1 FROM agent_task_queue t WHERE t.context->>'wakeup_id'=w.id::text AND t.status='dispatched')::bool AS own_claimed,+ (w.system_rule IS NULL AND EXISTS (SELECT 1 FROM agent_task_queue t WHERE t.issue_id=w.issue_id AND t.status='queued'+ AND t.agent_id=w.agent_id AND t.originator_user_id=w.created_by))::bool AS user_waiting,+ min(r.created_at)::timestamptz AS oldest, count(*)::int AS inputs+ FROM issue_wakeup_receipt r JOIN issue_wakeup w ON w.id=r.wakeup_id+ WHERE r.processed_at IS NULL+ AND ($5::uuid[] IS NULL OR w.workspace_id = ANY($5::uuid[]))+ GROUP BY 1,2,3,4,5,6+)+SELECT g.wakeup_id, g.issue_id, g.system_rule, g.reserved, g.own_claimed, g.user_waiting, g.oldest, g.inputs FROM groups g+WHERE $1::timestamptz IS NULL+ OR (g.oldest, g.wakeup_id, g.reserved) > ($1::timestamptz, $2::uuid, $3::bool)+ORDER BY g.oldest, g.wakeup_id, g.reserved LIMIT $4`-type ListPendingWakeupReceiptsParams struct {- WakeupID pgtype.UUID `json:"wakeup_id"`- Revision int64 `json:"revision"`-}--func (q *Queries) ListPendingWakeupReceipts(ctx context.Context, arg ListPendingWakeupReceiptsParams) ([]IssueWakeupReceipt, error) {- rows, err := q.db.Query(ctx, listPendingWakeupReceipts, arg.WakeupID, arg.Revision)+type ListPendingWakeupInputGroupsParams struct {+ AfterOldest pgtype.Timestamptz `json:"after_oldest"`+ AfterWakeupID pgtype.UUID `json:"after_wakeup_id"`+ AfterReserved bool `json:"after_reserved"`+ PageSize int32 `json:"page_size"`+ WorkspaceIds []pgtype.UUID `json:"workspace_ids"`+}++type ListPendingWakeupInputGroupsRow struct {+ WakeupID pgtype.UUID `json:"wakeup_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ SystemRule bool `json:"system_rule"`+ Reserved bool `json:"reserved"`+ OwnClaimed bool `json:"own_claimed"`+ UserWaiting bool `json:"user_waiting"`+ Oldest pgtype.Timestamptz `json:"oldest"`+ Inputs int32 `json:"inputs"`+}++// Scheduler observability over unprocessed inputs, grouped per rule and by+// whether a run still reserves them. Dispatch deliberately keeps some inputs+// pending while a run holds them; these flags mirror its checks:+//+// reserved: a claim reserved them for a run that has not started and has+// not ended (takenReceipts). A run that ended without starting+// releases them, and one that started has them consumed on the+// next dispatch, so both are backlog.+// own_claimed: the rule's own run is claimed (FindPendingWakeupTask).+// user_waiting: a queued run of the rule's agent, run as its creator, will+// take them along (hasWaitingRun). Platform rules wait for the+// issue's current target instead; the caller resolves that.+//+// Oldest groups first, one page at a time: the caller pages with the last+// group's (oldest, wakeup_id, reserved) until a short page, so no group is+// left unread however many there are.+func (q *Queries) ListPendingWakeupInputGroups(ctx context.Context, arg ListPendingWakeupInputGroupsParams) ([]ListPendingWakeupInputGroupsRow, error) {+ rows, err := q.db.Query(ctx, listPendingWakeupInputGroups,+ arg.AfterOldest,+ arg.AfterWakeupID,+ arg.AfterReserved,+ arg.PageSize,+ arg.WorkspaceIds,+ )if err != nil {return nil, err}defer rows.Close()- items := []IssueWakeupReceipt{}+ items := []ListPendingWakeupInputGroupsRow{}for rows.Next() {- var i IssueWakeupReceipt+ var i ListPendingWakeupInputGroupsRowif err := rows.Scan(- &i.ID,&i.WakeupID,- &i.Revision,- &i.EventKey,- &i.EventType,- &i.Payload,- &i.TaskID,- &i.ProcessedAt,- &i.CreatedAt,- &i.CoalesceKey,+ &i.IssueID,+ &i.SystemRule,+ &i.Reserved,+ &i.OwnClaimed,+ &i.UserWaiting,+ &i.Oldest,+ &i.Inputs,); err != nil {return nil, err}@@ -973,68 +1180,35 @@ func (q *Queries) ListPendingWakeupReceipts(ctx context.Context, arg ListPendingreturn items, nil}-const listReadyWakeups = `-- name: ListReadyWakeups :many-WITH candidates AS (- SELECT id FROM issue_wakeup WHERE enabled AND kind<>'event' AND next_fire_at<=now()- UNION- SELECT id FROM issue_wakeup WHERE enabled AND expires_at<=now()- UNION- SELECT id FROM issue_wakeup WHERE enabled AND condition IS NOT NULL AND next_fire_at<=now()- UNION- SELECT wakeup_id FROM issue_wakeup_receipt WHERE processed_at IS NULL-)-SELECT w.id, w.workspace_id, w.issue_id, w.agent_id, w.created_by, w.source_task_id, w.parent_comment_id, w.instruction, w.kind, w.mode, w.event_types, w.filter_agent_id, w.filter_task_id, w.interval_seconds, w.cron_expression, w.timezone, w.next_fire_at, w.enabled, w.disabled_at, w.revision, w.last_task_id, w.last_error, w.created_at, w.updated_at, w.filter_actor_type, w.filter_actor_id, w.expires_at, w.expiry_seconds, w.on_timeout, w.timed_out_at, w.system_rule, w.customized_at, w.condition, w.condition_state, w.max_fires, w.fire_count, w.paused_reason FROM candidates c JOIN issue_wakeup w ON w.id=c.id-WHERE $1::uuid[] IS NULL OR w.workspace_id = ANY($1::uuid[])-ORDER BY w.updated_at,w.id LIMIT 100+const listPendingWakeupReceipts = `-- name: ListPendingWakeupReceipts :many+SELECT id, wakeup_id, revision, event_key, event_type, payload, task_id, processed_at, created_at, coalesce_key FROM issue_wakeup_receipt WHERE wakeup_id= $1 AND revision= $2 AND processed_at IS NULL ORDER BY created_at,id LIMIT 100 FOR UPDATE`-func (q *Queries) ListReadyWakeups(ctx context.Context, workspaceIds []pgtype.UUID) ([]IssueWakeup, error) {- rows, err := q.db.Query(ctx, listReadyWakeups, workspaceIds)+type ListPendingWakeupReceiptsParams struct {+ WakeupID pgtype.UUID `json:"wakeup_id"`+ Revision int64 `json:"revision"`+}++func (q *Queries) ListPendingWakeupReceipts(ctx context.Context, arg ListPendingWakeupReceiptsParams) ([]IssueWakeupReceipt, error) {+ rows, err := q.db.Query(ctx, listPendingWakeupReceipts, arg.WakeupID, arg.Revision)if err != nil {return nil, err}defer rows.Close()- items := []IssueWakeup{}+ items := []IssueWakeupReceipt{}for rows.Next() {- var i IssueWakeup+ var i IssueWakeupReceiptif err := rows.Scan(&i.ID,- &i.WorkspaceID,- &i.IssueID,- &i.AgentID,- &i.CreatedBy,- &i.SourceTaskID,- &i.ParentCommentID,- &i.Instruction,- &i.Kind,- &i.Mode,- &i.EventTypes,- &i.FilterAgentID,- &i.FilterTaskID,- &i.IntervalSeconds,- &i.CronExpression,- &i.Timezone,- &i.NextFireAt,- &i.Enabled,- &i.DisabledAt,+ &i.WakeupID,&i.Revision,- &i.LastTaskID,- &i.LastError,+ &i.EventKey,+ &i.EventType,+ &i.Payload,+ &i.TaskID,+ &i.ProcessedAt,&i.CreatedAt,- &i.UpdatedAt,- &i.FilterActorType,- &i.FilterActorID,- &i.ExpiresAt,- &i.ExpirySeconds,- &i.OnTimeout,- &i.TimedOutAt,- &i.SystemRule,- &i.CustomizedAt,- &i.Condition,- &i.ConditionState,- &i.MaxFires,- &i.FireCount,- &i.PausedReason,+ &i.CoalesceKey,); err != nil {return nil, err}diff --git a/server/pkg/db/queries/wakeup.sql b/server/pkg/db/queries/wakeup.sqlindex e122400f35..80048c0c5d 100644--- a/server/pkg/db/queries/wakeup.sql+++ b/server/pkg/db/queries/wakeup.sql@@ -70,19 +70,63 @@ WHERE issue_id= @issue_id AND disabled_at IS NULL AND system_rule IS NULL;-- name: CancelUnstartedIssueWakeupTasks :manyUPDATE agent_task_queue SET status='cancelled',completed_at=now(),error='Issue closed; wakeup disabled'WHERE issue_id= @issue_id AND context->>'wakeup_id' IS NOT NULL AND status IN ('queued','deferred') AND started_at IS NULL RETURNING *;--- name: ListReadyWakeups :many+-- name: ListInputWakeups :many+-- Scheduler lane 1: rules with unprocessed inputs (subscribed events,+-- condition hints, "wake now"). Deliberately not filtered by enabled: a once+-- rule that stopped still delivers the inputs it captured before stopping.+-- The subquery reads only pending rows (issue_wakeup_receipt_pending_idx).+-- Rules already visited in this pass are skipped.+SELECT w.* FROM issue_wakeup w+WHERE w.id IN (SELECT r.wakeup_id FROM issue_wakeup_receipt r WHERE r.processed_at IS NULL)+ AND (sqlc.narg('workspace_ids')::uuid[] IS NULL OR w.workspace_id = ANY(sqlc.narg('workspace_ids')::uuid[]))+ AND NOT (w.id = ANY(@skip_ids::uuid[]))+ORDER BY w.updated_at,w.id LIMIT @row_limit;+-- name: ListDueWakeups :many+-- Scheduler lane 2: schedules, deadlines and condition checks that are due.+-- Rules already visited in this pass are skipped.WITH candidates AS (SELECT id FROM issue_wakeup WHERE enabled AND kind<>'event' AND next_fire_at<=now()UNIONSELECT id FROM issue_wakeup WHERE enabled AND expires_at<=now()UNIONSELECT id FROM issue_wakeup WHERE enabled AND condition IS NOT NULL AND next_fire_at<=now()- UNION- SELECT wakeup_id FROM issue_wakeup_receipt WHERE processed_at IS NULL)SELECT w.* FROM candidates c JOIN issue_wakeup w ON w.id=c.id-WHERE sqlc.narg('workspace_ids')::uuid[] IS NULL OR w.workspace_id = ANY(sqlc.narg('workspace_ids')::uuid[])-ORDER BY w.updated_at,w.id LIMIT 100;+WHERE (sqlc.narg('workspace_ids')::uuid[] IS NULL OR w.workspace_id = ANY(sqlc.narg('workspace_ids')::uuid[]))+ AND NOT (w.id = ANY(@skip_ids::uuid[]))+ORDER BY w.updated_at,w.id LIMIT @row_limit;+-- name: ListPendingWakeupInputGroups :many+-- Scheduler observability over unprocessed inputs, grouped per rule and by+-- whether a run still reserves them. Dispatch deliberately keeps some inputs+-- pending while a run holds them; these flags mirror its checks:+-- reserved: a claim reserved them for a run that has not started and has+-- not ended (takenReceipts). A run that ended without starting+-- releases them, and one that started has them consumed on the+-- next dispatch, so both are backlog.+-- own_claimed: the rule's own run is claimed (FindPendingWakeupTask).+-- user_waiting: a queued run of the rule's agent, run as its creator, will+-- take them along (hasWaitingRun). Platform rules wait for the+-- issue's current target instead; the caller resolves that.+-- Oldest groups first, one page at a time: the caller pages with the last+-- group's (oldest, wakeup_id, reserved) until a short page, so no group is+-- left unread however many there are.+WITH groups AS (+ SELECT w.id AS wakeup_id, w.issue_id, (w.system_rule IS NOT NULL)::bool AS system_rule,+ (r.task_id IS NOT NULL AND EXISTS (SELECT 1 FROM agent_task_queue t WHERE t.id=r.task_id+ AND t.started_at IS NULL AND t.status NOT IN ('running','completed','failed','cancelled')))::bool AS reserved,+ EXISTS (SELECT 1 FROM agent_task_queue t WHERE t.context->>'wakeup_id'=w.id::text AND t.status='dispatched')::bool AS own_claimed,+ (w.system_rule IS NULL AND EXISTS (SELECT 1 FROM agent_task_queue t WHERE t.issue_id=w.issue_id AND t.status='queued'+ AND t.agent_id=w.agent_id AND t.originator_user_id=w.created_by))::bool AS user_waiting,+ min(r.created_at)::timestamptz AS oldest, count(*)::int AS inputs+ FROM issue_wakeup_receipt r JOIN issue_wakeup w ON w.id=r.wakeup_id+ WHERE r.processed_at IS NULL+ AND (sqlc.narg('workspace_ids')::uuid[] IS NULL OR w.workspace_id = ANY(sqlc.narg('workspace_ids')::uuid[]))+ GROUP BY 1,2,3,4,5,6+)+SELECT g.wakeup_id, g.issue_id, g.system_rule, g.reserved, g.own_claimed, g.user_waiting, g.oldest, g.inputs FROM groups g+WHERE sqlc.narg('after_oldest')::timestamptz IS NULL+ OR (g.oldest, g.wakeup_id, g.reserved) > (sqlc.narg('after_oldest')::timestamptz, @after_wakeup_id::uuid, @after_reserved::bool)+ORDER BY g.oldest, g.wakeup_id, g.reserved LIMIT @page_size;-- name: ListPendingWakeupReceipts :manySELECT * FROM issue_wakeup_receipt WHERE wakeup_id= @wakeup_id AND revision= @revision AND processed_at IS NULL ORDER BY created_at,id LIMIT 100 FOR UPDATE;