fix(bd): canonicalize actor==assignee comparisons in unclaim.go and AuthorizeAssigneeTransferWithPools (#5439)

* fix(bd): canonicalize actor==assignee comparisons in unclaim.go and AuthorizeAssigneeTransferWithPools

Follow-up to ga-wzl83, which canonicalized the two pure-Go validators in
internal/validation/issue.go but explicitly left out two higher-risk sites.

UnclaimIssueInTx / UnclaimIssueIfAssigneeInTx compared actor/expectedAssignee
to the stored assignee verbatim, both in a Go-side precheck AND in the SQL
UPDATE's WHERE clause -- so canonicalizing only the Go side would not have
fixed `bd unclaim` end-to-end. Replaced the `assignee = ?` SQL predicate with
a `row_lock = ?` CAS against the RowVersion read moments earlier: every
ownership/status/started_at mutation always rewrites row_lock (the documented
freshRowLock invariant in lease.go), so this detects the exact same race the
old predicate did -- and more (status/started_at races too) -- without
embedding a spelling-sensitive string comparison in SQL.

AuthorizeAssigneeTransferWithPools (the single fence both the DBTX and
unit-of-work backends evaluate, per its own doc comment) compared
before.Assignee to request.Actor and to request.Patch.Assignee.Value
verbatim, so a caller naming the current holder under a different layer's
identity spelling was wrongly fenced as a stranger.

Both fixes reuse the canonicalActor/actorMatches shape from ga-wzl83, kept as
a small package-local duplicate in issueops (internal/storage/issueops
importing internal/validation would invert the layering).

Verified: new cross-spelling cases in aggregate_authorize_transfer_test.go
and new end-to-end cases in unclaim_embedded_test.go /
unclaim_conditional_embedded_test.go (against a real embedded Dolt backend)
all fail with the exact bug-report symptom against the pre-fix code and pass
after the fix, with no regressions in the existing suites.

ga-5ksp5

* fix(bd): close the sibling-CAS disagreement gate review flagged on #5439

Review verdict on #5439 was "MERGE AFTER ONE FIX": after this branch's
unclaim.go/aggregate.go fix, bd unclaim --if-assignee succeeds under a
respelled identity while bd update --expected-assignee on the same bead
still fails ErrAssigneeMismatch — the same verbatim actor==assignee defect
(ga-wzl83), left in two more places.

- internal/storage/issueops/update_cas.go:46 (CheckExpectedFieldsInTx) now
  compares under actorMatches (package-local, unexported — same package as
  identity.go, no new import needed).
- internal/storage/domain/issue.go:643 (ApplyUpdate, the unit-of-work twin)
  now compares under validation.ActorMatches. domain cannot import
  internal/storage/issueops (issueops already imports domain in several
  files — the reverse would cycle), but domain -> internal/validation is
  safe (validation depends only on internal/types), so this reuses the
  already-shipped validation copy instead of adding a third duplicate.

Two non-blocking asks from the same review, addressed:

- Exported internal/validation's canonicalActor/actorMatches to
  CanonicalActor/ActorMatches so domain/issue.go could reuse them (the
  reviewer's own point: "an issueops -> validation import creates no
  cycle... layering inversion is a style call, not a compile fact" applies
  equally to domain -> validation). Also fixed a garbled mid-sentence doc
  comment on ActorMatches while touching the file (separate nit from the
  same review, on #5438).
- Added a cross-package parity test
  (internal/storage/issueops/identity_parity_test.go) that runs the
  existing CanonicalActor/ActorMatches case tables through both this
  package's local duplicate and validation's exported version, so the two
  copies can't silently drift. Mutation-tested: dropped the hyphen
  separator from issueops's copy, confirmed the two hyphen-related cases
  correctly fail, reverted.

New conformance test (backend/conformance, wired into all three backend
legs) proves the fix end-to-end: an ExpectedAssignee guard now accepts a
different spelling of the current holder and still refuses a genuinely
different identity. Added as a SEPARATE function rather than extending the
existing RunIssueOperationsUpdateConditionalGuardsGateOrdinaryEdits — that
test's later "order-dependent composition" arm depends on the row's
assignee staying exactly "holder" through to the end, which a mid-test
respelling would have broken.

Verification: internal/validation, internal/storage/issueops,
internal/storage/domain(+db,fs,git) all green. New conformance test passes
on embeddeddolt and uow (dolt backend skips locally, no Docker — matches
the existing documented limitation, CI covers it). Broader regression
subset (Update/Claim/Unclaim, 28 embeddeddolt + 22 uow cases) green, no
regressions. go build/vet/gofmt clean.

Filed ga-4ymii for the reviewer's second (also non-blocking) ask: the
remaining verbatim sites at issueops/claim.go (SQL CAS + idempotent
re-claim), its domain/db and domain/issue.go uow twins, and
issueops/lease.go's heartbeat holder check — out of scope for this PR per
the reviewer's own framing ("please file the follow-up").

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

* fix(bd): dispatch the respelled-assignee contract case onto the role seam

TestRoleContractCasesCoverEveryContractCase (main, post-dating this branch's
fork point) caught a real gap: the ga-5ksp5 contract case added to this
branch's earlier commit (RunIssueOperationsUpdateConditionalGuardAccepts-
RespelledAssignee) had no roleContractCases dispatch row, so an external
backend running RunRoleContracts would never see it.

The reason isn't a missed row so much as the whole RunIssueOperationsUpdate*
family this case was written beside having been renamed and moved to
RunLifecycleUpdate* in backend/conformance/lifecycle_update_contract.go by
main's "de-stage the hard Lifecycle contracts onto the role seam" refactor,
which landed on main after this branch forked. Ported the case to match:
same logic, adapted to the new fixture's idioms (fixture.Lifecycle.Update
instead of fixture.Operations.Update, lifecycleUpdateRow(...).Priority
instead of a raw SQL assertion, storage.ErrAssigneeMismatch instead of
publicops.ErrAssigneeMismatch, seedLifecycleUpdateIssue instead of
seedClosePolicyIssue) — not a mechanical copy. Also wired it into the three
per-backend TestLifecycleUpdateContract dispatch lists (dolt, embeddeddolt,
uow) beside its ConditionalGuardsGateOrdinaryEdits sibling, so it actually
runs against real backends rather than only satisfying the completeness
guard.

Verified: TestRoleContractCasesCoverEveryContractCase passes; the ported
case passes against embeddeddolt (0.35s) and uow (0.17s) for real, not just
compiles (dolt backend test skips in this sandbox — no Docker); full
backend/conformance suite and repo build clean.

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Athos Bernardes 2026-08-09 15:35:01 -03:00 • committed by GitHub
commit df90ec784c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 380 additions and 59 deletions

View file

@ -905,6 +905,71 @@ func RunLifecycleUpdateConditionalGuardsGateOrdinaryEdits(t *testing.T, ctx cont
maskedEvents.assert(t, "guard masked by the one before it", 0)
}
// RunLifecycleUpdateConditionalGuardAcceptsRespelledAssignee pins the
// ga-5ksp5 fix beside RunLifecycleUpdateConditionalGuardsGateOrdinaryEdits
// above rather than inside it: that test's later "order-dependent composition"
// arm depends on the row's assignee still being exactly "holder" all the way
// to the end, so reassigning it mid-test to exercise a second spelling would
// invalidate its own assumption.
//
// The two Gas Town identity spellings a caller can send for the same actor
// (dot vs underscore separator, ga-wzl83) must not desync from the row's
// stored spelling: an ExpectedAssignee guard is satisfied by either spelling
// of the CURRENT holder, and still refused by a spelling of a genuinely
// different identity. Separate from RunLifecycleUpdateAssigneeTransferFence
// in this file, which pins the same respelling rule for the CLAIM/TRANSFER
// fence (AuthorizeAssigneeTransferWithPools) — this pins it for the plain
// compare-and-set guard (CheckExpectedFieldsInTx / ApplyUpdate's own check),
// the third, previously-split verbatim-comparison surface the ga-3ipxu gate
// review on #5439 found.
func RunLifecycleUpdateConditionalGuardAcceptsRespelledAssignee(t *testing.T, ctx context.Context, fixture LifecycleUpdateFixture) {
t.Helper()
id := fixture.IssuePrefix + "-lup-respelledguard"
seedLifecycleUpdateIssue(t, ctx, fixture, lifecycleUpdateIssue(id))
priorityEdit := func(priority int) publicops.UpdateRequest {
return publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{
Priority: publicops.Field[int]{Set: true, Value: priority},
}}
}
assertPriority := func(label string, want int) {
t.Helper()
if got := lifecycleUpdateRow(t, ctx, fixture, id).Priority; got != want {
t.Errorf("%s = %d, want %d", label, got, want)
}
}
assign := publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{
Assignee: publicops.Field[string]{Set: true, Value: "gastown.mayor"},
}}
if _, err := fixture.Lifecycle.Update(ctx, assign); err != nil {
t.Fatalf("assign %s under a dotted identity: %v", id, err)
}
// A guard naming the SAME identity under a different (and
// doubled-separator) spelling is satisfied, same as the row's own
// verbatim spelling would be.
respelled := "gastown__mayor"
respelledEdit := priorityEdit(1)
respelledEdit.ExpectedAssignee = &respelled
if result, err := fixture.Lifecycle.Update(ctx, respelledEdit); err != nil || !result.Changed {
t.Fatalf("edit guarded on a different spelling of the current holder = %#v, %v; want the edit applied", result, err)
}
assertPriority("priority after a guard naming the holder under a different spelling", 1)
// Canonicalization must not over-match: a spelling of a genuinely
// different identity — not just a respelling of the holder — still
// refuses, and still writes nothing.
foreign := "gastown_dog-1"
foreignEdit := priorityEdit(3)
foreignEdit.ExpectedAssignee = &foreign
if _, err := fixture.Lifecycle.Update(ctx, foreignEdit); !errors.Is(err, storage.ErrAssigneeMismatch) {
t.Fatalf("edit guarded on an unrelated identity: err = %v, want ErrAssigneeMismatch", err)
}
assertPriority("priority after a guard naming an unrelated identity", 1)
}
// RunLifecycleUpdateMetadataPatchOrdersMergeSetUnset pins the sentence
// MetadataPatch opens with: "Replace is mutually exclusive with Merge, Set, and
// Unset. Without Replace, operations apply Merge, then Set keys in

View file

@ -408,6 +408,7 @@ var roleContractCases = []roleContract{
RunLifecycleUpdateRefusesUnknownIDsAndActorlessRequests,
RunLifecycleUpdateRefusalWritesNoMemberOfThePatch,
RunLifecycleUpdateConditionalGuardsGateOrdinaryEdits,
RunLifecycleUpdateConditionalGuardAcceptsRespelledAssignee,
RunLifecycleUpdateMetadataPatchOrdersMergeSetUnset,
RunLifecycleUpdateClosePolicy,
RunLifecycleUpdateAssigneeTransferFence,

View file

@ -57,6 +57,36 @@ func TestUnclaimIfAssigneeCLI(t *testing.T) {
_ = bdUnclaimFail(t, bd, dir, issue.ID, "--if-assignee", "alice")
}
// TestUnclaimIfAssigneeCLIDifferentSpelling drives `bd unclaim --if-assignee`
// with an expectation that names the current holder under a different Gas
// Town identity spelling than the stored assignee (dot vs underscore
// separator — ga-5ksp5). This must count as a match, not a stale-expectation
// refusal: both the Go-side actorMatches precheck and the row_lock CAS that
// replaced the old verbatim `assignee = ?` SQL predicate need to agree it is
// the same identity, or the release silently affects zero rows even though
// the precheck said the CAS should succeed.
func TestUnclaimIfAssigneeCLIDifferentSpelling(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", "uw")
issue := bdCreate(t, bd, dir, "Conditional release, spelling variant", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--assignee", "gastown.mayor", "--status", "in_progress")
bdUnclaim(t, bd, dir, issue.ID, "--if-assignee", "gastown_mayor")
got := bdShow(t, bd, dir, issue.ID)
if got.Assignee != "" {
t.Errorf("after same-identity --if-assignee: assignee = %q, want empty", got.Assignee)
}
if got.Status != types.StatusOpen {
t.Errorf("after same-identity --if-assignee: status = %q, want open", got.Status)
}
}
// 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

View file

@ -219,4 +219,25 @@ func TestEmbeddedUnclaim(t *testing.T) {
t.Errorf("expected status open after --force unclaim, got %s", got.Status)
}
})
// The owner may release its own claim under a different spelling of its own
// identity (ga-5ksp5): dot vs underscore separator is the same Gas Town
// identity at two different layers, and both the Go-side ownership
// precheck and the SQL CAS predicate must recognize that — not just the
// former, or the UPDATE would silently affect zero rows and the release
// would fail even though the Go precheck said it should succeed.
t.Run("unclaim_owner_different_spelling_succeeds", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Owner spelling variant", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--claim", "--actor", "gastown.mayor")
bdUnclaim(t, bd, dir, issue.ID, "--actor", "gastown_mayor")
got := bdShow(t, bd, dir, issue.ID)
if got.Assignee != "" {
t.Errorf("expected assignee to be cleared after same-identity unclaim, got %q", got.Assignee)
}
if got.Status != types.StatusOpen {
t.Errorf("expected status open after same-identity unclaim, got %s", got.Status)
}
})
}

View file

@ -51,6 +51,9 @@ func TestLifecycleUpdateContract(t *testing.T) {
t.Run("ConditionalGuardsGateOrdinaryEdits", func(t *testing.T) {
conformance.RunLifecycleUpdateConditionalGuardsGateOrdinaryEdits(t, ctx, fixture)
})
t.Run("ConditionalGuardAcceptsRespelledAssignee", func(t *testing.T) {
conformance.RunLifecycleUpdateConditionalGuardAcceptsRespelledAssignee(t, ctx, fixture)
})
t.Run("MetadataPatchOrdersMergeSetUnset", func(t *testing.T) {
conformance.RunLifecycleUpdateMetadataPatchOrdersMergeSetUnset(t, ctx, fixture)
})

View file

@ -10,6 +10,7 @@ import (
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/dberrors"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/validation"
publicops "github.com/steveyegge/beads/issueops"
)
@ -660,6 +661,14 @@ func (u *issueUseCaseImpl) claim(ctx context.Context, id, actor string, useWisp
}
}
// ApplyUpdate applies spec's guarded field updates and returns the resulting
// issue. When ExpectedAssignee is set, the guard compares under
// validation.ActorMatches, not verbatim ==, so two spellings of the same
// identity (ga-wzl83) don't false-mismatch — the unit-of-work twin of
// issueops.CheckExpectedFieldsInTx's SQL-CAS guard; both paths of
// AuthorizeAssigneeTransferWithPools already made this fix, this was the
// third, previously-split verbatim-comparison surface (ga-5ksp5, gate review
// on #5439).
func (u *issueUseCaseImpl) ApplyUpdate(ctx context.Context, id string, spec UpdateSpec, actor string) (*types.Issue, error) {
if id == "" {
return nil, fmt.Errorf("ApplyUpdate: id must not be empty")
@ -686,7 +695,7 @@ func (u *issueUseCaseImpl) ApplyUpdate(ctx context.Context, id string, spec Upda
if spec.ExpectedVersion != nil && current.RowVersion != *spec.ExpectedVersion {
return nil, fmt.Errorf("%w: expected %d, got %d", storage.ErrVersionMismatch, *spec.ExpectedVersion, current.RowVersion)
}
if spec.ExpectedAssignee != nil && current.Assignee != *spec.ExpectedAssignee {
if spec.ExpectedAssignee != nil && !validation.ActorMatches(current.Assignee, *spec.ExpectedAssignee) {
return nil, fmt.Errorf("%w: %s is held by %q, expected %q",
storage.ErrAssigneeMismatch, id, current.Assignee, *spec.ExpectedAssignee)
}

View file

@ -52,6 +52,9 @@ func TestLifecycleUpdateContract(t *testing.T) {
t.Run("ConditionalGuardsGateOrdinaryEdits", func(t *testing.T) {
conformance.RunLifecycleUpdateConditionalGuardsGateOrdinaryEdits(t, ctx, fixture)
})
t.Run("ConditionalGuardAcceptsRespelledAssignee", func(t *testing.T) {
conformance.RunLifecycleUpdateConditionalGuardAcceptsRespelledAssignee(t, ctx, fixture)
})
t.Run("MetadataPatchOrdersMergeSetUnset", func(t *testing.T) {
conformance.RunLifecycleUpdateMetadataPatchOrdersMergeSetUnset(t, ctx, fixture)
})

View file

@ -145,11 +145,20 @@ func ValidateScalarUpdates(ctx context.Context, tx DBTX, updates map[string]inte
// it, so the two cannot drift into disagreeing about which transfers are
// fenced.
//
// The no-op and self-transfer exits (request.Patch.Assignee.Value against
// before.Assignee, and before.Assignee against request.Actor) are judged
// under actorMatches, not verbatim equality (ga-5ksp5): the same Gas Town
// identity arrives here spelled differently depending on which layer
// produced the string (a dotted alias vs its session-name form — see
// canonicalActor), and a byte-for-byte comparison would wrongly fence a
// holder editing its own claim, or reject an idempotent re-assert, just
// because the caller named the holder under a different layer's spelling.
//
// Passing nil pools answers every question except pool membership, so a caller
// that wants the config read only when it matters calls with nil first and
// re-evaluates with the loaded aliases on refusal.
func AuthorizeAssigneeTransferWithPools(before *types.Issue, request publicops.UpdateRequest, pools []string) error {
if !request.Patch.Assignee.Set || request.Patch.Assignee.Value == before.Assignee || request.ExpectedAssignee != nil || request.ForceAssigneeTransfer || before.Status != types.StatusInProgress || before.Assignee == "" || before.Assignee == request.Actor {
if !request.Patch.Assignee.Set || actorMatches(request.Patch.Assignee.Value, before.Assignee) || request.ExpectedAssignee != nil || request.ForceAssigneeTransfer || before.Status != types.StatusInProgress || before.Assignee == "" || actorMatches(before.Assignee, request.Actor) {
return nil
}
for _, pool := range pools {

View file

@ -73,6 +73,31 @@ func TestAuthorizeAssigneeTransferWithPools(t *testing.T) {
before: held(),
request: transfer(func(r *publicops.UpdateRequest) { r.Actor = "holder" }),
},
{
// ga-5ksp5: the same Gas Town identity spelled two different
// ways (dot vs underscore separator) must still count as
// "actor already holds it", not a foreign transfer.
name: "actor already holds it under a different spelling",
before: &types.Issue{ID: "bd-1", Status: types.StatusInProgress, Assignee: "gastown.mayor"},
request: transfer(func(r *publicops.UpdateRequest) { r.Actor = "gastown_mayor" }),
},
{
// ga-5ksp5: reasserting the current holder under a different
// (and doubled-separator) spelling is still the same
// idempotent no-op as reasserting it verbatim.
name: "reasserts the current assignee under a different spelling",
before: &types.Issue{ID: "bd-1", Status: types.StatusInProgress, Assignee: "gastown.mayor"},
request: transfer(func(r *publicops.UpdateRequest) { r.Patch.Assignee.Value = "gastown__mayor" }),
},
{
// ga-5ksp5: canonicalization must not over-match — an actor
// whose identity genuinely differs from the holder (not just
// a respelling of it) stays refused.
name: "foreign actor with an unrelated identity is still refused",
before: &types.Issue{ID: "bd-1", Status: types.StatusInProgress, Assignee: "gastown.mayor"},
request: transfer(func(r *publicops.UpdateRequest) { r.Actor = "gastown_dog-1" }),
refuse: true,
},
{
name: "holder is a configured pool alias",
before: &types.Issue{ID: "bd-1", Status: types.StatusInProgress, Assignee: "crew"},

View file

@ -0,0 +1,57 @@
package issueops
import "strings"
// canonicalActor normalizes an identity string so two spellings of the same
// Gas Town identity compare equal. The same identity arrives at bd in more
// than one spelling depending on which layer produced the string it was
// handed: a dotted alias like "gastown.mayor" gets its dot replaced wherever
// a dot is unsafe for that context — "__" in a session name, "_" in a Dolt
// table/database name, "-" elsewhere — and bd only ever sees the resulting
// string, never the substitution itself (ga-wzl83). None of ".", "_", "-"
// carries meaning in an identity string: each is always a positional
// separator between a rig and a role/agent name, never part of either name.
// Collapsing any run of them to one canonical separator lets two spellings
// of the same identity compare equal without weakening comparisons between
// genuinely different identities, whose non-separator characters still
// differ (e.g. "gastown.mayor" vs "gastown.dog-3" stay distinct).
//
// Empty stays empty: an actual absence of an actor must never canonicalize
// to the same value as a non-empty one, or a caller comparing against an
// unassigned issue would start matching everyone.
//
// This is a package-local duplicate of internal/validation/issue.go's
// canonicalActor (ga-wzl83): issueops sits below validation in the layering
// (storage depending on a higher-level validation package would invert it),
// so the two copies stay independent rather than sharing an import. Keep
// them in sync if the separator set or normalization rule ever changes
// (ga-5ksp5).
func canonicalActor(s string) string {
if s == "" {
return ""
}
var b strings.Builder
b.Grow(len(s))
inSeparator := false
for _, r := range s {
switch r {
case '.', '_', '-':
if !inSeparator {
b.WriteByte('_')
inSeparator = true
}
default:
b.WriteRune(r)
inSeparator = false
}
}
return b.String()
}
// actorMatches reports whether a and b denote the same identity: either
// they're byte-identical, or they canonicalize to the same string (see
// canonicalActor). The byte-identical check is not redundant — it avoids
// paying canonicalization on the overwhelmingly common exact-match path.
func actorMatches(a, b string) bool {
return a == b || canonicalActor(a) == canonicalActor(b)
}

View file

@ -0,0 +1,71 @@
package issueops
import (
"testing"
"github.com/steveyegge/beads/internal/validation"
)
// TestIdentityCanonicalizationParityWithValidation guards the two
// intentionally-duplicated copies of the identity-canonicalization rule
// (this package's canonicalActor/actorMatches, internal/validation's
// exported CanonicalActor/ActorMatches) against silent drift. issueops
// cannot import internal/storage/domain — internal/storage/issueops already
// imports internal/storage/domain in several files (config_helpers.go,
// dependencies.go, etc.), so the reverse import would cycle — but it CAN
// safely import internal/validation (validation depends only on
// internal/types), and does so here for test purposes only. Per the ga-3ipxu
// gate review on #5439: "I won't hold the PR for extraction to a shared leaf
// package, but two keep-in-sync copies need at least a cross-package parity
// test so the tables can't drift silently." Run the identical case tables
// TestCanonicalActor/TestActorMatches already pin in
// internal/validation/issue_test.go through BOTH implementations; a future
// edit to either separator set or matching rule that isn't mirrored in the
// other fails here, not in production.
func TestIdentityCanonicalizationParityWithValidation(t *testing.T) {
canonicalCases := []struct {
name string
in string
}{
{name: "empty stays empty", in: ""},
{name: "no separators is unchanged", in: "alice"},
{name: "dot separator canonicalizes", in: "gastown.mayor"},
{name: "double-underscore separator canonicalizes to the same form", in: "gastown__mayor"},
{name: "hyphen separator canonicalizes to the same form", in: "gastown-mayor"},
{name: "single underscore is already canonical", in: "gastown_mayor"},
{name: "mixed separators each collapse to one canonical separator", in: "gastown.dog-3"},
{name: "leading separator is preserved as a separator, not dropped", in: ".mayor"},
{name: "trailing separator is preserved as a separator, not dropped", in: "mayor."},
}
for _, tc := range canonicalCases {
t.Run("CanonicalActor/"+tc.name, func(t *testing.T) {
local := canonicalActor(tc.in)
shared := validation.CanonicalActor(tc.in)
if local != shared {
t.Errorf("issueops.canonicalActor(%q) = %q, internal/validation.CanonicalActor(%q) = %q — the two copies have drifted apart",
tc.in, local, tc.in, shared)
}
})
}
matchCases := []struct {
name string
assignee, actor string
}{
{name: "byte-identical matches", assignee: "alice", actor: "alice"},
{name: "different spellings of the same identity match (ga-wzl83)", assignee: "gastown.mayor", actor: "gastown__mayor"},
{name: "genuinely different identities do not match", assignee: "gastown.mayor", actor: "gastown.dog-3"},
{name: "both empty match", assignee: "", actor: ""},
{name: "empty assignee never matches a non-empty actor", assignee: "", actor: "mayor"},
}
for _, tc := range matchCases {
t.Run("ActorMatches/"+tc.name, func(t *testing.T) {
local := actorMatches(tc.assignee, tc.actor)
shared := validation.ActorMatches(tc.assignee, tc.actor)
if local != shared {
t.Errorf("issueops.actorMatches(%q, %q) = %v, internal/validation.ActorMatches(%q, %q) = %v — the two copies have drifted apart",
tc.assignee, tc.actor, local, tc.assignee, tc.actor, shared)
}
})
}
}

View file

@ -18,8 +18,11 @@ import (
//
// Ownership: only the current assignee may release its own claim. A mismatched
// actor is rejected with storage.ErrNotOwner rather than a silent no-op, so a
// second agent cannot yank a claim it does not hold. Pass force=true to bypass
// the ownership check (admin/reaper use, threaded from `bd unclaim --force`).
// second agent cannot yank a claim it does not hold. Ownership is compared
// under actorMatches (ga-5ksp5), so two spellings of the same Gas Town
// identity (e.g. a dotted alias vs its session-name form) both count as the
// owner — see canonicalActor. Pass force=true to bypass the ownership check
// (admin/reaper use, threaded from `bd unclaim --force`).
//
// Only works on issues that have an assignee and status is "open" or
// "in_progress". Returns error if:
@ -51,8 +54,10 @@ func UnclaimIssueInTx(ctx context.Context, tx DBTX, id string, actor string, for
}
// Validate ownership unless the caller forced the release. Without force, a
// process may only release its own claim.
if !force && oldIssue.Assignee != actor {
// process may only release its own claim. Compared under actorMatches, not
// verbatim, so a caller naming its own identity under a different layer's
// spelling (ga-5ksp5) is not refused as a stranger.
if !force && !actorMatches(oldIssue.Assignee, actor) {
return fmt.Errorf("%w: %s is held by %s; coordinate with the holder — pass --force only if their claim is abandoned (crashed agent, expired lease)",
storage.ErrNotOwner, id, oldIssue.Assignee)
}
@ -60,23 +65,23 @@ func UnclaimIssueInTx(ctx context.Context, tx DBTX, id string, actor string, for
now := time.Now().UTC()
// Atomic UPDATE: clear assignee, reset status to open, clear started_at,
// and rewrite row_lock. The predicate re-checks ownership (unless forced)
// so a claim that changed hands between the read above and this write is
// not clobbered. row_lock forces a racing reclaim/close on the same row to
// conflict rather than silently merge (see lease.go invariant).
ownerPredicate := "AND assignee = ?"
args := []interface{}{now, freshRowLock(), id, actor}
if force {
// Force still requires a current assignee, but from anyone.
ownerPredicate = "AND assignee != ''"
args = []interface{}{now, freshRowLock(), id}
}
// and rewrite row_lock. The predicate CASes on row_lock rather than
// assignee (ga-5ksp5): ownership was already authorized above (or bypassed
// by force) against the row read into oldIssue, and row_lock is rewritten
// by every path that mutates status/assignee/started_at (see the
// freshRowLock invariant in lease.go) — so requiring it to still equal
// oldIssue.RowVersion detects a claim that changed hands (or was released,
// or closed) between that read and this write exactly as precisely as the
// old `assignee = <actor>` predicate did, without embedding a
// spelling-sensitive string comparison in SQL. force does not exempt this
// check: force only widens WHO may unclaim, not whether the row is still
// the one we read.
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') %s
`, issueTable, ownerPredicate), args...)
WHERE id = ? AND status IN ('open', 'in_progress') AND row_lock = ?
`, issueTable), now, freshRowLock(), id, oldIssue.RowVersion)
if err != nil {
return fmt.Errorf("failed to unclaim issue: %w", err)
}
@ -89,12 +94,12 @@ func UnclaimIssueInTx(ctx context.Context, tx DBTX, id string, actor string, for
if rowsAffected == 0 {
// The pre-checks passed, so a 0-row result means the row changed
// underneath us: re-read to disambiguate an ownership change from a
// status change.
// status change. actorMatches, not verbatim, mirrors the precheck above.
current, gerr := GetIssueInTx(ctx, tx, id)
if gerr != nil {
return fmt.Errorf("failed to unclaim issue %s: no matching row", id)
}
if !force && current.Assignee != actor {
if !force && !actorMatches(current.Assignee, actor) {
return fmt.Errorf("%w: %s is held by %s; coordinate with the holder — pass --force only if their claim is abandoned (crashed agent, expired lease)",
storage.ErrNotOwner, id, current.Assignee)
}
@ -130,12 +135,16 @@ func finishUnclaimInTx(ctx context.Context, tx DBTX, eventTable string, id strin
// 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 —
// ClaimIssueInTx: a Go-side actorMatches precheck (ga-5ksp5) plus a conditional
// UPDATE CASed on row_lock, 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. "Still assigned to expectedAssignee" is judged
// under actorMatches, not verbatim equality, so a caller naming the current
// holder under a different layer's spelling of the same identity is a match,
// not a mismatch — see canonicalActor. 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 does not match 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.
@ -162,25 +171,34 @@ func UnclaimIssueIfAssigneeInTx(ctx context.Context, tx DBTX, id string, actor s
}
// 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 {
// already-released issue (empty assignee) — is a loud, typed no-op. Judged
// under actorMatches (ga-5ksp5), not verbatim equality, so expectedAssignee
// spelled under a different layer's separator convention than the stored
// assignee still counts as a match. 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 !actorMatches(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).
// Atomic UPDATE CASed on row_lock rather than assignee (ga-5ksp5): the
// Go-side check above already authorized the swap under actorMatches
// against the row read into oldIssue, and row_lock is rewritten by every
// path that mutates status/assignee/started_at (see the freshRowLock
// invariant in lease.go) — so requiring it to still equal
// oldIssue.RowVersion applies the same transition as UnclaimIssueInTx
// (assignee cleared, status reopened, started_at cleared, row_lock
// rewritten) while detecting a racing reclaim/close on the same row exactly
// as precisely as the old `assignee = <expectedAssignee>` predicate did,
// without embedding a spelling-sensitive string comparison in SQL.
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)
WHERE id = ? AND status IN ('open', 'in_progress') AND row_lock = ?
`, issueTable), now, freshRowLock(), id, oldIssue.RowVersion)
if err != nil {
return fmt.Errorf("failed to unclaim issue: %w", err)
}
@ -194,13 +212,13 @@ func UnclaimIssueIfAssigneeInTx(ctx context.Context, tx DBTX, id string, actor s
// 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.
// mismatched holder (under actorMatches) 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 {
if !actorMatches(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)

View file

@ -24,6 +24,12 @@ import (
// retry loop replays — the replayed attempt re-reads here and refuses.
// Together they close the read-then-write window.
//
// The assignee guard compares under actorMatches, not verbatim ==, so two
// spellings of the same identity (ga-wzl83) don't false-mismatch — the same
// fix already shipped for UnclaimIssueInTx's SQL-CAS predicate and
// AuthorizeAssigneeTransferWithPools; this was the third, previously-split
// verbatim-comparison surface (ga-5ksp5, gate review on #5439).
//
//nolint:gosec // G201: table name comes from WispTableRouting (hardcoded constants)
func CheckExpectedFieldsInTx(ctx context.Context, tx DBTX, id string, expectedAssignee, expectedStatus *string) error {
if expectedAssignee == nil && expectedStatus == nil {
@ -43,7 +49,7 @@ func CheckExpectedFieldsInTx(ctx context.Context, tx DBTX, id string, expectedAs
if err != nil {
return fmt.Errorf("failed to read assignee/status for %s: %w", id, err)
}
if expectedAssignee != nil && assignee.String != *expectedAssignee {
if expectedAssignee != nil && !actorMatches(assignee.String, *expectedAssignee) {
return fmt.Errorf("%w: %s is held by %q, expected %q", storage.ErrAssigneeMismatch, id, assignee.String, *expectedAssignee)
}
if expectedStatus != nil && status != *expectedStatus {

View file

@ -53,6 +53,9 @@ func TestLifecycleUpdateContract(t *testing.T) {
t.Run("ConditionalGuardsGateOrdinaryEdits", func(t *testing.T) {
conformance.RunLifecycleUpdateConditionalGuardsGateOrdinaryEdits(t, ctx, fixture)
})
t.Run("ConditionalGuardAcceptsRespelledAssignee", func(t *testing.T) {
conformance.RunLifecycleUpdateConditionalGuardAcceptsRespelledAssignee(t, ctx, fixture)
})
t.Run("MetadataPatchOrdersMergeSetUnset", func(t *testing.T) {
conformance.RunLifecycleUpdateMetadataPatchOrdersMergeSetUnset(t, ctx, fixture)
})

View file

@ -71,7 +71,7 @@ func NotPinned(force bool) IssueValidator {
}
}
// canonicalActor normalizes an identity string so two spellings of the same
// CanonicalActor normalizes an identity string so two spellings of the same
// Gas Town identity compare equal. The same identity arrives at bd in more
// than one spelling depending on which layer produced the string it was
// handed: a dotted alias like "gastown.mayor" gets its dot replaced wherever
@ -88,7 +88,7 @@ func NotPinned(force bool) IssueValidator {
// Empty stays empty: an actual absence of an actor must never canonicalize
// to the same value as a non-empty one, or AssigneeMatches would start
// accepting an empty actor against an assigned issue.
func canonicalActor(s string) string {
func CanonicalActor(s string) string {
if s == "" {
return ""
}
@ -110,14 +110,14 @@ func canonicalActor(s string) string {
return b.String()
}
// actorMatches reports whether actor has the same authority as assignee:
// ActorMatches reports whether actor has the same authority as assignee:
// either they're byte-identical, or they canonicalize to the same identity
// (see canonicalActor). The byte-identical check is not redundant — it is
// what keeps two DIFFERENT identities that happen to canonicalize the same
// way from ever being needed for this to matter in practice, and it avoids
// paying canonicalization on the overwhelmingly common exact-match path.
func actorMatches(assignee, actor string) bool {
return assignee == actor || canonicalActor(assignee) == canonicalActor(actor)
// (see CanonicalActor). The byte-identical check is not redundant — it
// avoids paying canonicalization on the overwhelmingly common exact-match
// path (ga-5ksp5 gate review, #5438: fixes a garbled doc comment, no
// behavior change).
func ActorMatches(assignee, actor string) bool {
return assignee == actor || CanonicalActor(assignee) == CanonicalActor(actor)
}
// AssigneeMatches validates that the actor has authority to close the issue.
@ -125,7 +125,7 @@ func actorMatches(assignee, actor string) bool {
// assignee. Returns an error on mismatch unless force is true.
//
// Authority is identity-by-string: actor is compared to assignee under
// canonicalActor, so two principals sharing one canonical actor name both
// CanonicalActor, so two principals sharing one canonical actor name both
// pass — including the same principal spelled two different ways by two
// different layers of Gas Town (ga-wzl83). bd has no identity layer, so this
// matches the existing semantics of the actor field — the guard removes
@ -140,7 +140,7 @@ func AssigneeMatches(actor string, force bool) IssueValidator {
if issue == nil || force {
return nil
}
if issue.Assignee == "" || actorMatches(issue.Assignee, actor) {
if issue.Assignee == "" || ActorMatches(issue.Assignee, actor) {
return nil
}
return fmt.Errorf("cannot close %s: assignee is %q, actor is %q; reclaim or use --force to override", id, issue.Assignee, actor)
@ -171,7 +171,7 @@ func AssigneeMatches(actor string, force bool) IssueValidator {
// the overwhelmingly common non-conflicting paths.
//
// Like AssigneeMatches, authority is identity-by-string — compared under
// canonicalActor rather than verbatim (ga-wzl83), so this removes silent
// CanonicalActor rather than verbatim (ga-wzl83), so this removes silent
// cross-actor takeovers without adding new identity guarantees, and without
// falsely treating the current holder as a stranger when actor or
// newAssignee names it under a different layer's spelling of the same
@ -181,7 +181,7 @@ func AssigneeNotStolen(actor, newAssignee string, poolAliases func() []string, f
if issue == nil || force {
return nil
}
if issue.Assignee == "" || actorMatches(issue.Assignee, actor) || actorMatches(issue.Assignee, newAssignee) {
if issue.Assignee == "" || ActorMatches(issue.Assignee, actor) || ActorMatches(issue.Assignee, newAssignee) {
return nil
}
if issue.Status != types.StatusInProgress {

View file

@ -163,8 +163,8 @@ func TestCanonicalActor(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := canonicalActor(tt.in); got != tt.want {
t.Errorf("canonicalActor(%q) = %q, want %q", tt.in, got, tt.want)
if got := CanonicalActor(tt.in); got != tt.want {
t.Errorf("CanonicalActor(%q) = %q, want %q", tt.in, got, tt.want)
}
})
}
@ -186,8 +186,8 @@ func TestActorMatches(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := actorMatches(tt.assignee, tt.actor); got != tt.want {
t.Errorf("actorMatches(%q, %q) = %v, want %v", tt.assignee, tt.actor, got, tt.want)
if got := ActorMatches(tt.assignee, tt.actor); got != tt.want {
t.Errorf("ActorMatches(%q, %q) = %v, want %v", tt.assignee, tt.actor, got, tt.want)
}
})
}
@ -386,7 +386,7 @@ func TestAssigneeNotStolen(t *testing.T) {
wantErr: true,
},
// ga-wzl83: same class as AssigneeMatches — actor and newAssignee are
// compared against the stored assignee under canonicalActor, so a
// compared against the stored assignee under CanonicalActor, so a
// different layer's spelling of the current holder's own identity is
// not mistaken for a stranger.
{