beads/internal/storage/issueops/close_batch.go
Denis Redozubov 02f05340f6
fix(externaldeps): guard explicit claims and batch closes (#6738)
* fix(externaldeps): guard explicit claims and batch closes

Preserve external capability policy across lifecycle updates and batch close/claim-next operations, including direct, embedded, and proxied paths. Follow up on upstream PR #4753 and issue #4769.

Agent-Signature: codex-unknown-model-unknown-reasoning on behalf of Denis Redozubov

* test(externaldeps): include embedded regression in CI discovery

* test(serve): preserve external close policy when peeling hooks

Replace the raw batch-closer identity assertion with a behavioral policy check, retaining the no-hooks assertion. Document full-workspace claim filtering and batch lookup cost.

Agent-Signature: codex-unknown-model-unknown-reasoning on behalf of Denis Redozubov

* test(externaldeps): align the mixed-batch pin with #6648's partial-failure exit

Maintainer fixup applied while adopting PR #6738.

`exerciseExternalMutationPolicy`'s `mixed_batch_and_claim_next` subtest asserted
that a partially-refused `bd close` batch keeps the CLI's zero exit status. That
was true at this PR's original base, but #6740 (Beads #6648) landed on main in
the meantime and made a partial batch close exit 1 with an
`N of M issues failed to close` summary. The two changes are independently
correct and merge without a textual conflict, so the stale expectation only
surfaces as a red `cmd/bd` shard after the rebase.

The PR's substance is unchanged: the externally blocked issue is still refused
with its blocker named, the eligible item still closes, and `--claim-next` still
claims. Only the exit-status expectation moves onto the current contract, and
the summary line is now pinned so the interaction between the two features stays
covered.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(dolt): check version scope on the transaction owner

withWriteTx and withRetryTx delegate transaction creation to commitWriteTx after #6719. Point the existing completeness guard at that owner so it still checks BeginTx and the versioned-history scope together.

Agent-Signature: codex-unknown-model-unknown-reasoning on behalf of Denis Redozubov

* fix(ci): register external policy files and isolate server cleanup

Include all six new Go files in Bazel targets. Run the direct-server fixture before parallel proxied tests because its cleanup purges dropped databases across their shared server; observed initialization failures coincide with that cleanup.

Agent-Signature: codex-unknown-model-unknown-reasoning on behalf of Denis Redozubov

* fix(externaldeps): scope close-only batch policy and drop the claim --force hint

Review-loop fixup for PR #6738 (iteration 1). The review approved with no
blocker or major findings; this takes its three minors and its nit, all in
code this PR introduces. Each minor lands with a test that a mutation of the
covered code turns red.

[minor] A refused proxied claim suggested an override that cannot work. The
external claim guard ignores --force but shares ErrCloseBlocked with the close
policy, so on the proxied route `bd update <id> --claim` against an externally
blocked issue printed "(use --force to override)". proxiedUpdateFailure now
reports a refused claim as the generic update failure, as the direct route
always has. claim_is_atomic asserts the refusal never mentions --force;
restoring the unconditional hint fails it on the proxied lane.

[minor] A close-only batch demanded policy support for unrelated blockers.
Without ClaimNext the batch closer still passed the workspace's whole
externally blocked set to BatchCloserWithPolicy, so one external blocker
anywhere made a backend lacking PolicyBatchCloserSource (such as one
registered through internal/storage/backends) refuse to close unblocked
issues. The policy is now scoped to the batch items unless the batch claims
next work, which still needs every blocker for FilterClaim. CheckClose looks
up exact ids, so no refusal changes. The NewBatchClosePolicy doc now says when
the whole set is required. TestBatchCloserScopesPolicyWithoutClaim covers an
unrelated blocker, a blocked item, and a next claim against such a backend.

[minor] The policy's fallback target read had no pin.
TestExecuteCloseBatchWithPolicyDefersToTheTargetRead drives it through
sqlmock: a missing target keeps the backend's not-found, and a failing status
read reports that failure, never ErrCloseBlocked. Refusing the missing target
or swallowing the read error each fails it.

[nit] DoltStore and EmbeddedDoltStore BatchCloserWithPolicy return
ErrUnsupported on a nil receiver, as NewBatchCloser does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.local>
2026-10-01 01:35:54 -07:00

175 lines
6.9 KiB
Go

package issueops
import (
"context"
"database/sql"
"fmt"
"strings"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
publicops "github.com/steveyegge/beads/issueops"
)
// ValidateCloseBatchRequest applies the request rules every BatchCloser
// implementation shares, so a rule is a contract rather than one backend's
// habit. It rejects the request outright; a per-item refusal is a result, not
// a validation failure, and never reaches here.
func ValidateCloseBatchRequest(request publicops.CloseBatchRequest) error {
if request.Actor == "" {
return fmt.Errorf("%w: close batch requires an actor", storage.ErrValidation)
}
if len(request.Items) == 0 {
return fmt.Errorf("%w: close batch requires at least one item", storage.ErrValidation)
}
for i, item := range request.Items {
if item.IssueID == "" {
return fmt.Errorf("%w: close batch item %d requires an issue ID", storage.ErrValidation, i)
}
}
if request.ClaimNext != nil {
if err := ValidateClaimNextRequest(publicops.ClaimNextRequest{Actor: request.Actor, Filter: *request.ClaimNext}); err != nil {
return err
}
}
return nil
}
// CloseBatchCommitMessage is the history entry a batch records. It is the
// only spelling — the request carries no label to override it, and could not
// compose this one, because it names what LANDED rather than what was asked for,
// which is why it is composed from the result and not from the request: a
// batch that skipped a mistyped id must not claim it in the log.
//
// LANDED is Changed, not "no error": an idempotent re-close persisted nothing,
// so naming it would put an id in `bd dolt log` under a commit that did not
// touch it.
//
// IT NAMES DURABLE LANDINGS ONLY. The wisp tables are dolt-ignored precisely so
// ephemeral work never ships, so an entry naming a wisp is the sync artifact
// ignoring them exists to prevent (issueops/batchcloser.go:128-135). An
// ephemeral landing is reported as a COUNT instead of being dropped, because
// the message is also the callers' commit-or-not signal: the unit-of-work
// backend reads "" as "roll this attempt back", and a batch that closed a wisp
// and nothing else must still keep the close (measured — a durable-only message
// leaves the wisp open there).
//
// It returns "" when nothing landed, which is how the callers spell "commit
// nothing" — a batch that wrote nothing records no history entry.
func CloseBatchCommitMessage(result publicops.CloseBatchResult) string {
ids := make([]string, 0, len(result.Outcomes))
ephemeral := 0
for _, outcome := range result.Outcomes {
if outcome.Err != nil || !outcome.Changed {
continue
}
if closeOutcomeIsEphemeral(outcome) {
ephemeral++
continue
}
ids = append(ids, outcome.IssueID)
}
var parts []string
switch {
case len(ids) > 0:
parts = append(parts, "close "+strings.Join(ids, ", "))
case ephemeral == 1:
parts = append(parts, "close 1 ephemeral item")
case ephemeral > 1:
parts = append(parts, fmt.Sprintf("close %d ephemeral items", ephemeral))
}
if result.ClaimedNext != nil {
parts = append(parts, "claim "+result.ClaimedNext.ID)
}
if len(parts) == 0 {
return ""
}
return "bd: " + strings.Join(parts, "; ")
}
// closeOutcomeIsEphemeral reports whether this landing was on the wisps plane,
// read off the snapshot the close hydrated rather than off a flag the outcome
// does not carry.
//
// A nil Issue counts as DURABLE. The role contract pins Issue non-nil whenever
// Err is nil, so this is unreachable; if it ever happens, naming an id is the
// safer of the two wrong answers, because the alternative silently shortens a
// message the unit-of-work backend reads as "commit nothing".
func closeOutcomeIsEphemeral(outcome publicops.CloseOutcome) bool {
return outcome.Issue != nil && IsWisp(outcome.Issue)
}
// ExecuteCloseBatch closes every item it can in tx and reports the durable
// tables changed. It is the store-backed body behind the BatchCloser accessor;
// the unit-of-work provider has its own, for the same reason Lifecycle does.
//
// A per-item failure lands in that item's outcome and the loop CONTINUES —
// skipping a refused id and committing the survivors is what closing a list of
// issues has always done, and it is the behavior the CLI's per-id stderr
// reports. Only a request-level failure aborts, and it aborts by returning an
// error, which rolls the whole transaction back.
//
// claimFilter is request.ClaimNext already translated by the caller's request
// builder, because this package speaks WorkFilter. A nil filter skips the
// claim, and so does a batch in which nothing landed — landed meaning an item
// that CHANGED, so a batch whose items were all already closed earns no claim.
func ExecuteCloseBatch(ctx context.Context, tx *sql.Tx, request publicops.CloseBatchRequest, claimFilter *types.WorkFilter) (publicops.CloseBatchResult, ChangedTables, error) {
return ExecuteCloseBatchWithPolicy(ctx, tx, request, claimFilter, storage.BatchClosePolicy{})
}
// ExecuteCloseBatchWithPolicy applies an externally resolved snapshot without
// splitting the closes and next claim into separate transactions.
func ExecuteCloseBatchWithPolicy(ctx context.Context, tx *sql.Tx, request publicops.CloseBatchRequest, claimFilter *types.WorkFilter, policy storage.BatchClosePolicy) (publicops.CloseBatchResult, ChangedTables, error) {
result := publicops.CloseBatchResult{Outcomes: make([]publicops.CloseOutcome, len(request.Items))}
tables := ChangedTables{}
landed := 0
for i, item := range request.Items {
if err := policy.CheckClose(item.IssueID, request.Force); err != nil {
// Preserve idempotent re-closes and not-found precedence. Only
// a live target can be refused by the external close policy.
closed, _, found, readErr := isClosedInTx(ctx, tx, item.IssueID)
if readErr != nil {
result.Outcomes[i] = publicops.CloseOutcome{IssueID: item.IssueID, Err: readErr}
continue
}
if found && !closed {
result.Outcomes[i] = publicops.CloseOutcome{IssueID: item.IssueID, Err: err}
continue
}
}
closed, changedTables, err := ExecuteClose(ctx, tx, publicops.CloseRequest{
Actor: request.Actor,
IssueID: item.IssueID,
Reason: item.Reason,
Session: request.Session,
Force: request.Force,
})
if err != nil {
result.Outcomes[i] = publicops.CloseOutcome{IssueID: item.IssueID, Err: err}
continue
}
tables.Merge(changedTables)
if closed.Changed {
landed++
}
result.Outcomes[i] = publicops.CloseOutcome{
IssueID: item.IssueID,
Issue: closed.Issue,
Changed: closed.Changed,
OpenChildren: closed.OpenChildren,
}
}
if claimFilter != nil && landed > 0 {
claim, claimTables, err := ExecuteClaimNext(ctx, tx, request.Actor, policy.FilterClaim(*claimFilter))
if err != nil {
return publicops.CloseBatchResult{}, nil, err
}
tables.Merge(claimTables)
result.ClaimedNext = claim.Claimed
}
return result, tables, nil
}