diff --git a/CHANGELOG.md b/CHANGELOG.md index 9bc373c69..547ac33ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 ` 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 diff --git a/cmd/bd/BUILD.bazel b/cmd/bd/BUILD.bazel index 96143f6ac..c75f22f04 100644 --- a/cmd/bd/BUILD.bazel +++ b/cmd/bd/BUILD.bazel @@ -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", diff --git a/cmd/bd/capability_registry.go b/cmd/bd/capability_registry.go index 15ac9acdf..de387c97e 100644 --- a/cmd/bd/capability_registry.go +++ b/cmd/bd/capability_registry.go @@ -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", diff --git a/cmd/bd/label.go b/cmd/bd/label.go index 86af49bc9..a1a2a8aec 100644 --- a/cmd/bd/label.go +++ b/cmd/bd/label.go @@ -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 ", + 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) } diff --git a/cmd/bd/label_embedded_test.go b/cmd/bd/label_embedded_test.go index 8f91d5acf..9a19657b3 100644 --- a/cmd/bd/label_embedded_test.go +++ b/cmd/bd/label_embedded_test.go @@ -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) { diff --git a/cmd/bd/label_proxied_integration_test.go b/cmd/bd/label_proxied_integration_test.go index b85bdf156..4e694495e 100644 --- a/cmd/bd/label_proxied_integration_test.go +++ b/cmd/bd/label_proxied_integration_test.go @@ -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") diff --git a/cmd/bd/label_proxied_server.go b/cmd/bd/label_proxied_server.go index bd5efb2f5..9d5b955a1 100644 --- a/cmd/bd/label_proxied_server.go +++ b/cmd/bd/label_proxied_server.go @@ -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 == "" { diff --git a/cmd/bd/label_rename_message_test.go b/cmd/bd/label_rename_message_test.go new file mode 100644 index 000000000..1f9183efa --- /dev/null +++ b/cmd/bd/label_rename_message_test.go @@ -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) + } + } +} diff --git a/cmd/bd/label_rename_publish_failure_test.go b/cmd/bd/label_rename_publish_failure_test.go new file mode 100644 index 000000000..21c6efaaf --- /dev/null +++ b/cmd/bd/label_rename_publish_failure_test.go @@ -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) + } +} diff --git a/cmd/bd/label_rename_test.go b/cmd/bd/label_rename_test.go new file mode 100644 index 000000000..5bb831008 --- /dev/null +++ b/cmd/bd/label_rename_test.go @@ -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) + } + }) + } +} diff --git a/docs/core-concepts/labels.md b/docs/core-concepts/labels.md index 3cd41f63a..1324801e7 100644 --- a/docs/core-concepts/labels.md +++ b/docs/core-concepts/labels.md @@ -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: diff --git a/internal/jira/tracker_test.go b/internal/jira/tracker_test.go index 5e10ffd63..47aa5a99c 100644 --- a/internal/jira/tracker_test.go +++ b/internal/jira/tracker_test.go @@ -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 } diff --git a/internal/storage/dolt/BUILD.bazel b/internal/storage/dolt/BUILD.bazel index 62b252c87..dffce7e49 100644 --- a/internal/storage/dolt/BUILD.bazel +++ b/internal/storage/dolt/BUILD.bazel @@ -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", diff --git a/internal/storage/dolt/label_rename_test.go b/internal/storage/dolt/label_rename_test.go new file mode 100644 index 000000000..7346f5984 --- /dev/null +++ b/internal/storage/dolt/label_rename_test.go @@ -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) + } +} diff --git a/internal/storage/dolt/labels.go b/internal/storage/dolt/labels.go index b12db1cce..16106e454 100644 --- a/internal/storage/dolt/labels.go +++ b/internal/storage/dolt/labels.go @@ -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 +} diff --git a/internal/storage/domain/db/label.go b/internal/storage/domain/db/label.go index cbe76ed26..4c8d91b4b 100644 --- a/internal/storage/domain/db/label.go +++ b/internal/storage/domain/db/label.go @@ -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") diff --git a/internal/storage/domain/db/label_usecase_test.go b/internal/storage/domain/db/label_usecase_test.go index d4b858cfb..7dff0ef84 100644 --- a/internal/storage/domain/db/label_usecase_test.go +++ b/internal/storage/domain/db/label_usecase_test.go @@ -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) +} diff --git a/internal/storage/domain/label.go b/internal/storage/domain/label.go index 16afe4f41..16421b2f3 100644 --- a/internal/storage/domain/label.go +++ b/internal/storage/domain/label.go @@ -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) } diff --git a/internal/storage/embeddeddolt/BUILD.bazel b/internal/storage/embeddeddolt/BUILD.bazel index 90086664c..1562cf0c7 100644 --- a/internal/storage/embeddeddolt/BUILD.bazel +++ b/internal/storage/embeddeddolt/BUILD.bazel @@ -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", diff --git a/internal/storage/embeddeddolt/label_rename_test.go b/internal/storage/embeddeddolt/label_rename_test.go new file mode 100644 index 000000000..dce2a6142 --- /dev/null +++ b/internal/storage/embeddeddolt/label_rename_test.go @@ -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) + } +} diff --git a/internal/storage/embeddeddolt/labels.go b/internal/storage/embeddeddolt/labels.go index 8e4c88167..8f3cd9179 100644 --- a/internal/storage/embeddeddolt/labels.go +++ b/internal/storage/embeddeddolt/labels.go @@ -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 +} diff --git a/internal/storage/hook_decorator.go b/internal/storage/hook_decorator.go index 3062f20a9..c0342252e 100644 --- a/internal/storage/hook_decorator.go +++ b/internal/storage/hook_decorator.go @@ -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. diff --git a/internal/storage/issueops/BUILD.bazel b/internal/storage/issueops/BUILD.bazel index eddfe312a..bebf4e08d 100644 --- a/internal/storage/issueops/BUILD.bazel +++ b/internal/storage/issueops/BUILD.bazel @@ -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", diff --git a/internal/storage/issueops/journal_completeness_test.go b/internal/storage/issueops/journal_completeness_test.go index 8f33f4106..7d2519968 100644 --- a/internal/storage/issueops/journal_completeness_test.go +++ b/internal/storage/issueops/journal_completeness_test.go @@ -105,6 +105,7 @@ var mutationEntryPoints = []string{ "RemoveDependencyInTx", "AddLabelInTx", "RemoveLabelInTx", + "RenameLabelInTx", "UpdateIssueIDInTx", "AddIssueCommentInTx", "ImportIssueCommentInTx", diff --git a/internal/storage/issueops/label_rename_merged_count_test.go b/internal/storage/issueops/label_rename_merged_count_test.go new file mode 100644 index 000000000..b2062ccb4 --- /dev/null +++ b/internal/storage/issueops/label_rename_merged_count_test.go @@ -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) + } +} diff --git a/internal/storage/issueops/labels.go b/internal/storage/issueops/labels.go index 4859d08a6..d69b2cc61 100644 --- a/internal/storage/issueops/labels.go +++ b/internal/storage/issueops/labels.go @@ -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() +} diff --git a/internal/storage/storage.go b/internal/storage/storage.go index b6463055d..dc66d2cac 100644 --- a/internal/storage/storage.go +++ b/internal/storage/storage.go @@ -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) diff --git a/internal/storage/uow/notifying.go b/internal/storage/uow/notifying.go index 0a0584e24..d61b68529 100644 --- a/internal/storage/uow/notifying.go +++ b/internal/storage/uow/notifying.go @@ -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 diff --git a/internal/telemetry/storage.go b/internal/telemetry/storage.go index 477bf551e..bd11798e6 100644 --- a/internal/telemetry/storage.go +++ b/internal/telemetry/storage.go @@ -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...) diff --git a/internal/types/types.go b/internal/types/types.go index 37dbf345b..725d8a01d 100644 --- a/internal/types/types.go +++ b/internal/types/types.go @@ -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"