Skip to content

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

Go
14.5 KB
Raw Blame
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
	workspace pgtype.UUID
	hasVCS    bool
	vcsErr    error
	vcsChecks int
	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
	}
	// The canned GitHub rows below describe an issue with no self-hosted VCS
	// pull requests; the VCS aggregation finds nothing to add. The VCS path
	// itself is covered against PostgreSQL by the condition test suite.
	if strings.Contains(sql, "FROM vcs_pull_request") {
		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
}

// QueryRow answers whether the workspace has a self-hosted VCS connection.
func (tx *prConditionTx) QueryRow(_ context.Context, sql string, args ...any) pgx.Row {
	if !strings.Contains(sql, "FROM vcs_connection") || len(args) != 1 || args[0] != tx.workspace {
		return prConditionRow{err: fmt.Errorf("unexpected VCS connection scope: %s %v", sql, args)}
	}
	tx.vcsChecks++
	return prConditionRow{value: tx.hasVCS, err: tx.vcsErr}
}

type prConditionRow struct {
	value bool
	err   error
}

func (r prConditionRow) Scan(dest ...any) error {
	if r.err != nil {
		return r.err
	}
	*dest[0].(*bool) = r.value
	return nil
}

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, head, "", "p1"} }
	// conflictRow describes a PR whose snapshot was fetched for snapshotHead
	// while the PR's current head is "head".
	conflictRow := func(state, snapshotHead, mergeable string) []any {
		return []any{int32(1), state, snapshotHead, "", "head", mergeable, "p1"}
	}
	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},
		{"checks verdict for an older head", "checks_finished", true, [][]any{{int32(1), "open", "old", "FAILURE", "head", "MERGEABLE", "p1"}}, errPRSnapshotPending, false},
		{"checks legacy row with empty head_sha", "checks_finished", true, [][]any{{int32(1), "open", "old", "SUCCESS", "", "MERGEABLE", "p1"}}, nil, true},
		{"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},
		{"conflicts unconfigured", "conflicts", false, [][]any{conflictRow("open", "head", "CONFLICTING")}, errPRSnapshotsUnavailable, false},
		{"conflicts unlinked", "conflicts", true, nil, errPRNotLinked, false},
		{"conflicts no snapshot", "conflicts", true, [][]any{conflictRow("open", "", "")}, errPRSnapshotPending, false},
		{"conflicts verdict for an older head", "conflicts", true, [][]any{conflictRow("open", "old", "CONFLICTING")}, errPRSnapshotPending, false},
		{"mergeable", "conflicts", true, [][]any{conflictRow("open", "head", "MERGEABLE")}, nil, false},
		{"mergeability unknown", "conflicts", true, [][]any{conflictRow("open", "head", "UNKNOWN")}, nil, false},
		{"conflicting", "conflicts", true, [][]any{conflictRow("open", "head", "CONFLICTING")}, nil, true},
		{"conflicting draft", "conflicts", true, [][]any{conflictRow("draft", "head", "CONFLICTING")}, nil, true},
		{"conflicting but closed", "conflicts", true, [][]any{conflictRow("closed", "head", "CONFLICTING")}, nil, false},
		{"conflicting but merged", "conflicts", true, [][]any{conflictRow("merged", "head", "CONFLICTING")}, nil, false},
		{"one conflicting PR", "conflicts", true, [][]any{conflictRow("open", "old", "MERGEABLE"), conflictRow("open", "head", "CONFLICTING")}, nil, true},
	} {
		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)
			}
		})
	}
}

// Without the snapshot client an unlinked checks rule is blocked by the
// missing client only when no self-hosted VCS PR could be linked instead;
// otherwise the missing link is what to fix. Conflicts need snapshots
// whichever PR is linked, so they keep the snapshot diagnostic.
func TestWakeupConditionPRUnlinkedDiagnostic(t *testing.T) {
	for _, event := range []string{"checks_finished", "conflicts", "merged"} {
		for _, available := range []bool{false, true} {
			for _, hasVCS := range []bool{false, true} {
				// merged needs no snapshots; only checks without the client
				// asks whether a VCS PR could be linked.
				wantErr, wantChecks := errPRNotLinked, 0
				switch {
				case event == "checks_finished" && !available:
					wantChecks = 1
					if !hasVCS {
						wantErr = errPRSnapshotsUnavailable
					}
				case event == "conflicts" && !available:
					wantErr = errPRSnapshotsUnavailable
				}
				t.Run(fmt.Sprintf("%s/snapshots=%t/vcs=%t", event, available, hasVCS), func(t *testing.T) {
					s := &IssueWakeupService{Tasks: &TaskService{PRSnapshotsEnabled: available}}
					w := db.IssueWakeup{IssueID: dbid.NewV7(), WorkspaceID: dbid.NewV7(), Condition: condition(t, map[string]any{"type": "pull_request", "event": event})}
					tx := &prConditionTx{issue: w.IssueID, workspace: w.WorkspaceID, hasVCS: hasVCS}
					met, _, _, err := s.evaluateCondition(context.Background(), tx, db.New(tx), w)
					if met || !errors.Is(err, wantErr) || tx.vcsChecks != wantChecks {
						t.Fatalf("met=%t err=%v connection lookups=%d; want unmet with %v and %d lookups", met, err, tx.vcsChecks, wantErr, wantChecks)
					}
				})
			}
		}
	}
	t.Run("lookup failure", func(t *testing.T) {
		s := &IssueWakeupService{Tasks: &TaskService{}}
		w := db.IssueWakeup{IssueID: dbid.NewV7(), WorkspaceID: dbid.NewV7(), Condition: condition(t, map[string]any{"type": "pull_request", "event": "checks_finished"})}
		lookupErr := errors.New("connection lookup failed")
		tx := &prConditionTx{issue: w.IssueID, workspace: w.WorkspaceID, vcsErr: lookupErr}
		_, _, _, err := s.evaluateCondition(context.Background(), tx, db.New(tx), w)
		if !errors.Is(err, lookupErr) || conditionDiagnostic(err) {
			t.Fatalf("err=%v; want the lookup failure, not a diagnostic", err)
		}
	})
}

func TestConditionNewlyMet(t *testing.T) {
	for _, tc := range []struct {
		previous, current string
		want              bool
	}{
		{"", "pr:a@1:conflicting", true},
		{"pr:a@1:conflicting", "pr:a@1:conflicting", false},
		{"pr:a@1:conflicting,b@1:conflicting", "pr:b@1:conflicting", false},
		{"pr:b@1:conflicting", "pr:a@1:conflicting,b@1:conflicting", true},
		{"pr:a@1:conflicting", "pr:a@2:conflicting", true},
		{"pr:1@h:SUCCESS,2@h:FAILURE", "pr:2@h:FAILURE", false},
		// Number-only keys repeat across repositories; a second one is news.
		{"pr:7", "pr:7,7", true},
		{"pr:7,7", "pr:7", false},
		{"pr:7,7", "pr:7,7", false},
		{"status:todo", "status:in_review", true},
		{"status:in_review", "status:in_review", false},
		{`property:{"a":1,"b":2}`, `property:{"a":1,"b":2}`, false},
		{"children:2", "children:3", true},
	} {
		if got := conditionNewlyMet(tc.previous, tc.current); got != tc.want {
			t.Errorf("conditionNewlyMet(%q, %q) = %t, want %t", tc.previous, tc.current, got, tc.want)
		}
	}
}

func TestWakeupConditionPRConflictsAcrossRecompute(t *testing.T) {
	ctx := context.Background()
	s := &IssueWakeupService{Tasks: &TaskService{PRSnapshotsEnabled: true}}
	w := db.IssueWakeup{ID: dbid.NewV7(), IssueID: dbid.NewV7(), Condition: condition(t, map[string]any{"type": "pull_request", "event": "conflicts"})}
	tx := &prConditionTx{issue: w.IssueID}
	q := db.New(tx)
	snapshot := func(head, mergeable string) [][]any {
		return [][]any{{int32(1), "open", head, "", head, mergeable, "p1"}}
	}
	for _, step := range []struct {
		name, previous string
		prs            [][]any
		wantMet        bool
		wantState      string
	}{
		{"conflict", "", snapshot("a", "CONFLICTING"), true, "pr:p1@a:conflicting"},
		{"recompute on the same head keeps it", "pr:p1@a:conflicting", snapshot("a", "UNKNOWN"), true, "pr:p1@a:conflicting"},
		{"resolved", "pr:p1@a:conflicting", snapshot("a", "MERGEABLE"), false, ""},
		{"recompute after resolving stays resolved", "", snapshot("a", "UNKNOWN"), false, ""},
		{"recompute on a new head starts over", "pr:p1@a:conflicting", snapshot("b", "UNKNOWN"), false, ""},
		{"new head still conflicting", "pr:p1@a:conflicting", snapshot("b", "CONFLICTING"), true, "pr:p1@b:conflicting"},
	} {
		t.Run(step.name, func(t *testing.T) {
			tx.prs = step.prs
			w.ConditionState = step.previous
			met, fingerprint, _, err := s.evaluateCondition(ctx, tx, q, w)
			if err != nil || met != step.wantMet || (met && fingerprint != step.wantState) {
				t.Fatalf("met=%t fingerprint=%q err=%v; want met=%t fingerprint=%q", met, fingerprint, err, step.wantMet, step.wantState)
			}
		})
	}
}

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", "", "", "head", "", "p1"}}, errPRSnapshotPending},
		{[][]any{{int32(1), "open", "head", "PENDING", "head", "MERGEABLE", "p1"}}, 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 TestSaveConditionDiagnosticReplacesEarlierFailures(t *testing.T) {
	ctx := context.Background()
	tx := &prConditionTx{}
	q := db.New(tx)
	realFailure := pgtype.Text{String: "dispatch failed", Valid: true}
	tx.lastError = realFailure
	w := db.IssueWakeup{ID: dbid.NewV7(), LastError: realFailure}

	if err := saveConditionDiagnostic(ctx, q, w, errPRNotLinked); err != nil {
		t.Fatal(err)
	}
	if tx.writes != 1 || tx.lastError.String != conditionDiagnosticPrefix+errPRNotLinked.Error() {
		t.Fatalf("recovered evaluation kept the earlier dispatch failure: writes=%d error=%+v", tx.writes, tx.lastError)
	}
	if err := saveConditionDiagnostic(ctx, q, w, nil); err != nil {
		t.Fatal(err)
	}
	if tx.writes != 2 || tx.lastError.Valid {
		t.Fatalf("recovered evaluation did not clear the earlier dispatch failure: 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 != 3 || 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 != 4 || tx.lastError.Valid {
		t.Fatalf("owned diagnostic was not cleared: writes=%d error=%+v", tx.writes, tx.lastError)
	}
}