diff --git a/changelog.d/fixed-18568-advisory-report-primary-only.md b/changelog.d/fixed-18568-advisory-report-primary-only.md new file mode 100644 index 0000000000..89ca386e04 --- /dev/null +++ b/changelog.d/fixed-18568-advisory-report-primary-only.md @@ -0,0 +1 @@ +- A multi-repo hive keeps exactly one `🐝 Hive Advisory Report`, in `project.primary_repo`. A candidate build had started opening an advisory report in every repo of `project.repos`, and posting the digest to each, so every monitored repo got its own report. The per-repo ensure and digest post are removed. The single report is still found by title and the `hive/advisory` label before anything is created, so a restart reuses it rather than filing a new one. Reports already opened in non-primary repos are not reopened by this build and can be closed ([#18568](https://github.com/hivecommons/hive/issues/18568)). diff --git a/src/cmd/hive/advisory_primary_only_test.go b/src/cmd/hive/advisory_primary_only_test.go new file mode 100644 index 0000000000..96396692cc --- /dev/null +++ b/src/cmd/hive/advisory_primary_only_test.go @@ -0,0 +1,240 @@ +package main + +import ( + "context" + "go/ast" + "go/parser" + "go/token" + "path/filepath" + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/config" +) + +// #18568: a hive keeps exactly ONE advisory report, in project.primary_repo. +// A candidate build ensured (and so created) a report in every repo of +// project.repos each eval cycle, opening one in every monitored repo of a +// multi-repo hive. These tests pin the primary-only rule at the cycle seam and +// guard the eval-cycle source against a per-repo fan-out coming back. + +func multiRepoAdvisoryConfig(primary string, repos ...string) *config.Config { + cfg := &config.Config{} + cfg.Project.Org = "hivecommons" + cfg.Project.PrimaryRepo = primary + cfg.Project.Repos = repos + return cfg +} + +// TestAdvisoryEnsure_MultiRepoHiveEnsuresOnlyThePrimary drives the eval +// cycle's ensure over several cycles of a multi-repo hive, and of a standalone +// hive whose primary is not listed first, and asserts only the primary repo is +// ever asked for an advisory issue. +func TestAdvisoryEnsure_MultiRepoHiveEnsuresOnlyThePrimary(t *testing.T) { + for _, tc := range []struct { + name string + cfg *config.Config + want string + }{ + { + name: "hive with many monitored repos", + cfg: multiRepoAdvisoryConfig("hive", "hive", "crux", "dibs", "docs", "pluk", "quorum"), + want: "hive", + }, + { + name: "standalone hive, primary listed after another repo", + cfg: multiRepoAdvisoryConfig("spyre-inference", "torch-spyre", "spyre-inference"), + want: "spyre-inference", + }, + } { + t.Run(tc.name, func(t *testing.T) { + var asked []string + deps := advisoryEnsureDeps{ + ensure: func(_ context.Context, repo string) (int, error) { + asked = append(asked, repo) + return 42, nil + }, + setenv: func(string, string) error { return nil }, + } + issues := map[string]int{} + const cycles = 5 + for i := 0; i < cycles; i++ { + if err := ensurePinnedAdvisoryIssue(context.Background(), issues, primaryAdvisoryRepo(tc.cfg), deps, nil); err != nil { + t.Fatalf("cycle %d: %v", i, err) + } + } + if len(asked) != 1 || asked[0] != tc.want { + t.Fatalf("ensure asked for %v, want exactly [%s] once", asked, tc.want) + } + if len(issues) != 1 || issues[tc.want] != 42 { + t.Fatalf("advisory issues = %v, want only %s", issues, tc.want) + } + }) + } +} + +// TestAdvisoryEnsure_RestartResolvesTheSameSingleReport models a restart as a +// fresh, empty advisoryIssues map against a forge that already holds the +// report: the restarted process asks once, for the primary only, and adopts +// the existing number. Creation idempotency itself (find by title and label +// before create) is pinned in pkg/github. +func TestAdvisoryEnsure_RestartResolvesTheSameSingleReport(t *testing.T) { + cfg := multiRepoAdvisoryConfig("hive", "hive", "crux", "dibs") + const existing = 2364 + forge := map[string]int{"hive": existing} + var asked []string + deps := advisoryEnsureDeps{ + ensure: func(_ context.Context, repo string) (int, error) { + asked = append(asked, repo) + return forge[repo], nil + }, + setenv: func(string, string) error { return nil }, + } + const restarts = 3 + for i := 0; i < restarts; i++ { + issues := map[string]int{} + if err := ensurePinnedAdvisoryIssue(context.Background(), issues, primaryAdvisoryRepo(cfg), deps, nil); err != nil { + t.Fatalf("restart %d: %v", i, err) + } + if len(issues) != 1 || issues["hive"] != existing { + t.Fatalf("restart %d: advisory issues = %v, want only hive=#%d", i, issues, existing) + } + } + for _, repo := range asked { + if repo != "hive" { + t.Fatalf("restart asked for an advisory issue in non-primary repo %q", repo) + } + } + if len(asked) != restarts { + t.Fatalf("ensure ran %d times over %d restarts, want once per restart", len(asked), restarts) + } +} + +// advisoryFanOutCalls are the calls that create or write an advisory report. +// None of them may run inside a loop in package main: the hive has one report +// repo, so iterating repos around any of them is the #18568 fan-out. +var advisoryFanOutCalls = map[string]bool{ + "EnsureAdvisoryIssue": true, + "PostAdvisoryDigest": true, + "ensurePinnedAdvisoryIssue": true, +} + +// TestAdvisoryWrites_NeverIssuedInsideALoop parses every non-test source file +// of package main and fails when an advisory ensure or digest post sits inside +// a for or range loop. +func TestAdvisoryWrites_NeverIssuedInsideALoop(t *testing.T) { + files, err := filepath.Glob("*.go") + if err != nil { + t.Fatalf("glob: %v", err) + } + fset := token.NewFileSet() + checked := 0 + for _, name := range files { + if strings.HasSuffix(name, "_test.go") { + continue + } + f, err := parser.ParseFile(fset, name, nil, parser.SkipObjectResolution) + if err != nil { + t.Fatalf("parse %s: %v", name, err) + } + checked++ + ast.Inspect(f, func(n ast.Node) bool { + var body *ast.BlockStmt + switch loop := n.(type) { + case *ast.RangeStmt: + body = loop.Body + case *ast.ForStmt: + body = loop.Body + default: + return true + } + ast.Inspect(body, func(inner ast.Node) bool { + call, ok := inner.(*ast.CallExpr) + if !ok { + return true + } + if fn := calledName(call.Fun); advisoryFanOutCalls[fn] { + t.Errorf("%s: %s called inside a loop; a hive has exactly one advisory report, in project.primary_repo (#18568)", + fset.Position(call.Pos()), fn) + } + return true + }) + return false + }) + } + if checked == 0 { + t.Fatal("no source files checked; the guard is not running") + } +} + +// advisoryWriterWiring is how many times each advisory writer may be wired as +// a value (not called directly) in package main. The eval cycle hands the +// client's EnsureAdvisoryIssue and PostAdvisoryDigest to its primary-repo +// seams exactly once each, and reads advisoryEnsureDepsForCycle.ensure only +// where it assigns it. The #18568 regression wired a second copy of each into +// a per-repo loop helper, which raised all of these counts to two. +var advisoryWriterWiring = map[string]int{ + "EnsureAdvisoryIssue": 1, + "PostAdvisoryDigest": 1, + "advisoryEnsureDepsForCycle.ensure": 1, +} + +// TestAdvisoryWriters_WiredOnceForThePrimaryOnly counts the value references +// above across every non-test source file of package main. +func TestAdvisoryWriters_WiredOnceForThePrimaryOnly(t *testing.T) { + files, err := filepath.Glob("*.go") + if err != nil { + t.Fatalf("glob: %v", err) + } + fset := token.NewFileSet() + got := map[string]int{} + for _, name := range files { + if strings.HasSuffix(name, "_test.go") { + continue + } + f, err := parser.ParseFile(fset, name, nil, parser.SkipObjectResolution) + if err != nil { + t.Fatalf("parse %s: %v", name, err) + } + called := map[ast.Expr]bool{} + ast.Inspect(f, func(n ast.Node) bool { + if call, ok := n.(*ast.CallExpr); ok { + called[call.Fun] = true + } + return true + }) + ast.Inspect(f, func(n ast.Node) bool { + sel, ok := n.(*ast.SelectorExpr) + if !ok { + return true + } + switch sel.Sel.Name { + case "EnsureAdvisoryIssue", "PostAdvisoryDigest": + if !called[sel] { + got[sel.Sel.Name]++ + } + case "ensure": + if x, isIdent := sel.X.(*ast.Ident); isIdent && x.Name == "advisoryEnsureDepsForCycle" { + got["advisoryEnsureDepsForCycle.ensure"]++ + } + } + return true + }) + } + for key, want := range advisoryWriterWiring { + if got[key] != want { + t.Errorf("%s wired %d times, want %d: a hive has exactly one advisory report, in project.primary_repo (#18568)", + key, got[key], want) + } + } +} + +func calledName(fun ast.Expr) string { + switch f := fun.(type) { + case *ast.Ident: + return f.Name + case *ast.SelectorExpr: + return f.Sel.Name + } + return "" +} diff --git a/src/cmd/hive/advisory_repo_issues.go b/src/cmd/hive/advisory_repo_issues.go deleted file mode 100644 index 2fa33d4995..0000000000 --- a/src/cmd/hive/advisory_repo_issues.go +++ /dev/null @@ -1,267 +0,0 @@ -package main - -import ( - "context" - "errors" - "fmt" - "log/slog" - "sync" - "time" - - "github.com/hivecommons/hive/pkg/advisory" - "github.com/hivecommons/hive/pkg/config" - "github.com/hivecommons/hive/pkg/github" -) - -// Multi-repo governor issues (#18448). Every repo in project.repos gets its own -// pinned advisory ("governor") issue, not just the primary. The primary keeps -// its long-standing path (boot ensure, ensurePinnedAdvisoryIssue, the -// hub-facing digest error and the App banner). The other repos are handled -// here, re-ensured every eval cycle while unresolved, so a repo added later in -// Settings gets its issue on the next cycle without a restart. Creation stays -// idempotent through EnsureAdvisoryIssue, which reuses an existing issue (open, -// or closed and reopened) found by title and label before it creates one. - -const ( - // advisoryRepoIssueAlertPrefix namespaces the per-repo dashboard alerts - // raised when a managed repo cannot hold a governor issue. - advisoryRepoIssueAlertPrefix = "advisory-repo-issue:" - // advisoryRepoIssueAlertSeverity is the dashboard severity of those - // alerts: the rest of the hive keeps working, so it is a warning. - advisoryRepoIssueAlertSeverity = "warning" - // advisoryRepoIssueRefusedBackoff is how long a repo whose ensure was - // refused for a reason retrying cannot fix (no write access, Issues - // disabled, repo moved or archived) waits before the next attempt, so a - // refused repo costs a few calls an hour rather than a few per cycle. - advisoryRepoIssueRefusedBackoff = time.Hour -) - -// advisoryRepoIssueAlerts is the dashboard surface for per-repo ensure -// refusals; *dashboard.Server satisfies it. -type advisoryRepoIssueAlerts interface { - AddSystemAlert(id, severity, message string) - ClearSystemAlertsExcept(prefix string, keep map[string]struct{}) -} - -// advisoryRepoIssueRefusal is one repo's most recent non-transient ensure -// refusal: when the next attempt is allowed, and the operator-facing message. -type advisoryRepoIssueRefusal struct { - retryAt time.Time - message string -} - -// advisoryRepoIssueBackoff remembers refused repos across eval cycles. -type advisoryRepoIssueBackoff struct { - mu sync.Mutex - refused map[string]advisoryRepoIssueRefusal -} - -func newAdvisoryRepoIssueBackoff() *advisoryRepoIssueBackoff { - return &advisoryRepoIssueBackoff{refused: map[string]advisoryRepoIssueRefusal{}} -} - -// advisoryRepoIssueGate is the process-wide backoff the eval cycle uses. -var advisoryRepoIssueGate = newAdvisoryRepoIssueBackoff() - -func (b *advisoryRepoIssueBackoff) get(repo string) (advisoryRepoIssueRefusal, bool) { - b.mu.Lock() - defer b.mu.Unlock() - r, ok := b.refused[repo] - return r, ok -} - -func (b *advisoryRepoIssueBackoff) set(repo string, r advisoryRepoIssueRefusal) { - b.mu.Lock() - defer b.mu.Unlock() - b.refused[repo] = r -} - -func (b *advisoryRepoIssueBackoff) clear(repo string) { - b.mu.Lock() - defer b.mu.Unlock() - delete(b.refused, repo) -} - -// advisorySecondaryRepos returns the managed repos other than the primary, -// whose governor issues this file owns. -func advisorySecondaryRepos(cfg *config.Config) []string { - repos := advisory.ManagedRepos(cfg) - if len(repos) <= 1 { - return nil - } - return repos[1:] -} - -// advisoryRepoIssueRefusalMessage reports whether err is a refusal retrying -// cannot fix and, if so, the operator-facing alert text naming repo and the -// remedy. A rate limit, 5xx or network error returns ok=false: the next cycle -// simply retries. -func advisoryRepoIssueRefusalMessage(repo string, err error) (string, bool) { - var disabled *github.IssuesDisabledError - if errors.As(err, &disabled) { - return fmt.Sprintf("No governor issue in %s: %s.", repo, disabled.Error()), true - } - var moved *github.RepoMovedError - if errors.As(err, &moved) { - return fmt.Sprintf("No governor issue in %s: %s.", repo, moved.Error()), true - } - switch classifyAdvisoryPostError(err) { - case advisoryPostWriteForbidden: - return fmt.Sprintf("No governor issue in %s: the hive's GitHub App cannot create issues there. Add the repository to the App installation and grant Issues read and write; the hive retries automatically.", repo), true - case advisoryPostRepoArchived: - return fmt.Sprintf("No governor issue in %s: the repository is archived and read-only.", repo), true - } - return "", false -} - -// ensureSecondaryAdvisoryIssues resolves (creating when missing) the governor -// issue of every non-primary managed repo that has none yet, recording each -// number in advisoryIssues under the repo's configured spelling. -// -// One repo's failure never stops the others. A refusal retrying cannot fix is -// logged, raised as a per-repo dashboard alert and backed off for -// advisoryRepoIssueRefusedBackoff; a transient failure is logged and retried -// next cycle. Alerts for repos that resolved or left project.repos are cleared. -// A paused repo is skipped quietly: the pause is the operator's choice. -// -// The returned map holds this cycle's ensure error per repo (nil-free), for -// tests and logging; callers need not act on it. -func ensureSecondaryAdvisoryIssues( - ctx context.Context, - advisoryIssues map[string]int, - repos []string, - ensure func(ctx context.Context, repo string) (int, error), - gate *advisoryRepoIssueBackoff, - alerts advisoryRepoIssueAlerts, - now time.Time, - logger *slog.Logger, -) map[string]error { - if logger == nil { - logger = slog.Default() - } - errs := map[string]error{} - keep := map[string]struct{}{} - defer func() { - if alerts != nil { - alerts.ClearSystemAlertsExcept(advisoryRepoIssueAlertPrefix, keep) - } - }() - if ensure == nil || advisoryIssues == nil { - return errs - } - for _, repo := range repos { - if !advisoryIssueUnresolved(advisoryIssues, repo) { - gate.clear(repo) - continue - } - if r, ok := gate.get(repo); ok && now.Before(r.retryAt) { - if r.message != "" { - keep[advisoryRepoIssueAlertPrefix+repo] = struct{}{} - } - continue - } - num, err := ensure(ctx, repo) - if err == nil && num > 0 { - advisoryIssues[repo] = num - gate.clear(repo) - logger.Info("governor issue ready", "repo", repo, "number", num) - continue - } - if err == nil { - err = fmt.Errorf("governor issue for %s did not resolve to an issue number", repo) - } - errs[repo] = err - var paused *github.RepoPausedError - if errors.As(err, &paused) { - gate.set(repo, advisoryRepoIssueRefusal{retryAt: now.Add(advisoryRepoIssueRefusedBackoff)}) - logger.Info("governor issue not ensured: repo paused", "repo", repo) - continue - } - if msg, refused := advisoryRepoIssueRefusalMessage(repo, err); refused { - gate.set(repo, advisoryRepoIssueRefusal{retryAt: now.Add(advisoryRepoIssueRefusedBackoff), message: msg}) - keep[advisoryRepoIssueAlertPrefix+repo] = struct{}{} - if alerts != nil { - alerts.AddSystemAlert(advisoryRepoIssueAlertPrefix+repo, advisoryRepoIssueAlertSeverity, msg) - } - logger.Warn("governor issue refused for repo; retrying later", - "repo", repo, "retry_after", advisoryRepoIssueRefusedBackoff.String(), "error", err) - continue - } - // Transient: keep any alert a refusal raised until a real answer. - if r, ok := gate.get(repo); ok && r.message != "" { - keep[advisoryRepoIssueAlertPrefix+repo] = struct{}{} - } - logger.Warn("governor issue still unresolved for repo; retrying next cycle", "repo", repo, "error", err) - } - return errs -} - -// advisorySecondaryPostDeps are the effects postAdvisoryDigestToSecondaryRepos -// performs; the eval cycle wires them to the GitHub client and post gate. -type advisorySecondaryPostDeps struct { - post func(ctx context.Context, repo string, issueNum int, md string) error - due func(repo string) bool - recordSuccess func(repo string) - // recordForbidden pauses further post attempts for repo after a - // non-transient 403. - recordForbidden func(repo string) -} - -// postAdvisoryDigestToSecondaryRepos writes the rendered digest to the -// governor issue of every non-primary repo that has one, paced per repo by the -// same post gate as the primary. Failures are logged per repo and never touch -// the primary's hub-facing digest error or the App banner, which describe the -// primary repo. It returns the repos posted to. -func postAdvisoryDigestToSecondaryRepos( - ctx context.Context, - md string, - advisoryIssues map[string]int, - repos []string, - deps advisorySecondaryPostDeps, - logger *slog.Logger, -) []string { - if md == "" || deps.post == nil { - return nil - } - if logger == nil { - logger = slog.Default() - } - var posted []string - for _, repo := range repos { - num, ok := advisoryIssueNumber(advisoryIssues, repo) - if !ok { - continue - } - if _, archived := archivedAdvisoryRepos.Load(repo); archived { - continue - } - if deps.due != nil && !deps.due(repo) { - continue - } - err := deps.post(ctx, repo, num, md) - var paused *github.RepoPausedError - switch { - case err == nil: - posted = append(posted, repo) - if deps.recordSuccess != nil { - deps.recordSuccess(repo) - } - logger.Info("posted advisory digest", "repo", repo, "issue", num, "via", "app") - case errors.As(err, &paused): - if deps.recordSuccess != nil { - deps.recordSuccess(repo) - } - case classifyAdvisoryPostError(err) == advisoryPostRepoArchived: - archivedAdvisoryRepos.Store(repo, struct{}{}) - logger.Warn("advisory repo is archived and read-only, skipping digest posts", "repo", repo) - case classifyAdvisoryPostError(err) == advisoryPostWriteForbidden: - if deps.recordForbidden != nil { - deps.recordForbidden(repo) - } - logger.Warn("advisory digest write forbidden for repo", "repo", repo, "issue", num, "error", err) - default: - logger.Warn("failed to post advisory digest to repo", "repo", repo, "issue", num, "error", err) - } - } - return posted -} diff --git a/src/cmd/hive/advisory_repo_issues_test.go b/src/cmd/hive/advisory_repo_issues_test.go deleted file mode 100644 index cb72549ae6..0000000000 --- a/src/cmd/hive/advisory_repo_issues_test.go +++ /dev/null @@ -1,279 +0,0 @@ -package main - -import ( - "context" - "errors" - "fmt" - "strings" - "testing" - "time" - - "github.com/hivecommons/hive/pkg/config" - "github.com/hivecommons/hive/pkg/github" -) - -// fakeRepoIssueAlerts records the per-repo governor-issue alerts. -type fakeRepoIssueAlerts struct { - alerts map[string]string -} - -func newFakeRepoIssueAlerts() *fakeRepoIssueAlerts { - return &fakeRepoIssueAlerts{alerts: map[string]string{}} -} - -func (f *fakeRepoIssueAlerts) AddSystemAlert(id, severity, message string) { - f.alerts[id] = severity + ": " + message -} - -func (f *fakeRepoIssueAlerts) ClearSystemAlertsExcept(prefix string, keep map[string]struct{}) { - for id := range f.alerts { - if !strings.HasPrefix(id, prefix) { - continue - } - if _, ok := keep[id]; !ok { - delete(f.alerts, id) - } - } -} - -// fakeGovernorForge stands in for GitHub: one governor issue per repo, found -// by EnsureAdvisoryIssue's search before it creates, as the real client does. -type fakeGovernorForge struct { - existing map[string]int // repo -> governor issue already on GitHub - refuse map[string]error // repo -> error every ensure returns - creates map[string]int // repo -> issues created - calls map[string]int // repo -> ensure calls - next int -} - -func newFakeGovernorForge() *fakeGovernorForge { - return &fakeGovernorForge{existing: map[string]int{}, refuse: map[string]error{}, creates: map[string]int{}, calls: map[string]int{}, next: 100} -} - -func (f *fakeGovernorForge) ensure(_ context.Context, repo string) (int, error) { - f.calls[repo]++ - if err := f.refuse[repo]; err != nil { - return 0, err - } - if n, ok := f.existing[repo]; ok { - return n, nil - } - f.next++ - f.existing[repo] = f.next - f.creates[repo]++ - return f.next, nil -} - -func multiRepoConfig(repos ...string) *config.Config { - cfg := &config.Config{} - cfg.Project.Org = "nate" - cfg.Project.Repos = repos - return cfg -} - -func TestAdvisorySecondaryRepos_AllButPrimaryDeduped(t *testing.T) { - cfg := multiRepoConfig("pr-pal", "talks", "nate/Talks", "other/notes") - got := advisorySecondaryRepos(cfg) - want := []string{"talks", "other/notes"} - if fmt.Sprint(got) != fmt.Sprint(want) { - t.Fatalf("secondary repos = %v, want %v", got, want) - } - if got := advisorySecondaryRepos(multiRepoConfig("only")); got != nil { - t.Fatalf("single-repo hive has no secondary repos, got %v", got) - } - cfg.Project.PrimaryRepo = "talks" - if got := advisorySecondaryRepos(cfg); fmt.Sprint(got) != fmt.Sprint([]string{"pr-pal", "other/notes"}) { - t.Fatalf("explicit primary must be excluded, got %v", got) - } -} - -// TestEnsureSecondaryAdvisoryIssues_EveryRepoGetsOne is #18448: a two-repo hive -// must end with a governor issue in BOTH repos, numbers stored per repo. -func TestEnsureSecondaryAdvisoryIssues_EveryRepoGetsOne(t *testing.T) { - cfg := multiRepoConfig("pr-pal", "talks", "slides") - forge := newFakeGovernorForge() - forge.existing["pr-pal"] = 9 // the primary, ensured at boot - issues := map[string]int{"pr-pal": 9} - - errs := ensureSecondaryAdvisoryIssues(context.Background(), issues, advisorySecondaryRepos(cfg), - forge.ensure, newAdvisoryRepoIssueBackoff(), newFakeRepoIssueAlerts(), time.Now(), nil) - if len(errs) != 0 { - t.Fatalf("unexpected errors: %v", errs) - } - for _, repo := range []string{"pr-pal", "talks", "slides"} { - if n, ok := issues[repo]; !ok || n <= 0 { - t.Fatalf("repo %s has no governor issue: %v", repo, issues) - } - } - if issues["talks"] == issues["slides"] { - t.Fatalf("each repo needs its own issue number, got %v", issues) - } - if forge.calls["pr-pal"] != 0 { - t.Fatalf("primary is owned by the primary path, ensured %d times here", forge.calls["pr-pal"]) - } -} - -// TestEnsureSecondaryAdvisoryIssues_IdempotentAcrossCyclesAndRestart: a resolved -// repo costs no call on later cycles, and a restart (empty map) reuses the -// existing issue instead of creating a duplicate. -func TestEnsureSecondaryAdvisoryIssues_IdempotentAcrossCyclesAndRestart(t *testing.T) { - repos := []string{"talks"} - forge := newFakeGovernorForge() - issues := map[string]int{} - gate := newAdvisoryRepoIssueBackoff() - now := time.Now() - - for cycle := 0; cycle < 3; cycle++ { - ensureSecondaryAdvisoryIssues(context.Background(), issues, repos, forge.ensure, gate, nil, now, nil) - } - if forge.calls["talks"] != 1 { - t.Fatalf("resolved repo re-ensured: %d calls, want 1", forge.calls["talks"]) - } - first := issues["talks"] - - restarted := map[string]int{} - ensureSecondaryAdvisoryIssues(context.Background(), restarted, repos, forge.ensure, newAdvisoryRepoIssueBackoff(), nil, now, nil) - if restarted["talks"] != first { - t.Fatalf("restart resolved #%d, want existing #%d", restarted["talks"], first) - } - if forge.creates["talks"] != 1 { - t.Fatalf("restart created a duplicate: %d creates", forge.creates["talks"]) - } -} - -// TestEnsureSecondaryAdvisoryIssues_RepoAddedLater: a repo added in Settings -// after boot gets its issue on the next cycle, with no restart. -func TestEnsureSecondaryAdvisoryIssues_RepoAddedLater(t *testing.T) { - cfg := multiRepoConfig("pr-pal") - forge := newFakeGovernorForge() - issues := map[string]int{"pr-pal": 9} - gate := newAdvisoryRepoIssueBackoff() - now := time.Now() - - ensureSecondaryAdvisoryIssues(context.Background(), issues, advisorySecondaryRepos(cfg), forge.ensure, gate, nil, now, nil) - if len(issues) != 1 { - t.Fatalf("single-repo hive touched other repos: %v", issues) - } - cfg.Project.Repos = append(cfg.Project.Repos, "talks") - ensureSecondaryAdvisoryIssues(context.Background(), issues, advisorySecondaryRepos(cfg), forge.ensure, gate, nil, now.Add(time.Minute), nil) - if _, ok := advisoryIssueNumber(issues, "talks"); !ok { - t.Fatalf("repo added later got no governor issue: %v", issues) - } -} - -// TestEnsureSecondaryAdvisoryIssues_NoWriteAccess: a repo the App cannot write -// is logged, surfaced as a per-repo alert and backed off, without stopping the -// other repos; once access is granted the alert clears. -func TestEnsureSecondaryAdvisoryIssues_NoWriteAccess(t *testing.T) { - repos := []string{"talks", "slides"} - forge := newFakeGovernorForge() - forge.refuse["talks"] = errors.New("creating advisory issue: POST https://api.github.com/repos/nate/talks/issues: 403 Resource not accessible by integration []") - issues := map[string]int{} - gate := newAdvisoryRepoIssueBackoff() - alerts := newFakeRepoIssueAlerts() - now := time.Now() - - errs := ensureSecondaryAdvisoryIssues(context.Background(), issues, repos, forge.ensure, gate, alerts, now, nil) - if errs["talks"] == nil { - t.Fatal("refused repo must report its error") - } - if _, ok := advisoryIssueNumber(issues, "slides"); !ok { - t.Fatalf("a refused repo must not block the others: %v", issues) - } - alert, ok := alerts.alerts[advisoryRepoIssueAlertPrefix+"talks"] - if !ok || !strings.Contains(alert, "talks") || !strings.HasPrefix(alert, advisoryRepoIssueAlertSeverity) { - t.Fatalf("no-write-access repo not surfaced: %v", alerts.alerts) - } - - // Inside the backoff: no new call, alert kept. - ensureSecondaryAdvisoryIssues(context.Background(), issues, repos, forge.ensure, gate, alerts, now.Add(time.Minute), nil) - if forge.calls["talks"] != 1 { - t.Fatalf("refused repo retried inside backoff: %d calls", forge.calls["talks"]) - } - if _, ok := alerts.alerts[advisoryRepoIssueAlertPrefix+"talks"]; !ok { - t.Fatal("alert dropped while the repo is still refused") - } - - // Access granted: the retry after the backoff resolves and clears it. - delete(forge.refuse, "talks") - ensureSecondaryAdvisoryIssues(context.Background(), issues, repos, forge.ensure, gate, alerts, now.Add(advisoryRepoIssueRefusedBackoff+time.Minute), nil) - if _, ok := advisoryIssueNumber(issues, "talks"); !ok { - t.Fatalf("repo not resolved after access granted: %v", issues) - } - if len(alerts.alerts) != 0 { - t.Fatalf("alert not cleared after the repo resolved: %v", alerts.alerts) - } -} - -func TestEnsureSecondaryAdvisoryIssues_TransientRetriesNextCycleWithoutAlert(t *testing.T) { - forge := newFakeGovernorForge() - forge.refuse["talks"] = errors.New("searching for advisory issue: 502 Bad Gateway") - issues := map[string]int{} - gate := newAdvisoryRepoIssueBackoff() - alerts := newFakeRepoIssueAlerts() - now := time.Now() - - ensureSecondaryAdvisoryIssues(context.Background(), issues, []string{"talks"}, forge.ensure, gate, alerts, now, nil) - ensureSecondaryAdvisoryIssues(context.Background(), issues, []string{"talks"}, forge.ensure, gate, alerts, now.Add(time.Minute), nil) - if forge.calls["talks"] != 2 { - t.Fatalf("transient failure must retry every cycle: %d calls", forge.calls["talks"]) - } - if len(alerts.alerts) != 0 { - t.Fatalf("transient failure raised an alert: %v", alerts.alerts) - } -} - -func TestEnsureSecondaryAdvisoryIssues_IssuesDisabledAndPaused(t *testing.T) { - forge := newFakeGovernorForge() - forge.refuse["fork"] = fmt.Errorf("ensure: %w", &github.IssuesDisabledError{Repo: "nate/fork", Fork: true}) - forge.refuse["held"] = &github.RepoPausedError{Repo: "nate/held"} - alerts := newFakeRepoIssueAlerts() - - ensureSecondaryAdvisoryIssues(context.Background(), map[string]int{}, []string{"fork", "held"}, forge.ensure, newAdvisoryRepoIssueBackoff(), alerts, time.Now(), nil) - if _, ok := alerts.alerts[advisoryRepoIssueAlertPrefix+"fork"]; !ok { - t.Fatalf("Issues-disabled repo not surfaced: %v", alerts.alerts) - } - if _, ok := alerts.alerts[advisoryRepoIssueAlertPrefix+"held"]; ok { - t.Fatal("a paused repo is the operator's choice, not an alert") - } -} - -func TestEnsureSecondaryAdvisoryIssues_RemovedRepoAlertCleared(t *testing.T) { - alerts := newFakeRepoIssueAlerts() - alerts.AddSystemAlert(advisoryRepoIssueAlertPrefix+"gone", advisoryRepoIssueAlertSeverity, "stale") - alerts.AddSystemAlert("unrelated", "error", "kept") - ensureSecondaryAdvisoryIssues(context.Background(), map[string]int{}, nil, newFakeGovernorForge().ensure, newAdvisoryRepoIssueBackoff(), alerts, time.Now(), nil) - if _, ok := alerts.alerts[advisoryRepoIssueAlertPrefix+"gone"]; ok { - t.Fatal("alert for a repo no longer managed was not cleared") - } - if _, ok := alerts.alerts["unrelated"]; !ok { - t.Fatal("cleared an alert outside the governor-issue prefix") - } -} - -func TestPostAdvisoryDigestToSecondaryRepos(t *testing.T) { - issues := map[string]int{"talks": 3, "slides": 4, "locked": 5} - var posts []string - var forbidden []string - deps := advisorySecondaryPostDeps{ - post: func(_ context.Context, repo string, n int, md string) error { - if repo == "locked" { - return errors.New("403 Resource not accessible by integration") - } - posts = append(posts, fmt.Sprintf("%s#%d", repo, n)) - return nil - }, - due: func(repo string) bool { return repo != "slides" }, - recordForbidden: func(repo string) { forbidden = append(forbidden, repo) }, - } - got := postAdvisoryDigestToSecondaryRepos(context.Background(), "digest", issues, []string{"talks", "slides", "locked", "unresolved"}, deps, nil) - if fmt.Sprint(got) != "[talks]" || fmt.Sprint(posts) != "[talks#3]" { - t.Fatalf("posted = %v (%v), want only talks#3", got, posts) - } - if fmt.Sprint(forbidden) != "[locked]" { - t.Fatalf("forbidden = %v, want [locked]", forbidden) - } - if got := postAdvisoryDigestToSecondaryRepos(context.Background(), "", issues, []string{"talks"}, deps, nil); got != nil { - t.Fatalf("empty digest posted: %v", got) - } -} diff --git a/src/cmd/hive/main_eval_cycle.go b/src/cmd/hive/main_eval_cycle.go index 114c130ba9..947db290a7 100644 --- a/src/cmd/hive/main_eval_cycle.go +++ b/src/cmd/hive/main_eval_cycle.go @@ -550,14 +550,9 @@ func runEvalCycle( if !budgetDecision.SkipOptional { advisoryEnsureErr = ensurePinnedAdvisoryIssue( ctx, advisoryIssues, primaryRepoAtCycleStart, advisoryEnsureDepsForCycle, logger) - // Every other managed repo gets its own governor issue too (#18448), - // including repos added in Settings after boot. - var repoIssueAlerts advisoryRepoIssueAlerts - if dashSrv != nil { - repoIssueAlerts = dashSrv - } - ensureSecondaryAdvisoryIssues(ctx, advisoryIssues, advisorySecondaryRepos(cfg), - advisoryEnsureDepsForCycle.ensure, advisoryRepoIssueGate, repoIssueAlerts, time.Now(), logger) + // Exactly one advisory report per hive, in the primary repo (#18568). + // No other managed repo is ever ensured: a hive that opened a report + // in every repo of project.repos spammed each of them. } var actionable *github.ActionableResult @@ -1621,22 +1616,6 @@ func runEvalCycle( } }, }, logger) - // The same digest goes to every other managed repo's governor - // issue (#18448), paced per repo by the post gate. - if advisoryTarget == config.AdvisoryTargetGitHub { - postAdvisoryDigestToSecondaryRepos(ctx, md, advisoryIssues, advisorySecondaryRepos(cfg), advisorySecondaryPostDeps{ - post: ghClient.PostAdvisoryDigest, - due: func(repo string) bool { - return advisoryPostDue(advCfg, repo, time.Now(), logger) - }, - recordSuccess: func(repo string) { - recordAdvisoryPostSuccess(repo, time.Now()) - }, - recordForbidden: func(repo string) { - recordAdvisoryPostForbidden(repo, time.Now(), advCfg.PostRetryBackoff()) - }, - }, logger) - } } } else if d := dashSrv.GetAdvisoryDigest(); d != nil { statusPayload.AdvisoryDigest = d diff --git a/src/docs/advisory.md b/src/docs/advisory.md index 1eaec0145c..14276293d9 100644 --- a/src/docs/advisory.md +++ b/src/docs/advisory.md @@ -6,14 +6,12 @@ open advisory beads of every agent into a single **advisory digest** and posts i as a pinned comment on the advisory issue of the primary repo, rewriting the same comment each cycle so a repo owner has exactly one place to look. -A hive that manages several repos keeps one advisory (governor) issue in -**each** repo in `project.repos`, and posts the same digest to each of them. -The other repos are ensured on every eval cycle until they have an issue, so a -repo added in Settings gets one without a restart. An existing issue is reused, -never duplicated, across restarts. When the hive cannot create the issue in a -repo (the GitHub App lacks write access there, Issues are disabled, or the repo -moved or was archived), the dashboard shows a warning naming that repo and the -hive retries hourly; the other repos are not affected. +A hive that manages several repos still keeps exactly **one** advisory report, +in `project.primary_repo` (or the first repo in `project.repos` when no primary +is set). No other repo in `project.repos` ever gets an advisory issue or a digest +comment. The report is found by its title and the `hive/advisory` label before +anything is created, so a restart reuses the open report instead of filing a new +one ([#18568](https://github.com/hivecommons/hive/issues/18568)). Everything on this page lives under `governor.advisory` in `hive.yaml`, and every setting is also editable from **Governor Config → Advisory** in the dashboard diff --git a/src/pkg/advisory/policy.go b/src/pkg/advisory/policy.go index 391627195c..c266eaf7a8 100644 --- a/src/pkg/advisory/policy.go +++ b/src/pkg/advisory/policy.go @@ -30,7 +30,6 @@ package advisory import ( "log/slog" - "strings" "sync" "time" @@ -55,43 +54,6 @@ func PrimaryRepo(cfg *config.Config) string { return "" } -// ManagedRepos returns every repo the hive manages, each of which carries its -// own governor (advisory) issue (#18448): PrimaryRepo first, then the rest of -// project.repos in configured order. An entry naming the same repository as an -// earlier one, bare ("talks") or org-qualified ("org/talks") and in any case, -// is dropped so one repository never gets two ensure attempts in a cycle. The -// spelling kept is the first one seen, because callers key advisoryIssues and -// the post gate by that exact string. -func ManagedRepos(cfg *config.Config) []string { - if cfg == nil { - return nil - } - org := strings.TrimSpace(cfg.Project.Org) - seen := make(map[string]struct{}, len(cfg.Project.Repos)+1) - out := make([]string, 0, len(cfg.Project.Repos)+1) - add := func(repo string) { - repo = strings.TrimSpace(repo) - if repo == "" { - return - } - key := repo - if !strings.Contains(key, "/") && org != "" { - key = org + "/" + key - } - key = strings.ToLower(key) - if _, dup := seen[key]; dup { - return - } - seen[key] = struct{}{} - out = append(out, repo) - } - add(PrimaryRepo(cfg)) - for _, r := range cfg.Project.Repos { - add(r) - } - return out -} - // IssueUnresolved reports whether the pinned advisory issue for repo is still // unknown, i.e. the digest has nowhere to go. A recorded 0 counts as // unresolved: it is the zero value a failed ensure would leave behind, and diff --git a/src/pkg/advisory/policy_managed_repos_test.go b/src/pkg/advisory/policy_managed_repos_test.go deleted file mode 100644 index 7220a599ab..0000000000 --- a/src/pkg/advisory/policy_managed_repos_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package advisory - -import ( - "fmt" - "testing" - - "github.com/hivecommons/hive/pkg/config" -) - -// TestManagedRepos pins #18448: every project repo is managed, primary first, -// and one repository spelled two ways is listed once under its first spelling. -func TestManagedRepos(t *testing.T) { - if got := ManagedRepos(nil); got != nil { - t.Fatalf("nil config = %v, want nil", got) - } - cfg := &config.Config{} - cfg.Project.Org = "nate" - cfg.Project.Repos = []string{"pr-pal", "talks", " NATE/talks ", "", "other/talks"} - if got, want := fmt.Sprint(ManagedRepos(cfg)), "[pr-pal talks other/talks]"; got != want { - t.Fatalf("ManagedRepos = %s, want %s", got, want) - } - cfg.Project.PrimaryRepo = "nate/talks" - if got, want := fmt.Sprint(ManagedRepos(cfg)), "[nate/talks pr-pal other/talks]"; got != want { - t.Fatalf("ManagedRepos with primary = %s, want %s", got, want) - } -} diff --git a/src/pkg/advisory/policy_primary_only_test.go b/src/pkg/advisory/policy_primary_only_test.go new file mode 100644 index 0000000000..a0435d0059 --- /dev/null +++ b/src/pkg/advisory/policy_primary_only_test.go @@ -0,0 +1,41 @@ +package advisory + +import ( + "testing" + + "github.com/hivecommons/hive/pkg/config" +) + +// TestPrimaryRepo_MultiRepoConfigNamesOnlyThePrimary pins #18568: a hive that +// manages several repos still has exactly one advisory report repo. The +// configured primary wins over every entry in project.repos, wherever it is +// listed, and with no primary configured the first listed repo is the single +// fallback. No configuration yields more than one repo. +func TestPrimaryRepo_MultiRepoConfigNamesOnlyThePrimary(t *testing.T) { + for _, tc := range []struct { + name string + primary string + repos []string + want string + }{ + {name: "primary listed first", primary: "hive", repos: []string{"hive", "crux", "dibs", "docs"}, want: "hive"}, + {name: "primary listed last", primary: "hive", repos: []string{"crux", "dibs", "hive"}, want: "hive"}, + {name: "primary not listed", primary: "hive", repos: []string{"crux", "dibs"}, want: "hive"}, + {name: "org-qualified primary", primary: "hivecommons/hive", repos: []string{"crux", "hive"}, want: "hivecommons/hive"}, + {name: "no primary falls back to first repo only", repos: []string{"spyre-inference", "torch-spyre"}, want: "spyre-inference"}, + {name: "nothing configured", want: ""}, + } { + t.Run(tc.name, func(t *testing.T) { + cfg := &config.Config{} + cfg.Project.Org = "hivecommons" + cfg.Project.PrimaryRepo = tc.primary + cfg.Project.Repos = tc.repos + if got := PrimaryRepo(cfg); got != tc.want { + t.Fatalf("PrimaryRepo = %q, want %q", got, tc.want) + } + }) + } + if got := PrimaryRepo(nil); got != "" { + t.Fatalf("PrimaryRepo(nil) = %q, want empty", got) + } +} diff --git a/src/pkg/github/advisory_multi_repo_test.go b/src/pkg/github/advisory_multi_repo_test.go deleted file mode 100644 index 54d7c3fe5c..0000000000 --- a/src/pkg/github/advisory_multi_repo_test.go +++ /dev/null @@ -1,99 +0,0 @@ -package github - -import ( - "context" - "encoding/json" - "net/http" - "net/http/httptest" - "strings" - "sync" - "testing" -) - -// multiRepoAdvisoryForge is a stateful fake GitHub holding the issues of -// several repos, so EnsureAdvisoryIssue's search-before-create runs against -// what earlier calls (or an earlier process) created. -type multiRepoAdvisoryForge struct { - mu sync.Mutex - issues map[string][]map[string]any // "owner/repo" -> issues - creates map[string]int - next int -} - -func (f *multiRepoAdvisoryForge) handler(t *testing.T) http.Handler { - mux := http.NewServeMux() - mux.HandleFunc("/search/issues", func(w http.ResponseWriter, r *http.Request) { - f.mu.Lock() - defer f.mu.Unlock() - var items []map[string]any - for _, field := range strings.Fields(r.URL.Query().Get("q")) { - if full, ok := strings.CutPrefix(field, "repo:"); ok { - items = f.issues[full] - } - } - if items == nil { - items = []map[string]any{} - } - _ = json.NewEncoder(w).Encode(map[string]any{"total_count": len(items), "items": items}) - }) - mux.HandleFunc("/repos/{owner}/{repo}/issues", func(w http.ResponseWriter, r *http.Request) { - f.mu.Lock() - defer f.mu.Unlock() - full := r.PathValue("owner") + "/" + r.PathValue("repo") - if r.Method == http.MethodPost { - f.next++ - issue := map[string]any{"number": f.next, "title": advisoryTitle, "state": "open"} - f.issues[full] = append(f.issues[full], issue) - f.creates[full]++ - w.WriteHeader(http.StatusCreated) - _ = json.NewEncoder(w).Encode(issue) - return - } - _ = json.NewEncoder(w).Encode([]map[string]any{}) - }) - mux.HandleFunc("/repos/{owner}/{repo}/labels", func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusCreated) - _ = json.NewEncoder(w).Encode(map[string]any{"name": advisoryLabelName}) - }) - return mux -} - -// TestEnsureAdvisoryIssue_OnePerRepoAndReusedAfterRestart is #18448 at the -// client: two repos each get their own governor issue, and a fresh client -// (a restart) finds both instead of creating duplicates. -func TestEnsureAdvisoryIssue_OnePerRepoAndReusedAfterRestart(t *testing.T) { - forge := &multiRepoAdvisoryForge{issues: map[string][]map[string]any{}, creates: map[string]int{}} - server := httptest.NewServer(forge.handler(t)) - defer server.Close() - - const org = "nate" - repos := []string{"pr-pal", "talks"} - first := map[string]int{} - c := newTestClient(t, server, org, repos) - for _, repo := range repos { - n, err := c.EnsureAdvisoryIssue(context.Background(), repo) - if err != nil { - t.Fatalf("EnsureAdvisoryIssue(%s): %v", repo, err) - } - first[repo] = n - } - if first["pr-pal"] <= 0 || first["talks"] <= 0 || first["pr-pal"] == first["talks"] { - t.Fatalf("each repo needs its own governor issue, got %v", first) - } - - restarted := newTestClient(t, server, org, repos) - for _, repo := range repos { - n, err := restarted.EnsureAdvisoryIssue(context.Background(), repo) - if err != nil { - t.Fatalf("EnsureAdvisoryIssue(%s) after restart: %v", repo, err) - } - if n != first[repo] { - t.Fatalf("%s after restart resolved #%d, want existing #%d", repo, n, first[repo]) - } - } - for _, repo := range repos { - if got := forge.creates[org+"/"+repo]; got != 1 { - t.Fatalf("%s: %d governor issues created, want exactly 1", repo, got) - } - } -} diff --git a/src/pkg/github/advisory_restart_idempotent_test.go b/src/pkg/github/advisory_restart_idempotent_test.go new file mode 100644 index 0000000000..e5f8f99ad4 --- /dev/null +++ b/src/pkg/github/advisory_restart_idempotent_test.go @@ -0,0 +1,172 @@ +package github + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" +) + +// advisoryRestartForge is a stateful fake GitHub for one hive's repos. It +// serves pre-existing issues through search and list, counts every create +// (POST) and every edit (PATCH) per repo, and appends created issues so a +// later client sees them. +type advisoryRestartForge struct { + mu sync.Mutex + issues map[string][]map[string]any // "owner/repo" -> issues + creates map[string]int + edits map[string]int + next int +} + +func newAdvisoryRestartForge() *advisoryRestartForge { + return &advisoryRestartForge{ + issues: map[string][]map[string]any{}, + creates: map[string]int{}, + edits: map[string]int{}, + next: 1000, + } +} + +func (f *advisoryRestartForge) seed(full string, number int, title string) { + f.issues[full] = append(f.issues[full], map[string]any{ + "number": number, + "title": title, + "state": "open", + "labels": []map[string]any{{"name": advisoryLabelName}}, + }) +} + +func (f *advisoryRestartForge) handler() http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("/search/issues", func(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + defer f.mu.Unlock() + items := []map[string]any{} + for _, field := range strings.Fields(r.URL.Query().Get("q")) { + if full, ok := strings.CutPrefix(field, "repo:"); ok && f.issues[full] != nil { + items = f.issues[full] + } + } + _ = json.NewEncoder(w).Encode(map[string]any{"total_count": len(items), "items": items}) + }) + mux.HandleFunc("/repos/{owner}/{repo}/issues", func(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + defer f.mu.Unlock() + full := r.PathValue("owner") + "/" + r.PathValue("repo") + if r.Method == http.MethodPost { + f.next++ + issue := map[string]any{"number": f.next, "title": advisoryTitle, "state": "open"} + f.issues[full] = append(f.issues[full], issue) + f.creates[full]++ + w.WriteHeader(http.StatusCreated) + _ = json.NewEncoder(w).Encode(issue) + return + } + items := f.issues[full] + if items == nil { + items = []map[string]any{} + } + _ = json.NewEncoder(w).Encode(items) + }) + mux.HandleFunc("/repos/{owner}/{repo}/issues/{number}", func(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + defer f.mu.Unlock() + full := r.PathValue("owner") + "/" + r.PathValue("repo") + if r.Method == http.MethodPatch { + f.edits[full]++ + } + for _, issue := range f.issues[full] { + if jsonNumberString(issue["number"]) == r.PathValue("number") { + _ = json.NewEncoder(w).Encode(issue) + return + } + } + w.WriteHeader(http.StatusNotFound) + _ = json.NewEncoder(w).Encode(map[string]any{"message": "Not Found"}) + }) + mux.HandleFunc("/repos/{owner}/{repo}/labels", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusCreated) + _ = json.NewEncoder(w).Encode(map[string]any{"name": advisoryLabelName}) + }) + return mux +} + +func jsonNumberString(v any) string { + b, err := json.Marshal(v) + if err != nil { + return "" + } + return string(b) +} + +// TestEnsureAdvisoryIssue_RestartReusesExistingOpenReport pins #18568 at the +// client: a hive restarted against a primary repo that already holds its open +// advisory report (found by title and the hive/advisory label) resolves that +// report and never files a new one, whichever title spelling the report +// carries. Every fresh client is a restart with no in-process memory. +func TestEnsureAdvisoryIssue_RestartReusesExistingOpenReport(t *testing.T) { + const org = "hivecommons" + const primary = "hive" + const existing = 2364 + for _, title := range []string{advisoryTitle, "[governor] " + advisoryTitle} { + t.Run(title, func(t *testing.T) { + forge := newAdvisoryRestartForge() + forge.seed(org+"/"+primary, existing, title) + server := httptest.NewServer(forge.handler()) + defer server.Close() + + const restarts = 3 + for i := 0; i < restarts; i++ { + c := newTestClient(t, server, org, []string{primary, "crux", "dibs"}) + n, err := c.EnsureAdvisoryIssue(context.Background(), primary) + if err != nil { + t.Fatalf("restart %d: EnsureAdvisoryIssue: %v", i, err) + } + if n != existing { + t.Fatalf("restart %d: resolved #%d, want existing #%d", i, n, existing) + } + } + if got := forge.creates[org+"/"+primary]; got != 0 { + t.Fatalf("%d advisory reports created across restarts, want 0", got) + } + if got := forge.edits[org+"/"+primary]; got != 0 { + t.Fatalf("%d edits of the open report, want 0 (it was never closed)", got) + } + for full, n := range forge.creates { + if full != org+"/"+primary && n != 0 { + t.Fatalf("%s: %d advisory reports created in a non-primary repo, want 0", full, n) + } + } + }) + } +} + +// TestEnsureAdvisoryIssue_CreatesOnceThenReusesAfterRestart pins the cold +// start: with no report yet, the first ensure files exactly one, and a +// restarted client finds it rather than filing a second. +func TestEnsureAdvisoryIssue_CreatesOnceThenReusesAfterRestart(t *testing.T) { + const org = "hivecommons" + const primary = "hive" + forge := newAdvisoryRestartForge() + server := httptest.NewServer(forge.handler()) + defer server.Close() + + first, err := newTestClient(t, server, org, []string{primary}).EnsureAdvisoryIssue(context.Background(), primary) + if err != nil || first <= 0 { + t.Fatalf("first ensure = (%d, %v), want a created issue", first, err) + } + again, err := newTestClient(t, server, org, []string{primary}).EnsureAdvisoryIssue(context.Background(), primary) + if err != nil { + t.Fatalf("ensure after restart: %v", err) + } + if again != first { + t.Fatalf("after restart resolved #%d, want #%d", again, first) + } + if got := forge.creates[org+"/"+primary]; got != 1 { + t.Fatalf("%d advisory reports created, want exactly 1", got) + } +}