cmd/bd: bd label rename <old> <new> (stacked on #6007) (#6009)

* storage: add RenameLabel primitive with merge semantics

Add a storage primitive that renames a label across every issue and
wisp that carries it, in one transaction per store. An issue that
already carries the new label is a merge - the stale old-label row is
dropped rather than raising a duplicate-key error - and the call
reports renamed/merged counts plus every touched id.

- internal/storage/issueops/labels.go: RenameLabelInTx sweeps the
  labels and wisp_labels tables (INSERT IGNORE then DELETE, so the
  merge never errors), emitting one EventLabelRenamed plus the usual
  full-snapshot journal row per touched issue/wisp, matching
  AddLabelInTx/RemoveLabelInTx's journal shape. A single batch event
  was considered and rejected: the journal-completeness guard requires
  every touched row to carry its own journal entry.
- internal/storage/storage.go: RenameLabel added to the Storage
  interface, next to AddLabel/RemoveLabel/GetIssuesByLabel.
- internal/storage/dolt, internal/storage/embeddeddolt: direct
  implementations. The dolt commit targets the fixed events/labels
  table pair; doltAddAndCommit's own HasStagedChanges guard skips it
  when the rename touched wisps only (wisp tables are dolt-ignored,
  same as AddLabel/RemoveLabel).
- internal/storage/hook_decorator.go: HookFiringStore.RenameLabel
  fires on_update per touched issue, matching AddLabel/RemoveLabel.
- internal/types/types.go: new EventLabelRenamed event type. Unlike
  EventLabelAdded/EventLabelRemoved, one rename produces exactly one
  of these per touched row, never a paired add+remove.
- internal/jira/tracker_test.go: mock stub for the new interface
  method.

Tests: internal/storage/dolt/label_rename_test.go, against a real
dolt-sql-server container - basic rename, merge, wisp sweep,
zero-carrier no-op, over-length refusal, event assertion. All green.
Also verified TestEveryBeadMutatorJournalsOrIsExempt still passes.

Gates: gofmt clean, go vet ./... clean, CGO_ENABLED=0 go test -tags
gms_pure_go -c -o /dev/null ./cmd/bd clean, go build ./... clean.

* storage: refuse RenameLabel(x, x) instead of wiping the label

RenameLabelInTx's merge branch treats every carrier of oldLabel as
already carrying newLabel when the two names collide (they are the
same string): the batched INSERT IGNORE no-ops on every row, and the
unconditional DELETE FROM <table> WHERE label = ? that follows then
removes every row for that label plane. A self-rename silently wiped
the label instead of leaving it untouched.

Reject oldLabel == newLabel (compared after trimming, case-sensitive)
before any write, returning the new ErrRenameLabelSameName. Verified
red->green: TestRenameLabel_SameNameRefused and
TestRenameLabel_SameNameAfterTrimRefused both fail (GetLabels returns
[] on both the labels and wisp_labels planes) against the pre-fix
code, and pass against the fix. Full TestRenameLabel* suite in
internal/storage/dolt still green.

* telemetry: instrument InstrumentedStorage.RenameLabel

AddLabel and RemoveLabel already get OTel spans/metrics through
InstrumentedStorage; RenameLabel had no override and so fell through
to the embedded storage.DoltStorage passthrough, invisible to
storage.* tracing. Add the override, mirroring the AddLabel/RemoveLabel
shape: span attributes for the old/new label pair (bd.label.old,
bd.label.new, matching the existing bd.dep.from/bd.dep.to pairing
convention), and on success a bd.result.count / bd.merged.count pair
following the SearchIssues-style "set result attributes after a
successful call" pattern already used elsewhere in this file.

* storage: document the O(N) round-trip cost of RenameLabelInTx's event loop

renameLabelInPlane's per-issue loop (InsertDerivedEvent + RecordEventInTx)
is O(len(oldIDs)) SQL round trips inside one transaction, up to four per
touched issue. On a huge label population that lengthens the transaction
and raises the odds an optimistic-concurrency retry has to redo the whole
rename from scratch.

No batching added: InsertDerivedEvent's dedup SELECT is a real
cross-replica convergence check (Protocol v0.1 C2.3), not a redundant one
this transaction could skip, and no batch primitive for this shape exists
anywhere in this package - building one here would be new shared
infrastructure grown for a single caller. AddLabelInTx/RemoveLabelInTx
already pay the identical per-call cost for their one issue; this loop is
that cost repeated once per touched issue. Documented inline as a
disclosed limitation rather than silently left unremarked.

* bda-lbjv: derive rename merge count from rows-affected, not a prior read

renameLabelInPlane computed merged from a snapshot SELECT of newLabel's
carriers taken before the INSERT IGNORE - a check-then-insert whose
result is used. A concurrent AddLabel(issue, newLabel) committing between
snapshot and insert made the reported count schedule-dependent while the
stored data stayed correct (cross-model finding: the Opus panel cleared
A1, codex flipped it to NOT-SAFE on exactly this line).

Now the count is a measurement: INSERT IGNORE reports one affected row
per id actually inserted, so merged = len(oldIDs) - inserted, and the
newLabel pre-read is gone entirely.

Tests: sqlmock scripts the racing schedule (insert sees a row the
snapshot read could not); mutation control confirms the old
implementation fails the new test. Full issueops package + live-store
TestRenameLabel_* green.

* bda-c77s: first-party coverage for EmbeddedDoltStore.RenameLabel

The embedded impl had zero tests while DoltStore.RenameLabel carries a
dedicated suite; AddLabel/RemoveLabel both have parallel embedded
coverage by convention. Four wiring cases (basic, merge, zero-carrier
no-op, same-name refusal) - the deep semantics stay pinned by the shared
issueops suite and the dolt-side tests against the same implementation.

BEADS_TEST_EMBEDDED_DOLT=1: 5 RUN, all green, 2.8s.

* storage: scope the rename delete to the ids the sweep captured

An unrestricted DELETE ... WHERE label = ? makes the sweep's blast radius
engine-dependent: under current-read DELETE semantics a row a concurrent
AddLabel(oldLabel) committed after this transaction's snapshot would be
removed without ever being renamed, counted or journaled. Restricting the
delete to the captured ids touches exactly the rows the INSERT IGNORE above
accounted for on every engine; a concurrent add outside the snapshot now
deterministically SURVIVES the rename - the same observable state as that
add landing after the rename committed, which is the only order-independent
reading of the race.

sqlmock WithArgs pins the id-scoped statement shape; the embedded-Dolt
lifecycle set stays green (5/5).

* cmd/bd: add `bd label rename <old> <new>` with dry-run preview

Wire the storage.RenameLabel primitive (previous commit) into a CLI
command that renames a label everywhere it appears in one call instead
of a per-issue add-then-remove loop.

- cmd/bd/label.go: `bd label rename <old> <new> [--dry-run]`.
  validateLabelRename refuses empty/identical labels and the
  'provides:' reserved prefix before any store call - it is a pure
  function so those rules are testable without a store. --dry-run
  previews the blast radius (count plus the first issues) read-only,
  via a path kept separate from the write path so it can never reach a
  transaction.
- cmd/bd/label_proxied_server.go: the proxied-server route composes
  the existing per-issue LabelUseCase.AddLabel/RemoveLabel (and wisp
  twins) in one uow.RunTx, the same fan-out shape label propagate
  already uses on this route. It journals as an add/remove pair per
  issue rather than the direct route's single EventLabelRenamed,
  because LabelUseCase has no rename-shaped event; the rename
  semantics (merge-on-collision, honest zero-carrier no-op, dry-run
  preview) are identical on both routes.
- docs/core-concepts/labels.md: documents rename, dry-run, and merge
  semantics under Label Management.

Tests: cmd/bd/label_rename_test.go (pure argument-validation table
test, no store needed) plus new subtests in
cmd/bd/label_embedded_test.go covering the full CLI path - basic
rename, merge, dry-run writes nothing, zero-carrier no-op,
identical/empty/reserved-prefix refusals. All green.

Gates: gofmt clean, go vet ./... clean, CGO_ENABLED=0 go test -tags
gms_pure_go -c -o /dev/null ./cmd/bd clean, go build ./... clean.

* cmd/bd,domain: emit label_renamed on the proxied route, not add+remove

runLabelRenameProxiedServer used to fan a rename out into a per-issue
AddLabel-then-RemoveLabel pair, journaling label_added/label_removed
instead of one EventLabelRenamed - a divergence from the direct
DoltStore/EmbeddedDoltStore route the upstream reviewer has already
rejected for another PR touching the same class of proxied/direct
split.

Add domain.LabelUseCase.RenameLabel and domain.LabelSQLRepository.
RenameLabel. The repository method delegates straight to
issueops.RenameLabelInTx (r.runner satisfies issueops.DBTX
structurally), so the proxied route is not merely the same SQL SHAPE
as the direct one, it is the same function: identical merge semantics,
the same ErrRenameLabelSameName refusal, and one EventLabelRenamed per
touched issue. runLabelRenameProxiedServer now just calls
uw.LabelUseCase().RenameLabel(...) inside its existing uow.RunTx.

Declare recordingLabelUC.RenameLabel so the notifying unit of work
records one update per touched issue/wisp (mirroring
HookFiringStore.RenameLabel on the direct route) instead of silently
recording nothing through the embedded interface - caught by the
existing structural parity guard, TestRecordingLabelUseCaseCoversItsSurface,
which fails on any domain.LabelUseCase method neither declared on
recordingLabelUC nor exempted with a reason.

Tests, verified red->green:
  - internal/storage/domain/db: TestLabelUseCase/RenameLabel adds 5
    subtests. EmitsOneRenamedEventPerIssue is the direct regression
    test - reverting RenameLabel to a simulated add-then-remove
    fan-out reproduces exactly the pre-fix event counts (renamed=0,
    added=2, removed=1) it now asserts against (renamed=1, added=1,
    removed=0).
  - cmd/bd/label_proxied_integration_test.go: new "rename" subtest
    exercises `bd label rename` end to end through the real proxied
    server and asserts the same label_renamed/added/removed counts
    directly against the events table.
  - internal/storage/uow: TestRecordingLabelUseCaseCoversItsSurface
    goes red (RenameLabel inherited, records nothing) without the
    recordingLabelUC override and green with it.

Full internal/storage/uow suite (287s) and the new domain/db and
cmd/bd tests all pass.

* cmd/bd: record commandDidWrite before the rename error return

runLabelRename read renamed>0 into commandDidWrite only after the
`if err != nil` early return, so a rename whose SQL side committed but
whose store call also returned an error - the Dolt publication step
failing after the working-set write landed - never marked the command
as having written. The caller's deferred auto-commit would then skip
creating a Dolt commit for a write that, on disk, actually happened.

Move the commandDidWrite.Store(true) check ahead of the error check,
matching applyLabelEdit's existing per-issue marking a few lines above
in the same file.

New test: TestRunLabelRename_CommandDidWriteSetBeforeErrorReturn wraps
a real *dolt.DoltStore in a spy whose RenameLabel reports a publish
failure (renamed>0, err!=nil) after delegating to the real rename, and
asserts commandDidWrite is set despite the returned error. Verified
red->green: reverting the ordering reproduces the exact failure this
guards against.

* bda-bnid: nolint:forbidigo on proxied bulk rename call

The route delegates to domain.LabelUseCase.RenameLabel deliberately: one
EventLabelRenamed per issue with identical merge semantics to the direct
route. Patch.Labels (the lint's suggested remedy) would reintroduce the
per-issue add/remove event divergence this delegation replaced. Matches
the file's own convention (4 sibling nolints, same shape).

Negative control: without the nolint golangci-lint forbidigo reports
exactly this line; with it, 0 issues.

* cmd/bd: address review on label rename (CHANGELOG entry, dry-run caveat, partial-failure count)

Two blocking items from review (bee-ghosttrack, PR #6009):

- Add the CHANGELOG entry for `bd label rename`, in the house voice used
  by the neighboring bd-label entries (bold lead sentence, PR link, dense
  explanatory prose on the merge/dry-run/partial-failure contract).
- The `--dry-run` merged count is a plain snapshot intersection of two
  independent reads - exactly the check-then-count shape
  renameLabelInPlane's own comment documents rejecting for the write
  path, because it is schedule-dependent under a concurrent
  AddLabel/RemoveLabel. That is an acceptable estimate for a preview, but
  nothing said so: the command's Long text, the --dry-run flag help, and
  an inline comment at the computation site now all say the number is
  not authoritative.

One non-blocking nit fixed (the other - hydrating full issue rows in the
direct dry-run just to print 10 titles - is left alone; see below):

- On a partial rename failure (renamed>0, err!=nil - e.g. a Dolt
  publication failure after the SQL side already committed) the command
  now reports how many issues were renamed and merged before the
  failure, instead of only the error. Mirrors the existing shape in
  conflicts.go's ResolveConflictRows handling ("resolved %d of %d
  conflict(s) before failing").

Left alone, and why: the GetIssuesByIDs-hydration nit. GetIssuesByLabel
hydrates every matching issue via GetIssuesByIDs on both the old-label
and new-label reads, which is wasteful on a label carrying 10k issues
when the text-mode preview only prints 10. But the JSON-mode contract
already returns every matching issue's id+title (not capped at the
preview limit), so avoiding hydration only helps the text-mode path and
would branch the two output modes apart for a marginal win on an
uncommon case (a rename dry-run over a 10k-issue label). Not clean
enough to do inline without its own test coverage and a decision about
whether the JSON contract should change too - flagged in the review as
skippable, so skipping it here.

Verification:
- go build ./... - clean
- go vet ./cmd/bd/... - clean
- gofmt -l cmd/bd/label.go - clean
- go test ./cmd/bd/... -run 'Label|LabelRename' - all pass
- BEADS_TEST_EMBEDDED_DOLT=1 go test ./cmd/bd/... -run 'TestEmbeddedLabel$' -v
  - all pass, including label_rename_basic/merge/dry_run_writes_nothing
- BEADS_TEST_PROXIED_SERVER=1 BEADS_TEST_EMBEDDED_DOLT=1 go test ./cmd/bd/...
  -run TestProxiedServerLabel -v - all pass, including the "rename" subtest
- BEADS_TEST_EMBEDDED_DOLT=1 go test ./internal/storage/issueops/... -run Rename -v
- BEADS_TEST_EMBEDDED_DOLT=1 go test ./internal/storage/dolt/... -run Rename -v (live dolt-sql-server)
- BEADS_TEST_EMBEDDED_DOLT=1 go test ./internal/storage/embeddeddolt/... -run Rename -v

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

* cmd/bd: report an upper bound on a failed rename, not a landed count

The partial-failure message asserted that renamed>0 means the SQL side committed. On both routes the counts are assigned inside the transaction closure (label_proxied_server.go RunTx, dolt/labels.go withRetryTx), so a Commit failure or retry exhaustion returns them holding the rolled-back attempt numbers - nothing landed, and the user read 'renamed 6 issue(s) before failing'. Retry exhaustion under a busy server is the likely failure for a bulk rename, so it misreported exactly when it fired. Now reports an upper bound. commandDidWrite keeps the same premise deliberately: it is fail-safe in the other direction.

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

* cmd/bd: pin the partial-failure wording, and hedge the merged count too

Round-3 review: the r2 correction rode unpinned. Nothing in the suite drives
a failing rename with renamed > 0, so the whole TestEmbeddedLabel suite passed
with the hunk reverted - the fix was unfalsifiable, which is the same defect
class the correction itself was about.

Extracts the sentence into labelRenamePartialFailureMessage, a pure function a
test can assert on without inducing a mid-transaction failure, and pins it:
the hedged phrasings must be present AND the two pre-correction phrasings must
be absent. Mutation-checked - restoring the old wording turns it red on three
assertions.

Also the round-3 nit: (%d merged) was the one unhedged clause in a hedged
sentence. It now reads (of which up to %d merged), so no number in the message
asserts a write that may never have landed.

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

* docs: retire the landed-count premise from the CHANGELOG too

Round-4 review, MAJOR: the code retracted a premise and the CHANGELOG kept
publishing it. The entry still said a partway failure 'reports how many issues
were renamed and merged before the failure' - a landed count - while
labelRenamePartialFailureMessage had already become an upper bound.

The sentence carried the premise TWICE and the review named one: besides the
count, its parenthetical offered 'a Dolt publication failure after the SQL side
already committed' as the case, when the whole point of the correction is that
renamed > 0 cannot distinguish that from a rollback. Rewrote both halves: the
bound is explicit, and the two failure shapes are named as indistinguishable
from the count alone.

Also round-4 MINOR: the helper had been inserted between reportLabelRename's
doc comment and its func, so the comment headed the wrong function and
reportLabelRename was left undocumented. Moved back down.

Not done, deliberately: the round-4 NIT that the pin covers the helper and not
the call site. It is marked 'noting, not asking', and an unrequested fix is the
one that ships a defect - this PR already demonstrated that.

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

* CHANGELOG: move this PR's entry under [Unreleased]

The 1.3.0 cut renamed the old [Unreleased] block, so these lines
merged cleanly into a released section (gastownhall/beads#6643).
Moved 31 line(s); the code is unchanged.

* cmd/bd: register label rename in the proxied capability registry

TestProxyCapabilityRegistryCoversCommandTree requires every command path to
carry a proxied-server row. label rename has a proxied route (RunE hands the
rename to runLabelRenameProxiedServer and the --dry-run preview to a proxied
read UOW), so it joins its label siblings in proxyPermittedPaths.

* storage: mint a version for every bead a label rename touches

TestEveryBeadMutatorMintsOrIsExempt (added with #6650) fails on this PR:
RenameLabelInTx writes the labels table but never reached
RecordVersionInTx. A rename changes the label set - part of the durable
snapshot - of every issue that carried oldLabel, whether it gained
newLabel or already had it (merge), so each touched issue now mints one
version row, the same gate AddLabelInTx/RemoveLabelInTx draw on a row
that landed. RecordVersionInTx is already a no-op for wisps and when
versioned history is disabled, and a rename nobody carries touches no
id, so the no-op shape mints nothing.

TestRenameLabelMintsOneVersionPerTouchedBead is the runtime twin of the
static guard: plain rename +1, merge +1, untouched bead +0, a second
rename with no carriers +0, current_revision equal to the row count.

* build(bazel): list this PR's six new test files in their go_test srcs

Generated-artifact drift repair, produced by the repository's own command
(`make bazel-sync`) and inspected before committing, not hand-written.

The PR adds six `_test.go` files and none were listed in their package's
`go_test` srcs, so Bazel compiled each of those packages' test targets without
them - green by omission. That was invisible on the pre-merge head because its
CI predates the Bazel lanes entirely (zero `Bazel /` rows). This merge brings in
e1b2e79484 (#6941), which makes those lanes feed the required gate, so the
omission would now surface as a real red.

Purely additive: 6 insertions, 0 deletions, `go_test` srcs only. No `go_library`
srcs change is needed because every added file is a test, which is also why this
cannot break the build the way a missing production source would.

Verified: `make bazel-sync` is now a no-op against this tree (empty porcelain),
and `bazel build //cmd/bd/... //internal/storage/... //internal/types/...
//internal/telemetry/...` completes successfully - 3429 actions, 0 errors.

---------

Co-authored-by: Marco Del Pin <marco@omniaevo.it>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
This commit is contained in:
Marco Del Pin 2026-09-30 02:02:35 +02:00 • committed by GitHub
commit 63d8cc2522
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
30 changed files with 1803 additions and 2 deletions

View file

@ -411,6 +411,37 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
([#6023](https://github.com/gastownhall/beads/issues/6023)), so callers can
count the same metadata-scoped set `bd list` returns without fetching every
row.
- **`bd label rename <old> <new>` fixes a label everywhere it appears, in one
command instead of a per-issue add-then-remove loop**
([#6009](https://github.com/gastownhall/beads/pull/6009)). An issue that
already carries the new label doesn't error — the rename drops its stale
old label and counts the issue as a merge instead, reported honestly:
`Renamed label 'Backend' to 'backend': 6 issues (2 already had 'backend')`.
A label nothing carries is a clean no-op (`No issues found with label
'Backend'`, exit 0). The sweep covers both planes, durable issues and
wisps, and the direct and proxied-server routes end at the same
`issueops.RenameLabelInTx` primitive — the proxied route journals through
`domain.LabelUseCase.RenameLabel` rather than a per-issue add+remove
fan-out, so merge semantics, the zero-carrier no-op, and the single
`label_renamed` event per touched row are identical on both.
`--dry-run` previews the blast radius (a count and the first 10 issues,
all of them under `--json`) without writing anything, through a read-only
path kept apart from the write path so a preview can never reach a
transaction. Its `merged` count is a plain snapshot intersection of two
independent reads, though, not the write path's measured one: the real
rename derives `merged` from what its `INSERT IGNORE` actually affected,
specifically so a concurrent label add between two reads can't skew the
count, and the preview has no insert to measure against. Treat the
dry-run number as an estimate — the flag's own help text says so now too.
A rename that fails partway through reports an UPPER BOUND - up to how many
issues may have been renamed, and up to how many of those were merges -
rather than only the error. It cannot be a landed count: both routes assign
those numbers inside the transaction, so a rollback or an exhausted retry
returns them still describing an attempt that landed nothing. Only a Dolt
publication failure after the SQL side already committed is a genuine
partial, and the count alone cannot tell the two apart.
### Fixed

View file

@ -826,6 +826,9 @@ go_test(
"label_list_all_test.go",
"label_normalization_test.go",
"label_proxied_integration_test.go",
"label_rename_message_test.go",
"label_rename_publish_failure_test.go",
"label_rename_test.go",
"label_test.go",
"label_whitespace_warn_test.go",
"last_touched_guard_test.go",

View file

@ -493,7 +493,7 @@ var proxyPermittedPaths = []string{
"comments", "comments add", "comments list",
"dep", "dep add", "dep cycles", "dep list", "dep relate", "dep remove", "dep tree", "dep unrelate",
"kv clear", "kv get", "kv list", "kv set",
"label add", "label list", "label list-all", "label propagate", "label remove",
"label add", "label list", "label list-all", "label propagate", "label remove", "label rename",
// molecules, epics, todos, state
"epic close-eligible", "epic status",

View file

@ -554,6 +554,249 @@ var labelPropagateCmd = &cobra.Command{
},
}
// labelRenamePreviewLimit caps how many issues a `--dry-run` blast-radius
// preview names before collapsing the rest into a count.
const labelRenamePreviewLimit = 10
var labelRenameCmd = &cobra.Command{
Use: "rename <old-label> <new-label>",
Short: "Rename a label across every issue and wisp that carries it",
Long: "Rename a label everywhere it appears. An issue that already carries " +
"the new label keeps it and drops the old one instead of erroring - a " +
"merge, reported honestly (the write path measures merged from what " +
"the insert actually affected, never from a snapshot check, so its " +
"count is correct under concurrent writes). Pass --dry-run to preview " +
"the blast radius (a count and the first issues) without writing " +
"anything; the preview's merged count is a plain snapshot intersection " +
"of two separate reads, so treat it as an estimate, not the number the " +
"rename itself will report.",
Args: cobra.ExactArgs(2),
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
dryRun, _ := cmd.Flags().GetBool("dry-run")
if !dryRun {
CheckReadonly("label rename")
}
evt := metrics.NewCommandEvent("label-rename")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
return runLabelRename(rootCtx, args, dryRun)
},
}
// validateLabelRename trims and checks the two rename arguments, returning
// the trimmed labels or the refusal a caller should surface. It is a pure
// function so the refusal rules are testable without a store.
func validateLabelRename(rawOld, rawNew string) (oldLabel, newLabel string, err error) {
oldLabel = strings.TrimSpace(rawOld)
newLabel = strings.TrimSpace(rawNew)
if oldLabel == "" || newLabel == "" {
return "", "", fmt.Errorf("label cannot be empty")
}
if oldLabel == newLabel {
return "", "", fmt.Errorf("cannot rename label '%s' to itself", oldLabel)
}
// Same reserved-prefix refusal runLabelAdd and label propagate apply: a
// rename is effectively an add of newLabel, and touching oldLabel would
// let a caller strip a 'provides:' capability outside 'bd ship'.
for _, label := range [2]string{oldLabel, newLabel} {
if strings.HasPrefix(label, "provides:") {
return "", "", fmt.Errorf("'provides:' labels are reserved for cross-project capabilities. Hint: use 'bd ship' instead")
}
}
return oldLabel, newLabel, nil
}
func runLabelRename(ctx context.Context, args []string, dryRun bool) error {
oldLabel, newLabel, err := validateLabelRename(args[0], args[1])
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
warnLabelsContainingWhitespace([]string{oldLabel, newLabel})
if dryRun {
return runLabelRenameDryRun(ctx, oldLabel, newLabel)
}
var renamed, merged int
if usesProxiedServer() {
renamed, merged, err = runLabelRenameProxiedServer(ctx, oldLabel, newLabel)
} else {
renamed, merged, _, err = store.RenameLabel(ctx, oldLabel, newLabel, actor)
}
// Recorded from renamed>0 BEFORE the error check: a rename can commit its
// SQL side and still return a non-nil err (e.g. the Dolt publication step
// failing after the working-set write landed), and the caller's deferred
// commit needs to know a write happened either way.
if renamed > 0 {
commandDidWrite.Store(true)
}
if err != nil {
// The counts are assigned INSIDE the transaction closure on both
// routes (label_proxied_server.go RunTx, dolt/labels.go
// withRetryTx), so a Commit failure or retry exhaustion returns
// them still holding the rolled-back attempt's numbers - nothing
// landed. Only doltAddAndCommit failing after the SQL tx committed
// is a genuine partial, and renamed>0 cannot discriminate the two.
// Report an UPPER BOUND rather than assert a write that may not
// have happened; commandDidWrite above shares the premise but is
// fail-safe in the other direction, this message is not.
if renamed > 0 {
return HandleErrorRespectJSON("%s", labelRenamePartialFailureMessage(renamed, merged, err))
}
return HandleErrorRespectJSON("label rename: %v", err)
}
return reportLabelRename(oldLabel, newLabel, renamed, merged, jsonOutput)
}
// labelRenameCandidatesProxied is the read-only counterpart of
// runLabelRenameProxiedServer, used only by --dry-run: two label searches, no
// write. Kept separate from the write path so a dry-run can never reach a
// uow.RunTx call.
func labelRenameCandidatesProxied(ctx context.Context, oldLabel, newLabel string) (oldIssues, newIssues []*types.Issue, err error) {
uw, err := proxiedOpenReadUOW(ctx)
if err != nil {
return nil, nil, err
}
defer uw.Close(ctx)
oldPage, err := uw.IssueUseCase().SearchIssues(ctx, "", types.IssueFilter{Labels: []string{oldLabel}})
if err != nil {
return nil, nil, fmt.Errorf("searching issues with label %q: %w", oldLabel, err)
}
if len(oldPage.Items) == 0 {
return nil, nil, nil
}
newPage, err := uw.IssueUseCase().SearchIssues(ctx, "", types.IssueFilter{Labels: []string{newLabel}})
if err != nil {
return nil, nil, fmt.Errorf("searching issues with label %q: %w", newLabel, err)
}
return oldPage.Items, newPage.Items, nil
}
func runLabelRenameDryRun(ctx context.Context, oldLabel, newLabel string) error {
var (
oldIssues, newIssues []*types.Issue
err error
)
if usesProxiedServer() {
oldIssues, newIssues, err = labelRenameCandidatesProxied(ctx, oldLabel, newLabel)
} else {
oldIssues, err = store.GetIssuesByLabel(ctx, oldLabel)
if err == nil {
newIssues, err = store.GetIssuesByLabel(ctx, newLabel)
}
}
if err != nil {
return HandleErrorRespectJSON("label rename --dry-run: %v", err)
}
// A preview-only snapshot intersection of two independent reads, NOT the
// write path's measured count: renameLabelInPlane derives merged from
// what its INSERT IGNORE actually affected, specifically to avoid the
// schedule-dependent count a check-then-insert shape used to produce
// under a concurrent AddLabel/RemoveLabel between the two reads (see the
// comment on that function). This dry-run has no insert to measure
// against, so it falls back to exactly that check-then-count shape - an
// acceptable estimate for a preview, but callers must not treat it as
// authoritative. The flag help and command Long text say so too.
alreadyNew := make(map[string]struct{}, len(newIssues))
for _, issue := range newIssues {
alreadyNew[issue.ID] = struct{}{}
}
merged := 0
for _, issue := range oldIssues {
if _, ok := alreadyNew[issue.ID]; ok {
merged++
}
}
if jsonOutput {
preview := make([]map[string]interface{}, 0, len(oldIssues))
for _, issue := range oldIssues {
preview = append(preview, map[string]interface{}{
"issue_id": issue.ID,
"title": issue.Title,
})
}
return outputJSON(map[string]interface{}{
"dry_run": true,
"old_label": oldLabel,
"new_label": newLabel,
"count": len(oldIssues),
"merged": merged,
"issues": preview,
})
}
if len(oldIssues) == 0 {
fmt.Printf("No issues found with label '%s'\n", oldLabel)
return nil
}
fmt.Printf("Would rename label '%s' to '%s': %d issues", oldLabel, newLabel, len(oldIssues))
if merged > 0 {
fmt.Printf(" (%d already have '%s')", merged, newLabel)
}
fmt.Println()
limit := len(oldIssues)
if limit > labelRenamePreviewLimit {
limit = labelRenamePreviewLimit
}
for _, issue := range oldIssues[:limit] {
fmt.Printf(" %s %s\n", issue.ID, issue.Title)
}
if len(oldIssues) > limit {
fmt.Printf(" ... and %d more\n", len(oldIssues)-limit)
}
return nil
}
// labelRenamePartialFailureMessage phrases a failed rename as an UPPER BOUND.
// Both routes assign the counts inside the transaction closure, so on a Commit
// failure or retry exhaustion they still hold the rolled-back attempt's numbers
// and nothing landed; only doltAddAndCommit failing after the SQL transaction
// committed is a genuine partial, and renamed > 0 cannot tell the two apart.
// Every number in the sentence is therefore hedged - a definite count here would
// assert a write that may never have happened.
func labelRenamePartialFailureMessage(renamed, merged int, err error) string {
return fmt.Sprintf("label rename: up to %d issue(s) (of which up to %d merged) may have been renamed before failing: %v",
renamed, merged, err)
}
// reportLabelRename prints what a (non-dry-run) rename landed: an honest
// zero-issues no-op, or the count plus how many of those were merges.
func reportLabelRename(oldLabel, newLabel string, renamed, merged int, jsonOut bool) error {
if jsonOut {
return outputJSON(map[string]interface{}{
"status": "renamed",
"old_label": oldLabel,
"new_label": newLabel,
"renamed": renamed,
"merged": merged,
})
}
if renamed == 0 {
fmt.Printf("No issues found with label '%s'\n", oldLabel)
return nil
}
noun := "issue"
if renamed != 1 {
noun = "issues"
}
fmt.Printf("Renamed label '%s' to '%s': %d %s", oldLabel, newLabel, renamed, noun)
if merged > 0 {
fmt.Printf(" (%d already had '%s')", merged, newLabel)
}
fmt.Println()
return nil
}
func init() {
// Issue ID completions
labelAddCmd.ValidArgsFunction = issueIDCompletion
@ -561,11 +804,14 @@ func init() {
labelListCmd.ValidArgsFunction = issueIDCompletion
labelPropagateCmd.ValidArgsFunction = issueIDCompletion
labelRenameCmd.Flags().Bool("dry-run", false, "Preview the blast radius without renaming anything (merged count is a snapshot intersection, not authoritative - see --help)")
labelCmd.AddCommand(labelAddCmd)
labelCmd.AddCommand(labelRemoveCmd)
labelCmd.AddCommand(labelListCmd)
labelCmd.AddCommand(labelListAllCmd)
labelCmd.AddCommand(labelPropagateCmd)
labelCmd.AddCommand(labelRenameCmd)
rootCmd.AddCommand(labelCmd)
}

View file

@ -473,6 +473,71 @@ func TestEmbeddedLabel(t *testing.T) {
}
})
// ===== Label Rename =====
t.Run("label_rename_basic", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Rename basic", "--type", "task", "--label", "backend")
out := bdLabel(t, bd, dir, "rename", "backend", "server")
if !strings.Contains(out, "Renamed") {
t.Errorf("expected 'Renamed' in output: %s", out)
}
labels := bdLabelListJSON(t, bd, dir, issue.ID)
if len(labels) != 1 || labels[0] != "server" {
t.Errorf("expected labels [server], got %v", labels)
}
})
t.Run("label_rename_merge", func(t *testing.T) {
onlyOld := bdCreate(t, bd, dir, "Rename merge only-old", "--type", "task", "--label", "wip-r")
both := bdCreate(t, bd, dir, "Rename merge both", "--type", "task",
"--label", "wip-r", "--label", "in-progress-r")
out := bdLabel(t, bd, dir, "rename", "wip-r", "in-progress-r")
if !strings.Contains(out, "Renamed") {
t.Errorf("expected 'Renamed' in output: %s", out)
}
labels := bdLabelListJSON(t, bd, dir, onlyOld.ID)
if len(labels) != 1 || labels[0] != "in-progress-r" {
t.Errorf("only-old: expected [in-progress-r], got %v", labels)
}
labels = bdLabelListJSON(t, bd, dir, both.ID)
if len(labels) != 1 || labels[0] != "in-progress-r" {
t.Errorf("both: expected exactly [in-progress-r] (no duplicate), got %v", labels)
}
})
t.Run("label_rename_dry_run_writes_nothing", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Rename dry run", "--type", "task", "--label", "dry-old")
out := bdLabel(t, bd, dir, "rename", "dry-old", "dry-new", "--dry-run")
if !strings.Contains(out, "Would rename") {
t.Errorf("expected 'Would rename' in dry-run output: %s", out)
}
labels := bdLabelListJSON(t, bd, dir, issue.ID)
if len(labels) != 1 || labels[0] != "dry-old" {
t.Errorf("dry-run must not write: expected [dry-old] unchanged, got %v", labels)
}
})
t.Run("label_rename_zero_carrier_is_honest_noop", func(t *testing.T) {
out := bdLabel(t, bd, dir, "rename", "no-such-label-anywhere", "irrelevant")
if !strings.Contains(out, "No issues found") {
t.Errorf("expected 'No issues found' for a zero-carrier rename: %s", out)
}
})
t.Run("label_rename_identical_fails", func(t *testing.T) {
bdLabelFail(t, bd, dir, "rename", "same-label", "same-label")
})
t.Run("label_rename_empty_fails", func(t *testing.T) {
bdLabelFail(t, bd, dir, "rename", "", "new-name")
})
t.Run("label_rename_reserved_provides_fails", func(t *testing.T) {
bdLabelFail(t, bd, dir, "rename", "plain-label", "provides:auth")
})
// ===== Error Cases =====
t.Run("label_add_empty_label", func(t *testing.T) {

View file

@ -83,6 +83,59 @@ func TestProxiedServerLabel(t *testing.T) {
}
})
// rename is the end-to-end regression test for the finding that
// runLabelRenameProxiedServer used to fan a rename out into a per-issue
// AddLabel + RemoveLabel pair (journaling label_added/label_removed)
// instead of calling domain.LabelUseCase.RenameLabel, which emits one
// label_renamed event. internal/storage/domain/db's
// TestLabelUseCase/RenameLabel/EmitsOneRenamedEventPerIssue exercises the
// same use case directly against dolt; this closes the gap through the
// actual `bd label rename` CLI + proxied server wiring.
t.Run("rename", func(t *testing.T) {
t.Parallel()
p := newSharedProxiedProject(t, bd, "lr")
issue := bdProxiedCreate(t, bd, p.dir, "Rename target")
bdProxiedLabel(t, bd, p.dir, "add", issue.ID, "old-name")
out := bdProxiedLabel(t, bd, p.dir, "rename", "old-name", "new-name")
if !strings.Contains(out, "Renamed label 'old-name' to 'new-name': 1 issue") {
t.Errorf("expected the rename confirmation, got:\n%s", out)
}
if got := bdProxiedLabelListJSON(t, bd, p.dir, issue.ID); len(got) != 1 || got[0] != "new-name" {
t.Fatalf("labels after rename = %v, want [new-name]", got)
}
db := openProxiedDB(t, p)
var renamedCount int
if err := db.QueryRowContext(context.Background(),
"SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = 'label_renamed' AND old_value = 'old-name' AND new_value = 'new-name'",
issue.ID).Scan(&renamedCount); err != nil {
t.Fatalf("count label_renamed events: %v", err)
}
if renamedCount != 1 {
t.Errorf("label_renamed events = %d, want 1", renamedCount)
}
var addedCount, removedCount int
if err := db.QueryRowContext(context.Background(),
"SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = 'label_added'",
issue.ID).Scan(&addedCount); err != nil {
t.Fatalf("count label_added events: %v", err)
}
if err := db.QueryRowContext(context.Background(),
"SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = 'label_removed'",
issue.ID).Scan(&removedCount); err != nil {
t.Fatalf("count label_removed events: %v", err)
}
if addedCount != 1 {
t.Errorf("label_added events = %d, want 1 (only the initial `label add`, not a second one from a rename-as-add)", addedCount)
}
if removedCount != 0 {
t.Errorf("label_removed events = %d, want 0 (the rename must not journal label_removed)", removedCount)
}
})
t.Run("add_multiple_issues", func(t *testing.T) {
t.Parallel()
p := newSharedProxiedProject(t, bd, "lm")

View file

@ -132,6 +132,34 @@ func runLabelListAllProxiedServer(ctx context.Context) error {
return nil
}
// runLabelRenameProxiedServer is the proxied-server counterpart of
// DoltStore/EmbeddedDoltStore.RenameLabel. It calls the same
// domain.LabelUseCase.RenameLabel every proxied write reaches through
// uw.LabelUseCase(), which in turn delegates to issueops.RenameLabelInTx -
// the identical merge semantics, same-name refusal and one EventLabelRenamed
// per touched issue that the direct route produces. A prior version of this
// route fanned each issue out into a per-issue AddLabel-then-RemoveLabel
// pair, journaling label_added/label_removed instead of label_renamed; that
// divergence is what this delegation replaces.
func runLabelRenameProxiedServer(ctx context.Context, oldLabel, newLabel string) (renamed, merged int, err error) {
if uowProvider == nil {
return 0, 0, HandleError("proxied-server UOW provider not initialized")
}
err = uow.RunTx(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (string, error) {
var rerr error
renamed, merged, _, rerr = uw.LabelUseCase().RenameLabel(ctx, oldLabel, newLabel, actor) //nolint:forbidigo // bulk rename; no role serves it, and Patch.Labels would reintroduce the per-issue add/remove event divergence this delegation replaced
if rerr != nil {
return "", fmt.Errorf("rename label '%s' -> '%s': %w", oldLabel, newLabel, rerr)
}
if renamed == 0 {
return "", nil
}
return fmt.Sprintf("bd: label rename '%s' -> '%s' (%d issues)", oldLabel, newLabel, renamed), nil
})
return renamed, merged, err
}
func runLabelPropagateProxiedServer(ctx context.Context, args []string) error {
label := strings.TrimSpace(args[1])
if label == "" {

View file

@ -0,0 +1,39 @@
package main
import (
"errors"
"strings"
"testing"
)
// The partial-failure wording is a semantic claim, not cosmetics: the counts are
// assigned inside the transaction closure on both routes, so a Commit failure or
// retry exhaustion leaves them holding an attempt that never landed. Nothing else
// in the suite drives a failing rename with renamed > 0, so without this test the
// hunk can be reverted and every other test stays green.
func TestLabelRenamePartialFailureMessageIsAnUpperBound(t *testing.T) {
msg := labelRenamePartialFailureMessage(6, 2, errors.New("commit failed"))
for _, want := range []string{
"up to 6 issue(s)",
"of which up to 2 merged",
"may have been renamed before failing",
"commit failed",
} {
if !strings.Contains(msg, want) {
t.Errorf("message %q does not contain %q", msg, want)
}
}
// No clause may assert that a write landed. These are the phrasings the
// message carried before the correction, and the ones a future edit is
// most likely to reintroduce.
for _, forbidden := range []string{
"renamed 6 issue(s)",
"(2 merged)",
} {
if strings.Contains(msg, forbidden) {
t.Errorf("message %q asserts a landed count via %q; every number must stay hedged", msg, forbidden)
}
}
}

View file

@ -0,0 +1,120 @@
//go:build cgo
package main
import (
"context"
"errors"
"os"
"path/filepath"
"testing"
"github.com/steveyegge/beads/internal/storage/dolt"
"github.com/steveyegge/beads/internal/testutil"
)
// renameLabelPublishFailureStore wraps a real *dolt.DoltStore and makes
// RenameLabel report a publish failure (renamed>0, err!=nil) after the SQL
// side has genuinely committed - reproducing the "SQL committed, Dolt
// publication failed" shape runLabelRename's commandDidWrite ordering must
// survive: the working-set write landed (labels actually changed) but the
// call still returns an error.
type renameLabelPublishFailureStore struct {
*dolt.DoltStore
}
func (s *renameLabelPublishFailureStore) RenameLabel(ctx context.Context, oldLabel, newLabel, actor string) (renamed, merged int, ids []string, err error) {
renamed, merged, ids, err = s.DoltStore.RenameLabel(ctx, oldLabel, newLabel, actor)
if err == nil && renamed > 0 {
err = errors.New("simulated Dolt publication failure")
}
return renamed, merged, ids, err
}
// TestRunLabelRename_CommandDidWriteSetBeforeErrorReturn is the regression
// test for the finding: runLabelRename read renamed>0 into commandDidWrite
// only AFTER the `if err != nil` early return, so a rename whose SQL side
// committed but whose store call also returned an error (a Dolt publication
// failure after the working-set write landed) never marked the command as
// having written - the caller's deferred auto-commit would then skip
// creating a Dolt commit for a write that, on disk, actually happened.
func TestRunLabelRename_CommandDidWriteSetBeforeErrorReturn(t *testing.T) {
if testDoltServerPort == 0 {
t.Skip("Dolt test server not available")
}
if testutil.DoltContainerCrashed() {
t.Skipf("Dolt test server crashed: %v", testutil.DoltContainerCrashError())
}
ensureTestMode(t)
saved := saveAndRestoreGlobals(t)
_ = saved
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatal(err)
}
origWd, _ := os.Getwd()
if err := os.Chdir(tmpDir); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = os.Chdir(origWd) })
dbName := uniqueTestDBName(t)
testDBPath := filepath.Join(beadsDir, "dolt")
writeTestMetadata(t, testDBPath, dbName)
inner := newTestStore(t, testDBPath)
spy := &renameLabelPublishFailureStore{DoltStore: inner}
store = spy
storeMutex.Lock()
storeActive = true
storeMutex.Unlock()
t.Cleanup(func() {
store = nil
storeMutex.Lock()
storeActive = false
storeMutex.Unlock()
})
ctx := context.Background()
rootCtx = ctx
// Seed one issue carrying the label so RenameLabel actually touches
// something (renamed>0 is the precondition for the defect to bite).
if _, err := inner.DB().ExecContext(ctx, `INSERT INTO issues (id, title, description, design, acceptance_criteria, notes, status, priority, issue_type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
"rlw-1", "Rename publish-failure seed", "body", "", "", "", "open", 1, "task"); err != nil {
t.Fatalf("seed issue: %v", err)
}
if err := inner.AddLabel(ctx, "rlw-1", "old-label", "tester"); err != nil {
t.Fatalf("seed label: %v", err)
}
commandDidWrite.Store(false)
usesProxiedServerOverride := usesProxiedServer()
if usesProxiedServerOverride {
t.Fatal("test assumes the direct (non-proxied) store.RenameLabel path; proxiedServerMode leaked from another test")
}
err := runLabelRename(ctx, []string{"old-label", "new-label"}, false)
if err == nil {
t.Fatal("expected the simulated publish failure to surface as an error")
}
if !commandDidWrite.Load() {
t.Error("commandDidWrite must be set once RenameLabel reports renamed>0, even though it also " +
"returned an error (SQL committed, Dolt publication failed) - it was being read only after " +
"the early `if err != nil` return, so this write was silently invisible to the caller's " +
"deferred auto-commit")
}
// The rename's SQL side genuinely landed despite the reported error - the
// premise the whole test rests on.
labels, err := inner.GetLabels(ctx, "rlw-1")
if err != nil {
t.Fatalf("GetLabels: %v", err)
}
if len(labels) != 1 || labels[0] != "new-label" {
t.Fatalf("GetLabels = %v, want [new-label] (the rename's SQL side must have landed for this test to mean anything)", labels)
}
}

View file

@ -0,0 +1,85 @@
package main
import (
"strings"
"testing"
)
// TestValidateLabelRename pins the argument-refusal rules for `bd label
// rename` - the checks that must fire BEFORE any store is touched, so they
// need no dolt/docker fixture to test.
func TestValidateLabelRename(t *testing.T) {
tests := []struct {
name string
rawOld string
rawNew string
wantOld string
wantNew string
wantErr bool
errContains string
}{
{
name: "trims whitespace",
rawOld: " backend ",
rawNew: " server ",
wantOld: "backend",
wantNew: "server",
},
{
name: "empty old label refused",
rawOld: "",
rawNew: "server",
wantErr: true,
errContains: "empty",
},
{
name: "empty new label refused",
rawOld: "backend",
rawNew: " ",
wantErr: true,
errContains: "empty",
},
{
name: "identical labels refused",
rawOld: "backend",
rawNew: "backend",
wantErr: true,
errContains: "itself",
},
{
name: "reserved provides prefix on new label refused",
rawOld: "backend",
rawNew: "provides:auth",
wantErr: true,
errContains: "reserved",
},
{
name: "reserved provides prefix on old label refused",
rawOld: "provides:auth",
rawNew: "backend",
wantErr: true,
errContains: "reserved",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotOld, gotNew, err := validateLabelRename(tt.rawOld, tt.rawNew)
if tt.wantErr {
if err == nil {
t.Fatalf("expected an error, got none (old=%q new=%q)", gotOld, gotNew)
}
if tt.errContains != "" && !strings.Contains(strings.ToLower(err.Error()), tt.errContains) {
t.Errorf("error %q does not mention %q", err.Error(), tt.errContains)
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if gotOld != tt.wantOld || gotNew != tt.wantNew {
t.Errorf("got (%q, %q), want (%q, %q)", gotOld, gotNew, tt.wantOld, tt.wantNew)
}
})
}
}

View file

@ -361,6 +361,29 @@ Output:
]
```
### Renaming Labels
`bd label rename` fixes a label everywhere it appears, in one command, instead
of a per-issue add-then-remove loop:
```bash
# Fix a typo or a taxonomy drift across the whole database
bd label rename Backend backend
# Preview the blast radius first - no writes, just a count and the first issues
bd label rename Backend backend --dry-run
```
If an issue already carries the new label, the rename doesn't error - it
drops the stale old label and reports that issue as a merge:
```
Renamed label 'Backend' to 'backend': 6 issues (2 already had 'backend')
```
A label nothing carries renames to a clean no-op (`No issues found with label
'Backend'`, exit 0). Rename sweeps both planes: durable issues and wisps.
### Bulk Operations
Add labels in batch during creation:

View file

@ -802,6 +802,9 @@ func (s *configStore) GetLabels(_ context.Context, _ string) ([]string, error) {
func (s *configStore) GetIssuesByLabel(_ context.Context, _ string) ([]*types.Issue, error) {
return nil, nil
}
func (s *configStore) RenameLabel(_ context.Context, _, _, _ string) (int, int, []string, error) {
return 0, 0, nil, nil
}
func (s *configStore) GetReadyWork(_ context.Context, _ types.WorkFilter) ([]*types.Issue, error) {
return nil, nil
}

View file

@ -256,6 +256,7 @@ go_test(
"journal_scope_completeness_test.go",
"journal_test.go",
"keyset_search_test.go",
"label_rename_test.go",
"labels_test.go",
"lease_migration_test.go",
"lease_test.go",

View file

@ -0,0 +1,321 @@
package dolt
import (
"context"
"errors"
"testing"
"time"
"github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/internal/types"
)
// TestRenameLabel_Basic renames a label carried by two issues and confirms
// it lands on both: old gone, new present, no merge (neither issue already
// had newLabel).
func TestRenameLabel_Basic(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
a := &types.Issue{ID: "rename-basic-a", Title: "A", Status: types.StatusOpen, Priority: 1, IssueType: types.TypeTask}
b := &types.Issue{ID: "rename-basic-b", Title: "B", Status: types.StatusOpen, Priority: 1, IssueType: types.TypeTask}
for _, issue := range []*types.Issue{a, b} {
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatalf("create %s: %v", issue.ID, err)
}
}
if err := store.AddLabel(ctx, a.ID, "backend", "tester"); err != nil {
t.Fatalf("add label a: %v", err)
}
if err := store.AddLabel(ctx, b.ID, "backend", "tester"); err != nil {
t.Fatalf("add label b: %v", err)
}
renamed, merged, ids, err := store.RenameLabel(ctx, "backend", "server", "tester")
if err != nil {
t.Fatalf("RenameLabel: %v", err)
}
if renamed != 2 {
t.Errorf("renamed = %d, want 2", renamed)
}
if merged != 0 {
t.Errorf("merged = %d, want 0", merged)
}
if len(ids) != 2 {
t.Errorf("ids = %v, want 2 entries", ids)
}
for _, id := range []string{a.ID, b.ID} {
labels, err := store.GetLabels(ctx, id)
if err != nil {
t.Fatalf("GetLabels(%s): %v", id, err)
}
if len(labels) != 1 || labels[0] != "server" {
t.Errorf("GetLabels(%s) = %v, want [server]", id, labels)
}
}
events, err := store.GetEvents(ctx, a.ID, 100)
if err != nil {
t.Fatalf("GetEvents: %v", err)
}
found := false
for _, e := range events {
if e.EventType == types.EventLabelRenamed && e.OldValue != nil && *e.OldValue == "backend" &&
e.NewValue != nil && *e.NewValue == "server" {
found = true
}
}
if !found {
t.Errorf("expected a label_renamed event old=backend new=server on %s, events: %+v", a.ID, events)
}
}
// TestRenameLabel_Merge covers an issue that already carries newLabel: the
// rename must degrade to a merge (old row dropped, no duplicate-key error)
// and report that issue in merged.
func TestRenameLabel_Merge(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
onlyOld := &types.Issue{ID: "rename-merge-only-old", Title: "OnlyOld", Status: types.StatusOpen, Priority: 1, IssueType: types.TypeTask}
both := &types.Issue{ID: "rename-merge-both", Title: "Both", Status: types.StatusOpen, Priority: 1, IssueType: types.TypeTask}
for _, issue := range []*types.Issue{onlyOld, both} {
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatalf("create %s: %v", issue.ID, err)
}
}
if err := store.AddLabel(ctx, onlyOld.ID, "wip", "tester"); err != nil {
t.Fatalf("add label onlyOld: %v", err)
}
if err := store.AddLabel(ctx, both.ID, "wip", "tester"); err != nil {
t.Fatalf("add label both/wip: %v", err)
}
if err := store.AddLabel(ctx, both.ID, "in-progress", "tester"); err != nil {
t.Fatalf("add label both/in-progress: %v", err)
}
renamed, merged, _, err := store.RenameLabel(ctx, "wip", "in-progress", "tester")
if err != nil {
t.Fatalf("RenameLabel: %v", err)
}
if renamed != 2 {
t.Errorf("renamed = %d, want 2", renamed)
}
if merged != 1 {
t.Errorf("merged = %d, want 1", merged)
}
labels, err := store.GetLabels(ctx, both.ID)
if err != nil {
t.Fatalf("GetLabels(both): %v", err)
}
if len(labels) != 1 || labels[0] != "in-progress" {
t.Errorf("GetLabels(both) = %v, want exactly [in-progress] (no duplicate, no leftover wip)", labels)
}
labels, err = store.GetLabels(ctx, onlyOld.ID)
if err != nil {
t.Fatalf("GetLabels(onlyOld): %v", err)
}
if len(labels) != 1 || labels[0] != "in-progress" {
t.Errorf("GetLabels(onlyOld) = %v, want [in-progress]", labels)
}
}
// TestRenameLabel_WispSwept confirms the wisp_labels plane is swept too, not
// only the durable labels table.
func TestRenameLabel_WispSwept(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
wisp := &types.Issue{
ID: "rename-wisp-target", Title: "Wisp", Status: types.StatusOpen,
Priority: 1, IssueType: types.TypeTask, Ephemeral: true,
}
if err := store.CreateIssue(ctx, wisp, "tester"); err != nil {
t.Fatalf("create wisp: %v", err)
}
if err := store.AddLabel(ctx, wisp.ID, "temp-tag", "tester"); err != nil {
t.Fatalf("add label: %v", err)
}
renamed, merged, ids, err := store.RenameLabel(ctx, "temp-tag", "final-tag", "tester")
if err != nil {
t.Fatalf("RenameLabel: %v", err)
}
if renamed != 1 {
t.Errorf("renamed = %d, want 1", renamed)
}
if merged != 0 {
t.Errorf("merged = %d, want 0", merged)
}
if len(ids) != 1 || ids[0] != wisp.ID {
t.Errorf("ids = %v, want [%s]", ids, wisp.ID)
}
labels, err := store.GetLabels(ctx, wisp.ID)
if err != nil {
t.Fatalf("GetLabels(wisp): %v", err)
}
if len(labels) != 1 || labels[0] != "final-tag" {
t.Errorf("GetLabels(wisp) = %v, want [final-tag]", labels)
}
}
// TestRenameLabel_ZeroCarrierIsHonestNoOp confirms renaming a label nothing
// carries is a clean no-op: no error, both counts 0, nothing written.
func TestRenameLabel_ZeroCarrierIsHonestNoOp(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
renamed, merged, ids, err := store.RenameLabel(ctx, "never-used-label", "irrelevant", "tester")
if err != nil {
t.Fatalf("RenameLabel: %v", err)
}
if renamed != 0 || merged != 0 {
t.Errorf("renamed=%d merged=%d, want 0, 0", renamed, merged)
}
if len(ids) != 0 {
t.Errorf("ids = %v, want empty", ids)
}
}
// TestRenameLabel_OverLongNewLabelRefused confirms the same over-length
// refusal AddLabel applies (ErrFieldTooLong) is enforced before any write,
// consistent across every label-mutating entry point.
func TestRenameLabel_OverLongNewLabelRefused(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
issue := &types.Issue{ID: "rename-overlong", Title: "OverLong", Status: types.StatusOpen, Priority: 1, IssueType: types.TypeTask}
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatalf("create: %v", err)
}
if err := store.AddLabel(ctx, issue.ID, "short", "tester"); err != nil {
t.Fatalf("add label: %v", err)
}
tooLong := make([]byte, types.MaxFieldLen+1)
for i := range tooLong {
tooLong[i] = 'x'
}
_, _, _, err := store.RenameLabel(ctx, "short", string(tooLong), "tester")
if err == nil {
t.Fatal("expected ErrFieldTooLong, got nil")
}
labels, err := store.GetLabels(ctx, issue.ID)
if err != nil {
t.Fatalf("GetLabels: %v", err)
}
if len(labels) != 1 || labels[0] != "short" {
t.Errorf("GetLabels = %v, want unchanged [short] (refusal must write nothing)", labels)
}
}
// TestRenameLabel_SameNameRefused confirms that renaming a label to itself is
// refused with ErrRenameLabelSameName rather than treated as a no-op merge.
// Without the refusal, RenameLabelInTx's merge branch treats every carrier of
// oldLabel as already carrying newLabel (they are the same string): the
// INSERT IGNORE no-ops and the unconditional DELETE FROM ... WHERE label = ?
// then removes every row for that label, wiping it instead of leaving it
// alone. Covers both label planes (labels and wisp_labels) so a fix scoped to
// only one plane still fails this test.
func TestRenameLabel_SameNameRefused(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
issue := &types.Issue{ID: "rename-samename-issue", Title: "Issue", Status: types.StatusOpen, Priority: 1, IssueType: types.TypeTask}
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatalf("create issue: %v", err)
}
if err := store.AddLabel(ctx, issue.ID, "dup", "tester"); err != nil {
t.Fatalf("add label issue: %v", err)
}
wisp := &types.Issue{
ID: "rename-samename-wisp", Title: "Wisp", Status: types.StatusOpen,
Priority: 1, IssueType: types.TypeTask, Ephemeral: true,
}
if err := store.CreateIssue(ctx, wisp, "tester"); err != nil {
t.Fatalf("create wisp: %v", err)
}
if err := store.AddLabel(ctx, wisp.ID, "dup", "tester"); err != nil {
t.Fatalf("add label wisp: %v", err)
}
renamed, merged, ids, err := store.RenameLabel(ctx, "dup", "dup", "tester")
if !errors.Is(err, issueops.ErrRenameLabelSameName) {
t.Fatalf("RenameLabel(same name) err = %v, want ErrRenameLabelSameName", err)
}
if renamed != 0 || merged != 0 || ids != nil {
t.Errorf("RenameLabel(same name) = (%d, %d, %v), want (0, 0, nil)", renamed, merged, ids)
}
labels, err := store.GetLabels(ctx, issue.ID)
if err != nil {
t.Fatalf("GetLabels(issue): %v", err)
}
if len(labels) != 1 || labels[0] != "dup" {
t.Errorf("GetLabels(issue) = %v, want unchanged [dup] (self-rename must write nothing)", labels)
}
wispLabels, err := store.GetLabels(ctx, wisp.ID)
if err != nil {
t.Fatalf("GetLabels(wisp): %v", err)
}
if len(wispLabels) != 1 || wispLabels[0] != "dup" {
t.Errorf("GetLabels(wisp) = %v, want unchanged [dup] (self-rename must write nothing on the wisp plane either)", wispLabels)
}
}
// TestRenameLabel_SameNameAfterTrimRefused confirms the same-name refusal
// compares after trimming: incidental leading/trailing whitespace on one side
// must not mask what is otherwise the identical wipe-out shape.
func TestRenameLabel_SameNameAfterTrimRefused(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
issue := &types.Issue{ID: "rename-samename-trim", Title: "Issue", Status: types.StatusOpen, Priority: 1, IssueType: types.TypeTask}
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatalf("create issue: %v", err)
}
if err := store.AddLabel(ctx, issue.ID, "dup", "tester"); err != nil {
t.Fatalf("add label: %v", err)
}
_, _, _, err := store.RenameLabel(ctx, "dup", " dup ", "tester")
if !errors.Is(err, issueops.ErrRenameLabelSameName) {
t.Fatalf("RenameLabel(\"dup\", \" dup \") err = %v, want ErrRenameLabelSameName", err)
}
labels, err := store.GetLabels(ctx, issue.ID)
if err != nil {
t.Fatalf("GetLabels: %v", err)
}
if len(labels) != 1 || labels[0] != "dup" {
t.Errorf("GetLabels = %v, want unchanged [dup]", labels)
}
}

View file

@ -78,3 +78,27 @@ func (s *DoltStore) GetIssuesByLabel(ctx context.Context, label string) ([]*type
}
return s.GetIssuesByIDs(ctx, ids)
}
// RenameLabel renames a label across every issue and wisp that carries it,
// delegating the sweep to issueops.RenameLabelInTx and owning only the
// dolt-specific commit step. The commit targets the fixed "events"/"labels"
// pair, mirroring AddLabel/RemoveLabel; doltAddAndCommit's own
// HasStagedChanges guard skips it when a wisp-only rename left those tables
// untouched.
func (s *DoltStore) RenameLabel(ctx context.Context, oldLabel, newLabel, actor string) (renamed, merged int, ids []string, err error) {
err = s.withCircuitWrite(ctx, func(ctx context.Context) error {
if txErr := s.withRetryTx(ctx, func(tx *sql.Tx) error {
var innerErr error
renamed, merged, ids, innerErr = issueops.RenameLabelInTx(ctx, tx, oldLabel, newLabel, actor)
return innerErr
}); txErr != nil {
return txErr
}
if renamed == 0 {
return nil
}
return s.doltAddAndCommit(ctx, []string{"events", "labels"},
fmt.Sprintf("bd: label rename '%s' -> '%s' (%d issues)", oldLabel, newLabel, renamed))
})
return renamed, merged, ids, err
}

View file

@ -91,6 +91,18 @@ func (r *labelSQLRepositoryImpl) Insert(ctx context.Context, issueID, label, act
return issueops.RecordVersionInTx(ctx, r.runner, issueID, actor)
}
// RenameLabel sweeps both label planes (labels and wisp_labels) for oldLabel,
// reusing issueops.RenameLabelInTx rather than restating its SQL shape here:
// r.runner satisfies issueops.DBTX structurally, so this is the exact same
// merge logic, same-name refusal (issueops.ErrRenameLabelSameName) and
// EventLabelRenamed emission the direct DoltStore/EmbeddedDoltStore route
// uses. That identity, not merely a matching shape, is what keeps this route
// and the direct one from drifting the way runLabelRenameProxiedServer's
// hand-rolled add-then-remove fan-out used to.
func (r *labelSQLRepositoryImpl) RenameLabel(ctx context.Context, oldLabel, newLabel, actor string) (renamed, merged int, ids []string, err error) {
return issueops.RenameLabelInTx(ctx, r.runner, oldLabel, newLabel, actor)
}
func (r *labelSQLRepositoryImpl) Delete(ctx context.Context, issueID, label, actor string, opts domain.LabelOpts) error {
if issueID == "" {
return fmt.Errorf("db: LabelSQLRepository.Delete: issueID must not be empty")

View file

@ -1,10 +1,21 @@
package db
import (
"errors"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/internal/types"
)
func (s *testSuite) TestLabelUseCase() {
s.Run("RenameLabel", func() {
s.Run("EmptyOldLabelReturnsError", s.lucRenameLabelEmptyOld)
s.Run("EmptyNewLabelReturnsError", s.lucRenameLabelEmptyNew)
s.Run("SameNameRefused", s.lucRenameLabelSameName)
s.Run("EmitsOneRenamedEventPerIssue", s.lucRenameLabelEmitsRenamedEvent)
s.Run("MergesOnCollisionAcrossBothPlanes", s.lucRenameLabelMergesAcrossPlanes)
})
s.Run("RemoveLabel", func() {
s.Run("EmptyIDReturnsError", s.lucRemoveLabelEmptyID)
s.Run("EmptyLabelReturnsError", s.lucRemoveLabelEmptyLabel)
@ -210,3 +221,108 @@ func (s *testSuite) lucSetWispLabelsDiffs() {
s.Require().NoError(err)
s.Equal([]string{"add", "keep"}, wispLabels)
}
func (s *testSuite) lucRenameLabelEmptyOld() {
_, _, _, err := s.labelUseCase().RenameLabel(s.Ctx(), "", "new", "tester")
s.Require().Error(err)
}
func (s *testSuite) lucRenameLabelEmptyNew() {
_, _, _, err := s.labelUseCase().RenameLabel(s.Ctx(), "old", "", "tester")
s.Require().Error(err)
}
// lucRenameLabelSameName confirms the proxied-server route inherits the
// storage layer's ErrRenameLabelSameName refusal (both routes reach
// issueops.RenameLabelInTx) rather than wiping the label the way the merge
// branch would if a self-rename fell through unrefused.
func (s *testSuite) lucRenameLabelSameName() {
s.seedIssueRow("bd-luc-rn-same")
uc := s.labelUseCase()
s.Require().NoError(uc.AddLabel(s.Ctx(), "bd-luc-rn-same", "dup", "tester"))
_, _, _, err := uc.RenameLabel(s.Ctx(), "dup", "dup", "tester")
s.Require().Error(err)
s.Require().True(errors.Is(err, issueops.ErrRenameLabelSameName), "want ErrRenameLabelSameName, got %v", err)
labels, err := uc.GetLabels(s.Ctx(), "bd-luc-rn-same")
s.Require().NoError(err)
s.Equal([]string{"dup"}, labels, "self-rename must write nothing")
}
// lucRenameLabelEmitsRenamedEvent is the regression test for the divergence
// finding: runLabelRenameProxiedServer used to fan a rename out into a
// per-issue AddLabel + RemoveLabel pair, journaling label_added/label_removed
// instead of one label_renamed. Assert both halves of the fix: the renamed
// event exists with the right old/new values, and the two-event shape's rows
// do not appear beyond the one label_added the initial seed itself produced.
func (s *testSuite) lucRenameLabelEmitsRenamedEvent() {
s.seedIssueRow("bd-luc-rn-evt")
uc := s.labelUseCase()
s.Require().NoError(uc.AddLabel(s.Ctx(), "bd-luc-rn-evt", "old-name", "tester"))
renamed, merged, ids, err := uc.RenameLabel(s.Ctx(), "old-name", "new-name", "tester")
s.Require().NoError(err)
s.Equal(1, renamed)
s.Equal(0, merged)
s.Equal([]string{"bd-luc-rn-evt"}, ids)
labels, err := uc.GetLabels(s.Ctx(), "bd-luc-rn-evt")
s.Require().NoError(err)
s.Equal([]string{"new-name"}, labels)
var renamedCount int
s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(),
"SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ? AND old_value = ? AND new_value = ?",
"bd-luc-rn-evt", string(types.EventLabelRenamed), "old-name", "new-name",
).Scan(&renamedCount))
s.Equal(1, renamedCount, "expected exactly one label_renamed event")
var addedCount, removedCount int
s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(),
"SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ?",
"bd-luc-rn-evt", string(types.EventLabelAdded),
).Scan(&addedCount))
s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(),
"SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ?",
"bd-luc-rn-evt", string(types.EventLabelRemoved),
).Scan(&removedCount))
s.Equal(1, addedCount, "the only label_added row must be the initial seed's, not a second one from a rename-as-add")
s.Equal(0, removedCount, "rename must not journal label_removed (that was the pre-fix proxied shape)")
}
// lucRenameLabelMergesAcrossPlanes exercises the merge-on-collision path
// across BOTH label planes in one rename, matching the direct route's
// TestRenameLabel_Merge/TestRenameLabel_WispSwept coverage in
// internal/storage/dolt/label_rename_test.go.
func (s *testSuite) lucRenameLabelMergesAcrossPlanes() {
uc := s.labelUseCase()
s.seedIssueRow("bd-luc-rn-only-old")
s.Require().NoError(uc.AddLabel(s.Ctx(), "bd-luc-rn-only-old", "wip", "tester"))
s.seedIssueRow("bd-luc-rn-both")
s.Require().NoError(uc.AddLabel(s.Ctx(), "bd-luc-rn-both", "wip", "tester"))
s.Require().NoError(uc.AddLabel(s.Ctx(), "bd-luc-rn-both", "in-progress", "tester"))
s.seedWispRow("bd-luc-rn-wisp")
s.Require().NoError(uc.AddWispLabel(s.Ctx(), "bd-luc-rn-wisp", "wip", "tester"))
renamed, merged, ids, err := uc.RenameLabel(s.Ctx(), "wip", "in-progress", "tester")
s.Require().NoError(err)
s.Equal(3, renamed)
s.Equal(1, merged)
s.ElementsMatch([]string{"bd-luc-rn-only-old", "bd-luc-rn-both", "bd-luc-rn-wisp"}, ids)
labels, err := uc.GetLabels(s.Ctx(), "bd-luc-rn-only-old")
s.Require().NoError(err)
s.Equal([]string{"in-progress"}, labels)
labels, err = uc.GetLabels(s.Ctx(), "bd-luc-rn-both")
s.Require().NoError(err)
s.Equal([]string{"in-progress"}, labels, "no duplicate, no leftover wip")
wispLabels, err := uc.GetWispLabels(s.Ctx(), "bd-luc-rn-wisp")
s.Require().NoError(err)
s.Equal([]string{"in-progress"}, wispLabels)
}

View file

@ -16,6 +16,11 @@ type LabelSQLRepository interface {
ListByIssueIDs(ctx context.Context, issueIDs []string, opts LabelOpts) (map[string][]string, error)
DeleteAllForIDs(ctx context.Context, ids []string, opts LabelOpts) (int, error)
CountAllForIDs(ctx context.Context, ids []string, opts LabelOpts) (int, error)
// RenameLabel renames oldLabel to newLabel across every issue and wisp
// that carries it - both label planes, not the one LabelOpts would
// otherwise pick, since a rename by definition is not scoped to one id's
// plane. See domain.LabelUseCase.RenameLabel for the return contract.
RenameLabel(ctx context.Context, oldLabel, newLabel, actor string) (renamed, merged int, ids []string, err error)
}
type LabelUseCase interface {
@ -28,6 +33,19 @@ type LabelUseCase interface {
GetLabelsForIssues(ctx context.Context, issueIDs []string) (map[string][]string, error)
InheritFromParent(ctx context.Context, childID, parentID, actor string, skipExisting []string) ([]string, error)
// RenameLabel renames oldLabel to newLabel across every issue and wisp
// that carries it - the proxied-server counterpart of
// DoltStore/EmbeddedDoltStore.RenameLabel, carrying the same merge
// semantics (an issue that already carries newLabel keeps it and drops
// the stale oldLabel row instead of erroring) and emitting one
// EventLabelRenamed per touched issue, matching the direct route event
// for event, rather than an add+remove pair. renamed is the count of
// issues and wisps that carried oldLabel; merged is the subset that
// already had newLabel; ids lists every touched id, both planes
// together. oldLabel and newLabel equal after trimming is refused with
// issueops.ErrRenameLabelSameName.
RenameLabel(ctx context.Context, oldLabel, newLabel, actor string) (renamed, merged int, ids []string, err error)
AddWispLabel(ctx context.Context, wispID, label, actor string) error
RemoveWispLabel(ctx context.Context, wispID, label, actor string) error
AddWispLabels(ctx context.Context, wispID string, labels []string, actor string) error
@ -69,6 +87,24 @@ func (u *labelUseCaseImpl) add(ctx context.Context, id, label, actor string, use
return nil
}
// RenameLabel is not id-scoped like the verbs around it - a rename sweeps
// both label planes for every carrier of oldLabel, so it validates the two
// label arguments rather than an issue id and delegates straight to the
// repository, which owns the merge semantics and the same-name refusal.
func (u *labelUseCaseImpl) RenameLabel(ctx context.Context, oldLabel, newLabel, actor string) (renamed, merged int, ids []string, err error) {
if oldLabel == "" {
return 0, 0, nil, fmt.Errorf("rename label: oldLabel must not be empty")
}
if newLabel == "" {
return 0, 0, nil, fmt.Errorf("rename label: newLabel must not be empty")
}
renamed, merged, ids, err = u.labelRepo.RenameLabel(ctx, oldLabel, newLabel, actor)
if err != nil {
return 0, 0, nil, fmt.Errorf("rename label %s -> %s: %w", oldLabel, newLabel, err)
}
return renamed, merged, ids, nil
}
func (u *labelUseCaseImpl) RemoveLabel(ctx context.Context, issueID, label, actor string) error {
return u.remove(ctx, issueID, label, actor, false)
}

View file

@ -156,6 +156,7 @@ go_test(
"journal_retention_test.go",
"journal_truncation_test.go",
"label_list_all_benchmark_test.go",
"label_rename_test.go",
"lease_replica_test.go",
"lease_test.go",
"lenient_gate_warning_test.go",

View file

@ -0,0 +1,184 @@
//go:build cgo
package embeddeddolt_test
import (
"errors"
"testing"
"github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/internal/types"
)
// TestRenameLabel gives EmbeddedDoltStore.RenameLabel the same first-party
// coverage AddLabel/RemoveLabel already carry (bda-c77s sibling finding: the
// embedded impl had zero tests while DoltStore.RenameLabel has a dedicated
// suite). The deep merge/wisp/event semantics live in issueops and are pinned
// by internal/storage/dolt/label_rename_test.go against the same shared
// implementation; these cases pin the embedded WIRING - the store method
// reaches RenameLabelInTx and reports its counts through withConn.
func TestRenameLabel(t *testing.T) {
skipUnlessEmbeddedDolt(t)
t.Run("basic", func(t *testing.T) {
te := newTestEnv(t, "rl")
ctx := t.Context()
for _, id := range []string{"rl-a", "rl-b"} {
issue := &types.Issue{ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
if err := te.store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatalf("CreateIssue(%s): %v", id, err)
}
if err := te.store.AddLabel(ctx, id, "backend", "tester"); err != nil {
t.Fatalf("AddLabel(%s): %v", id, err)
}
}
renamed, merged, ids, err := te.store.RenameLabel(ctx, "backend", "server", "tester")
if err != nil {
t.Fatalf("RenameLabel: %v", err)
}
if renamed != 2 {
t.Errorf("renamed = %d, want 2", renamed)
}
if merged != 0 {
t.Errorf("merged = %d, want 0", merged)
}
if len(ids) != 2 {
t.Errorf("ids = %v, want 2 entries", ids)
}
for _, id := range []string{"rl-a", "rl-b"} {
labels, err := te.store.GetLabels(ctx, id)
if err != nil {
t.Fatalf("GetLabels(%s): %v", id, err)
}
if len(labels) != 1 || labels[0] != "server" {
t.Errorf("GetLabels(%s) = %v, want [server]", id, labels)
}
}
})
t.Run("merge", func(t *testing.T) {
te := newTestEnv(t, "rlm")
ctx := t.Context()
issue := &types.Issue{ID: "rlm-both", Title: "Both", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
if err := te.store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatalf("CreateIssue: %v", err)
}
for _, l := range []string{"wip", "in-progress"} {
if err := te.store.AddLabel(ctx, "rlm-both", l, "tester"); err != nil {
t.Fatalf("AddLabel(%s): %v", l, err)
}
}
renamed, merged, _, err := te.store.RenameLabel(ctx, "wip", "in-progress", "tester")
if err != nil {
t.Fatalf("RenameLabel: %v", err)
}
if renamed != 1 {
t.Errorf("renamed = %d, want 1", renamed)
}
if merged != 1 {
t.Errorf("merged = %d, want 1", merged)
}
labels, err := te.store.GetLabels(ctx, "rlm-both")
if err != nil {
t.Fatalf("GetLabels: %v", err)
}
if len(labels) != 1 || labels[0] != "in-progress" {
t.Errorf("GetLabels = %v, want exactly [in-progress]", labels)
}
})
t.Run("zero-carrier-no-op", func(t *testing.T) {
te := newTestEnv(t, "rlz")
ctx := t.Context()
renamed, merged, ids, err := te.store.RenameLabel(ctx, "nobody-has-this", "target", "tester")
if err != nil {
t.Fatalf("RenameLabel: %v", err)
}
if renamed != 0 || merged != 0 || len(ids) != 0 {
t.Errorf("renamed=%d merged=%d ids=%v, want all zero/empty", renamed, merged, ids)
}
})
t.Run("same-name-refused", func(t *testing.T) {
te := newTestEnv(t, "rls")
ctx := t.Context()
_, _, _, err := te.store.RenameLabel(ctx, "x", "x", "tester")
if !errors.Is(err, issueops.ErrRenameLabelSameName) {
t.Errorf("err = %v, want ErrRenameLabelSameName", err)
}
})
}
// TestRenameLabelMintsOneVersionPerTouchedBead pins the versioned-history law
// (#6135 FR-1/FR-2/FR-5) for a rename. Every bead whose label set the rename
// changed mints exactly one version row - a plain rename and a merge alike,
// since both drop oldLabel. A bead that never carried oldLabel mints none, a
// rename nobody carries mints none, and current_revision stays equal to the
// row count. issueops' TestEveryBeadMutatorMintsOrIsExempt only proves
// statically that RenameLabelInTx reaches RecordVersionInTx; this is its
// runtime twin, on the same probe TestEmbeddedEveryAcceptedLifecycleMutationMintsOneVersion uses.
func TestRenameLabelMintsOneVersionPerTouchedBead(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "rlver")
ctx := t.Context()
p := newVersionProbe(t, te, "rlver")
plain := p.kit.IssuePrefix + "-plain"
merge := p.kit.IssuePrefix + "-merge"
untouched := p.kit.IssuePrefix + "-untouched"
seed := map[string][]string{
plain: {"old"},
merge: {"old", "new"},
untouched: {"other"},
}
for _, id := range []string{plain, merge, untouched} {
if err := p.kit.CreateIssue(ctx, &types.Issue{
ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask,
}, "seed"); err != nil {
t.Fatalf("CreateIssue(%s): %v", id, err)
}
for _, label := range seed[id] {
if err := te.store.AddLabel(ctx, id, label, "seed"); err != nil {
t.Fatalf("AddLabel(%s, %s): %v", id, label, err)
}
}
}
np, nm, nu := p.rows(plain), p.rows(merge), p.rows(untouched)
renamed, merged, _, err := te.store.RenameLabel(ctx, "old", "new", "actor")
if err != nil {
t.Fatalf("RenameLabel: %v", err)
}
if renamed != 2 || merged != 1 {
t.Fatalf("RenameLabel counts = (renamed %d, merged %d), want (2, 1)", renamed, merged)
}
np = p.expect("rename (plain)", plain, np, 1)
nm = p.expect("rename (merge)", merge, nm, 1)
nu = p.expect("rename (untouched)", untouched, nu, 0)
for _, id := range []string{plain, merge} {
if labels := labelsOf(p.latestState(id)); len(labels) != 1 || labels[0] != "new" {
t.Fatalf("rename: latest durable_state labels for %s = %v, want [new]", id, labels)
}
}
// The no-op shape: nothing carries oldLabel any more.
renamed, _, _, err = te.store.RenameLabel(ctx, "old", "new", "actor")
if err != nil {
t.Fatalf("RenameLabel (no carriers): %v", err)
}
if renamed != 0 {
t.Fatalf("RenameLabel (no carriers): renamed = %d, want 0", renamed)
}
p.expect("no-op rename (plain)", plain, np, 0)
p.expect("no-op rename (merge)", merge, nm, 0)
p.expect("no-op rename (untouched)", untouched, nu, 0)
for _, id := range []string{plain, merge, untouched} {
p.revisionMatchesRows(id)
}
}

View file

@ -31,3 +31,15 @@ func (s *EmbeddedDoltStore) RemoveLabel(ctx context.Context, issueID, label, act
return issueops.RemoveLabelInTx(ctx, tx, "", "", issueID, label, actor)
})
}
// RenameLabel renames a label across every issue and wisp that carries it.
// The embedded store has no separate dolt-commit step (unlike DoltStore):
// withConn's own transaction commit is the durable boundary here.
func (s *EmbeddedDoltStore) RenameLabel(ctx context.Context, oldLabel, newLabel, actor string) (renamed, merged int, ids []string, err error) {
err = s.withConn(ctx, true, func(tx *sql.Tx) error {
var innerErr error
renamed, merged, ids, innerErr = issueops.RenameLabelInTx(ctx, tx, oldLabel, newLabel, actor)
return innerErr
})
return renamed, merged, ids, err
}

View file

@ -327,6 +327,19 @@ func (h *HookFiringStore) RemoveLabel(ctx context.Context, issueID, label, actor
return nil
}
// RenameLabel renames a label across every issue and wisp that carries it,
// firing on_update for each touched id.
func (h *HookFiringStore) RenameLabel(ctx context.Context, oldLabel, newLabel, actor string) (renamed, merged int, ids []string, err error) {
renamed, merged, ids, err = h.inner.RenameLabel(ctx, oldLabel, newLabel, actor)
if err != nil {
return renamed, merged, ids, err
}
for _, id := range ids {
h.fireHookByID(ctx, hooks.EventUpdate, id)
}
return renamed, merged, ids, nil
}
// ── Comment mutations ───────────────────────────────────────────────
// AddIssueComment adds a comment and fires on_update.

View file

@ -155,6 +155,7 @@ go_test(
"journal_prune_test.go",
"journal_truncation_test.go",
"journal_vocabulary_test.go",
"label_rename_merged_count_test.go",
"lease_replica_test.go",
"metadata_test.go",
"public_claim_test.go",

View file

@ -105,6 +105,7 @@ var mutationEntryPoints = []string{
"RemoveDependencyInTx",
"AddLabelInTx",
"RemoveLabelInTx",
"RenameLabelInTx",
"UpdateIssueIDInTx",
"AddIssueCommentInTx",
"ImportIssueCommentInTx",

View file

@ -0,0 +1,130 @@
package issueops
import (
"context"
"testing"
"github.com/DATA-DOG/go-sqlmock"
)
// These tests pin the bda-lbjv contract: the merge count a rename reports is
// MEASURED from what the INSERT IGNORE actually affected, never predicted
// from a snapshot read taken earlier in the transaction.
//
// The race they encode: an issue carries oldLabel; a concurrent
// AddLabel(issue, newLabel) COMMITS after this transaction's snapshot is
// established but before its INSERT IGNORE executes. Under REPEATABLE READ
// the insert sees the committed row and no-ops (correct - that IS the
// merge), but a merge count computed from the earlier snapshot read reports
// 0. The data was always fine; the count was schedule-dependent. sqlmock
// scripts exactly that observable: the SELECT-visible state says "no
// carrier of newLabel", the insert's rows-affected says one row already
// existed. A count derived from rows-affected reads 1; the old
// check-then-insert shape read 0 against this same script.
// expectRenameEventScript scripts the per-issue event mint that follows the
// label sweep (InsertDerivedEvent: same-content SELECT + INSERT). The
// journal half (RecordEventInTx) no-ops because neither the context key nor
// the per-tx registration enables it here.
func expectRenameEventScript(mock sqlmock.Sqlmock, times int) {
for i := 0; i < times; i++ {
mock.ExpectQuery(`SELECT id FROM events`).
WillReturnRows(sqlmock.NewRows([]string{"id"}))
mock.ExpectExec(`INSERT INTO events`).
WillReturnResult(sqlmock.NewResult(0, 1))
}
}
func TestRenameLabelInPlane_ConcurrentAddLabelStillCountsMerge(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("sqlmock.New: %v", err)
}
defer db.Close()
mock.ExpectBegin()
// Snapshot read: i1 carries oldLabel. (No read of newLabel's carriers
// exists any more - the fix removed it; nothing here scripts one, so a
// regression reintroducing the check-then-insert SELECT fails loudly on
// an unexpected query.)
mock.ExpectQuery(`SELECT issue_id FROM labels WHERE label = \?`).
WithArgs("old").
WillReturnRows(sqlmock.NewRows([]string{"issue_id"}).AddRow("i1"))
// The concurrently-committed (i1, new) row makes the INSERT IGNORE a
// no-op: zero rows affected.
mock.ExpectExec(`INSERT IGNORE INTO labels`).
WithArgs("i1", "new").
WillReturnResult(sqlmock.NewResult(0, 0))
// The delete is ID-SCOPED (label AND issue_id IN (...)): an unrestricted
// `WHERE label = ?` would let a current-read engine remove a row a
// concurrent AddLabel(oldLabel) committed to an issue OUTSIDE the
// snapshot - deleting a label the sweep never renamed, counted or
// journaled. sqlmock's WithArgs is the pin: a regression back to the
// unrestricted form fails on the argument mismatch.
mock.ExpectExec(`DELETE FROM labels WHERE label = \? AND issue_id IN`).
WithArgs("old", "i1").
WillReturnResult(sqlmock.NewResult(0, 1))
expectRenameEventScript(mock, 1)
ctx := context.Background()
tx, err := db.BeginTx(ctx, nil)
if err != nil {
t.Fatalf("BeginTx: %v", err)
}
renamed, merged, ids, err := renameLabelInPlane(ctx, tx, "labels", "events", "old", "new", "tester")
if err != nil {
t.Fatalf("renameLabelInPlane: %v", err)
}
if renamed != 1 {
t.Errorf("renamed = %d, want 1", renamed)
}
if merged != 1 {
t.Errorf("merged = %d, want 1 (the concurrently-committed row IS a merge; a snapshot-read count reports 0 here)", merged)
}
if len(ids) != 1 || ids[0] != "i1" {
t.Errorf("ids = %v, want [i1]", ids)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("unmet expectations: %v", err)
}
}
func TestRenameLabelInPlane_CleanRenameCountsZeroMerges(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("sqlmock.New: %v", err)
}
defer db.Close()
mock.ExpectBegin()
mock.ExpectQuery(`SELECT issue_id FROM labels WHERE label = \?`).
WithArgs("old").
WillReturnRows(sqlmock.NewRows([]string{"issue_id"}).AddRow("i1").AddRow("i2"))
// Both rows genuinely inserted: nothing carried newLabel.
mock.ExpectExec(`INSERT IGNORE INTO labels`).
WithArgs("i1", "new", "i2", "new").
WillReturnResult(sqlmock.NewResult(0, 2))
mock.ExpectExec(`DELETE FROM labels WHERE label = \? AND issue_id IN`).
WithArgs("old", "i1", "i2").
WillReturnResult(sqlmock.NewResult(0, 2))
expectRenameEventScript(mock, 2)
ctx := context.Background()
tx, err := db.BeginTx(ctx, nil)
if err != nil {
t.Fatalf("BeginTx: %v", err)
}
renamed, merged, _, err := renameLabelInPlane(ctx, tx, "labels", "events", "old", "new", "tester")
if err != nil {
t.Fatalf("renameLabelInPlane: %v", err)
}
if renamed != 2 {
t.Errorf("renamed = %d, want 2", renamed)
}
if merged != 0 {
t.Errorf("merged = %d, want 0", merged)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("unmet expectations: %v", err)
}
}

View file

@ -2,6 +2,7 @@ package issueops
import (
"context"
"errors"
"fmt"
"strings"
@ -238,3 +239,203 @@ func removeLabelInTx(ctx context.Context, tx DBTX, labelTable, eventTable, issue
}
return RecordVersionInTx(ctx, tx, issueID, actor)
}
// renameLabelPlanes pairs each label table with the event table journaling
// its issues, so RenameLabelInTx sweeps both without hardcoding the pairing
// twice.
var renameLabelPlanes = [2]struct {
labelTable string
eventTable string
}{
{labelTable: "labels", eventTable: "events"},
{labelTable: "wisp_labels", eventTable: "wisp_events"},
}
// ErrRenameLabelSameName is returned when RenameLabelInTx is asked to rename
// a label to itself. Refused before any write: the merge branch below treats
// every carrier of oldLabel as already carrying newLabel (they are the same
// string), so "insert the merge row, then drop the stale oldLabel row"
// degenerates into "insert a row that already exists via INSERT IGNORE, then
// delete every row carrying this label" -- the label is wiped, not renamed.
// Compared after trimming so incidental leading/trailing whitespace on one
// side does not mask the same no-op; the comparison itself stays
// case-sensitive, matching label identity everywhere else in this store.
var ErrRenameLabelSameName = errors.New("rename label: old and new label are the same")
// RenameLabelInTx renames a label across every issue and wisp that carries
// it. An issue that already carries newLabel is a merge: the stale oldLabel
// row is dropped rather than raising a duplicate-key error, and merged
// counts the subset of renamed where that happened. oldLabel carried by
// nothing is an honest no-op (renamed, merged both 0, err nil). ids lists
// every touched issue and wisp id, both planes concatenated. Each touched
// durable issue mints one version row (its label set changed); a no-op
// rename mints nothing. oldLabel and
// newLabel equal after trimming is refused with ErrRenameLabelSameName
// rather than treated as a no-op -- see that error's doc for why silently
// proceeding would wipe the label instead of leaving it alone.
func RenameLabelInTx(ctx context.Context, tx DBTX, oldLabel, newLabel, actor string) (renamed, merged int, ids []string, err error) {
if strings.TrimSpace(oldLabel) == strings.TrimSpace(newLabel) {
return 0, 0, nil, ErrRenameLabelSameName
}
if err := types.CheckFieldLen("label", newLabel); err != nil {
return 0, 0, nil, err
}
for _, plane := range renameLabelPlanes {
r, m, planeIDs, err := renameLabelInPlane(ctx, tx, plane.labelTable, plane.eventTable, oldLabel, newLabel, actor)
if err != nil {
return 0, 0, nil, fmt.Errorf("rename label in %s: %w", plane.labelTable, err)
}
renamed += r
merged += m
ids = append(ids, planeIDs...)
}
return renamed, merged, ids, nil
}
// renameLabelInPlane sweeps one label table (and its matching event table)
// for oldLabel and returns the touched-id and already-had-newLabel counts.
//
//nolint:gosec // G201: labelTable/eventTable are hardcoded routing constants from renameLabelPlanes ("labels"/"events" or "wisp_labels"/"wisp_events").
func renameLabelInPlane(ctx context.Context, tx DBTX, labelTable, eventTable, oldLabel, newLabel, actor string) (renamed, merged int, ids []string, err error) {
oldIDs, err := issueIDsWithLabelInTx(ctx, tx, labelTable, oldLabel)
if err != nil {
return 0, 0, nil, fmt.Errorf("query issues carrying %q: %w", oldLabel, err)
}
if len(oldIDs) == 0 {
return 0, 0, nil, nil
}
// INSERT IGNORE so an issue that already carries newLabel silently no-ops
// here instead of raising a duplicate-key error - this IS the merge.
//
// merged is MEASURED from what the insert actually affected, never
// predicted from a prior SELECT: INSERT IGNORE reports one affected row
// per id it really inserted, so an id whose (issue_id, newLabel) row
// already exists - including one committed by a concurrent AddLabel
// after this transaction's snapshot was taken - contributes zero, and
// len(oldIDs) - inserted is exactly the merge count. The previous
// check-then-insert shape computed merged from a snapshot read of
// newLabel's carriers taken before the insert, so a concurrent
// AddLabel(newLabel) made the reported count schedule-dependent while
// the stored data stayed correct.
inserted := 0
for start := 0; start < len(oldIDs); start += queryBatchSize {
end := start + queryBatchSize
if end > len(oldIDs) {
end = len(oldIDs)
}
batch := oldIDs[start:end]
placeholders := make([]string, len(batch))
args := make([]any, 0, len(batch)*2)
for i, id := range batch {
placeholders[i] = "(?, ?)"
args = append(args, id, newLabel)
}
res, err := tx.ExecContext(ctx, fmt.Sprintf(
`INSERT IGNORE INTO %s (issue_id, label) VALUES %s`,
labelTable, strings.Join(placeholders, ",")), args...)
if err != nil {
return 0, 0, nil, fmt.Errorf("insert renamed label: %w", err)
}
n, err := res.RowsAffected()
if err != nil {
return 0, 0, nil, fmt.Errorf("count inserted renamed-label rows: %w", err)
}
inserted += int(n)
}
merged = len(oldIDs) - inserted
// The delete is RESTRICTED to the ids this transaction actually renamed,
// never `WHERE label = ?` alone: an unrestricted delete's blast radius
// depends on the engine's DELETE visibility (a current-read engine could
// remove a row a concurrent AddLabel committed after our snapshot -
// destroying a label this loop never renamed, counted or journaled),
// while the id-scoped form touches exactly the rows the insert above
// accounted for on every engine. A concurrent add of oldLabel to an
// issue outside oldIDs therefore SURVIVES the rename, which is the same
// observable state as that add having happened after this transaction
// committed - the only order-independent reading of the race.
for start := 0; start < len(oldIDs); start += queryBatchSize {
end := start + queryBatchSize
if end > len(oldIDs) {
end = len(oldIDs)
}
batch := oldIDs[start:end]
placeholders := make([]string, len(batch))
args := make([]any, 0, len(batch)+1)
args = append(args, oldLabel)
for i, id := range batch {
placeholders[i] = "?"
args = append(args, id)
}
if _, err := tx.ExecContext(ctx, fmt.Sprintf(
`DELETE FROM %s WHERE label = ? AND issue_id IN (%s)`,
labelTable, strings.Join(placeholders, ",")), args...); err != nil {
return 0, 0, nil, fmt.Errorf("delete old label rows: %w", err)
}
}
comment := fmt.Sprintf("Renamed label: '%s' to '%s'", oldLabel, newLabel)
// KNOWN COST: this loop is O(len(oldIDs)) SQL round trips, not one batch -
// InsertDerivedEvent does its own dedup SELECT (a real cross-replica
// convergence check, Protocol v0.1 C2.3, not a redundant one this
// transaction could skip: two independently-created rows with identical
// content must land on the same content-derived id) plus an INSERT, and
// RecordEventInTx does its own snapshot SELECT plus an INSERT, and
// RecordVersionInTx re-reads the issue and its dependencies to mint the
// version row - several round trips per touched issue, inside one long
// transaction. On a
// huge label population that lengthens the transaction, which raises the
// odds an optimistic-concurrency retry has to redo the whole rename from
// scratch rather than just its own small write.
//
// Not batched: no batch primitive exists for this shape anywhere in this
// package (issueops), and building one here would be new shared
// infrastructure grown for a single caller rather than a mitigation
// scoped to this fix - AddLabelInTx/RemoveLabelInTx pay the identical
// per-call cost for their one issue today, and this loop is exactly that
// cost repeated once per touched issue. Left as a disclosed limitation.
for _, id := range oldIDs {
if err := InsertDerivedEvent(ctx, tx, eventTable, AuxEvent{
IssueID: id,
EventType: types.EventLabelRenamed,
Actor: actor,
OldValue: str(oldLabel),
NewValue: str(newLabel),
Comment: str(comment),
}); err != nil {
return 0, 0, nil, fmt.Errorf("rename label: record event for %s: %w", id, err)
}
if err := RecordEventInTx(ctx, tx, EventUpdate, id, actor); err != nil {
return 0, 0, nil, fmt.Errorf("rename label: journal %s: %w", id, err)
}
// Every id here lost its oldLabel row (and gained newLabel unless it
// already carried it), so its label set - part of the durable
// snapshot - changed: mint one version per touched bead, the same
// gate AddLabelInTx/RemoveLabelInTx draw on a row that landed.
// RecordVersionInTx is itself a no-op for wisps and when versioned
// history is disabled, so the wisp plane needs no special case.
if err := RecordVersionInTx(ctx, tx, id, actor); err != nil {
return 0, 0, nil, fmt.Errorf("rename label: version %s: %w", id, err)
}
}
return len(oldIDs), merged, oldIDs, nil
}
// issueIDsWithLabelInTx returns every issue/wisp id carrying label in the
// given label table (unordered).
//
//nolint:gosec // G201: labelTable is a hardcoded routing constant ("labels" or "wisp_labels").
func issueIDsWithLabelInTx(ctx context.Context, tx DBTX, labelTable, label string) ([]string, error) {
rows, err := tx.QueryContext(ctx, fmt.Sprintf(`SELECT issue_id FROM %s WHERE label = ?`, labelTable), label)
if err != nil {
return nil, err
}
defer rows.Close()
var ids []string
for rows.Next() {
var id string
if err := rows.Scan(&id); err != nil {
return nil, fmt.Errorf("scan issue id: %w", err)
}
ids = append(ids, id)
}
return ids, rows.Err()
}

View file

@ -407,6 +407,19 @@ type Storage interface {
RemoveLabel(ctx context.Context, issueID, label, actor string) error
GetLabels(ctx context.Context, issueID string) ([]string, error)
GetIssuesByLabel(ctx context.Context, label string) ([]*types.Issue, error)
// RenameLabel renames a label across every issue and wisp that carries
// it. An issue that already carries newLabel is a merge (the stale
// oldLabel row is dropped, no error) rather than a duplicate-key
// conflict. renamed is the count of issues and wisps that carried
// oldLabel; merged is the subset that already had newLabel; ids lists
// every touched id, both planes together. oldLabel carried by nothing is
// an honest no-op: renamed and merged are 0, ids is nil, err is nil.
// oldLabel and newLabel equal after trimming is refused with
// issueops.ErrRenameLabelSameName instead of treated as a no-op - the
// merge branch above would otherwise wipe the label instead of leaving
// it alone (every carrier already "has newLabel", so the stale-row drop
// removes every row).
RenameLabel(ctx context.Context, oldLabel, newLabel, actor string) (renamed, merged int, ids []string, err error)
// Work queries
GetReadyWork(ctx context.Context, filter types.WorkFilter) ([]*types.Issue, error)

View file

@ -1289,6 +1289,23 @@ func (u *recordingLabelUC) RemoveLabel(ctx context.Context, issueID, label, acto
return nil
}
// RenameLabel records one update per touched issue/wisp, mirroring
// HookFiringStore.RenameLabel on the DoltStorage plumbing (both fire on_update
// per id). THE SNAPSHOT IS anyPlane, because RenameLabel sweeps both the
// labels and wisp_labels tables together and the returned ids do not say
// which plane each one belongs to - the same reason CompareAndSetMetadataKey
// and ReleaseIssue above use it.
func (u *recordingLabelUC) RenameLabel(ctx context.Context, oldLabel, newLabel, actor string) (renamed, merged int, ids []string, err error) {
renamed, merged, ids, err = u.LabelUseCase.RenameLabel(ctx, oldLabel, newLabel, actor)
if err != nil {
return renamed, merged, ids, err
}
for _, id := range ids {
u.rec.record(opUpdate, u.snap.anyPlane(ctx, id))
}
return renamed, merged, ids, nil
}
func (u *recordingLabelUC) AddLabels(ctx context.Context, issueID string, labels []string, actor string) error {
if err := u.LabelUseCase.AddLabels(ctx, issueID, labels, actor); err != nil {
return err

View file

@ -390,6 +390,23 @@ func (s *InstrumentedStorage) RemoveLabel(ctx context.Context, issueID, label, a
return err
}
func (s *InstrumentedStorage) RenameLabel(ctx context.Context, oldLabel, newLabel, actor string) (renamed, merged int, ids []string, err error) {
attrs := []attribute.KeyValue{
attribute.String("bd.label.old", oldLabel),
attribute.String("bd.label.new", newLabel),
}
ctx, span, t := s.op(ctx, "RenameLabel", attrs...)
renamed, merged, ids, err = s.inner.RenameLabel(ctx, oldLabel, newLabel, actor)
if err == nil {
span.SetAttributes(
attribute.Int("bd.result.count", renamed),
attribute.Int("bd.merged.count", merged),
)
}
s.done(ctx, span, t, err, attrs...)
return renamed, merged, ids, err
}
func (s *InstrumentedStorage) GetLabels(ctx context.Context, issueID string) ([]string, error) {
attrs := []attribute.KeyValue{attribute.String("bd.issue.id", issueID)}
ctx, span, t := s.op(ctx, "GetLabels", attrs...)

View file

@ -1682,7 +1682,12 @@ const (
EventDependencyRemoved EventType = "dependency_removed"
EventLabelAdded EventType = "label_added"
EventLabelRemoved EventType = "label_removed"
EventCompacted EventType = "compacted"
// EventLabelRenamed records a bulk `bd label rename` sweep landing on one
// issue or wisp. old_value/new_value hold the old and new label strings.
// Unlike EventLabelAdded/EventLabelRemoved, one rename produces exactly
// one of these per touched row, never a paired add+remove.
EventLabelRenamed EventType = "label_renamed"
EventCompacted EventType = "compacted"
// EventLeaseReclaimed records that a stale lease was reverted to ready by
// bd reclaim (dead-worker recovery). old_value is the previous owner.
EventLeaseReclaimed EventType = "lease_reclaimed"