Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-7794 fix(wakeups): surface recoverable PR condition diagnostics [ZIC-302] (#9066)

ZIce756cdd915c85
diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.go
index 72e77cb99c..27fe2e4d1a 100644
--- a/server/internal/daemon/execenv/runtime_config_sections.go
+++ b/server/internal/daemon/execenv/runtime_config_sections.go
@@ -265,7 +265,7 @@ func writeAvailableCommands(b *strings.Builder, ctx TaskContextForEnv) {
b.WriteString("- `multica issue assign <id> (--to X | --to-id <uuid> | --unassign)` — change ownership; assigning to an agent can start a run.\n")
writeIssueStatusCommand(b, ctx)
b.WriteString(duplicateOfCommandLine)
- b.WriteString("- `multica issue wakeup <create|list|get|update|disable|trigger|delete|runs|events>` — persist an event, condition or time wakeup on this issue, then finish the current run. When the platform can check the fact itself, use a condition (`--until-status`, `--until-pr checks`, `--until-children-done`, `--until-issue`) so no run starts before it holds. Use `--event comment.created --filter-actor-type member --filter-actor-id USER_ID` to wait for a specific member to comment. See `multica issue wakeup --help` and the multica-platform issues reference.\n")
+ b.WriteString("- `multica issue wakeup <create|list|get|update|disable|trigger|delete|runs|events>` — persist an event, condition or time wakeup on this issue, then finish the current run. When the platform can check the fact itself, use a condition (`--until-status`, `--until-pr checks`, `--until-children-done`, `--until-issue`) so no run starts before it holds. PR conditions watch only PRs linked to this exact issue; `--until-pr checks` also requires server-side GitHub check snapshots. Check the rule's `last_error` for missing links or unavailable snapshots; delayed links and snapshots are retried automatically. Use `--event comment.created --filter-actor-type member --filter-actor-id USER_ID` to wait for a specific member to comment. See `multica issue wakeup --help` and the multica-platform issues reference.\n")
b.WriteString("- `multica issue children <id> [--output json]` — list a parent's sub-issues grouped by stage.\n")
b.WriteString("- `multica issue comment add <issue-id> [--content \"...\" | --content-file <path> | --content-stdin] [--parent <comment-id>] [--attachment <path>]` — post a comment. Agent-authored bodies MUST use `--content-file`; see `## Comment Formatting` for why. `multica issue comment add --help` for full flags.\n")
b.WriteString("- `multica repo checkout <url> [--ref <branch-or-sha>] [--fresh]` — repository checkout on a dedicated branch. Re-running it keeps an existing checkout that has uncommitted or unpushed work, or is already on this task's branch, and only fetches. `--fresh` discards uncommitted and untracked files and starts a new branch; commits stay on the old branch, but push any you still need first.\n\n")
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index bfe72f9bf7..393806a3e2 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -536,6 +536,7 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *event
slog.Warn("github: PR snapshot pipeline disabled (invalid App private key)", "err", err)
}
h.PRRefresh = ghsnapshot.NewManager(ghClient, queries, txStarter, h.broadcastPRSnapshotApplied)
+ taskSvc.PRSnapshotsEnabled = h.PRRefresh.Enabled()
return h
}
diff --git a/server/internal/service/builtin_skills/multica-platform/references/issues.md b/server/internal/service/builtin_skills/multica-platform/references/issues.md
index d460e3bcfd..7d41d579f2 100644
--- a/server/internal/service/builtin_skills/multica-platform/references/issues.md
+++ b/server/internal/service/builtin_skills/multica-platform/references/issues.md
@@ -443,7 +443,7 @@ multica issue wakeup create <issue> --until-issue <other-issue-id> --until-issue
```
- `--until-status KEY` — this issue's status is that key (built-in or one of the workspace's statuses).
-- `--until-pr checks` — a linked pull request's checks finished, passing or failing, on its current head. `--until-pr merged` — a linked pull request merged. With several linked pull requests, any one satisfies it.
+- `--until-pr checks` — a linked pull request's checks finished, passing or failing, on its current head. `--until-pr merged` — a linked pull request merged. With several linked pull requests, any one satisfies it. Both conditions inspect only PRs linked directly to this issue; they do not inherit a parent issue's PRs. Check evaluation also requires server-side GitHub snapshots. A missing link or snapshot is recorded in the rule's `last_error` and retried automatically rather than rejecting the rule.
- `--until-children-done` — every sub-issue, staged or not, is closed (`done` or `cancelled`). With `--stage N` it waits only for staged sub-issues up to stage N, and stage N must have at least one. A parent with no sub-issues never fires. The parent's assignee already gets the sub-issue wakeup described under Stages; do not add this condition for the same wake.
- `--until-issue ISSUE` — another issue in this workspace (identifier or UUID) reaches `--until-issue-state`: `done` (default), `ended` (done or cancelled), or `in_review`.
- The same form also accepts `--until-assignee member|agent|squad:ID`, `--until-label LABEL_ID`, and `--until-property PROPERTY_ID=VALUE` (VALUE may be JSON). `multica issue wakeup create --help` lists them.
diff --git a/server/internal/service/issue_wakeup.go b/server/internal/service/issue_wakeup.go
index 01b37df9ca..840c905eb6 100644
--- a/server/internal/service/issue_wakeup.go
+++ b/server/internal/service/issue_wakeup.go
@@ -573,7 +573,11 @@ func (s *IssueWakeupService) save(ctx context.Context, issueID, member, source,
return out, err
}
if len(out.Condition) > 0 && conditionFiresOnChange(out.Condition) {
- if err = baselineCondition(ctx, tx, q, out, now); err != nil {
+ if err = s.baselineCondition(ctx, tx, q, out, now); err != nil {
+ return out, err
+ }
+ out, err = q.LockIssueWakeup(ctx, out.ID)
+ if err != nil {
return out, err
}
}
@@ -832,7 +836,7 @@ func (s *IssueWakeupService) dispatch(ctx context.Context, prev db.IssueWakeup)
// one condition.met input; a rule that ended only drops the hints.
if len(w.Condition) > 0 {
if w.Enabled && !timedOut {
- if next, err = pollCondition(ctx, tx, q, w, now); err != nil {
+ if next, err = s.pollCondition(ctx, tx, q, w, now); err != nil {
return err
}
} else if _, _, err = consumeConditionHints(ctx, tx, w.ID); err != nil {
diff --git a/server/internal/service/issue_wakeup_capacity_test.go b/server/internal/service/issue_wakeup_capacity_test.go
index c36279e8d5..25a941122a 100644
--- a/server/internal/service/issue_wakeup_capacity_test.go
+++ b/server/internal/service/issue_wakeup_capacity_test.go
@@ -169,19 +169,36 @@ func TestIssueWakeupCaptureRacingConsumptionKeepsNewInput(t *testing.T) {
func TestIssueWakeupReceiptExpiryIsBoundedAndKeepsPending(t *testing.T) {
f, s, issue, agent := wakeFixture(t)
w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", EventTypes: []string{"comment.created"}, Instruction: "check"})
- f.Exec(t, `INSERT INTO issue_wakeup_receipt(id,wakeup_id,revision,event_key,event_type,payload,created_at,processed_at)
+ ctx := context.Background()
+ tx, err := f.Pool.Begin(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer tx.Rollback(ctx)
+ q := f.q.WithTx(tx)
+ _, err = tx.Exec(ctx, `INSERT INTO issue_wakeup_receipt(id,wakeup_id,revision,event_key,event_type,payload,created_at,processed_at)
SELECT gen_random_uuid(),$1,1,n::text,'comment.created','{}',now()-interval '10 days',now()-interval '8 days' FROM generate_series(1,1050) n`, w.ID)
- f.Exec(t, `INSERT INTO issue_wakeup_receipt(id,wakeup_id,revision,event_key,event_type,payload,created_at,processed_at)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = tx.Exec(ctx, `INSERT INTO issue_wakeup_receipt(id,wakeup_id,revision,event_key,event_type,payload,created_at,processed_at)
VALUES(gen_random_uuid(),$1,1,'pending','comment.created','{}',now()-interval '10 days',NULL),
(gen_random_uuid(),$1,1,'recent','comment.created','{}',now()-interval '10 days',now())`, w.ID)
- removed, err := f.q.DeleteExpiredWakeupReceipts(context.Background(), pgtype.Timestamptz{Time: time.Now().Add(-7 * 24 * time.Hour), Valid: true})
+ if err != nil {
+ t.Fatal(err)
+ }
+ removed, err := q.DeleteExpiredWakeupReceipts(ctx, pgtype.Timestamptz{Time: time.Now().Add(-7 * 24 * time.Hour), Valid: true})
if err != nil {
t.Fatal(err)
}
if removed != 1000 {
t.Fatalf("cleanup not bounded: %d", removed)
}
- if got := f.Count(t, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1 AND event_key IN ('pending','recent')", w.ID); got != 2 {
+ var kept int
+ if err = tx.QueryRow(ctx, "SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id=$1 AND event_key IN ('pending','recent')", w.ID).Scan(&kept); err != nil {
+ t.Fatal(err)
+ }
+ if kept != 2 {
t.Fatal("expired pending input or recent dedup key")
}
}
diff --git a/server/internal/service/issue_wakeup_condition.go b/server/internal/service/issue_wakeup_condition.go
index 23a2b26bd7..7baff1ae09 100644
--- a/server/internal/service/issue_wakeup_condition.go
+++ b/server/internal/service/issue_wakeup_condition.go
@@ -22,7 +22,10 @@ import (
// conditionPollInterval bounds how long a platform-evaluated condition can
// stay satisfied before its rule notices. Same-issue field conditions also
// subscribe to the matching event, so they usually react on the next tick.
-const conditionPollInterval = 30 * time.Second
+const (
+ conditionPollInterval = 30 * time.Second
+ conditionDiagnosticPrefix = "Condition pending: "
+)
// WakeupCondition is a structured predicate the platform evaluates itself, so
// a rule only wakes its agent when the predicate becomes true. It compares
@@ -55,6 +58,18 @@ type WakeupCondition struct {
var errBadCondition = errors.New("invalid condition")
+// These are recoverable observations, not invalid rules or database failures.
+// Keep polling so delayed webhooks, snapshots or restored configuration heal.
+var (
+ errPRSnapshotsUnavailable = errors.New("PR checks cannot be evaluated: GitHub snapshot refresh is unavailable on this server; ask the server administrator to configure the GitHub App snapshot client")
+ errPRNotLinked = errors.New("No pull request is linked to this issue; link the PR to this issue (a parent issue's PR is not included), or wait for the linking webhook")
+ errPRSnapshotPending = errors.New("PR check snapshot is not available yet; inspect this issue's pull-requests snapshot_available field and ask the server administrator to check snapshot refresh if it persists")
+)
+
+func conditionDiagnostic(err error) bool {
+ return errors.Is(err, errPRSnapshotsUnavailable) || errors.Is(err, errPRNotLinked) || errors.Is(err, errPRSnapshotPending)
+}
+
func badCondition(msg string) error {
return fmt.Errorf("%w: %w: %s", ErrWakeupInput, errBadCondition, msg)
}
@@ -205,7 +220,7 @@ func validateCondition(ctx context.Context, tx pgx.Tx, issue db.Issue, raw json.
// evaluateCondition reports whether the predicate holds, a fingerprint of the
// satisfying facts (so a rule fires when they change, not on every tick) and a
// small observation for the woken agent's trigger facts.
-func evaluateCondition(ctx context.Context, tx pgx.Tx, q *db.Queries, w db.IssueWakeup) (bool, string, map[string]any, error) {
+func (s *IssueWakeupService) evaluateCondition(ctx context.Context, tx pgx.Tx, q *db.Queries, w db.IssueWakeup) (bool, string, map[string]any, error) {
var c WakeupCondition
if err := json.Unmarshal(w.Condition, &c); err != nil {
return false, "", nil, err
@@ -244,11 +259,15 @@ func evaluateCondition(ctx context.Context, tx pgx.Tx, q *db.Queries, w db.Issue
met, fingerprint, observed := childrenDone(c, children)
return met, fingerprint, observed, nil
case "pull_request":
+ if c.Event == "checks_finished" && (s.Tasks == nil || !s.Tasks.PRSnapshotsEnabled) {
+ return false, "", nil, errPRSnapshotsUnavailable
+ }
rows, err := tx.Query(ctx, `SELECT pr.pr_number,pr.state,COALESCE(pr.snapshot_head_sha,''),COALESCE(pr.checks_rollup_state,'')
FROM github_pull_request pr JOIN issue_pull_request ipr ON ipr.pull_request_id=pr.id WHERE ipr.issue_id=$1`, w.IssueID)
if err != nil {
return false, "", nil, err
}
+ linked, missingSnapshot := 0, false
var keys []string
var prs []map[string]any
for rows.Next() {
@@ -258,6 +277,8 @@ func evaluateCondition(ctx context.Context, tx pgx.Tx, q *db.Queries, w db.Issue
rows.Close()
return false, "", nil, err
}
+ linked++
+ missingSnapshot = missingSnapshot || head == ""
switch c.Event {
case "merged":
if state == "merged" {
@@ -275,6 +296,13 @@ func evaluateCondition(ctx context.Context, tx pgx.Tx, q *db.Queries, w db.Issue
if err = rows.Err(); err != nil {
return false, "", nil, err
}
+ if linked == 0 {
+ return false, "", nil, errPRNotLinked
+ }
+ // Any matching PR satisfies the rule, even if another awaits a snapshot.
+ if c.Event == "checks_finished" && len(keys) == 0 && missingSnapshot {
+ return false, "", nil, errPRSnapshotPending
+ }
sort.Strings(keys)
return len(keys) > 0, "pr:" + strings.Join(keys, ","), map[string]any{"pull_requests": prs}, nil
case "other_issue":
@@ -354,7 +382,7 @@ func consumeConditionHints(ctx context.Context, tx pgx.Tx, id pgtype.UUID) (bool
// pollCondition evaluates a condition rule when it is due or a related event
// arrived, and returns the next scheduled evaluation. A newly satisfied
// predicate becomes one condition.met input for the ordinary dispatch below.
-func pollCondition(ctx context.Context, tx pgx.Tx, q *db.Queries, w db.IssueWakeup, now time.Time) (pgtype.Timestamptz, error) {
+func (s *IssueWakeupService) pollCondition(ctx context.Context, tx pgx.Tx, q *db.Queries, w db.IssueWakeup, now time.Time) (pgtype.Timestamptz, error) {
hinted, causes, err := consumeConditionHints(ctx, tx, w.ID)
if err != nil {
return w.NextFireAt, err
@@ -362,8 +390,11 @@ func pollCondition(ctx context.Context, tx pgx.Tx, q *db.Queries, w db.IssueWake
if !hinted && w.NextFireAt.Valid && w.NextFireAt.Time.After(now) {
return w.NextFireAt, nil
}
- met, fingerprint, observed, err := evaluateCondition(ctx, tx, q, w)
- if err != nil {
+ met, fingerprint, observed, err := s.evaluateCondition(ctx, tx, q, w)
+ if err != nil && !conditionDiagnostic(err) {
+ return w.NextFireAt, err
+ }
+ if err = saveConditionDiagnostic(ctx, q, w, err); err != nil {
return w.NextFireAt, err
}
// condition_state dedups a satisfied predicate; each new satisfaction
@@ -393,9 +424,12 @@ func conditionFiresOnChange(raw []byte) bool {
// baselineCondition records which facts already satisfy a new or re-enabled
// rule, so it wakes the agent when they change rather than immediately.
-func baselineCondition(ctx context.Context, tx pgx.Tx, q *db.Queries, w db.IssueWakeup, now time.Time) error {
- met, fingerprint, _, err := evaluateCondition(ctx, tx, q, w)
- if err != nil {
+func (s *IssueWakeupService) baselineCondition(ctx context.Context, tx pgx.Tx, q *db.Queries, w db.IssueWakeup, now time.Time) error {
+ met, fingerprint, _, err := s.evaluateCondition(ctx, tx, q, w)
+ if err != nil && !conditionDiagnostic(err) {
+ return err
+ }
+ if err = saveConditionDiagnostic(ctx, q, w, err); err != nil {
return err
}
if !met {
@@ -404,6 +438,28 @@ func baselineCondition(ctx context.Context, tx pgx.Tx, q *db.Queries, w db.Issue
return q.SetWakeupConditionState(ctx, db.SetWakeupConditionStateParams{ID: w.ID, ConditionState: fingerprint, NextFireAt: pgtype.Timestamptz{Time: now.Add(conditionPollInterval), Valid: true}})
}
+// saveConditionDiagnostic owns only last_error values carrying its prefix.
+// Dispatch failures share the column and must survive a condition poll. Avoid
+// rewriting an unchanged diagnostic on every polling interval as well.
+func saveConditionDiagnostic(ctx context.Context, q *db.Queries, w db.IssueWakeup, diagnostic error) error {
+ owned := w.LastError.Valid && strings.HasPrefix(w.LastError.String, conditionDiagnosticPrefix)
+ var lastError pgtype.Text
+ if diagnostic != nil {
+ lastError = pgtype.Text{String: conditionDiagnosticPrefix + diagnostic.Error(), Valid: true}
+ if w.LastError.Valid {
+ if w.LastError.String == lastError.String {
+ return nil
+ }
+ if !owned {
+ return nil
+ }
+ }
+ } else if !owned {
+ return nil
+ }
+ return q.NoteWakeupFailure(ctx, db.NoteWakeupFailureParams{ID: w.ID, LastError: lastError})
+}
+
// subIssue is one sub-issue as the children_done condition reads it. Closed
// covers the done and closed status categories; Cancelled is closed without
// finishing.
diff --git a/server/internal/service/issue_wakeup_condition_pr_test.go b/server/internal/service/issue_wakeup_condition_pr_test.go
new file mode 100644
index 0000000000..7687989853
--- /dev/null
+++ b/server/internal/service/issue_wakeup_condition_pr_test.go
@@ -0,0 +1,166 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgconn"
+ "github.com/jackc/pgx/v5/pgtype"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
+)
+
+// Exercise evaluation and diagnostic persistence even without local PostgreSQL.
+// The DB-backed test covers the full registration/dispatch and parent-link path.
+type prConditionTx struct {
+ pgx.Tx
+ issue pgtype.UUID
+ prs [][]any
+ queryErr error
+ lastError pgtype.Text
+ next pgtype.Timestamptz
+ writes int
+}
+
+func (tx *prConditionTx) Query(_ context.Context, sql string, args ...any) (pgx.Rows, error) {
+ if strings.Contains(sql, "UPDATE issue_wakeup_receipt") {
+ return &sliceRows{}, nil
+ }
+ if !strings.Contains(sql, "WHERE ipr.issue_id=$1") || len(args) != 1 || args[0] != tx.issue {
+ return nil, fmt.Errorf("unexpected PR scope: %s %v", sql, args)
+ }
+ return &sliceRows{rows: tx.prs}, tx.queryErr
+}
+
+func (tx *prConditionTx) Exec(_ context.Context, sql string, args ...any) (pgconn.CommandTag, error) {
+ switch {
+ case strings.Contains(sql, "NoteWakeupFailure"):
+ tx.lastError = args[0].(pgtype.Text)
+ tx.writes++
+ case strings.Contains(sql, "SetWakeupConditionState"):
+ tx.next = args[1].(pgtype.Timestamptz)
+ default:
+ return pgconn.CommandTag{}, fmt.Errorf("unexpected write: %s", sql)
+ }
+ return pgconn.NewCommandTag("UPDATE 1"), nil
+}
+
+func TestWakeupConditionPREvaluation(t *testing.T) {
+ row := func(state, head, checks string) []any { return []any{int32(1), state, head, checks} }
+ for _, tc := range []struct {
+ name, event string
+ available bool
+ prs [][]any
+ wantErr error
+ wantMet bool
+ }{
+ {"unconfigured", "checks_finished", false, nil, errPRSnapshotsUnavailable, false},
+ {"unlinked", "checks_finished", true, nil, errPRNotLinked, false},
+ {"unlinked merged", "merged", false, nil, errPRNotLinked, false},
+ {"no snapshot", "checks_finished", true, [][]any{row("open", "", "SUCCESS")}, errPRSnapshotPending, false},
+ {"pending", "checks_finished", true, [][]any{row("open", "head", "PENDING")}, nil, false},
+ {"no checks", "checks_finished", true, [][]any{row("open", "head", "")}, nil, false},
+ {"success", "checks_finished", true, [][]any{row("open", "head", "SUCCESS")}, nil, true},
+ {"failure", "checks_finished", true, [][]any{row("open", "head", "FAILURE")}, nil, true},
+ {"error", "checks_finished", true, [][]any{row("open", "head", "ERROR")}, nil, true},
+ {"one matching PR", "checks_finished", true, [][]any{row("open", "", ""), row("open", "head", "SUCCESS")}, nil, true},
+ {"merge without snapshots", "merged", false, [][]any{row("merged", "", "")}, nil, true},
+ {"open without snapshots", "merged", false, [][]any{row("open", "", "")}, nil, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ s := &IssueWakeupService{Tasks: &TaskService{PRSnapshotsEnabled: tc.available}}
+ w := db.IssueWakeup{IssueID: dbid.NewV7(), Condition: condition(t, map[string]any{"type": "pull_request", "event": tc.event})}
+ tx := &prConditionTx{issue: w.IssueID, prs: tc.prs}
+ met, fingerprint, observed, err := s.evaluateCondition(context.Background(), tx, db.New(tx), w)
+ if met != tc.wantMet || !errors.Is(err, tc.wantErr) {
+ t.Fatalf("met=%t err=%v; want met=%t err=%v", met, err, tc.wantMet, tc.wantErr)
+ }
+ if met && (fingerprint == "" || len(observed["pull_requests"].([]map[string]any)) != 1) {
+ t.Fatalf("missing terminal PR evidence: fingerprint=%q observed=%v", fingerprint, observed)
+ }
+ })
+ }
+}
+
+func TestWakeupConditionPRDiagnosticPolling(t *testing.T) {
+ ctx := context.Background()
+ s := &IssueWakeupService{Tasks: &TaskService{}}
+ w := db.IssueWakeup{ID: dbid.NewV7(), IssueID: dbid.NewV7(), Condition: condition(t, map[string]any{"type": "pull_request", "event": "checks_finished"})}
+ tx := &prConditionTx{issue: w.IssueID}
+ q := db.New(tx)
+ now := time.Now()
+ wantUnavailable := conditionDiagnosticPrefix + errPRSnapshotsUnavailable.Error()
+ if err := s.baselineCondition(ctx, tx, q, w, now); err != nil || tx.lastError.String != wantUnavailable {
+ t.Fatalf("registration must retain diagnostic without rejecting: %v, %+v", err, tx.lastError)
+ }
+ w.LastError = tx.lastError
+ if err := s.baselineCondition(ctx, tx, q, w, now); err != nil || tx.writes != 1 {
+ t.Fatalf("unchanged diagnostic must not be rewritten: err=%v writes=%d", err, tx.writes)
+ }
+ s.Tasks.PRSnapshotsEnabled = true
+ for _, step := range []struct {
+ prs [][]any
+ want error
+ }{
+ {nil, errPRNotLinked},
+ {[][]any{{int32(1), "open", "", ""}}, errPRSnapshotPending},
+ {[][]any{{int32(1), "open", "head", "PENDING"}}, nil},
+ } {
+ tx.prs = step.prs
+ w.LastError = tx.lastError
+ next, err := s.pollCondition(ctx, tx, q, w, now)
+ if err != nil || !next.Valid || !next.Time.Equal(now.Add(conditionPollInterval)) {
+ t.Fatalf("poll must remain scheduled: next=%+v err=%v", next, err)
+ }
+ if step.want == nil {
+ if tx.lastError.Valid {
+ t.Fatalf("recovery retained diagnostic: %+v", tx.lastError)
+ }
+ } else if tx.lastError.String != conditionDiagnosticPrefix+step.want.Error() {
+ t.Fatalf("diagnostic=%+v, want %v", tx.lastError, step.want)
+ }
+ }
+ // Real query failures still propagate; they are never treated as unmet facts.
+ tx.queryErr = errors.New("database offline")
+ if _, err := s.pollCondition(ctx, tx, q, w, now); !errors.Is(err, tx.queryErr) {
+ t.Fatalf("database error swallowed: %v", err)
+ }
+}
+
+func TestSaveConditionDiagnosticPreservesDispatchErrors(t *testing.T) {
+ ctx := context.Background()
+ tx := &prConditionTx{}
+ q := db.New(tx)
+ realFailure := pgtype.Text{String: "dispatch failed", Valid: true}
+ w := db.IssueWakeup{ID: dbid.NewV7(), LastError: realFailure}
+
+ if err := saveConditionDiagnostic(ctx, q, w, errPRNotLinked); err != nil {
+ t.Fatal(err)
+ }
+ if err := saveConditionDiagnostic(ctx, q, w, nil); err != nil {
+ t.Fatal(err)
+ }
+ if tx.writes != 0 || tx.lastError.Valid {
+ t.Fatalf("condition evaluation changed an unrelated error: writes=%d error=%+v", tx.writes, tx.lastError)
+ }
+
+ w.LastError = pgtype.Text{String: conditionDiagnosticPrefix + errPRNotLinked.Error(), Valid: true}
+ if err := saveConditionDiagnostic(ctx, q, w, errPRSnapshotPending); err != nil {
+ t.Fatal(err)
+ }
+ if tx.writes != 1 || tx.lastError.String != conditionDiagnosticPrefix+errPRSnapshotPending.Error() {
+ t.Fatalf("owned diagnostic was not updated: writes=%d error=%+v", tx.writes, tx.lastError)
+ }
+ w.LastError = tx.lastError
+ if err := saveConditionDiagnostic(ctx, q, w, nil); err != nil {
+ t.Fatal(err)
+ }
+ if tx.writes != 2 || tx.lastError.Valid {
+ t.Fatalf("owned diagnostic was not cleared: writes=%d error=%+v", tx.writes, tx.lastError)
+ }
+}
diff --git a/server/internal/service/issue_wakeup_condition_test.go b/server/internal/service/issue_wakeup_condition_test.go
index 64f1890c10..10e7f36160 100644
--- a/server/internal/service/issue_wakeup_condition_test.go
+++ b/server/internal/service/issue_wakeup_condition_test.go
@@ -159,6 +159,7 @@ func TestWakeupConditionChildrenAndOtherIssue(t *testing.T) {
func TestWakeupConditionPullRequestChecksWaitForNewResult(t *testing.T) {
f, s, issue, agent := conditionFixture(t)
+ s.Tasks.PRSnapshotsEnabled = true
ctx := context.Background()
var pr string
if err := f.Pool.QueryRow(ctx, `INSERT INTO github_pull_request(workspace_id,installation_id,repo_owner,repo_name,pr_number,title,state,html_url,pr_created_at,pr_updated_at,snapshot_head_sha,checks_rollup_state)
@@ -215,3 +216,65 @@ func TestWakeupConditionValidation(t *testing.T) {
}
}
}
+
+func TestWakeupConditionPRDiagnosticsRecover(t *testing.T) {
+ for _, event := range []string{"checks_finished", "merged"} {
+ t.Run(event, func(t *testing.T) {
+ f, s, issue, agent := conditionFixture(t)
+ ctx := context.Background()
+ parent := f.Issue(t, "PR owner")
+ f.Exec(t, "UPDATE issue SET parent_issue_id=$2 WHERE id=$1", issue, parent)
+ pr := f.Insert(t, "github_pull_request", testutil.Cols{
+ "workspace_id": f.WorkspaceID, "installation_id": 1,
+ "repo_owner": "fixture", "repo_name": "wakeup", "pr_number": 1,
+ "title": "PR", "state": "open", "html_url": "https://example.test/pr/1",
+ "pr_created_at": "2026-01-01T00:00:00Z", "pr_updated_at": "2026-01-01T00:00:00Z",
+ })
+ f.Cleanup(t, "DELETE FROM issue_pull_request WHERE pull_request_id=$1", pr)
+ f.Exec(t, "INSERT INTO issue_pull_request(issue_id,pull_request_id) VALUES($1,$2)", parent, pr)
+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Instruction: "Review PR",
+ Condition: condition(t, map[string]any{"type": "pull_request", "event": event})})
+ assertWaiting := func(w db.IssueWakeup, diagnostic error) {
+ t.Helper()
+ if !w.Enabled || !w.LastError.Valid || w.LastError.String != conditionDiagnosticPrefix+diagnostic.Error() || w.FireCount != 0 || wakeRuns(t, f, w.ID) != 0 {
+ t.Fatalf("expected enabled, unfired rule with %q; got enabled=%t fires=%d error=%+v", diagnostic, w.Enabled, w.FireCount, w.LastError)
+ }
+ if !w.NextFireAt.Valid {
+ t.Fatal("diagnostic stopped condition polling")
+ }
+ }
+ if event == "checks_finished" {
+ // A disabled snapshot client is visible even in the create response.
+ assertWaiting(w, errPRSnapshotsUnavailable)
+ assertWaiting(wakeTick(t, f, s, w.ID), errPRSnapshotsUnavailable)
+ s.Tasks.PRSnapshotsEnabled = true
+ }
+ // Linking to the parent must never satisfy a child issue's rule.
+ assertWaiting(wakeTick(t, f, s, w.ID), errPRNotLinked)
+ f.Exec(t, "INSERT INTO issue_pull_request(issue_id,pull_request_id) VALUES($1,$2)", issue, pr)
+ if event == "checks_finished" {
+ assertWaiting(wakeTick(t, f, s, w.ID), errPRSnapshotPending)
+ // Re-enabling also accepts a transiently missing snapshot.
+ disabled, err := s.Disable(ctx, issue, w.ID, parseTestUUID(t, f.UserID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ w, err = s.Enable(ctx, issue, parseTestUUID(t, f.UserID), pgtype.UUID{}, w.ID, WakeupEnableInput{Revision: disabled.Revision})
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertWaiting(w, errPRSnapshotPending)
+ f.Exec(t, "UPDATE github_pull_request SET snapshot_head_sha='new',checks_rollup_state='PENDING' WHERE id=$1", pr)
+ }
+ got := wakeTick(t, f, s, w.ID)
+ if got.LastError.Valid || !got.Enabled || wakeRuns(t, f, w.ID) != 0 {
+ t.Fatalf("normal pending condition did not clear diagnostic: %+v", got.LastError)
+ }
+ f.Exec(t, "UPDATE github_pull_request SET state='merged',checks_rollup_state='SUCCESS' WHERE id=$1", pr)
+ got = wakeTick(t, f, s, w.ID)
+ if got.Enabled || got.LastError.Valid || wakeRuns(t, f, w.ID) != 1 {
+ t.Fatalf("recovered condition failed to fire once: enabled=%t error=%+v", got.Enabled, got.LastError)
+ }
+ })
+ }
+}
diff --git a/server/internal/service/issue_wakeup_system.go b/server/internal/service/issue_wakeup_system.go
index 6a4df182c6..8afbaf2d11 100644
--- a/server/internal/service/issue_wakeup_system.go
+++ b/server/internal/service/issue_wakeup_system.go
@@ -473,7 +473,7 @@ func (s *IssueWakeupService) dispatchSystem(ctx context.Context, prev db.IssueWa
if err != nil {
return err
}
- met, fingerprint, observed, err := evaluateCondition(ctx, tx, q, w)
+ met, fingerprint, observed, err := s.evaluateCondition(ctx, tx, q, w)
if err != nil {
return err
}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 31095f83d3..08f31c121e 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -44,6 +44,8 @@ type TaskService struct {
Analytics analytics.Client
Metrics *obsmetrics.BusinessMetrics
Wakeup TaskWakeupNotifier
+ // PRSnapshotsEnabled reports whether the server can refresh GitHub check snapshots.
+ PRSnapshotsEnabled bool
// Entitlements supplies Cloud's workspace-scoped issue-count instruction.
// Nil keeps self-hosted and isolated test services unlimited.
Entitlements entitlement.Provider