fix(update): exit nonzero when a multi-ID update partially fails (#4726)
* fix(update): exit nonzero when a multi-ID update partially fails
bd update applies updates per issue ID, but the exit code only went
nonzero when every ID failed (len(args) > 0 && firstUpdatedID == "").
A single successful ID reset the whole batch to exit 0, so a bogus or
unresolvable ID mid-batch was silently swallowed and callers (scripts,
orchestrators) could not detect a partial batch. The GH audit flagged
this: per-ID errors were printed inline on stderr, but the process
reported success.
Empirical baseline-vs-patched evidence (red-team scenarios S1-S7):
baseline `bd update good1 bogus good2 --priority 1` exits rc=0 with one
inline stderr line; patched exits rc=1 with "1 of 3 issues failed to
update" plus a per-ID report. In --json mode the last stderr line is
now a machine-parseable failure report ({error, failed[], schema_version},
envelope-aware) while stdout keeps the array-of-updated-issues success
shape (parsed_list_len=2, both good IDs applied - the command stays
per-ID, not atomic). All-good paths are unchanged: rc=0 and stderr
byte-identical to baseline in both text and JSON modes.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs: auto-regenerate CLI reference
Applied from the cli-docs-freshness-patch artifact of https://github.com/gastownhall/beads/actions/runs/29144979580
(generated with CI's canonical pinned build). See
scripts/check-cli-docs-drift.sh for how drift is attributed.
* docs: auto-regenerate CLI reference
Applied from the cli-docs-freshness-patch artifact of https://github.com/gastownhall/beads/actions/runs/29521598853
(generated with CI's canonical pinned build). See
scripts/check-cli-docs-drift.sh for how drift is attributed.
* fix(update): per-ID failure handling + output parity for multi-ID batches
Maintainer review fixup for PR #4726.
`bd update` over multiple IDs is per-ID, not atomic: every failed ID must
be reported and the command must exit nonzero while the other IDs still
update. Several paths still short-circuited that contract; this fixup
brings them all in line with the documented behavior.
Direct-mode metadata failures are now per-ID (review finding: major /
correctness). A `--metadata` merge or `--set-metadata`/`--unset-metadata`
edit that failed for one ID (e.g. that issue's stored metadata is not a
JSON object) used to return immediately -- aborting the batch, skipping
later IDs, and in --json mode writing the error to stdout instead of the
stderr failure report. It now prints the per-ID error, records the failed
ID, closes the unmutated result, and continues, exactly like the
resolve/update/label/parent paths. Added text and --json coverage with a
middle ID whose existing metadata is non-object for both the merge and the
edit paths.
Proxied-server exit-code parity (review finding: major / correctness). The
proxied path used to exit 0 whenever another ID in the batch succeeded,
hiding generic per-ID failures from exit-code automation.
runUpdateProxiedServer now accumulates every failed ID -- generic per-ID
errors and lost --claim races alike -- and returns the shared
reportUpdateFailures() after emitting successful output, so the batch
exits nonzero with the same stderr failure report (text and --json) as the
non-proxied path.
Proxied output-mode consistency (review finding: minor / maintainability).
Proxied success output now keys off the same global JSON decision (--json
OR --format json OR config) that reportUpdateFailures uses, so success
output and the failure report can no longer disagree on format within one
invocation.
Also fold the non-proxied reparent old-parent RemoveDependency failure
into the failed-ID ledger (review finding: minor / correctness): a failed
removal no longer proceeds to add the new parent edge on top of a stale
one, and no longer counts the ID as a silent success.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
---------
Co-authored-by: Test User <test@test.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
This commit is contained in:
parent
d0603697dc
commit
b2b153b7b8
5 changed files with 586 additions and 41 deletions
5
cmd/bd/testdata/update_errors.txt
vendored
5
cmd/bd/testdata/update_errors.txt
vendored
|
|
@ -2,9 +2,10 @@
|
|||
|
||||
bd init --prefix test
|
||||
|
||||
# Update nonexistent issue prints error to stderr (exits 0 - known issue)
|
||||
bd update nonexistent-id --title 'New title'
|
||||
# Update nonexistent issue prints a per-ID error report and exits nonzero
|
||||
! bd update nonexistent-id --title 'New title'
|
||||
stderr 'no issue found'
|
||||
stderr 'failed to update'
|
||||
|
||||
# Create a real issue for validation tests
|
||||
bd create 'Test issue'
|
||||
|
|
|
|||
113
cmd/bd/update.go
113
cmd/bd/update.go
|
|
@ -26,7 +26,11 @@ var updateCmd = &cobra.Command{
|
|||
Long: `Update one or more issues.
|
||||
|
||||
If no issue ID is provided, updates the last touched issue (from most recent
|
||||
create, update, show, or close operation).`,
|
||||
create, update, show, or close operation).
|
||||
|
||||
Updates are applied per issue ID, not atomically across IDs: when some IDs
|
||||
fail, the remaining issues are still updated, every failed ID is reported on
|
||||
stderr, and the command exits nonzero.`,
|
||||
Args: cobra.MinimumNArgs(0),
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
|
|
@ -314,12 +318,10 @@ create, update, show, or close operation).`,
|
|||
|
||||
updatedIssues := []*types.Issue{}
|
||||
var firstUpdatedID string // Track first successful update for last-touched
|
||||
// claimFailed records a requested-but-lost claim. In a mixed batch (one
|
||||
// claim won, another lost) firstUpdatedID is set by the winner, so the
|
||||
// command would otherwise exit 0 and hide the lost claim from exit-code
|
||||
// automation. Track it separately and exit non-zero when any claim was
|
||||
// requested but not granted (beads audit finding #10).
|
||||
claimFailed := false
|
||||
var failures []updateIDFailure
|
||||
recordFailure := func(id, reason string) {
|
||||
failures = append(failures, updateIDFailure{ID: id, Error: reason})
|
||||
}
|
||||
mutatedStores := map[storage.DoltStorage][]string{}
|
||||
mutatedResults := map[*RoutedResult]bool{}
|
||||
pendingCloseResults := []*RoutedResult{}
|
||||
|
|
@ -356,6 +358,7 @@ create, update, show, or close operation).`,
|
|||
result.Close()
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "Error resolving %s: %v\n", id, err)
|
||||
recordFailure(id, fmt.Sprintf("resolving issue: %v", err))
|
||||
continue
|
||||
}
|
||||
if result == nil || result.Issue == nil {
|
||||
|
|
@ -363,6 +366,7 @@ create, update, show, or close operation).`,
|
|||
result.Close()
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "Issue %s not found\n", id)
|
||||
recordFailure(id, "issue not found")
|
||||
continue
|
||||
}
|
||||
issue := result.Issue
|
||||
|
|
@ -370,6 +374,7 @@ create, update, show, or close operation).`,
|
|||
|
||||
if err := validateIssueUpdatable(id, issue); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "%s\n", err)
|
||||
recordFailure(id, err.Error())
|
||||
closeIfUnmutated(result)
|
||||
continue
|
||||
}
|
||||
|
|
@ -378,7 +383,7 @@ create, update, show, or close operation).`,
|
|||
if claimFlag {
|
||||
if err := issueStore.ClaimIssue(ctx, result.ResolvedID, actor); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error claiming %s: %v\n", id, err)
|
||||
claimFailed = true
|
||||
recordFailure(id, fmt.Sprintf("claiming issue: %v", err))
|
||||
closeIfUnmutated(result)
|
||||
continue
|
||||
}
|
||||
|
|
@ -400,20 +405,32 @@ create, update, show, or close operation).`,
|
|||
regularUpdates["status"] = string(types.StatusOpen)
|
||||
}
|
||||
|
||||
// Handle --metadata: merge with existing metadata instead of replacing
|
||||
// Handle --metadata: merge with existing metadata instead of replacing.
|
||||
// A merge failure (e.g. the issue's existing metadata is not a JSON
|
||||
// object) is a per-ID failure, not a batch abort: record it and move
|
||||
// on like the resolve/update/label/parent paths above, so later IDs
|
||||
// still update and the failed ID surfaces in the nonzero-exit report
|
||||
// instead of the generic stdout error path.
|
||||
if newMeta, ok := regularUpdates["metadata"].(json.RawMessage); ok && len(issue.Metadata) > 0 {
|
||||
merged, err := mergeMetadata(issue.Metadata, newMeta)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("metadata merge failed for %s: %v", id, err)
|
||||
fmt.Fprintf(os.Stderr, "Error merging metadata for %s: %v\n", id, err)
|
||||
recordFailure(id, fmt.Sprintf("merging metadata: %v", err))
|
||||
closeIfUnmutated(result)
|
||||
continue
|
||||
}
|
||||
regularUpdates["metadata"] = merged
|
||||
}
|
||||
// Handle incremental metadata edits (GH#1406)
|
||||
// Handle incremental metadata edits (GH#1406). Same per-ID failure
|
||||
// contract as the merge path above.
|
||||
if setMeta, ok := updates["_set_metadata"].([]string); ok {
|
||||
unsetMeta, _ := updates["_unset_metadata"].([]string)
|
||||
merged, err := applyMetadataEdits(issue.Metadata, setMeta, unsetMeta)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("metadata edit failed for %s: %v", id, err)
|
||||
fmt.Fprintf(os.Stderr, "Error editing metadata for %s: %v\n", id, err)
|
||||
recordFailure(id, fmt.Sprintf("editing metadata: %v", err))
|
||||
closeIfUnmutated(result)
|
||||
continue
|
||||
}
|
||||
regularUpdates["metadata"] = merged
|
||||
}
|
||||
|
|
@ -429,6 +446,7 @@ create, update, show, or close operation).`,
|
|||
if len(regularUpdates) > 0 {
|
||||
if err := issueStore.UpdateIssue(ctx, result.ResolvedID, regularUpdates, actor); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error updating %s: %v\n", id, err)
|
||||
recordFailure(id, fmt.Sprintf("updating issue: %v", err))
|
||||
closeIfUnmutated(result)
|
||||
continue
|
||||
}
|
||||
|
|
@ -459,6 +477,7 @@ create, update, show, or close operation).`,
|
|||
if len(setLabels) > 0 || len(addLabels) > 0 || len(removeLabels) > 0 {
|
||||
if err := applyLabelUpdates(ctx, issueStore, result.ResolvedID, actor, setLabels, addLabels, removeLabels); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error updating labels for %s: %v\n", id, err)
|
||||
recordFailure(id, fmt.Sprintf("updating labels: %v", err))
|
||||
closeIfUnmutated(result)
|
||||
continue
|
||||
}
|
||||
|
|
@ -472,11 +491,13 @@ create, update, show, or close operation).`,
|
|||
parentIssue, err := issueStore.GetIssue(ctx, newParent)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error getting parent %s: %v\n", newParent, err)
|
||||
recordFailure(id, fmt.Sprintf("getting parent %s: %v", newParent, err))
|
||||
closeIfUnmutated(result)
|
||||
continue
|
||||
}
|
||||
if parentIssue == nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: parent issue %s not found\n", newParent)
|
||||
recordFailure(id, fmt.Sprintf("parent issue %s not found", newParent))
|
||||
closeIfUnmutated(result)
|
||||
continue
|
||||
}
|
||||
|
|
@ -486,19 +507,32 @@ create, update, show, or close operation).`,
|
|||
deps, err := issueStore.GetDependencyRecords(ctx, result.ResolvedID)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error getting dependencies for %s: %v\n", id, err)
|
||||
recordFailure(id, fmt.Sprintf("getting dependencies: %v", err))
|
||||
closeIfUnmutated(result)
|
||||
continue
|
||||
}
|
||||
oldParentRemoveFailed := false
|
||||
for _, dep := range deps {
|
||||
if dep.Type == types.DepParentChild {
|
||||
if err := issueStore.RemoveDependency(ctx, result.ResolvedID, dep.DependsOnID, actor); err != nil {
|
||||
// Reparenting removes the old parent edge before adding
|
||||
// the new one; if removal fails, adding the new edge would
|
||||
// leave the issue with two parents. Record the failed ID
|
||||
// and stop so it surfaces in the nonzero-exit report
|
||||
// instead of being silently counted as a success.
|
||||
fmt.Fprintf(os.Stderr, "Error removing old parent dependency: %v\n", err)
|
||||
recordFailure(id, fmt.Sprintf("removing old parent dependency: %v", err))
|
||||
oldParentRemoveFailed = true
|
||||
} else {
|
||||
trackMutation(result)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
if oldParentRemoveFailed {
|
||||
closeIfUnmutated(result)
|
||||
continue
|
||||
}
|
||||
|
||||
// Add new parent-child dependency (if not removing parent)
|
||||
if newParent != "" {
|
||||
|
|
@ -509,6 +543,7 @@ create, update, show, or close operation).`,
|
|||
}
|
||||
if err := issueStore.AddDependency(ctx, newDep, actor); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error adding parent dependency: %v\n", err)
|
||||
recordFailure(id, fmt.Sprintf("adding parent dependency: %v", err))
|
||||
closeIfUnmutated(result)
|
||||
continue
|
||||
}
|
||||
|
|
@ -565,13 +600,63 @@ create, update, show, or close operation).`,
|
|||
}
|
||||
}
|
||||
|
||||
if (len(args) > 0 && firstUpdatedID == "") || claimFailed {
|
||||
return SilentExit()
|
||||
// Updates are per-ID, not atomic across IDs: successful updates above
|
||||
// stay applied (and committed), but any per-ID failure must surface as
|
||||
// a nonzero exit so callers can detect a partial batch (GH audit:
|
||||
// multi-ID update used to exit 0 after mid-batch failures).
|
||||
if len(failures) > 0 {
|
||||
return reportUpdateFailures(failures, len(args))
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
// updateIDFailure records one issue ID that could not be updated and why.
|
||||
type updateIDFailure struct {
|
||||
ID string `json:"id"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
// reportUpdateFailures emits a per-ID failure report on stderr and returns a
|
||||
// nonzero exit error. In --json mode the report is a single compact JSON
|
||||
// line — the last line on stderr — so callers can parse which IDs failed
|
||||
// while stdout keeps the plain array-of-updated-issues success shape. In
|
||||
// text mode the individual errors were already printed inline; this adds a
|
||||
// summary naming every failed ID.
|
||||
func reportUpdateFailures(failures []updateIDFailure, total int) error {
|
||||
msg := fmt.Sprintf("%d of %d issues failed to update", len(failures), total)
|
||||
if jsonOutput {
|
||||
inner := map[string]interface{}{
|
||||
"error": msg,
|
||||
"failed": failures,
|
||||
}
|
||||
var payload interface{}
|
||||
if jsonEnvelopeEnabled() {
|
||||
payload = map[string]interface{}{
|
||||
"schema_version": JSONSchemaVersion,
|
||||
"data": inner,
|
||||
}
|
||||
} else {
|
||||
inner["schema_version"] = JSONSchemaVersion
|
||||
payload = inner
|
||||
}
|
||||
data, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
// Marshaling flat strings cannot realistically fail; fall back to
|
||||
// the text summary rather than exiting silently.
|
||||
fmt.Fprintf(os.Stderr, "Error: %s\n", msg)
|
||||
} else {
|
||||
fmt.Fprintln(os.Stderr, string(data))
|
||||
}
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Error: %s\n", msg)
|
||||
for _, f := range failures {
|
||||
fmt.Fprintf(os.Stderr, " %s: %s\n", f.ID, f.Error)
|
||||
}
|
||||
}
|
||||
return &exitError{Code: 1}
|
||||
}
|
||||
|
||||
// mergeMetadata merges new metadata JSON into existing metadata.
|
||||
// Keys from newMeta overwrite keys in existing; keys only in existing are preserved.
|
||||
func mergeMetadata(existing, newMeta json.RawMessage) (json.RawMessage, error) {
|
||||
|
|
|
|||
380
cmd/bd/update_multi_id_exit_test.go
Normal file
380
cmd/bd/update_multi_id_exit_test.go
Normal file
|
|
@ -0,0 +1,380 @@
|
|||
// Tests for multi-ID `bd update` exit-code semantics (GH audit: multi-ID
|
||||
// update exits 0 after a mid-batch failure, so callers cannot detect that
|
||||
// some IDs were not updated).
|
||||
//
|
||||
// Contract under test:
|
||||
// - `bd update` applies updates per issue ID, not atomically across IDs:
|
||||
// successful IDs stay applied even when other IDs fail.
|
||||
// - Any per-ID failure makes the command exit nonzero with a per-ID error
|
||||
// report on stderr.
|
||||
// - In --json mode stdout keeps the existing success shape (array of
|
||||
// updated issues) and the failure report is emitted as a single JSON
|
||||
// line on stderr listing which IDs failed.
|
||||
// - The all-good path is unchanged: exit 0, clean stderr.
|
||||
//
|
||||
// This file MUST NOT carry a cgo build tag: it exercises the default sqlite
|
||||
// backend via a bd binary built with the gms_pure_go tag.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// multiIDUpdateEnv returns a hermetic environment for bd subprocess runs:
|
||||
// no inherited BEADS_* variables, HOME pinned to the test dir, metrics and
|
||||
// daemons disabled.
|
||||
func multiIDUpdateEnv(dir string) []string {
|
||||
var env []string
|
||||
for _, e := range os.Environ() {
|
||||
if strings.HasPrefix(e, "BEADS_") {
|
||||
continue
|
||||
}
|
||||
env = append(env, e)
|
||||
}
|
||||
return append(env,
|
||||
"HOME="+dir,
|
||||
"BD_NON_INTERACTIVE=1",
|
||||
"BD_DISABLE_METRICS=1",
|
||||
"BD_DISABLE_EVENT_FLUSH=1",
|
||||
"BEADS_NO_DAEMON=1",
|
||||
"BEADS_DOLT_AUTO_START=0",
|
||||
)
|
||||
}
|
||||
|
||||
// runBDMultiID runs the bd binary and returns stdout, stderr, and the exit
|
||||
// code. Only a failure to launch the process fails the test; nonzero exits
|
||||
// are returned to the caller for assertion.
|
||||
func runBDMultiID(t *testing.T, bd, dir string, args ...string) (stdout, stderr string, exitCode int) {
|
||||
t.Helper()
|
||||
cmd := exec.Command(bd, args...)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = multiIDUpdateEnv(dir)
|
||||
var outBuf, errBuf bytes.Buffer
|
||||
cmd.Stdout = &outBuf
|
||||
cmd.Stderr = &errBuf
|
||||
if err := cmd.Run(); err != nil {
|
||||
var ee *exec.ExitError
|
||||
if !errors.As(err, &ee) {
|
||||
t.Fatalf("bd %v did not run: %v", args, err)
|
||||
}
|
||||
return outBuf.String(), errBuf.String(), ee.ExitCode()
|
||||
}
|
||||
return outBuf.String(), errBuf.String(), 0
|
||||
}
|
||||
|
||||
// setupMultiIDUpdateDB builds bd and initializes a fresh sqlite-backed
|
||||
// database in a temp dir.
|
||||
func setupMultiIDUpdateDB(t *testing.T) (bd, dir string) {
|
||||
t.Helper()
|
||||
bd = buildBDForInitTests(t)
|
||||
dir = t.TempDir()
|
||||
stdout, stderr, code := runBDMultiID(t, bd, dir,
|
||||
"init", "--prefix", "test", "--quiet", "--non-interactive", "--skip-hooks", "--skip-agents")
|
||||
if code != 0 {
|
||||
t.Fatalf("bd init failed (exit %d):\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
|
||||
}
|
||||
return bd, dir
|
||||
}
|
||||
|
||||
// createMultiIDUpdateIssue creates an issue and returns its ID.
|
||||
func createMultiIDUpdateIssue(t *testing.T, bd, dir, title string) string {
|
||||
t.Helper()
|
||||
stdout, stderr, code := runBDMultiID(t, bd, dir, "create", title, "-p", "2", "--json")
|
||||
if code != 0 {
|
||||
t.Fatalf("bd create failed (exit %d):\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
|
||||
}
|
||||
var issue struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(stdout), &issue); err != nil {
|
||||
t.Fatalf("parsing create --json output: %v\n%s", err, stdout)
|
||||
}
|
||||
if issue.ID == "" {
|
||||
t.Fatalf("bd create --json returned no id:\n%s", stdout)
|
||||
}
|
||||
return issue.ID
|
||||
}
|
||||
|
||||
// showMultiIDUpdatePriority fetches an issue's priority via bd show --json.
|
||||
func showMultiIDUpdatePriority(t *testing.T, bd, dir, id string) int {
|
||||
t.Helper()
|
||||
stdout, stderr, code := runBDMultiID(t, bd, dir, "show", id, "--json")
|
||||
if code != 0 {
|
||||
t.Fatalf("bd show %s failed (exit %d):\nstdout:\n%s\nstderr:\n%s", id, code, stdout, stderr)
|
||||
}
|
||||
var details []struct {
|
||||
ID string `json:"id"`
|
||||
Priority int `json:"priority"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(stdout), &details); err != nil {
|
||||
t.Fatalf("parsing show --json output for %s: %v\n%s", id, err, stdout)
|
||||
}
|
||||
if len(details) != 1 || details[0].ID != id {
|
||||
t.Fatalf("show --json for %s returned unexpected issues:\n%s", id, stdout)
|
||||
}
|
||||
return details[0].Priority
|
||||
}
|
||||
|
||||
// bogusMultiIDUpdateID is an ID that cannot collide with generated issue IDs
|
||||
// (bd resolves fuzzy/substring matches, so it must not be a substring of a
|
||||
// real ID either).
|
||||
const bogusMultiIDUpdateID = "test-zzzzzzzzzz"
|
||||
|
||||
func TestMultiIDUpdatePartialFailureExitsNonzero(t *testing.T) {
|
||||
bd, dir := setupMultiIDUpdateDB(t)
|
||||
id1 := createMultiIDUpdateIssue(t, bd, dir, "first issue")
|
||||
id2 := createMultiIDUpdateIssue(t, bd, dir, "second issue")
|
||||
|
||||
stdout, stderr, code := runBDMultiID(t, bd, dir, "update", id1, bogusMultiIDUpdateID, id2, "--priority", "0")
|
||||
if code == 0 {
|
||||
t.Errorf("bd update with a bogus ID mid-batch exited 0, want nonzero\nstdout:\n%s\nstderr:\n%s", stdout, stderr)
|
||||
}
|
||||
if !strings.Contains(stderr, bogusMultiIDUpdateID) {
|
||||
t.Errorf("stderr does not mention the failed ID %s:\n%s", bogusMultiIDUpdateID, stderr)
|
||||
}
|
||||
|
||||
// The command is per-ID, not atomic: both good IDs must still be applied.
|
||||
for _, id := range []string{id1, id2} {
|
||||
if got := showMultiIDUpdatePriority(t, bd, dir, id); got != 0 {
|
||||
t.Errorf("issue %s priority = %d, want 0 (successful IDs must stay applied)", id, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMultiIDUpdatePartialFailureJSONReportsFailedIDs(t *testing.T) {
|
||||
bd, dir := setupMultiIDUpdateDB(t)
|
||||
id1 := createMultiIDUpdateIssue(t, bd, dir, "first issue")
|
||||
id2 := createMultiIDUpdateIssue(t, bd, dir, "second issue")
|
||||
|
||||
stdout, stderr, code := runBDMultiID(t, bd, dir, "update", id1, bogusMultiIDUpdateID, id2, "--priority", "0", "--json")
|
||||
if code == 0 {
|
||||
t.Errorf("bd update --json with a bogus ID mid-batch exited 0, want nonzero\nstdout:\n%s\nstderr:\n%s", stdout, stderr)
|
||||
}
|
||||
|
||||
// stdout keeps the existing success shape: an array of the successfully
|
||||
// updated issues.
|
||||
var updated []struct {
|
||||
ID string `json:"id"`
|
||||
Priority int `json:"priority"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(stdout), &updated); err != nil {
|
||||
t.Fatalf("stdout is not the array-of-issues success shape: %v\n%s", err, stdout)
|
||||
}
|
||||
gotIDs := map[string]bool{}
|
||||
for _, u := range updated {
|
||||
gotIDs[u.ID] = true
|
||||
if u.Priority != 0 {
|
||||
t.Errorf("updated issue %s priority = %d, want 0", u.ID, u.Priority)
|
||||
}
|
||||
}
|
||||
if !gotIDs[id1] || !gotIDs[id2] || len(updated) != 2 {
|
||||
t.Errorf("stdout array = %v, want exactly [%s %s]", updated, id1, id2)
|
||||
}
|
||||
|
||||
// The last stderr line is a machine-parseable failure report naming the
|
||||
// failed ID.
|
||||
lines := strings.Split(strings.TrimSpace(stderr), "\n")
|
||||
last := lines[len(lines)-1]
|
||||
var report struct {
|
||||
Error string `json:"error"`
|
||||
Failed []struct {
|
||||
ID string `json:"id"`
|
||||
Error string `json:"error"`
|
||||
} `json:"failed"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(last), &report); err != nil {
|
||||
t.Fatalf("last stderr line is not a JSON failure report: %v\nstderr:\n%s", err, stderr)
|
||||
}
|
||||
if report.Error == "" {
|
||||
t.Errorf("JSON failure report has empty error message: %s", last)
|
||||
}
|
||||
if len(report.Failed) != 1 || report.Failed[0].ID != bogusMultiIDUpdateID {
|
||||
t.Errorf("JSON failure report failed list = %+v, want exactly one entry for %s", report.Failed, bogusMultiIDUpdateID)
|
||||
}
|
||||
if len(report.Failed) == 1 && report.Failed[0].Error == "" {
|
||||
t.Errorf("JSON failure report entry has empty per-ID error: %s", last)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMultiIDUpdateAllFailStillExitsNonzero(t *testing.T) {
|
||||
bd, dir := setupMultiIDUpdateDB(t)
|
||||
|
||||
stdout, stderr, code := runBDMultiID(t, bd, dir, "update", bogusMultiIDUpdateID, "--priority", "0")
|
||||
if code == 0 {
|
||||
t.Errorf("bd update with only a bogus ID exited 0, want nonzero\nstdout:\n%s\nstderr:\n%s", stdout, stderr)
|
||||
}
|
||||
if !strings.Contains(stderr, bogusMultiIDUpdateID) {
|
||||
t.Errorf("stderr does not mention the failed ID %s:\n%s", bogusMultiIDUpdateID, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMultiIDUpdateAllGoodPathUnchanged(t *testing.T) {
|
||||
bd, dir := setupMultiIDUpdateDB(t)
|
||||
id1 := createMultiIDUpdateIssue(t, bd, dir, "first issue")
|
||||
id2 := createMultiIDUpdateIssue(t, bd, dir, "second issue")
|
||||
|
||||
stdout, stderr, code := runBDMultiID(t, bd, dir, "update", id1, id2, "--priority", "1", "--json")
|
||||
if code != 0 {
|
||||
t.Fatalf("all-good bd update --json exited %d, want 0\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
|
||||
}
|
||||
if stderr != "" {
|
||||
t.Errorf("all-good bd update --json wrote to stderr (success path must stay byte-identical):\n%s", stderr)
|
||||
}
|
||||
var updated []struct {
|
||||
ID string `json:"id"`
|
||||
Priority int `json:"priority"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(stdout), &updated); err != nil {
|
||||
t.Fatalf("stdout is not the array-of-issues success shape: %v\n%s", err, stdout)
|
||||
}
|
||||
if len(updated) != 2 {
|
||||
t.Fatalf("updated %d issues, want 2:\n%s", len(updated), stdout)
|
||||
}
|
||||
for _, u := range updated {
|
||||
if u.Priority != 1 {
|
||||
t.Errorf("updated issue %s priority = %d, want 1", u.ID, u.Priority)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// seedNonObjectMetadata sets an issue's metadata to a JSON array so a later
|
||||
// --metadata merge or --set-metadata edit for that ID fails ("existing metadata
|
||||
// is not a JSON object"). --metadata only requires valid JSON, not an object,
|
||||
// so the non-object value persists and reproduces the mid-batch metadata
|
||||
// failure the per-ID contract must survive.
|
||||
func seedNonObjectMetadata(t *testing.T, bd, dir, id string) {
|
||||
t.Helper()
|
||||
stdout, stderr, code := runBDMultiID(t, bd, dir, "update", id, "--metadata", "[]")
|
||||
if code != 0 {
|
||||
t.Fatalf("seeding non-object metadata on %s failed (exit %d):\nstdout:\n%s\nstderr:\n%s", id, code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// showMultiIDUpdateMetadataValue returns a string-valued metadata key for an
|
||||
// issue via bd show --json, failing the test if the key is missing or not a
|
||||
// JSON string. Used to confirm that IDs surrounding a failed one still received
|
||||
// their metadata update.
|
||||
func showMultiIDUpdateMetadataValue(t *testing.T, bd, dir, id, key string) string {
|
||||
t.Helper()
|
||||
stdout, stderr, code := runBDMultiID(t, bd, dir, "show", id, "--json")
|
||||
if code != 0 {
|
||||
t.Fatalf("bd show %s failed (exit %d):\nstdout:\n%s\nstderr:\n%s", id, code, stdout, stderr)
|
||||
}
|
||||
var details []struct {
|
||||
ID string `json:"id"`
|
||||
Metadata map[string]json.RawMessage `json:"metadata"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(stdout), &details); err != nil {
|
||||
t.Fatalf("parsing show --json output for %s: %v\n%s", id, err, stdout)
|
||||
}
|
||||
if len(details) != 1 || details[0].ID != id {
|
||||
t.Fatalf("show --json for %s returned unexpected issues:\n%s", id, stdout)
|
||||
}
|
||||
raw, ok := details[0].Metadata[key]
|
||||
if !ok {
|
||||
t.Fatalf("issue %s metadata has no key %q:\n%s", id, key, stdout)
|
||||
}
|
||||
var val string
|
||||
if err := json.Unmarshal(raw, &val); err != nil {
|
||||
t.Fatalf("issue %s metadata[%q] = %s, not a JSON string: %v", id, key, raw, err)
|
||||
}
|
||||
return val
|
||||
}
|
||||
|
||||
// TestMultiIDUpdatePartialMetadataMergeFailure covers a --metadata merge that
|
||||
// fails for one middle ID (its stored metadata is not a JSON object). The merge
|
||||
// failure must be a per-ID failure — reported on stderr with a nonzero exit —
|
||||
// not a batch abort that skips the trailing IDs.
|
||||
func TestMultiIDUpdatePartialMetadataMergeFailure(t *testing.T) {
|
||||
bd, dir := setupMultiIDUpdateDB(t)
|
||||
id1 := createMultiIDUpdateIssue(t, bd, dir, "first issue")
|
||||
id2 := createMultiIDUpdateIssue(t, bd, dir, "second issue")
|
||||
id3 := createMultiIDUpdateIssue(t, bd, dir, "third issue")
|
||||
seedNonObjectMetadata(t, bd, dir, id2)
|
||||
|
||||
stdout, stderr, code := runBDMultiID(t, bd, dir, "update", id1, id2, id3, "--metadata", `{"team":"platform"}`)
|
||||
if code == 0 {
|
||||
t.Errorf("bd update with a mid-batch metadata-merge failure exited 0, want nonzero\nstdout:\n%s\nstderr:\n%s", stdout, stderr)
|
||||
}
|
||||
if !strings.Contains(stderr, id2) {
|
||||
t.Errorf("stderr does not mention the failed ID %s:\n%s", id2, stderr)
|
||||
}
|
||||
// Per-ID, not atomic: the IDs on either side of the failure must still carry
|
||||
// the merged metadata.
|
||||
for _, id := range []string{id1, id3} {
|
||||
if got := showMultiIDUpdateMetadataValue(t, bd, dir, id, "team"); got != "platform" {
|
||||
t.Errorf("issue %s metadata team = %q, want \"platform\" (successful IDs must stay applied)", id, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestMultiIDUpdatePartialMetadataEditFailureJSON covers a --set-metadata edit
|
||||
// that fails for one middle ID under --json. stdout must keep the success array
|
||||
// for the applied IDs while the failed ID is reported only in the JSON failure
|
||||
// line on stderr, with a nonzero exit.
|
||||
func TestMultiIDUpdatePartialMetadataEditFailureJSON(t *testing.T) {
|
||||
bd, dir := setupMultiIDUpdateDB(t)
|
||||
id1 := createMultiIDUpdateIssue(t, bd, dir, "first issue")
|
||||
id2 := createMultiIDUpdateIssue(t, bd, dir, "second issue")
|
||||
id3 := createMultiIDUpdateIssue(t, bd, dir, "third issue")
|
||||
seedNonObjectMetadata(t, bd, dir, id2)
|
||||
|
||||
stdout, stderr, code := runBDMultiID(t, bd, dir, "update", id1, id2, id3, "--set-metadata", "team=platform", "--json")
|
||||
if code == 0 {
|
||||
t.Errorf("bd update --json with a mid-batch metadata-edit failure exited 0, want nonzero\nstdout:\n%s\nstderr:\n%s", stdout, stderr)
|
||||
}
|
||||
|
||||
// stdout keeps the array-of-updated-issues success shape for the IDs that
|
||||
// applied; the failed ID must not appear there.
|
||||
var updated []struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(stdout), &updated); err != nil {
|
||||
t.Fatalf("stdout is not the array-of-issues success shape: %v\n%s", err, stdout)
|
||||
}
|
||||
gotIDs := map[string]bool{}
|
||||
for _, u := range updated {
|
||||
gotIDs[u.ID] = true
|
||||
}
|
||||
if !gotIDs[id1] || !gotIDs[id3] || len(updated) != 2 {
|
||||
t.Errorf("stdout array = %v, want exactly [%s %s]", updated, id1, id3)
|
||||
}
|
||||
if gotIDs[id2] {
|
||||
t.Errorf("failed ID %s must not appear in the stdout success array:\n%s", id2, stdout)
|
||||
}
|
||||
|
||||
// The last stderr line is a machine-parseable failure report naming the
|
||||
// failed ID.
|
||||
lines := strings.Split(strings.TrimSpace(stderr), "\n")
|
||||
last := lines[len(lines)-1]
|
||||
var report struct {
|
||||
Error string `json:"error"`
|
||||
Failed []struct {
|
||||
ID string `json:"id"`
|
||||
Error string `json:"error"`
|
||||
} `json:"failed"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(last), &report); err != nil {
|
||||
t.Fatalf("last stderr line is not a JSON failure report: %v\nstderr:\n%s", err, stderr)
|
||||
}
|
||||
if len(report.Failed) != 1 || report.Failed[0].ID != id2 {
|
||||
t.Errorf("JSON failure report failed list = %+v, want exactly one entry for %s", report.Failed, id2)
|
||||
}
|
||||
if len(report.Failed) == 1 && report.Failed[0].Error == "" {
|
||||
t.Errorf("JSON failure report entry has empty per-ID error: %s", last)
|
||||
}
|
||||
|
||||
// The IDs surrounding the failure still carry the edited metadata.
|
||||
for _, id := range []string{id1, id3} {
|
||||
if got := showMultiIDUpdateMetadataValue(t, bd, dir, id, "team"); got != "platform" {
|
||||
t.Errorf("issue %s metadata team = %q, want \"platform\"", id, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -123,6 +123,83 @@ func TestProxiedServerUpdate(t *testing.T) {
|
|||
}
|
||||
})
|
||||
|
||||
// Parity with the non-proxied TestMultiIDUpdatePartialFailureExitsNonzero:
|
||||
// a generic per-ID failure (a bogus ID) between two good IDs must exit
|
||||
// non-zero and name the failed ID, while the good IDs stay applied. Before
|
||||
// the proxied-parity fix the proxied path returned exit 0 whenever another
|
||||
// ID succeeded, hiding the failure from exit-code automation.
|
||||
t.Run("generic_batch_partial_failure_exits_nonzero", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
p := newSharedProxiedProject(t, bd, "ugbp")
|
||||
good1 := bdProxiedCreate(t, bd, p.dir, "Batch good 1")
|
||||
good2 := bdProxiedCreate(t, bd, p.dir, "Batch good 2")
|
||||
const bogus = "ugbp-zzzzzzzzzz" // cannot collide with generated IDs
|
||||
|
||||
out := bdProxiedUpdateFail(t, bd, p.dir, good1.ID, bogus, good2.ID, "--priority", "0")
|
||||
if !strings.Contains(out, bogus) {
|
||||
t.Errorf("expected failed ID %s in output, got: %s", bogus, out)
|
||||
}
|
||||
// The command is per-ID, not atomic: both good IDs must still be applied.
|
||||
for _, id := range []string{good1.ID, good2.ID} {
|
||||
if got := bdProxiedShow(t, bd, p.dir, id); got.Priority != 0 {
|
||||
t.Errorf("issue %s priority = %d, want 0 (successful IDs must stay applied)", id, got.Priority)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// The --json partial-failure contract on the proxied path: stdout keeps the
|
||||
// array-of-updated-issues success shape and the last stderr line is the
|
||||
// machine-parseable failed-ID report, matching the non-proxied path.
|
||||
t.Run("generic_batch_partial_failure_json_reports_failed_ids", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
p := newSharedProxiedProject(t, bd, "ugbj")
|
||||
good1 := bdProxiedCreate(t, bd, p.dir, "JSON good 1")
|
||||
good2 := bdProxiedCreate(t, bd, p.dir, "JSON good 2")
|
||||
const bogus = "ugbj-zzzzzzzzzz"
|
||||
|
||||
stdout, stderr, err := bdProxiedUpdateRaw(t, bd, p.dir, "--json", good1.ID, bogus, good2.ID, "--priority", "0")
|
||||
if err == nil {
|
||||
t.Fatalf("proxied --json batch with a bogus ID exited 0, want non-zero\nstdout:\n%s\nstderr:\n%s", stdout, stderr)
|
||||
}
|
||||
|
||||
// stdout keeps the success array of the two updated issues.
|
||||
start := strings.Index(stdout, "[")
|
||||
if start < 0 {
|
||||
t.Fatalf("no JSON success array on stdout:\n%s", stdout)
|
||||
}
|
||||
var updated []*types.Issue
|
||||
if uerr := json.Unmarshal([]byte(stdout[start:]), &updated); uerr != nil {
|
||||
t.Fatalf("stdout is not the array-of-issues success shape: %v\n%s", uerr, stdout)
|
||||
}
|
||||
gotIDs := map[string]bool{}
|
||||
for _, u := range updated {
|
||||
gotIDs[u.ID] = true
|
||||
}
|
||||
if len(updated) != 2 || !gotIDs[good1.ID] || !gotIDs[good2.ID] {
|
||||
t.Errorf("stdout success array = %v, want exactly the two good IDs %s %s", updated, good1.ID, good2.ID)
|
||||
}
|
||||
|
||||
// The last stderr line is a JSON failure report naming the bogus ID.
|
||||
lines := strings.Split(strings.TrimSpace(stderr), "\n")
|
||||
last := lines[len(lines)-1]
|
||||
var report struct {
|
||||
Error string `json:"error"`
|
||||
Failed []struct {
|
||||
ID string `json:"id"`
|
||||
Error string `json:"error"`
|
||||
} `json:"failed"`
|
||||
}
|
||||
if uerr := json.Unmarshal([]byte(last), &report); uerr != nil {
|
||||
t.Fatalf("last stderr line is not a JSON failure report: %v\nstderr:\n%s", uerr, stderr)
|
||||
}
|
||||
if report.Error == "" {
|
||||
t.Errorf("JSON failure report has empty error message: %s", last)
|
||||
}
|
||||
if len(report.Failed) != 1 || report.Failed[0].ID != bogus {
|
||||
t.Errorf("JSON failure report failed list = %+v, want exactly one entry for %s", report.Failed, bogus)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("add_remove_labels", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
p := newSharedProxiedProject(t, bd, "ul")
|
||||
|
|
|
|||
|
|
@ -32,28 +32,28 @@ func runUpdateProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri
|
|||
return nil
|
||||
}
|
||||
|
||||
jsonOut, _ := cmd.Flags().GetBool("json")
|
||||
// Derive success-output format from the global JSON decision (--json OR
|
||||
// --format json OR config), the same signal reportUpdateFailures uses, so
|
||||
// success output and the failure report never disagree on format within one
|
||||
// invocation. This matches the non-proxied path in update.go.
|
||||
jsonOut := jsonOutput
|
||||
var updated []*types.Issue
|
||||
var anyUpdated bool
|
||||
// claimFailed records a requested-but-lost --claim. In a mixed batch (one
|
||||
// claim won, another lost to a different owner) anyUpdated is set by the
|
||||
// winner, so the command would otherwise exit 0 and hide the lost claim from
|
||||
// exit-code automation. Track it separately and exit non-zero, mirroring the
|
||||
// non-proxied path in update.go (beads audit finding #10).
|
||||
claimFailed := false
|
||||
// failures accumulates every requested ID that could not be updated —
|
||||
// generic per-ID errors as well as a lost --claim race. In a mixed batch a
|
||||
// later winner used to flip the exit code back to success and hide the
|
||||
// failed IDs from exit-code automation; report them all and exit non-zero,
|
||||
// mirroring the non-proxied path in update.go (beads audit finding #10).
|
||||
var failures []updateIDFailure
|
||||
|
||||
for _, id := range args {
|
||||
issue, ok, claimLost, err := applyUpdateProxiedOne(ctx, id, in)
|
||||
issue, failReason, err := applyUpdateProxiedOne(ctx, id, in)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if claimLost {
|
||||
claimFailed = true
|
||||
}
|
||||
if !ok {
|
||||
if failReason != "" {
|
||||
failures = append(failures, updateIDFailure{ID: id, Error: failReason})
|
||||
continue
|
||||
}
|
||||
anyUpdated = true
|
||||
if jsonOut {
|
||||
updated = append(updated, issue)
|
||||
} else {
|
||||
|
|
@ -64,8 +64,8 @@ func runUpdateProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri
|
|||
if jsonOut && len(updated) > 0 {
|
||||
_ = outputJSON(updated)
|
||||
}
|
||||
if !anyUpdated || claimFailed {
|
||||
return SilentExit()
|
||||
if len(failures) > 0 {
|
||||
return reportUpdateFailures(failures, len(args))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -76,13 +76,15 @@ type updateProxiedResult struct {
|
|||
updated bool
|
||||
}
|
||||
|
||||
// applyUpdateProxiedOne applies one ID's update on the proxied path. The third
|
||||
// return (claimLost) reports a requested --claim that lost to a different owner
|
||||
// (already-claimed / not-claimable), so the caller can flip the batch exit code
|
||||
// even when another ID succeeded — matching the non-proxied path.
|
||||
func applyUpdateProxiedOne(ctx context.Context, id string, in *updateInput) (*types.Issue, bool, bool, error) {
|
||||
// applyUpdateProxiedOne applies one ID's update on the proxied path. On success
|
||||
// it returns the updated issue and an empty failReason. On a per-ID failure it
|
||||
// returns a non-empty failReason (already printed inline on stderr), including a
|
||||
// lost --claim race (already-claimed / not-claimable), so the caller records the
|
||||
// failed ID and exits non-zero — matching the non-proxied path. A non-nil error
|
||||
// is reserved for a hard, batch-aborting condition (uninitialized UOW provider).
|
||||
func applyUpdateProxiedOne(ctx context.Context, id string, in *updateInput) (*types.Issue, string, error) {
|
||||
if uowProvider == nil {
|
||||
return nil, false, false, HandleError("proxied-server UOW provider not initialized")
|
||||
return nil, "", HandleError("proxied-server UOW provider not initialized")
|
||||
}
|
||||
|
||||
var claimLost bool
|
||||
|
|
@ -122,10 +124,10 @@ func applyUpdateProxiedOne(ctx context.Context, id string, in *updateInput) (*ty
|
|||
if err != nil {
|
||||
if claimLost {
|
||||
fmt.Fprintf(os.Stderr, "Error claiming %s: %v\n", id, err)
|
||||
return nil, false, true, nil
|
||||
return nil, fmt.Sprintf("claiming issue: %v", err), nil
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
return nil, false, false, nil
|
||||
return nil, err.Error(), nil
|
||||
}
|
||||
|
||||
if res.updated {
|
||||
|
|
@ -133,7 +135,7 @@ func applyUpdateProxiedOne(ctx context.Context, id string, in *updateInput) (*ty
|
|||
fmt.Fprintf(os.Stderr, "warning: %s: %v\n", id, err)
|
||||
}
|
||||
}
|
||||
return res.after, res.updated, false, nil
|
||||
return res.after, "", nil
|
||||
}
|
||||
|
||||
func fireProxiedUpdateHooks(ctx context.Context, before, after *types.Issue) error {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue