beads/cmd/bd/gate_check_proxied_integration_test.go
Julian Knutsen dff9492c61
fix(http): gate check records a bead gate's sighting through Lifecycle.Update (#7604)
* fix(http): gate check's bead sighting goes through Lifecycle.Update (issues.update)

The bead-gate sighting was written through the legacy map-based
UpdateIssue, which the http store does not implement, so the refusal
happened client-side and no issues.update was ever sent: every open bead
gate with an open target failed on every sweep over HTTP.

- recordSeen and the gh:run await_id persist now go through the Lifecycle
  role (updateGateThroughLifecycle): a single-key metadata set for the
  sighting, an AwaitID patch for the run. The http client still refuses the
  await_id patch before the dial (W-IssuePatch.AwaitID); the gate's error now
  names the await_id update instead of a Go method.
- backend/http/corpus TestServedGateCheckOverAwaitTypedGates seeds
  await-typed gates in the served store and proves, through the reference
  proxy: --dry-run writes nothing, timers close, the bead sighting persists,
  merged gh:pr gates close, and the gh:run persist refuses by name with
  await_id untouched.
- CHANGELOG corrected.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(cmd/bd): gate check skips template gates; narrow the await_id reword

Review fixes for the gate-check sighting change.

- A persisted proto's gates (bd cook --persist) are templates, and
  issueops.ListGates lists them with the open gates. bd gate check now
  leaves them out of its listing's query: GateListRequest gains
  ExcludeTemplates, which only listOpenGatesWith sets, and it adds
  `template=false` to the expression, so the cut at --limit counts only
  the gates that remain. bd gate list leaves it unset and still lists
  templates. Dropping them from the page after the cut would let a page
  of a proto's gates (newer than the live ones at the same priority)
  fill --limit: the sweep would print "No open gates found." and exit 0
  with the live gates unchecked. filterCheckableGates, which both the
  direct and the proxied-server routes select through, keeps the skip
  as a backstop. Before this, each route mishandled templates in its
  own way:
  - Direct route: the Lifecycle role refused the sighting and await_id
    writes, so the sweep failed every time, after a gh:run template had
    already queried GitHub. In a local workspace, an expired template
    timer gate was closed in the proto.
  - Over HTTP: bd serve refused the close with 409 template_read_only.
  - Proxied-server route: the template timer gate was closed and a
    sighting was stamped on the template bead gate, silently.
- persistGateCheckAwaitID rewords only the HTTP wire's
  W-IssuePatch.AwaitID refusal. The new message names the run, await_id
  and the bd serve URL, and advises checking the gate in a local
  workspace: giving it a numeric run ID would be the same await_id edit
  the wire refuses. The error chain is kept, so *storage.ErrUnsupported
  and the ledger row stay reachable. Every other error comes back as the
  role raised it, including a capability the server does not advertise
  (#7589's issues.update.gates) and a local backend's ErrUnsupported.
  Before, every ErrUnsupported got the same sentence.
- Tests:
  - Unit: the template skip for every type filter; a sweep over template
    gates beside a live one; ListGates putting `template=false` in the
    query under ExcludeTemplates, and gate check's listing setting it;
    the reword and its chain; the pass-through cases; the sighting patch
    matching its map form.
  - Embedded: a cooked proto's gh:run, bead and timer gates are
    untouched, and gh is never run. With --limit 1 behind that proto's
    gates, a live expired timer gate is checked and closed.
  - Proxied-server: template timer and bead gates stay open and
    unstamped. With --limit 1 behind two newer template timer gates, the
    live one is checked and closed.
  - Served: the template gates are untouched, and the gh:run error names
    the server. --dry-run --limit 3 behind three template gates checks
    three live gates.
  - Each --limit case first shows, through bd gate list, that a template
    leads the listing.
  - Against the PR-head bd, the embedded, proxied and served template
    cases fail. Against a bd that skips templates after the cut, the
    three --limit cases fail, printing "No open gates found." and
    exiting 0.
- bd_test gains the //internal/httpclient{,/encode} deps (gazelle-checked).
  The embedded shard manifest lists both TestEmbeddedGateCheck* tests.
  The CHANGELOG notes the template skip, that templates take no row of
  --limit, and the new wording.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
2026-10-16 15:14:53 +00:00

357 lines
14 KiB
Go

//go:build cgo
package main
import (
"context"
"database/sql"
"encoding/json"
"strings"
"testing"
"time"
"github.com/steveyegge/beads/internal/types"
)
func seedGateAwait(t *testing.T, db *sql.DB, id, awaitType, awaitID string, createdAt time.Time, timeout time.Duration) {
t.Helper()
if _, err := db.ExecContext(context.Background(),
"UPDATE issues SET await_type=?, await_id=?, timeout_ns=?, created_at=? WHERE id=?",
awaitType, awaitID, int64(timeout), createdAt.UTC(), id); err != nil {
t.Fatalf("seed await columns for %s: %v", id, err)
}
}
func TestProxiedServerGateCheck(t *testing.T) {
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
const expiredTimeout = time.Hour
longAgo := func() time.Time { return time.Now().UTC().Add(-48 * time.Hour) }
longFuture := time.Hour * 1000
t.Run("no_gates", func(t *testing.T) {
t.Parallel()
p := newSharedProxiedProject(t, bd, "gcn")
out, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "gate", "check")
if err != nil {
t.Fatalf("gate check failed: %v\nstderr:\n%s", err, stderr)
}
if !strings.Contains(out, "No open gates") {
t.Errorf("expected 'No open gates' message, got:\n%s", out)
}
})
t.Run("timer_expired_resolves", func(t *testing.T) {
t.Parallel()
p := newSharedProxiedProject(t, bd, "gce")
gate := bdProxiedCreate(t, bd, p.dir, "Expired timer gate", "--type", "gate")
db := openProxiedDB(t, p)
seedGateAwait(t, db, gate.ID, "timer", "", longAgo(), expiredTimeout)
out, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "gate", "check", "--type", "timer")
if err != nil {
t.Fatalf("gate check failed: %v\nstderr:\n%s", err, stderr)
}
if got := readStatus(t, db, gate.ID); got != types.StatusClosed {
t.Errorf("expired timer gate should be closed, got %q", got)
}
if !strings.Contains(out, "Checked 1 gates: 1 resolved") {
t.Errorf("expected summary with 1 resolved, got:\n%s", out)
}
})
t.Run("timer_pending_stays_open", func(t *testing.T) {
t.Parallel()
p := newSharedProxiedProject(t, bd, "gcp")
gate := bdProxiedCreate(t, bd, p.dir, "Pending timer gate", "--type", "gate")
db := openProxiedDB(t, p)
seedGateAwait(t, db, gate.ID, "timer", "", time.Now().UTC(), longFuture)
out, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "gate", "check", "--type", "timer")
if err != nil {
t.Fatalf("gate check failed: %v\nstderr:\n%s", err, stderr)
}
if got := readStatus(t, db, gate.ID); got == types.StatusClosed {
t.Error("pending timer gate should stay open")
}
if !strings.Contains(out, "0 resolved") {
t.Errorf("expected 0 resolved for pending timer, got:\n%s", out)
}
})
t.Run("dry_run_does_not_close", func(t *testing.T) {
t.Parallel()
p := newSharedProxiedProject(t, bd, "gcd")
gate := bdProxiedCreate(t, bd, p.dir, "Dry run timer gate", "--type", "gate")
db := openProxiedDB(t, p)
seedGateAwait(t, db, gate.ID, "timer", "", longAgo(), expiredTimeout)
out, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "gate", "check", "--type", "timer", "--dry-run")
if err != nil {
t.Fatalf("gate check --dry-run failed: %v\nstderr:\n%s", err, stderr)
}
if got := readStatus(t, db, gate.ID); got == types.StatusClosed {
t.Error("dry-run must not close the gate")
}
if !strings.Contains(out, "would resolve") {
t.Errorf("expected 'would resolve' in dry-run output, got:\n%s", out)
}
})
t.Run("bead_gate_resolves_when_target_closes", func(t *testing.T) {
t.Parallel()
p := newSharedProxiedProject(t, bd, "gcb")
target := bdProxiedCreate(t, bd, p.dir, "Bead gate target")
gate := bdProxiedCreate(t, bd, p.dir, "Bead gate", "--type", "gate")
db := openProxiedDB(t, p)
seedGateAwait(t, db, gate.ID, "bead", target.ID, time.Now().UTC(), 0)
if _, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "gate", "check", "--type", "bead"); err != nil {
t.Fatalf("gate check (target open) failed: %v\nstderr:\n%s", err, stderr)
}
if got := readStatus(t, db, gate.ID); got == types.StatusClosed {
t.Error("bead gate should stay pending while target is open")
}
bdProxiedClose(t, bd, p.dir, target.ID)
out, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "gate", "check", "--type", "bead")
if err != nil {
t.Fatalf("gate check (target closed) failed: %v\nstderr:\n%s", err, stderr)
}
if got := readStatus(t, db, gate.ID); got != types.StatusClosed {
t.Errorf("bead gate should resolve after target closes, got %q", got)
}
if !strings.Contains(out, "1 resolved") {
t.Errorf("expected 1 resolved after target close, got:\n%s", out)
}
})
}
// TestProxiedServerGateCheckB holds more of TestProxiedServerGateCheck's cases, split
// off so the bd_proxied_test shard manifest can place them on another shard.
func TestProxiedServerGateCheckB(t *testing.T) {
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
const expiredTimeout = time.Hour
longAgo := func() time.Time { return time.Now().UTC().Add(-48 * time.Hour) }
t.Run("bead_gate_resolves_when_seen_target_is_deleted", func(t *testing.T) {
t.Parallel()
p := newSharedProxiedProject(t, bd, "gcg")
target := bdProxiedCreate(t, bd, p.dir, "Deleted bead gate target")
gate := bdProxiedCreate(t, bd, p.dir, "Bead gate", "--type", "gate")
db := openProxiedDB(t, p)
seedGateAwait(t, db, gate.ID, "bead", target.ID, time.Now().UTC(), 0)
// The first check sees the open target and records that on the gate.
if _, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "gate", "check", "--type", "bead"); err != nil {
t.Fatalf("gate check (target open) failed: %v\nstderr:\n%s", err, stderr)
}
if got := readStatus(t, db, gate.ID); got == types.StatusClosed {
t.Fatal("bead gate should stay pending while target is open")
}
var metadata string
if err := db.QueryRowContext(context.Background(),
"SELECT metadata FROM issues WHERE id = ?", gate.ID).Scan(&metadata); err != nil {
t.Fatalf("read gate metadata: %v", err)
}
if !strings.Contains(metadata, beadGateSeenKey) {
t.Fatalf("gate metadata %s does not record that the target was seen", metadata)
}
if _, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "delete", target.ID, "--force"); err != nil {
t.Fatalf("delete target failed: %v\nstderr:\n%s", err, stderr)
}
out, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "gate", "check", "--type", "bead")
if err != nil {
t.Fatalf("gate check (target deleted) failed: %v\nstderr:\n%s", err, stderr)
}
if got := readStatus(t, db, gate.ID); got != types.StatusClosed {
t.Errorf("bead gate should resolve after its seen target is deleted, got %q", got)
}
if !strings.Contains(out, "1 resolved") || !strings.Contains(out, "no longer exists") {
t.Errorf("expected 1 resolved with a 'no longer exists' reason, got:\n%s", out)
}
})
t.Run("bead_gate_never_seen_target_stays_pending", func(t *testing.T) {
t.Parallel()
p := newSharedProxiedProject(t, bd, "gcu")
gate := bdProxiedCreate(t, bd, p.dir, "Bead gate on a mistyped target", "--type", "gate")
db := openProxiedDB(t, p)
seedGateAwait(t, db, gate.ID, "bead", "gcu-nosuchbead", time.Now().UTC(), 0)
out, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "gate", "check", "--type", "bead")
if err != nil {
t.Fatalf("gate check failed: %v\nstderr:\n%s", err, stderr)
}
if got := readStatus(t, db, gate.ID); got == types.StatusClosed {
t.Error("a bead gate whose target no check ever saw must stay pending")
}
if !strings.Contains(out, "no earlier gate check saw it") {
t.Errorf("expected the never-seen diagnostic, got:\n%s", out)
}
})
t.Run("type_filter_scopes_evaluation", func(t *testing.T) {
t.Parallel()
p := newSharedProxiedProject(t, bd, "gcf")
timerGate := bdProxiedCreate(t, bd, p.dir, "Timer gate", "--type", "gate")
prGate := bdProxiedCreate(t, bd, p.dir, "PR gate", "--type", "gate")
db := openProxiedDB(t, p)
seedGateAwait(t, db, timerGate.ID, "timer", "", longAgo(), expiredTimeout)
seedGateAwait(t, db, prGate.ID, "gh:pr", "1", time.Now().UTC(), 0)
if _, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "gate", "check", "--type", "timer"); err != nil {
t.Fatalf("gate check --type timer failed: %v\nstderr:\n%s", err, stderr)
}
if got := readStatus(t, db, timerGate.ID); got != types.StatusClosed {
t.Errorf("timer gate should be closed under --type timer, got %q", got)
}
if got := readStatus(t, db, prGate.ID); got == types.StatusClosed {
t.Error("gh:pr gate must be untouched under --type timer")
}
})
t.Run("limit_bounds_gates_checked", func(t *testing.T) {
t.Parallel()
p := newSharedProxiedProject(t, bd, "gcl")
db := openProxiedDB(t, p)
var ids []string
for i := 0; i < 3; i++ {
g := bdProxiedCreate(t, bd, p.dir, "Limit timer gate", "--type", "gate")
seedGateAwait(t, db, g.ID, "timer", "", longAgo(), expiredTimeout)
ids = append(ids, g.ID)
}
if _, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "gate", "check", "--type", "timer", "--limit", "1"); err != nil {
t.Fatalf("gate check --limit 1 failed: %v\nstderr:\n%s", err, stderr)
}
closed := 0
for _, id := range ids {
if readStatus(t, db, id) == types.StatusClosed {
closed++
}
}
if closed > 1 {
t.Errorf("--limit 1 should close at most 1 gate, closed %d", closed)
}
})
t.Run("timer_escalate_is_noop_and_resolves", func(t *testing.T) {
t.Parallel()
p := newSharedProxiedProject(t, bd, "gcx")
gate := bdProxiedCreate(t, bd, p.dir, "Escalate timer gate", "--type", "gate")
db := openProxiedDB(t, p)
seedGateAwait(t, db, gate.ID, "timer", "", longAgo(), expiredTimeout)
out, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "gate", "check", "--type", "timer", "--escalate")
if err != nil {
t.Fatalf("gate check --escalate failed: %v\nstderr:\n%s", err, stderr)
}
if got := readStatus(t, db, gate.ID); got != types.StatusClosed {
t.Errorf("expired timer gate should resolve with --escalate, got %q", got)
}
if strings.Contains(out, "ESCALATE") {
t.Errorf("timer gates never escalate; --escalate should be a no-op, got:\n%s", out)
}
})
// A persisted proto's gates are templates. The listing returns them, but no
// sweep evaluates them: neither the expired template timer nor the template
// bead gate, whose target is open, is closed or written.
t.Run("template_gates_are_not_checked", func(t *testing.T) {
t.Parallel()
p := newSharedProxiedProject(t, bd, "gck")
target := bdProxiedCreate(t, bd, p.dir, "Template bead gate target")
live := bdProxiedCreate(t, bd, p.dir, "Live timer gate", "--type", "gate")
tplTimer := bdProxiedCreate(t, bd, p.dir, "Template timer gate", "--type", "gate")
tplBead := bdProxiedCreate(t, bd, p.dir, "Template bead gate", "--type", "gate")
db := openProxiedDB(t, p)
seedGateAwait(t, db, live.ID, "timer", "", longAgo(), expiredTimeout)
seedGateAwait(t, db, tplTimer.ID, "timer", "", longAgo(), expiredTimeout)
seedGateAwait(t, db, tplBead.ID, "bead", target.ID, time.Now().UTC(), 0)
for _, id := range []string{tplTimer.ID, tplBead.ID} {
if _, err := db.ExecContext(context.Background(),
"UPDATE issues SET is_template = 1 WHERE id = ?", id); err != nil {
t.Fatalf("mark %s a template: %v", id, err)
}
}
out, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "gate", "check")
if err != nil {
t.Fatalf("gate check failed: %v\nstderr:\n%s", err, stderr)
}
if got := readStatus(t, db, live.ID); got != types.StatusClosed {
t.Errorf("the live expired timer gate should be closed, got %q", got)
}
if !strings.Contains(out, "Checked 1 gates: 1 resolved") {
t.Errorf("expected only the live gate checked, got:\n%s", out)
}
for _, id := range []string{tplTimer.ID, tplBead.ID} {
if got := readStatus(t, db, id); got != types.StatusOpen {
t.Errorf("template gate %s status = %q, want open", id, got)
}
}
var metadata string
if err := db.QueryRowContext(context.Background(),
"SELECT metadata FROM issues WHERE id = ?", tplBead.ID).Scan(&metadata); err != nil {
t.Fatalf("read template gate metadata: %v", err)
}
if strings.Contains(metadata, beadGateSeenKey) {
t.Errorf("template gate metadata %s records a sighting", metadata)
}
})
// The template gates, expired timers too, are newer than the live one, so
// they lead the listing. The query leaves them out before --limit cuts it:
// they used to fill the one row, and the sweep reported no open gates and
// exited 0 with the live gate unchecked.
t.Run("limit_counts_only_live_gates", func(t *testing.T) {
t.Parallel()
p := newSharedProxiedProject(t, bd, "gcv")
live := bdProxiedCreate(t, bd, p.dir, "Live timer gate", "--type", "gate")
tplA := bdProxiedCreate(t, bd, p.dir, "Template timer gate A", "--type", "gate")
tplB := bdProxiedCreate(t, bd, p.dir, "Template timer gate B", "--type", "gate")
db := openProxiedDB(t, p)
seedGateAwait(t, db, live.ID, "timer", "", longAgo(), expiredTimeout)
for _, id := range []string{tplA.ID, tplB.ID} {
seedGateAwait(t, db, id, "timer", "", time.Now().UTC().Add(-2*expiredTimeout), expiredTimeout)
if _, err := db.ExecContext(context.Background(),
"UPDATE issues SET is_template = 1 WHERE id = ?", id); err != nil {
t.Fatalf("mark %s a template: %v", id, err)
}
}
// bd gate list still lists templates: its first row is one, so a cut at
// one row taken before the template skip leaves the sweep nothing.
listed, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "gate", "list", "--limit", "1", "--json")
if err != nil {
t.Fatalf("gate list --limit 1 --json failed: %v\nstderr:\n%s", err, stderr)
}
var first []map[string]any
if start := strings.Index(listed, "["); start < 0 || json.Unmarshal([]byte(listed[start:]), &first) != nil ||
len(first) != 1 || (first[0]["id"] != tplA.ID && first[0]["id"] != tplB.ID) {
t.Fatalf("gate list --limit 1 --json = %s, want one of the template gates first", listed)
}
out, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "gate", "check", "--limit", "1")
if err != nil {
t.Fatalf("gate check --limit 1 failed: %v\nstderr:\n%s", err, stderr)
}
if got := readStatus(t, db, live.ID); got != types.StatusClosed {
t.Errorf("the live expired timer gate should be closed, got %q\noutput:\n%s", got, out)
}
if !strings.Contains(out, "Checked 1 gates: 1 resolved") {
t.Errorf("expected the live gate checked past the templates, got:\n%s", out)
}
for _, id := range []string{tplA.ID, tplB.ID} {
if got := readStatus(t, db, id); got != types.StatusOpen {
t.Errorf("template gate %s status = %q, want open", id, got)
}
}
})
}