beads/cmd/bd/gate_proxied_server.go
Julian Knutsen b126a7d1d2
fix(http): bd gate check over HTTP through issueops.ListGates (#7578)
* fix(http): bd gate check over http through issueops.ListGates

gate check listed its open gates with a raw SearchIssues filter (gate type,
closed excluded, --limit), which the HTTP backend refuses, so the command
failed before reading a gate on a remote scope and gc's core gate-sweep order
(bd gate check --type=timer --escalate) failed every tick there.

The listing now goes through issueops.ListGates over openQuerier on the
direct and proxied routes, the same entry bd gate list took in S20 (#7549):
the same question, served as queryIssues by every deployed server. The close,
the bead-gate target read and sighting, the pure timer arm and the gh/gt execs
are unchanged. The gh:run discovery's await_id persist still refuses on the
wire and counts as that gate's error.

The served corpus gains mc-gate-check-timer, mc-gate-check-gh (gate-sweep's
argv) and gate-check-all. No seeded gate carries an await type, since no wire
create accepts await_*, so these prove the listing is served.

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

* docs(gate): name both refused gate check writes; close gate's filter hole

Review fixes for #7578 (apply-fixes, iteration 1).

CHANGELOG, minor (taken): the entry said a bead gate's sighting was
already served over HTTP. It is not. evaluateBeadGate records the first
sighting (await_seen) through recordSeen, which calls the raw
store.UpdateIssue (cmd/bd/gate.go:675). The HTTP Store has no UpdateIssue
override, so its embedded unsupportedDoltStorage refuses the call in the
client before any request is sent (internal/httpclient/unsupported_gen.go),
exactly as it refuses the gh:run discovery's await_id persist. "Refuses on
the wire" was wrong for the same reason. The entry now names both writes
and keeps "counts as that gate's error" (applyGateCheckResults counts
r.err). The sighting is written only when the check finds the awaited
bead, not yet closed, in the gate's own store; inspectBeadGate sets
seenHere only there.

CHANGELOG, nit (taken): `bd gate check --limit -1` used to list every
open gate on the direct and proxied routes, because the raw search
emitted no LIMIT clause for a negative limit. The listing now goes
through issueops.ListGates, whose Querier rejects a negative limit as
ErrValidation, and the HTTP server rejects it too
(internal/httpapi/query.go). The entry says so.

.golangci.yml, minor (taken): at this head cmd/bd/gate.go and
gate_proxied_server.go name no filter type (one each at the base), so
their slot in the cmd/bd forbidigo family only kept a hole open. `gate`
leaves the alternation, with a "LEFT this list" note like the ones for
search, status and count. gate_discover keeps its own hole:
findPendingGates still builds the raw filter.

Declined:
- bd gate discover still refuses over HTTP in findPendingGates (minor):
  the synthesis' first remedy is no change in this PR, and the file is
  not in this PR's diff. Finalize files the follow-up to move it onto
  ListGates.
- the proxied listing is not pinned on its own (nit): it calls the same
  listOpenGatesForCheck as the direct route (gate_proxied_server.go:106),
  and the synthesis calls accepting the gap defensible.
- listOpenGatesForCheck/listOpenGatesWith naming (nit): the remedy is
  "leave as is".

Verified:
- git diff --check: clean.
- bazel build --config=nogo -- //cmd/bd:all on the edited config: 16
  targets, exit 0.
- Probe, then reverted: a types.IssueFilter literal in gate.go and a
  types.WorkFilter literal in gate_proxied_server.go each failed nogo
  with forbidigo's "do not write a filter here", so the hole is shut.
- git merge-tree against the heads of all 102 other open PRs that touch
  CHANGELOG.md or .golangci.yml (today's census): this commit changes
  no conflict count in either file. 43 PR/file pairs already conflict
  with or without it.

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>
2026-10-16 09:20:24 +00:00

528 lines
15 KiB
Go

package main
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/audit"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/storage/uow"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/workapi"
)
type proxiedGateClose struct {
before *types.Issue
after *types.Issue
oldStatus string
reason string
}
type gateCheckApply struct {
closed []proxiedGateClose
updated []*types.Issue
closeErrs map[string]error
awaitErrs map[string]error
seenErrs map[string]error
}
// proxiedFreshReadGetter reads bead gate targets in proxied-server mode, each
// lookup in a fresh read transaction. A target can be an issue or a wisp. A
// local miss falls back to prefix routing like the direct getter; proxied
// mode has no contributor auto-routing.
type proxiedFreshReadGetter struct{}
func (g proxiedFreshReadGetter) GetIssue(ctx context.Context, id string) (*types.Issue, error) {
issue, _, err := g.getBeadGateTarget(ctx, id)
return issue, err
}
func (proxiedFreshReadGetter) getBeadGateTarget(ctx context.Context, id string) (*types.Issue, bool, error) {
uw, err := proxiedOpenReadUOW(ctx)
if err != nil {
return nil, false, err
}
issue, _, localErr := workapi.GetIssueOrWisp(ctx, workapi.NewUOWDetailSource(uw), id)
uw.Close(ctx)
if localErr == nil {
return issue, true, nil
}
if !gateProxiedNotFound(localErr) {
return nil, false, localErr
}
routed, routeErr := prefixRoutedBeadGateTarget(ctx, id)
if routeErr != nil {
return nil, false, routeErr
}
if routed != nil {
return routed, false, nil
}
return nil, true, localErr
}
func runGateCheckProxiedServer(cmd *cobra.Command, ctx context.Context) error {
CheckReadonly("gate check")
evt := metrics.NewCommandEvent("gate-check")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
gateTypeFilter, _ := cmd.Flags().GetString("type")
dryRun, _ := cmd.Flags().GetBool("dry-run")
escalateFlag, _ := cmd.Flags().GetBool("escalate")
limit, _ := cmd.Flags().GetInt("limit")
if uowProvider == nil {
return HandleErrorRespectJSON("proxied-server UOW provider not initialized")
}
discovered := map[string]string{}
var seen []*types.Issue
var persistAwaitID func(gateID, runID string) error
var recordSeen func(gate *types.Issue) error
if !dryRun {
persistAwaitID = func(gateID, runID string) error {
discovered[gateID] = runID
return nil
}
recordSeen = func(gate *types.Issue) error {
seen = append(seen, gate)
return nil
}
}
// The listing is the shared entry's, on this route too (gate list's S20).
gates, err := listOpenGatesForCheck(ctx, limit)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
filteredGates := filterCheckableGates(gates, gateTypeFilter)
if len(filteredGates) == 0 {
printNoOpenGates(gateTypeFilter)
return nil
}
results := evaluateGates(ctx, filteredGates, time.Now(), proxiedFreshReadGetter{}, persistAwaitID, recordSeen)
if dryRun {
resolved, escalated, errCount := applyGateCheckResults(results, true, escalateFlag, nil)
return printGateCheckSummary(len(results), resolved, escalated, errCount, dryRun)
}
applied, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (gateCheckApply, string, error) {
out := gateCheckApply{
closeErrs: map[string]error{},
awaitErrs: map[string]error{},
seenErrs: map[string]error{},
}
for gateID, runID := range discovered {
if err := uw.IssueUseCase().UpdateIssue(ctx, gateID, map[string]any{"await_id": runID}, currentActor()); err != nil {
out.awaitErrs[gateID] = fmt.Errorf("failed to update gate with discovered run ID: %w", err)
continue
}
if after, getErr := uw.IssueUseCase().GetIssue(ctx, gateID); getErr == nil && after != nil {
out.updated = append(out.updated, after)
}
}
for _, gate := range seen {
if err := recordBeadGateSeenProxied(ctx, uw, gate); err != nil {
out.seenErrs[gate.ID] = err
continue
}
out.updated = append(out.updated, gate)
}
for _, r := range results {
if r.err != nil || !r.resolved {
continue
}
if _, awaitFailed := out.awaitErrs[r.gate.ID]; awaitFailed {
continue
}
before, _ := uw.IssueUseCase().GetIssue(ctx, r.gate.ID)
if before != nil && before.Status == types.StatusClosed {
continue
}
res, closeErr := uw.IssueUseCase().CloseIssue(ctx, r.gate.ID, domain.CloseIssueParams{Reason: r.reason}, currentActor())
if closeErr != nil {
out.closeErrs[r.gate.ID] = closeErr
continue
}
oldStatus := "open"
if before != nil && before.Status != "" {
oldStatus = string(before.Status)
}
out.closed = append(out.closed, proxiedGateClose{
before: before,
after: res.Issue,
oldStatus: oldStatus,
reason: r.reason,
})
}
return out, "bd: gate check", nil
})
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
for _, c := range applied.closed {
audit.LogFieldChange(c.after.ID, "status", c.oldStatus, "closed", currentActor(), c.reason)
}
if len(applied.closed) > 0 || len(applied.updated) > 0 {
commandDidWrite.Store(true)
}
for i := range results {
if awaitErr, failed := applied.awaitErrs[results[i].gate.ID]; failed {
results[i].resolved = false
results[i].escalated = false
results[i].err = awaitErr
}
if seenErr, failed := applied.seenErrs[results[i].gate.ID]; failed {
results[i].resolved = false
results[i].escalated = false
results[i].err = seenErr
}
}
resolved, escalated, errCount := applyGateCheckResults(results, false, escalateFlag,
func(gate *types.Issue, reason string) error {
return applied.closeErrs[gate.ID]
})
return printGateCheckSummary(len(results), resolved, escalated, errCount, dryRun)
}
// recordBeadGateSeenProxied is the proxied-server form of the direct route's
// recordSeen write: it stamps beadGateSeenKey on a bead gate, which may be an
// issue or a wisp.
func recordBeadGateSeenProxied(ctx context.Context, uw uow.UnitOfWork, gate *types.Issue) error {
_, isWisp, err := workapi.GetIssueOrWisp(ctx, workapi.NewUOWDetailSource(uw), gate.ID)
if err == nil {
err = proxiedUpdateByID(ctx, uw, gate.ID, isWisp, beadGateSeenUpdate(gate.AwaitID))
}
if err != nil {
targetID, _ := beadGateTargetID(gate.AwaitID)
return fmt.Errorf("recording that bead %s exists: %w", targetID, err)
}
return nil
}
// gateProxiedNotFound reports whether an issue lookup failed because the row
// does not exist, as opposed to the read itself failing. The distinction is
// what keeps `bd gate show` fail-closed: "no gate" and "could not read" must
// not collapse into one message.
func gateProxiedNotFound(err error) bool {
return errors.Is(err, storage.ErrNotFound) || errors.Is(err, sql.ErrNoRows)
}
func runGateShowProxiedServer(_ *cobra.Command, ctx context.Context, args []string) error {
evt := metrics.NewCommandEvent("gate-show")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
gateID := args[0]
uw, err := proxiedOpenReadUOW(ctx)
if err != nil {
return err
}
defer uw.Close(ctx)
issue, err := uw.IssueUseCase().GetIssue(ctx, gateID)
if gateProxiedNotFound(err) {
return HandleErrorRespectJSON("gate not found: %s", gateID)
}
if err != nil {
// A failed read is not "no gate": it exits nonzero with its own
// message so a caller grepping the output cannot mistake an
// unreachable server for a missing gate.
return HandleErrorRespectJSON("reading gate %s: %v", gateID, err)
}
if issue.IssueType != "gate" {
return HandleErrorRespectJSON("%s is not a gate issue (type=%s)", gateID, issue.IssueType)
}
if jsonOutput {
return outputJSON(issue)
}
renderGateShow(issue)
return nil
}
type gateAddWaiterApply struct {
already bool
after *types.Issue
}
func runGateAddWaiterProxiedServer(_ *cobra.Command, ctx context.Context, args []string) error {
CheckReadonly("gate add-waiter")
evt := metrics.NewCommandEvent("gate-add-waiter")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
gateID := args[0]
waiter := args[1]
if uowProvider == nil {
return HandleError("proxied-server UOW provider not initialized")
}
applied, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (gateAddWaiterApply, string, error) {
var out gateAddWaiterApply
issue, err := uw.IssueUseCase().GetIssue(ctx, gateID)
if gateProxiedNotFound(err) {
return out, "", fmt.Errorf("gate not found: %s", gateID)
}
if err != nil {
return out, "", fmt.Errorf("reading gate %s: %w", gateID, err)
}
if issue.IssueType != "gate" {
return out, "", fmt.Errorf("%s is not a gate issue (type=%s)", gateID, issue.IssueType)
}
for _, w := range issue.Waiters {
if w == waiter {
out.already = true
// Empty commit message: a registered waiter is a no-op, and a
// no-op writes no Dolt commit.
return out, "", nil
}
}
newWaiters := append(issue.Waiters, waiter)
if err := uw.IssueUseCase().UpdateIssue(ctx, gateID, map[string]any{"waiters": newWaiters}, currentActor()); err != nil {
return out, "", fmt.Errorf("updating gate: %w", err)
}
if after, getErr := uw.IssueUseCase().GetIssue(ctx, gateID); getErr == nil {
out.after = after
}
return out, fmt.Sprintf("bd: gate add-waiter %s", gateID), nil
})
if err != nil {
return HandleError("%v", err)
}
if applied.already {
renderGateWaiterAlready(gateID)
return nil
}
commandDidWrite.Store(true)
renderGateWaiterAdded(gateID, waiter)
return nil
}
type gateCreateApply struct {
gate *types.Issue
target *types.Issue
}
func runGateCreateProxiedServer(cmd *cobra.Command, ctx context.Context) error {
CheckReadonly("gate create")
evt := metrics.NewCommandEvent("gate-create")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
in, err := gatherGateCreateInput(cmd)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
if uowProvider == nil {
return HandleError("proxied-server UOW provider not initialized")
}
// One transaction, one Dolt commit for the whole invocation: the direct
// route's create + add-dependency + explicit store.Commit collapse into a
// single unit of work carrying the same commit message. Semantically
// equivalent, minus the window where the gate exists without its edge.
applied, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (gateCreateApply, string, error) {
var out gateCreateApply
target, err := uw.IssueUseCase().GetIssue(ctx, in.blocksID)
if err != nil {
// The direct route reports every target-lookup failure as
// not-found; keep that message for parity.
return out, "", fmt.Errorf("issue not found: %s", in.blocksID)
}
gate := buildGateIssue(in, target.ID)
metadata, metaErr := gateMetadataForCreate(in, target)
if metaErr != nil {
return out, "", metaErr
}
gate.Metadata = metadata
res, err := uw.IssueUseCase().CreateIssue(ctx, domain.CreateIssueParams{Issue: gate}, currentActor())
if err != nil {
return out, "", fmt.Errorf("creating gate: %w", err)
}
dep := &types.Dependency{
IssueID: target.ID,
DependsOnID: res.Issue.ID,
Type: types.DepBlocks,
}
if err := uw.DependencyUseCase().AddDependency(ctx, dep, currentActor()); err != nil {
return out, "", fmt.Errorf("adding blocking dependency: %w", err)
}
out.gate = res.Issue
out.target = target
return out, fmt.Sprintf("bd: create gate %s blocking %s", res.Issue.ID, target.ID), nil
})
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
commandDidWrite.Store(true)
if jsonOutput {
return outputJSON(applied.gate)
}
renderGateCreated(applied.gate, applied.target, in)
return nil
}
type gateResolveApply struct {
before *types.Issue
after *types.Issue
oldStatus string
closed bool // CloseIssueResult.Closed: false when the gate was already closed
}
func runGateResolveProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error {
CheckReadonly("gate resolve")
evt := metrics.NewCommandEvent("gate-resolve")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
gateID := args[0]
reason, _ := cmd.Flags().GetString("reason")
if uowProvider == nil {
return HandleError("proxied-server UOW provider not initialized")
}
applied, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (gateResolveApply, string, error) {
var out gateResolveApply
issue, err := uw.IssueUseCase().GetIssue(ctx, gateID)
if gateProxiedNotFound(err) {
return out, "", fmt.Errorf("gate not found: %s", gateID)
}
if err != nil {
return out, "", fmt.Errorf("reading gate %s: %w", gateID, err)
}
if issue.IssueType != "gate" {
return out, "", fmt.Errorf("%s is not a gate issue (type=%s)", gateID, issue.IssueType)
}
res, err := uw.IssueUseCase().CloseIssue(ctx, gateID, domain.CloseIssueParams{Reason: reason}, currentActor())
if err != nil {
return out, "", fmt.Errorf("closing gate: %w", err)
}
out.before = issue
out.after = res.Issue
out.oldStatus = "open"
if issue.Status != "" {
out.oldStatus = string(issue.Status)
}
out.closed = res.Closed
return out, fmt.Sprintf("bd: gate resolve %s", gateID), nil
})
if err != nil {
return HandleError("%v", err)
}
// Audit only when this invocation actually closed the gate — a
// double-resolve must not re-log it (same guard as the o.closed check in
// close_proxied_server.go).
if applied.closed && applied.after != nil {
audit.LogFieldChange(applied.after.ID, "status", applied.oldStatus, "closed", currentActor(), reason)
}
commandDidWrite.Store(true)
renderGateResolved(gateID, reason)
return nil
}
func runGateListProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error {
allFlag, _ := cmd.Flags().GetBool("all")
limit, _ := cmd.Flags().GetInt("limit")
if len(args) == 0 {
// The workspace-wide listing is the shared entry's, on this route too.
return runGateList(ctx, allFlag, limit)
}
uw, err := proxiedOpenReadUOW(ctx)
if err != nil {
return err
}
defer uw.Close(ctx)
target, isWisp, err := workapi.GetIssueOrWisp(ctx, workapi.NewUOWDetailSource(uw), args[0])
if errors.Is(err, storage.ErrNotFound) {
return HandleErrorRespectJSON("issue not found: %s", args[0])
}
if err != nil {
return HandleErrorRespectJSON("resolving %s: %v", args[0], err)
}
var metas []*types.IssueWithDependencyMetadata
if isWisp {
metas, err = uw.DependencyUseCase().ListWispWithIssueMetadata(ctx, target.ID, domain.DepListFilter{Direction: domain.DepDirectionOut})
} else {
metas, err = uw.DependencyUseCase().ListWithIssueMetadata(ctx, target.ID, domain.DepListFilter{Direction: domain.DepDirectionOut})
}
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
deps := make([]*types.Issue, 0, len(metas))
for _, m := range metas {
if m != nil {
deps = append(deps, &m.Issue)
}
}
gates := filterIssueGates(deps, allFlag, limit)
if jsonOutput {
return outputJSON(gates)
}
displayGates(gates, allFlag)
return nil
}