diff --git a/CHANGELOG.md b/CHANGELOG.md index 81198504a..b94004485 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,6 +43,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 claimable by any actor through the same atomic compare-and-swap — the claim stamps the normal lease, and issues assigned to a real actor (or to an alias not in the config) keep their anti-steal protection. + Pool-aware claiming works in every dolt mode — the proxied-server claim + path applies the same predicate — and `claim.*` is a recognized config + namespace (documented in `bd config --help`). Note: if a pool take's + lease expires, `bd reclaim` returns the issue to the unassigned pool, + not to the pool alias it was dispatched to. Off by default: with no `claim.pools` configured, behavior is unchanged. - **Work leases: claim-TTL, heartbeat, and reclaim for dead-worker recovery** diff --git a/cmd/bd/claim_pools_embedded_test.go b/cmd/bd/claim_pools_embedded_test.go index 431c49515..f67b209da 100644 --- a/cmd/bd/claim_pools_embedded_test.go +++ b/cmd/bd/claim_pools_embedded_test.go @@ -31,6 +31,11 @@ func TestEmbeddedClaimPools(t *testing.T) { cfgCmd.Env = bdEnv(dir) if out, err := cfgCmd.CombinedOutput(); err != nil { t.Fatalf("bd config set claim.pools failed: %v\n%s", err, out) + } else if strings.Contains(string(out), "not a recognized config key") { + // The exit code alone missed this once: claim.* must be a + // recognized namespace so the feature's setup command doesn't + // warn every adopter. + t.Fatalf("bd config set claim.pools warned about an unrecognized key:\n%s", out) } t.Run("claim_from_pool_succeeds", func(t *testing.T) { diff --git a/cmd/bd/config.go b/cmd/bd/config.go index 924db0631..cd60efb86 100644 --- a/cmd/bd/config.go +++ b/cmd/bd/config.go @@ -39,6 +39,7 @@ Common namespaces: - notion.* Notion integration settings - custom.* Custom integration settings - status.* Issue status configuration + - claim.* Claim arbitration settings (pool-aware claiming) - doctor.suppress.* Suppress specific bd doctor warnings (GH#1095) Auto-Export (config.yaml): @@ -72,6 +73,18 @@ Custom Status States: This enables issues to use statuses like 'awaiting_review' in addition to the built-in statuses (open, in_progress, blocked, deferred, closed). +Claim Pools: + A dispatcher can pre-assign issues to a pool pseudo-assignee (e.g. + "fable-crew") and let any actor take them with --claim. List the pool + aliases in the claim.pools config key, comma-separated: + + bd config set claim.pools "fable-crew,night-crew" + + Issues assigned to a real actor (or to an alias not in the list) keep + their anti-steal protection. Pool takes carry the normal lease; note + that if a taker's lease expires, bd reclaim returns the issue to the + unassigned pool, not to the pool alias it was dispatched to. + Suppressing Doctor Warnings: Suppress specific bd doctor warnings by check name slug: bd config set doctor.suppress.pending-migrations true @@ -88,6 +101,7 @@ Examples: bd config set jira.url "https://company.atlassian.net" bd config set jira.project "PROJ" bd config set status.custom "awaiting_review,awaiting_testing" + bd config set claim.pools "fable-crew,night-crew" # Pool aliases claimable by any actor bd config set doctor.suppress.pending-migrations true bd config set dolt.debug true # Enable Dolt sql-server debug mode (loglevel=debug, --prof cpu) bd config set dolt.local-only true # Skip wiring a Dolt sync remote during bd init @@ -926,6 +940,7 @@ var recognizedConfigPrefixes = []string{ "status.", "types.", "doctor.suppress.", "routing.", "sync.", "git.", "directory.", "repos.", "external_projects.", "validation.", "hierarchy.", "ai.", "backup.", "federation.", "metrics.", "agent.", + "claim.", } // allRecognizedConfigPrefixes returns the static namespaces plus the prefix of diff --git a/cmd/bd/config_validate_key_test.go b/cmd/bd/config_validate_key_test.go index 8462d4407..0eb326ac6 100644 --- a/cmd/bd/config_validate_key_test.go +++ b/cmd/bd/config_validate_key_test.go @@ -13,6 +13,7 @@ func TestIsRecognizedConfigKey(t *testing.T) { "doctor.suppress.git-hooks", "no-git-ops", "beads.role", "status.custom", "types.custom", "types.infra", "ai.model", "backup.enabled", "import.path", "dolt.local-only", "agent.profile", + "claim.pools", // Tracker namespaces are derived from the registry (GH#4427); cover // ado (the original bug) plus the others removed from the static list. "ado.org", "ado.project", "github.token", "linear.api-key", diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md index 2bb2062d1..9cb0177ef 100644 --- a/docs/CLI_REFERENCE.md +++ b/docs/CLI_REFERENCE.md @@ -2769,6 +2769,7 @@ Common namespaces: - notion.* Notion integration settings - custom.* Custom integration settings - status.* Issue status configuration + - claim.* Claim arbitration settings (pool-aware claiming) - doctor.suppress.* Suppress specific bd doctor warnings (GH#1095) Auto-Export (config.yaml): @@ -2802,6 +2803,18 @@ Custom Status States: This enables issues to use statuses like 'awaiting_review' in addition to the built-in statuses (open, in_progress, blocked, deferred, closed). +Claim Pools: + A dispatcher can pre-assign issues to a pool pseudo-assignee (e.g. + "fable-crew") and let any actor take them with --claim. List the pool + aliases in the claim.pools config key, comma-separated: + + bd config set claim.pools "fable-crew,night-crew" + + Issues assigned to a real actor (or to an alias not in the list) keep + their anti-steal protection. Pool takes carry the normal lease; note + that if a taker's lease expires, bd reclaim returns the issue to the + unassigned pool, not to the pool alias it was dispatched to. + Suppressing Doctor Warnings: Suppress specific bd doctor warnings by check name slug: bd config set doctor.suppress.pending-migrations true @@ -2818,6 +2831,7 @@ Examples: bd config set jira.url "https://company.atlassian.net" bd config set jira.project "PROJ" bd config set status.custom "awaiting_review,awaiting_testing" + bd config set claim.pools "fable-crew,night-crew" # Pool aliases claimable by any actor bd config set doctor.suppress.pending-migrations true bd config set dolt.debug true # Enable Dolt sql-server debug mode (loglevel=debug, --prof cpu) bd config set dolt.local-only true # Skip wiring a Dolt sync remote during bd init diff --git a/docs/cli-reference/config.md b/docs/cli-reference/config.md index f82e81381..616c56b95 100644 --- a/docs/cli-reference/config.md +++ b/docs/cli-reference/config.md @@ -22,6 +22,7 @@ Common namespaces: - notion.* Notion integration settings - custom.* Custom integration settings - status.* Issue status configuration + - claim.* Claim arbitration settings (pool-aware claiming) - doctor.suppress.* Suppress specific bd doctor warnings (GH#1095) Auto-Export (config.yaml): @@ -55,6 +56,18 @@ Custom Status States: This enables issues to use statuses like 'awaiting_review' in addition to the built-in statuses (open, in_progress, blocked, deferred, closed). +Claim Pools: + A dispatcher can pre-assign issues to a pool pseudo-assignee (e.g. + "fable-crew") and let any actor take them with --claim. List the pool + aliases in the claim.pools config key, comma-separated: + + bd config set claim.pools "fable-crew,night-crew" + + Issues assigned to a real actor (or to an alias not in the list) keep + their anti-steal protection. Pool takes carry the normal lease; note + that if a taker's lease expires, bd reclaim returns the issue to the + unassigned pool, not to the pool alias it was dispatched to. + Suppressing Doctor Warnings: Suppress specific bd doctor warnings by check name slug: bd config set doctor.suppress.pending-migrations true @@ -71,6 +84,7 @@ Examples: bd config set jira.url "https://company.atlassian.net" bd config set jira.project "PROJ" bd config set status.custom "awaiting_review,awaiting_testing" + bd config set claim.pools "fable-crew,night-crew" # Pool aliases claimable by any actor bd config set doctor.suppress.pending-migrations true bd config set dolt.debug true # Enable Dolt sql-server debug mode (loglevel=debug, --prof cpu) bd config set dolt.local-only true # Skip wiring a Dolt sync remote during bd init diff --git a/internal/storage/domain/db/issue.go b/internal/storage/domain/db/issue.go index b391ca1c3..fd7c1e333 100644 --- a/internal/storage/domain/db/issue.go +++ b/internal/storage/domain/db/issue.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "fmt" + "slices" "strconv" "strings" "time" @@ -225,25 +226,44 @@ func (r *issueSQLRepositoryImpl) Claim(ctx context.Context, id, actor string, op // row_lock invariant guards against (see issueops/lease.go). leaseClause, leaseArgs := issueops.LeaseSetClause(now, issueops.LeaseTTL(ctx)) + // Mirror the primary path's pool-aware predicate (bd-bguz6): aliases in + // the claim.pools config are claimable by any actor. This dual must stay + // in lockstep with issueops.ClaimIssueInTx — the lease comment above is + // the scar from the last time it drifted. (Known remaining drift: this + // path claims from status = 'open' only, not the custom active statuses + // of ClaimableSourceStatusesInTx.) + pools, err := issueops.ClaimPoolAliasesInTx(ctx, r.runner) + if err != nil { + return domain.ClaimRowResult{}, fmt.Errorf("db: Claim %s: resolve claim pools: %w", id, err) + } + assigneePredicate := "assignee = '' OR assignee IS NULL OR assignee = ?" + assigneeArgs := []any{actor} + for _, pool := range pools { + assigneePredicate += " OR assignee = ?" + assigneeArgs = append(assigneeArgs, pool) + } + var res sql.Result if startedWasZero { args := append([]any{actor, now, now}, leaseArgs...) - args = append(args, id, actor) + args = append(args, id) + args = append(args, assigneeArgs...) //nolint:gosec // G201: table is one of two hardcoded constants res, err = r.runner.ExecContext(ctx, fmt.Sprintf(` UPDATE %s SET assignee = ?, status = 'in_progress', updated_at = ?, started_at = ?, %s - WHERE id = ? AND status = 'open' AND (assignee = '' OR assignee IS NULL OR assignee = ?) - `, table, leaseClause), args...) + WHERE id = ? AND status = 'open' AND (%s) + `, table, leaseClause, assigneePredicate), args...) } else { args := append([]any{actor, now}, leaseArgs...) - args = append(args, id, actor) + args = append(args, id) + args = append(args, assigneeArgs...) //nolint:gosec // G201: table is one of two hardcoded constants res, err = r.runner.ExecContext(ctx, fmt.Sprintf(` UPDATE %s SET assignee = ?, status = 'in_progress', updated_at = ?, %s - WHERE id = ? AND status = 'open' AND (assignee = '' OR assignee IS NULL OR assignee = ?) - `, table, leaseClause), args...) + WHERE id = ? AND status = 'open' AND (%s) + `, table, leaseClause, assigneePredicate), args...) } if err != nil { return domain.ClaimRowResult{}, fmt.Errorf("db: Claim %s: %w", id, err) @@ -267,11 +287,12 @@ func (r *issueSQLRepositoryImpl) Claim(ctx context.Context, id, actor string, op assignee = currentAssignee.String } return domain.ClaimRowResult{ - Updated: false, - CurrentAssignee: assignee, - CurrentStatus: currentStatus, - StartedAtWasZero: startedWasZero, - OldIssue: oldIssue, + Updated: false, + CurrentAssignee: assignee, + CurrentAssigneeIsPool: slices.Contains(pools, assignee), + CurrentStatus: currentStatus, + StartedAtWasZero: startedWasZero, + OldIssue: oldIssue, }, nil } diff --git a/internal/storage/domain/db/issue_test.go b/internal/storage/domain/db/issue_test.go index b3eca8acc..9f790e6ec 100644 --- a/internal/storage/domain/db/issue_test.go +++ b/internal/storage/domain/db/issue_test.go @@ -41,6 +41,9 @@ func (s *testSuite) TestIssueSQLRepository() { s.Run("EmptyIDReturnsError", s.issueClaimEmptyID) s.Run("RecordsClaimedEvent", s.issueClaimRecordsEvent) s.Run("StampsLeaseAndIsReclaimable", s.issueClaimStampsLease) + s.Run("PoolAliasClaimableByAnyActor", s.issueClaimPoolAlias) + s.Run("UnconfiguredAliasStillProtected", s.issueClaimPoolUnconfiguredAlias) + s.Run("PoolStatusConflictFlagsPoolAssignee", s.issueClaimPoolStatusConflict) }) s.Run("Get", func() { s.Run("MissingIDReturnsErrNoRows", s.issueGetMissing) @@ -692,6 +695,83 @@ func (s *testSuite) issueClaimStampsLease() { s.Equal("", out.Assignee) } +// setClaimPools configures claim.pools for a subtest and returns a cleanup +// func. Sibling subtests share this database (SetupTest resets per suite +// method, not per s.Run), so the key must not leak past the subtest. +func (s *testSuite) setClaimPools(value string) func() { + s.Require().NoError(issueops.SetConfigInTx(s.Ctx(), s.Runner(), "claim.pools", value)) + return func() { + _, err := s.db.ExecContext(s.Ctx(), "DELETE FROM config WHERE `key` = 'claim.pools'") + s.Require().NoError(err) + } +} + +// issueClaimPoolAlias asserts the proxied-server (uow) claim path honors +// claim.pools (bd-bguz6): an issue pre-assigned to a configured pool alias is +// claimable by any actor, exactly like the primary issueops.ClaimIssueInTx +// path. +func (s *testSuite) issueClaimPoolAlias() { + cleanup := s.setClaimPools("fable-crew, night-crew") + defer cleanup() + + r := s.issueRepo() + in := newTestIssue("bd-claim-pool", "pool-dispatched item") + in.Assignee = "fable-crew" + s.Require().NoError(r.Insert(s.Ctx(), in, "dispatcher", domain.InsertIssueOpts{})) + + res, err := r.Claim(s.Ctx(), "bd-claim-pool", "bob", domain.IssueTableOpts{}) + s.Require().NoError(err) + s.Require().True(res.Updated, "pool-assigned issue must be claimable by any actor through the proxied path") + + out, err := r.Get(s.Ctx(), "bd-claim-pool", domain.IssueTableOpts{}) + s.Require().NoError(err) + s.Equal("bob", out.Assignee) + s.Equal(types.StatusInProgress, out.Status) + + var leaseExpires sql.NullTime + s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(), + "SELECT lease_expires_at FROM issues WHERE id = ?", "bd-claim-pool").Scan(&leaseExpires)) + s.Require().True(leaseExpires.Valid, "a pool take is a normal claim and must stamp a lease") +} + +// issueClaimPoolUnconfiguredAlias asserts an alias absent from claim.pools +// keeps the anti-steal protection on this path too. +func (s *testSuite) issueClaimPoolUnconfiguredAlias() { + cleanup := s.setClaimPools("fable-crew") + defer cleanup() + + r := s.issueRepo() + in := newTestIssue("bd-claim-pool-other", "other crew's work") + in.Assignee = "other-crew" + s.Require().NoError(r.Insert(s.Ctx(), in, "dispatcher", domain.InsertIssueOpts{})) + + res, err := r.Claim(s.Ctx(), "bd-claim-pool-other", "bob", domain.IssueTableOpts{}) + s.Require().NoError(err) + s.False(res.Updated, "unconfigured alias must not be claimable") + s.Equal("other-crew", res.CurrentAssignee) + s.False(res.CurrentAssigneeIsPool, "unconfigured alias is not a pool") +} + +// issueClaimPoolStatusConflict asserts a pool-assigned issue that loses the +// CAS on status is flagged CurrentAssigneeIsPool, so the use-case layer +// reports a status conflict instead of a held-by-pseudo-assignee refusal. +func (s *testSuite) issueClaimPoolStatusConflict() { + cleanup := s.setClaimPools("fable-crew") + defer cleanup() + + r := s.issueRepo() + in := newTestIssue("bd-claim-pool-blocked", "blocked pool item") + in.Assignee = "fable-crew" + in.Status = types.StatusBlocked + s.Require().NoError(r.Insert(s.Ctx(), in, "dispatcher", domain.InsertIssueOpts{})) + + res, err := r.Claim(s.Ctx(), "bd-claim-pool-blocked", "bob", domain.IssueTableOpts{}) + s.Require().NoError(err) + s.False(res.Updated) + s.True(res.CurrentAssigneeIsPool, "pool assignee must be flagged for status-conflict error mapping") + s.Equal(types.StatusBlocked, res.CurrentStatus) +} + func (s *testSuite) issueClaimRecordsEvent() { r := s.issueRepo() s.Require().NoError(r.Insert(s.Ctx(), newTestIssue("bd-claim-evt", "x"), "tester", domain.InsertIssueOpts{})) diff --git a/internal/storage/domain/issue.go b/internal/storage/domain/issue.go index 566872675..58060e78f 100644 --- a/internal/storage/domain/issue.go +++ b/internal/storage/domain/issue.go @@ -22,11 +22,16 @@ type IssueTableOpts struct { } type ClaimRowResult struct { - Updated bool - CurrentAssignee string - CurrentStatus types.Status - StartedAtWasZero bool - OldIssue *types.Issue + Updated bool + // CurrentAssignee is the assignee found on the 0-row disambiguation + // read; CurrentAssigneeIsPool marks it as a claim.pools alias, so the + // caller reports a status conflict instead of a held-by-someone + // refusal (a pool alias never "holds" a claim). + CurrentAssignee string + CurrentAssigneeIsPool bool + CurrentStatus types.Status + StartedAtWasZero bool + OldIssue *types.Issue } type IssueSQLRepository interface { @@ -416,6 +421,12 @@ func (u *issueUseCaseImpl) claim(ctx context.Context, id, actor string, useWisp return ClaimResult{AlreadyClaimed: true, PriorAssignee: actor}, nil } if row.CurrentAssignee != "" && row.CurrentAssignee != actor { + // A pool-assigned issue only loses the CAS for a non-assignee + // reason (status changed underneath us): report the status, not a + // misleading held-by refusal (mirrors issueops.ClaimIssueInTx). + if row.CurrentAssigneeIsPool { + return ClaimResult{}, fmt.Errorf("%w: status %s", storage.ErrNotClaimable, row.CurrentStatus) + } return ClaimResult{}, fmt.Errorf("%w by %s", storage.ErrAlreadyClaimed, row.CurrentAssignee) } return ClaimResult{}, fmt.Errorf("%w: status %s", storage.ErrNotClaimable, row.CurrentStatus)