feat(unclaim): add --if-assignee conditional release (CAS inverse of claim) (#4727)

* feat(unclaim): add --if-assignee conditional release (CAS inverse of claim)

bd has an atomic compare-and-swap on the claim side (ClaimIssueInTx:
UPDATE ... WHERE assignee = '' with RowsAffected as the verdict) but no
inverse on the release side. The concurrency audit flagged this as the
conditional-release gap: a supervisor returning a dead worker's issue
(e.g. gas city's orphan release) can only do read-then-unclaim, a TOCTOU
window in which the claim may be reclaimed and re-taken by another worker
-- the stale releaser then silently clobbers the live claim. The only
atomic workaround was raw `bd sql`, which is neither portable nor part of
the CLI contract.

This adds `bd unclaim --if-assignee <who>`, backed by a new
Storage.UnclaimIssueIfAssignee that reuses the claim-side CAS idiom:
UPDATE ... WHERE id = ? AND assignee = ? in the same mutation tx,
returning typed storage.ErrAssigneeMismatch (naming the current holder)
and leaving the row untouched when the holder differs. On success it
applies the same transition as an ordinary unclaim (assignee cleared,
status reopened, started_at cleared, lease dropped, row_lock rewritten,
"unclaimed" event recorded). Wired through the shared issueops helper and
both storage backends (Dolt server and embedded Dolt), and instrumented
in telemetry. Covered by storage conformance cases (match + stale) and an
end-to-end CLI test.

Adopted onto current main via the /adopt-pr workflow: the original PR
predated the storage refactor that removed the sqlkit/SQLite/MySQL/Postgres
backends, so the change was re-expressed against the current Dolt-only
Storage interface (which had also gained unclaim's force flag), dropping
the now-obsolete per-backend "unsupported" wiring.

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

* fix(unclaim): reject empty --if-assignee and conflicting --force

Review (attempt 1) found the CLI selected the conditional compare-and-swap
release on `ifAssignee != ""`, so an explicitly empty `--if-assignee ""` (an
unset variable expanded into the flag) silently fell back to an
unconditional, --force-capable release, and `--force`/`--if-assignee` could
be combined with one flag silently winning.

Dispatch on cmd.Flags().Changed("if-assignee") instead, reject an explicitly
empty expected assignee before processing any IDs, and mark --force and
--if-assignee mutually exclusive. Update the command help to state the
contract and add CLI regression tests for the empty-value and combined-flag
cases (both run as the holder, so the pre-fix behavior would have released
the claim).

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

* fix: extend embedded conformance timeout

---------

Co-authored-by: Test User <test@test.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Julian Knutsen 2026-07-18 03:23:13 -07:00 • committed by GitHub
commit 639c56f819
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
12 changed files with 386 additions and 14 deletions

View file

@ -203,9 +203,9 @@ jobs:
# Conformance suite (conformance.RunAll via TestConformance) against the
# embedded Dolt backend. Split from test-embedded-storage so each job
# stays well under its timeout; the server twin runs in mybd-665b's job.
# 30m matches the repo's integration timeout: the audit suite is large and
# embedded Dolt under -race is slow, so 15m no longer left headroom.
run: /tmp/embeddeddolt-test -test.v -test.count=1 -test.timeout=30m -test.run '^TestConformance$'
# 45m gives the audit-heavy embedded run enough headroom without making
# the workflow open-ended.
run: /tmp/embeddeddolt-test -test.v -test.count=1 -test.timeout=45m -test.run '^TestConformance$'
test-server-storage:
name: Test (Server Dolt Conformance)

View file

@ -25,10 +25,23 @@ actor's claim requires --force and should be coordinated with the holder
first — their claim may be live even if the issue looks idle. Prefer
letting lease expiry reclaim genuinely abandoned work.
With --if-assignee, the release is an atomic compare-and-swap (the inverse of
claim): the issue is released only while it is still assigned to the given
assignee. If the holder differs — e.g. the claim was already reclaimed and
re-taken by another worker — nothing is changed and bd exits nonzero with an
error naming the current holder. Use this from supervisors that must return a
specific worker's issue without ever clobbering someone else's live claim.
--if-assignee requires a non-empty assignee and cannot be combined with --force
(they encode contradictory intent).
Exit status: 0 when every issue was released; 1 when any release failed
(including an --if-assignee mismatch).
Examples:
bd unclaim bd-123
bd unclaim bd-123 --reason "Agent crashed"
bd unclaim bd-123 bd-456`,
bd unclaim bd-123 bd-456
bd unclaim bd-123 --if-assignee worker-7 # only if still held by worker-7`,
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if usesProxiedServer() {
@ -37,6 +50,18 @@ Examples:
CheckReadonly("unclaim")
reason, _ := cmd.Flags().GetString("reason")
force, _ := cmd.Flags().GetBool("force")
ifAssignee, _ := cmd.Flags().GetString("if-assignee")
// A conditional release is selected by the presence of --if-assignee, not
// by a non-empty value. An explicitly empty --if-assignee "" is almost
// always an unset variable that expanded into the flag; treating it as an
// omitted flag would silently downgrade the compare-and-swap to an
// unconditional release, so reject it before touching any issue. (--force
// and --if-assignee are mutually exclusive at the flag-group level; this
// guards the remaining empty-value case.)
conditional := cmd.Flags().Changed("if-assignee")
if conditional && ifAssignee == "" {
return HandleErrorRespectJSON("--if-assignee requires a non-empty assignee; it releases the issue only while that assignee still holds it")
}
ctx := rootCtx
unclaimedIssues := []*types.Issue{}
@ -56,8 +81,14 @@ Examples:
fullID := result.ResolvedID
issueStore := result.Store
if err := issueStore.UnclaimIssue(ctx, fullID, actor, force); err != nil {
fmt.Fprintf(os.Stderr, "Error unclaiming %s: %v\n", fullID, err)
var unclaimErr error
if conditional {
unclaimErr = issueStore.UnclaimIssueIfAssignee(ctx, fullID, actor, ifAssignee)
} else {
unclaimErr = issueStore.UnclaimIssue(ctx, fullID, actor, force)
}
if unclaimErr != nil {
fmt.Fprintf(os.Stderr, "Error unclaiming %s: %v\n", fullID, unclaimErr)
hasError = true
result.Close()
continue
@ -102,6 +133,13 @@ Examples:
func init() {
unclaimCmd.Flags().StringP("reason", "r", "", "Reason for unclaiming")
unclaimCmd.Flags().Bool("force", false, "Release the claim even if held by a different actor (admin/reaper use)")
unclaimCmd.Flags().String("if-assignee", "", "Only release if still assigned to this assignee (atomic compare-and-swap; exits nonzero without changing the issue when the holder differs)")
// --force (unconditional bypass of the ownership check) and --if-assignee
// (release only while a specific assignee still holds it) encode
// contradictory intent. Rejecting the combination stops a reaper script that
// habitually passes --force from silently dropping it when it also passes
// --if-assignee for one case.
unclaimCmd.MarkFlagsMutuallyExclusive("force", "if-assignee")
unclaimCmd.ValidArgsFunction = issueIDCompletion
rootCmd.AddCommand(unclaimCmd)
}

View file

@ -0,0 +1,115 @@
//go:build cgo
package main
import (
"os"
"strings"
"testing"
"github.com/steveyegge/beads/internal/types"
)
// TestUnclaimIfAssigneeCLI drives `bd unclaim --if-assignee` end-to-end against
// the embedded Dolt backend: the conditional release must be a compare-and-swap,
// not a read-then-clobber. A stale expectation exits nonzero, names the current
// holder, and leaves the claim untouched; the matching expectation releases the
// claim; and releasing an already-released issue is a distinct failure, not a
// silent success (the exactly-once property a release-if-current supervisor
// depends on).
func TestUnclaimIfAssigneeCLI(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir, _, _ := bdInit(t, bd, "--prefix", "ur")
issue := bdCreate(t, bd, dir, "Conditional release", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--assignee", "alice", "--status", "in_progress")
// Stale expectation: distinct failure that names the current holder, claim intact.
out := bdUnclaimFail(t, bd, dir, issue.ID, "--if-assignee", "bob")
if !strings.Contains(out, "alice") {
t.Errorf("mismatch error should name the current holder alice, got:\n%s", out)
}
got := bdShow(t, bd, dir, issue.ID)
if got.Assignee != "alice" {
t.Errorf("stale --if-assignee clobbered the claim: assignee = %q, want alice", got.Assignee)
}
if got.Status != types.StatusInProgress {
t.Errorf("stale --if-assignee changed status to %q, want in_progress", got.Status)
}
// Matching expectation: releases the claim.
bdUnclaim(t, bd, dir, issue.ID, "--if-assignee", "alice")
got = bdShow(t, bd, dir, issue.ID)
if got.Assignee != "" {
t.Errorf("after matching --if-assignee: assignee = %q, want empty", got.Assignee)
}
if got.Status != types.StatusOpen {
t.Errorf("after matching --if-assignee: status = %q, want open", got.Status)
}
// Releasing an already-released issue with --if-assignee is also a distinct
// failure (exactly-once), not a silent success.
_ = bdUnclaimFail(t, bd, dir, issue.ID, "--if-assignee", "alice")
}
// TestUnclaimIfAssigneeFlagValidation drives the CLI guards that keep the
// conditional-release contract unambiguous. A conditional unclaim is selected by
// the *presence* of --if-assignee, so an explicitly empty --if-assignee "" (an
// unset variable that expanded into the flag) must be rejected rather than
// silently downgraded to an unconditional, --force-capable release; and --force
// cannot be combined with --if-assignee. Both cases must exit nonzero and leave
// the claim untouched. Each subtest runs as the holder so the pre-fix behavior
// (fall through to UnclaimIssue / let one flag win) would actually have released
// the claim, making these true regression guards.
func TestUnclaimIfAssigneeFlagValidation(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir, _, _ := bdInit(t, bd, "--prefix", "uv")
t.Run("empty_if_assignee_rejected", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Empty expectation", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--assignee", "alice", "--status", "in_progress")
// As the holder (alice), a pre-fix empty --if-assignee "" would have
// fallen through to an unconditional owner release and cleared the claim.
out := bdUnclaimFail(t, bd, dir, issue.ID, "--if-assignee", "", "--actor", "alice")
if !strings.Contains(out, "if-assignee requires a non-empty assignee") {
t.Errorf("empty --if-assignee should be rejected with a clear error, got:\n%s", out)
}
got := bdShow(t, bd, dir, issue.ID)
if got.Assignee != "alice" {
t.Errorf("empty --if-assignee released the claim: assignee = %q, want alice", got.Assignee)
}
if got.Status != types.StatusInProgress {
t.Errorf("empty --if-assignee changed status to %q, want in_progress", got.Status)
}
})
t.Run("force_and_if_assignee_mutually_exclusive", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Conflicting flags", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--assignee", "alice", "--status", "in_progress")
// --force + a matching --if-assignee would, pre-fix, take the CAS path and
// release the claim. The combination must instead be rejected outright.
out := bdUnclaimFail(t, bd, dir, issue.ID, "--force", "--if-assignee", "alice")
if !strings.Contains(out, "force") || !strings.Contains(out, "if-assignee") {
t.Errorf("--force with --if-assignee should be rejected as mutually exclusive, got:\n%s", out)
}
got := bdShow(t, bd, dir, issue.ID)
if got.Assignee != "alice" {
t.Errorf("--force --if-assignee released the claim: assignee = %q, want alice", got.Assignee)
}
if got.Status != types.StatusInProgress {
t.Errorf("--force --if-assignee changed status to %q, want in_progress", got.Status)
}
})
}

View file

@ -54,4 +54,13 @@ func TestUnclaimCommand_Flags(t *testing.T) {
if forceFlag.DefValue != "false" {
t.Errorf("expected force default value 'false', got %q", forceFlag.DefValue)
}
// The --if-assignee flag makes the release an atomic compare-and-swap.
ifAssigneeFlag := unclaimCmd.Flags().Lookup("if-assignee")
if ifAssigneeFlag == nil {
t.Fatal("if-assignee flag should be defined")
}
if ifAssigneeFlag.DefValue != "" {
t.Errorf("expected if-assignee default value '', got %q", ifAssigneeFlag.DefValue)
}
}

View file

@ -737,6 +737,9 @@ func (s *configStore) SlotGet(_ context.Context, _, _ string) (string, error) {
}
func (s *configStore) SlotClear(_ context.Context, _, _, _ string) error { return nil }
func (s *configStore) UnclaimIssue(_ context.Context, _ string, _ string, _ bool) error { return nil }
func (s *configStore) UnclaimIssueIfAssignee(_ context.Context, _ string, _ string, _ string) error {
return nil
}
func (s *configStore) CountIssues(_ context.Context, _ string, _ types.IssueFilter) (int64, error) {
return 0, nil

View file

@ -247,3 +247,64 @@ func testReclaimSkipsFreshLease(t *testing.T, f Factory) {
t.Errorf("fresh claim disturbed: status=%q assignee=%q", got.Status, got.Assignee)
}
}
// testUnclaimIfAssigneeMatch: a conditional release with the correct expected
// assignee clears the claim exactly once (assignee empty, status open). A repeat
// of the same conditional release finds the claim already gone and fails with
// storage.ErrAssigneeMismatch instead of silently succeeding — the "exactly
// once" property a release-if-current caller (e.g. a supervisor returning a
// dead worker's bead) depends on.
func testUnclaimIfAssigneeMatch(t *testing.T, f Factory) {
s := f(t)
must(t, s.CreateIssue(ctx(), withDefaults(&types.Issue{ID: "ur-1", Title: "T"}), "a"))
must(t, s.ClaimIssue(ctx(), "ur-1", "worker1"))
must(t, s.UnclaimIssueIfAssignee(ctx(), "ur-1", "releaser", "worker1"))
got, err := s.GetIssue(ctx(), "ur-1")
must(t, err)
if got.Assignee != "" {
t.Errorf("after conditional release: assignee = %q, want empty", got.Assignee)
}
if got.Status != types.StatusOpen {
t.Errorf("after conditional release: status = %q, want open", got.Status)
}
err = s.UnclaimIssueIfAssignee(ctx(), "ur-1", "releaser", "worker1")
if !errors.Is(err, storage.ErrAssigneeMismatch) {
t.Errorf("repeat conditional release: err = %v, want ErrAssigneeMismatch", err)
}
}
// testUnclaimIfAssigneeStale: a conditional release whose expected assignee is
// stale (someone else holds the claim) is a loud no-op: it returns
// storage.ErrAssigneeMismatch naming the current holder, leaves the claim
// untouched, and records no "unclaimed" event. This is the CAS that makes
// release-if-current safe across processes — a stale releaser can never clobber
// another worker's live claim.
func testUnclaimIfAssigneeStale(t *testing.T, f Factory) {
s := f(t)
must(t, s.CreateIssue(ctx(), withDefaults(&types.Issue{ID: "ur-2", Title: "T"}), "a"))
must(t, s.ClaimIssue(ctx(), "ur-2", "worker2"))
err := s.UnclaimIssueIfAssignee(ctx(), "ur-2", "releaser", "worker1")
if !errors.Is(err, storage.ErrAssigneeMismatch) {
t.Errorf("stale conditional release: err = %v, want ErrAssigneeMismatch", err)
}
got, err := s.GetIssue(ctx(), "ur-2")
must(t, err)
if got.Assignee != "worker2" {
t.Errorf("stale release clobbered claim: assignee = %q, want worker2", got.Assignee)
}
if got.Status != types.StatusInProgress {
t.Errorf("stale release changed status to %q, want in_progress", got.Status)
}
events, err := s.GetEvents(ctx(), "ur-2", 0)
must(t, err)
for _, e := range events {
if e.EventType == types.EventType("unclaimed") {
t.Errorf("stale conditional release recorded an unclaimed event: %+v", e)
}
}
}

View file

@ -153,6 +153,8 @@ func RunAll(t *testing.T, factory Factory) {
t.Run("HeartbeatWisp", func(t *testing.T) { testHeartbeatWisp(t, factory) })
t.Run("ReclaimExpiredLease", func(t *testing.T) { testReclaimExpiredLease(t, factory) })
t.Run("ReclaimSkipsFreshLease", func(t *testing.T) { testReclaimSkipsFreshLease(t, factory) })
t.Run("UnclaimIfAssigneeMatch", func(t *testing.T) { testUnclaimIfAssigneeMatch(t, factory) })
t.Run("UnclaimIfAssigneeStale", func(t *testing.T) { testUnclaimIfAssigneeStale(t, factory) })
// Labels
t.Run("Labels", func(t *testing.T) { testLabels(t, factory) })

View file

@ -350,6 +350,32 @@ func (s *DoltStore) UnclaimIssue(ctx context.Context, id string, actor string, f
})
}
// UnclaimIssueIfAssignee releases a claim only while the issue is still assigned
// to expectedAssignee (compare-and-swap, the inverse of ClaimIssue). Returns
// storage.ErrAssigneeMismatch, leaving the issue untouched, when the current
// assignee differs. Delegates SQL work to issueops.UnclaimIssueIfAssigneeInTx;
// handles Dolt-specific concerns (DOLT_ADD/COMMIT). Wrapped in withRetryTx like
// UnclaimIssue so a concurrent writer that loses Dolt's optimistic commit-time
// merge is retried rather than surfaced as a hard failure.
func (s *DoltStore) UnclaimIssueIfAssignee(ctx context.Context, id string, actor string, expectedAssignee string) error {
return s.withRetryTx(ctx, func(tx *sql.Tx) error {
if err := issueops.UnclaimIssueIfAssigneeInTx(ctx, tx, id, actor, expectedAssignee); err != nil {
return err
}
// Dolt versioning for permanent issues.
for _, table := range []string{"issues", "events"} {
_, _ = tx.ExecContext(ctx, "CALL DOLT_ADD(?)", table)
}
commitMsg := fmt.Sprintf("bd: unclaim %s", id)
if _, err := tx.ExecContext(ctx, "CALL DOLT_COMMIT('-m', ?, '--author', ?)",
commitMsg, s.commitAuthorString()); err != nil && !isDoltNothingToCommit(err) {
return fmt.Errorf("dolt commit: %w", err)
}
return nil
})
}
// ReopenIssue reopens a closed issue, setting status to open and clearing
// closed_at and defer_until. If reason is non-empty, it is recorded as a comment.
// Wraps UpdateIssue for Dolt-specific concerns (wisp routing, DOLT_COMMIT, etc.).

View file

@ -43,6 +43,17 @@ func (s *EmbeddedDoltStore) UnclaimIssue(ctx context.Context, id string, actor s
})
}
// UnclaimIssueIfAssignee releases a claim only while the issue is still assigned
// to expectedAssignee (compare-and-swap, the inverse of ClaimIssue). Returns
// storage.ErrAssigneeMismatch, leaving the issue untouched, when the current
// assignee differs. Delegates SQL work to issueops; EmbeddedDolt auto-commits
// the transaction.
func (s *EmbeddedDoltStore) UnclaimIssueIfAssignee(ctx context.Context, id string, actor string, expectedAssignee string) error {
return s.withConn(ctx, true, func(tx *sql.Tx) error {
return issueops.UnclaimIssueIfAssigneeInTx(ctx, tx, id, actor, expectedAssignee)
})
}
// UpdateIssue updates fields on an issue.
// Delegates SQL work to issueops; EmbeddedDolt auto-commits the transaction.
func (s *EmbeddedDoltStore) UpdateIssue(ctx context.Context, id string, updates map[string]interface{}, actor string) error {

View file

@ -102,23 +102,107 @@ func UnclaimIssueInTx(ctx context.Context, tx *sql.Tx, id string, actor string,
return fmt.Errorf("failed to unclaim issue %s: no matching row", id)
}
// The claim is over: drop its lease row (no-op when none exists, e.g. a
// wisp or an open-but-assigned issue that was never leased).
return finishUnclaimInTx(ctx, tx, eventTable, id, actor, oldIssue)
}
// finishUnclaimInTx applies the post-UPDATE half of a release shared by
// UnclaimIssueInTx and UnclaimIssueIfAssigneeInTx: it drops the lease row (a
// no-op when none exists, e.g. a wisp or an open-but-assigned issue that was
// never leased) and records the "unclaimed" event. The row mutation
// (assignee/status/started_at/row_lock) must already have been applied in tx.
func finishUnclaimInTx(ctx context.Context, tx *sql.Tx, eventTable string, id string, actor string, oldIssue *types.Issue) error {
if err := DeleteLeaseInTx(ctx, tx, id); err != nil {
return err
}
// Record the unclaim event
oldData, _ := json.Marshal(oldIssue)
newUpdates := map[string]interface{}{
newData, _ := json.Marshal(map[string]interface{}{
"assignee": "",
"status": "open",
}
newData, _ := json.Marshal(newUpdates)
})
if err := RecordFullEventInTable(ctx, tx, eventTable, id, "unclaimed", actor, string(oldData), string(newData)); err != nil {
return fmt.Errorf("failed to record unclaim event: %w", err)
}
return nil
}
// UnclaimIssueIfAssigneeInTx atomically releases a claim only while the issue is
// still assigned to expectedAssignee — the compare-and-swap inverse of
// ClaimIssueInTx: a conditional UPDATE ... WHERE id = ? AND assignee = ? with
// RowsAffected as the verdict, so a stale releaser can never clobber a claim
// that has since moved to (or been re-taken by) someone else. On success it
// applies the same transition as UnclaimIssueInTx (assignee cleared, status
// reopened, started_at cleared, lease dropped, row_lock rewritten, "unclaimed"
// event recorded). When the current assignee differs from expectedAssignee —
// including when the issue is no longer assigned at all — it returns
// storage.ErrAssigneeMismatch naming the current holder and leaves the row
// untouched. actor is recorded as the event author.
//
//nolint:gosec // G201: table names come from WispTableRouting (hardcoded constants)
func UnclaimIssueIfAssigneeInTx(ctx context.Context, tx *sql.Tx, id string, actor string, expectedAssignee string) error {
if expectedAssignee == "" {
return fmt.Errorf("conditional unclaim of %s: expected assignee must not be empty (use UnclaimIssueInTx for an unconditional release)", id)
}
// Route to the correct table (issues/wisps) automatically, matching
// UnclaimIssueInTx.
isWisp := IsActiveWispInTx(ctx, tx, id)
issueTable, _, eventTable, _ := WispTableRouting(isWisp)
oldIssue, err := GetIssueInTx(ctx, tx, id)
if err != nil {
return fmt.Errorf("failed to get issue for unclaim: %w", err)
}
// Validate: cannot unclaim closed issues.
if oldIssue.Status == types.StatusClosed {
return fmt.Errorf("cannot unclaim closed issue %s", id)
}
// Compare-and-swap precheck: a mismatched holder — including an
// already-released issue (empty assignee) — is a loud, typed no-op. The read
// and the UPDATE below run in the same transaction, so this check and the
// CAS WHERE clause see the same row state.
if oldIssue.Assignee != expectedAssignee {
return fmt.Errorf("%w: %s is held by %q, expected %q", storage.ErrAssigneeMismatch, id, oldIssue.Assignee, expectedAssignee)
}
now := time.Now().UTC()
// Atomic UPDATE pinned to the expected assignee (CAS), applying the same
// transition as UnclaimIssueInTx: clear assignee, reset status to open,
// clear started_at, and rewrite row_lock so a racing reclaim/close on the
// same row conflicts rather than silently merging (see lease.go invariant).
result, err := tx.ExecContext(ctx, fmt.Sprintf(`
UPDATE %s
SET assignee = '', status = 'open', updated_at = ?,
started_at = NULL, row_lock = ?
WHERE id = ? AND status IN ('open', 'in_progress') AND assignee = ?
`, issueTable), now, freshRowLock(), id, expectedAssignee)
if err != nil {
return fmt.Errorf("failed to unclaim issue: %w", err)
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return fmt.Errorf("failed to get rows affected: %w", err)
}
if rowsAffected == 0 {
// The precheck passed and the read + UPDATE share this transaction, so a
// 0-row result is not an assignee race (the row cannot change under us
// mid-tx). Re-read and disambiguate, mirroring UnclaimIssueInTx: a
// mismatched holder is the CAS verdict (ErrAssigneeMismatch), otherwise
// the status is no longer releasable.
current, gerr := GetIssueInTx(ctx, tx, id)
if gerr != nil {
return fmt.Errorf("failed to unclaim issue %s: no matching row", id)
}
if current.Assignee != expectedAssignee {
return fmt.Errorf("%w: %s is held by %q, expected %q", storage.ErrAssigneeMismatch, id, current.Assignee, expectedAssignee)
}
return fmt.Errorf("failed to unclaim issue %s: no matching row", id)
}
return finishUnclaimInTx(ctx, tx, eventTable, id, actor, oldIssue)
}

View file

@ -28,6 +28,12 @@ var ErrNotClaimable = errors.New("issue not claimable")
// escape hatch (bd unclaim --force), reserved for admin/reaper use.
var ErrNotOwner = errors.New("issue claimed by a different actor")
// ErrAssigneeMismatch is returned by UnclaimIssueIfAssignee when the issue's
// current assignee does not match the expected assignee (including when the
// issue is no longer assigned at all). The caller's view of the claim was
// stale; the issue is left untouched.
var ErrAssigneeMismatch = errors.New("assignee mismatch")
// ErrNotFound is returned when a requested entity does not exist in the database.
var ErrNotFound = errors.New("not found")
@ -51,6 +57,11 @@ type Storage interface {
UpdateIssue(ctx context.Context, id string, updates map[string]interface{}, actor string) error
ReopenIssue(ctx context.Context, id string, reason string, actor string) error
UnclaimIssue(ctx context.Context, id string, actor string, force bool) error
// UnclaimIssueIfAssignee releases a claim only while the issue is still
// assigned to expectedAssignee (compare-and-swap, the inverse of
// ClaimIssue). Returns ErrAssigneeMismatch, leaving the issue untouched,
// when the current assignee differs.
UnclaimIssueIfAssignee(ctx context.Context, id string, actor string, expectedAssignee string) error
UpdateIssueType(ctx context.Context, id string, issueType string, actor string) error
CloseIssue(ctx context.Context, id string, reason string, actor string, session string) error
DeleteIssue(ctx context.Context, id string) error

View file

@ -175,6 +175,18 @@ func (s *InstrumentedStorage) UnclaimIssue(ctx context.Context, id string, actor
return err
}
func (s *InstrumentedStorage) UnclaimIssueIfAssignee(ctx context.Context, id string, actor string, expectedAssignee string) error {
attrs := []attribute.KeyValue{
attribute.String("bd.issue.id", id),
attribute.String("bd.actor", actor),
attribute.String("bd.issue.expected_assignee", expectedAssignee),
}
ctx, span, t := s.op(ctx, "UnclaimIssueIfAssignee", attrs...)
err := s.inner.UnclaimIssueIfAssignee(ctx, id, actor, expectedAssignee)
s.done(ctx, span, t, err, attrs...)
return err
}
func (s *InstrumentedStorage) UpdateIssueType(ctx context.Context, id string, issueType string, actor string) error {
attrs := []attribute.KeyValue{
attribute.String("bd.issue.id", id),