fix(labels): guard exclusive namespaces on proxied and rename paths (bd-7u5ki)

Review-loop fixup for #4757 (exclusive label namespaces).

- proxied route: LabelSQLRepository.Insert runs the shared
  issueops.CheckExclusiveLabelInTx guard; ApplyUpdate removes before it
  adds, so a swap inside one namespace passes; proxied create settles
  inherited labels the way the direct front door does (explicit beats
  inherited)
- bd label rename refuses a rename that would create a new violation;
  a same-namespace rename or a merge into a held label still passes
- the empty-database auto-import (ImportJSONLData) and the molecules
  loader replay in warn mode, so one historical violation no longer
  fails hydration
- bd create, bd q, and the create form share resolveInheritedLabels:
  a config read error is surfaced, and an inherited-only conflict names
  the parent and --no-inherit-labels (labelns.ResolveCreateLabels)
- re-adding a label the issue already carries is a no-op, not a refusal
- proxied import reports exclusive_label_conflicts; bd label add
  --replace reports the labels it evicted, in text and as --json rows
  with status "removed", and its flag help says so
- the guard comment and configuration.md name the doctor scan as the
  backstop for concurrent writes and Dolt merges; config help and docs
  list rename and the boundary rules; json-schema.md documents
  exclusive_label_conflicts
- tests: domain/db TestExclusiveLabelNamespaces, embeddeddolt
  auto-import and create/rename tests, a uow ImportBatch subtest, and
  proxied and embedded CLI subtests; the pure eviction test moves to an
  untagged file so non-cgo lanes run it
- bazel: make bazel-sync registers the new internal/labelns package in
  the go_srcs-managed repo_files filegroups and the tools/bazel
  go_library list
- ci: the 15-shard embedded-storage manifest lists the two new
  embeddeddolt tests (gen_embedded_storage_shard_manifest.py --write)
- the large-batch statement-count pins move +1 per create item, the
  labels.exclusive-prefixes read NewBatchContext now makes (embedded and
  server: 356 +102, 712 +204, classic +10)

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Eddie the Engineer 2026-10-07 00:47:18 +00:00
commit e52d7ecbff
37 changed files with 910 additions and 165 deletions

View file

@ -152,6 +152,7 @@
15 1 TestEmbeddedRelationsAnswersAWispTargetInTheOutDirection
15 1 TestEmbeddedRelationsLeavesAnExternalTargetOutOfTheAnswer
15 1 TestEmbeddedRoleFixtureKitHooksAreUsable
15 1 TestImportJSONLData_KeepsExclusiveLabelViolations
15 1 TestLifecycleCreateContract
15 1 TestMergeWithStrategy_OursKeepsLocal
@ -537,6 +538,7 @@
15 15 TestEmbeddedTransactionStandaloneWispLifecyclePersistsWithoutDoltCommit
15 15 TestEventsJournalPruneNeverSplitsASkewedPair
15 15 TestEventsJournal_ActorMatrixOnEmbedded
15 15 TestExclusiveLabels_CreateAndRename
15 15 TestGetIssueCommentsPageEmbedded
15 15 TestGetReadyWorkIncludeEphemeralExcludesNonReadyWisps
15 15 TestIgnoredCursorHealIsIdempotent

View file

@ -297,6 +297,7 @@ filegroup(
"//internal/httpclient/wire:repo_files",
"//internal/idgen:repo_files",
"//internal/jira:repo_files",
"//internal/labelns:repo_files",
"//internal/linear:repo_files",
"//internal/lockfile:repo_files",
"//internal/memoryapi:repo_files",

View file

@ -878,6 +878,7 @@ go_test(
"kv_test.go",
"label_embedded_test.go",
"label_exclusive_test.go",
"label_exclusive_unit_test.go",
"label_list_all_test.go",
"label_normalization_test.go",
"label_prefix_test.go",

View file

@ -99,9 +99,10 @@ Exclusive Label Namespaces:
bd config set labels.exclusive-prefixes "tier:,review:"
Adding a second label in an exclusive namespace is then rejected on every
write path ('bd label add --replace' swaps instead). Import warns and keeps
violating labels; 'bd doctor' reports existing violations. Unset the key to
restore fully free-form labels (the default).
write path, 'bd label rename' included ('bd label add --replace' swaps
instead). Import warns and keeps violating labels; 'bd doctor' reports
existing violations, including any that concurrent writes or a Dolt merge
let through. Unset the key to restore fully free-form labels (the default).
Suppressing Doctor Warnings:
Suppress specific bd doctor warnings by check name slug:

View file

@ -459,18 +459,13 @@ var createCmd = &cobra.Command{
}
}
var exclusivePrefixes []string
if store != nil {
raw, _ := store.GetConfig(rootCtx, labelns.ConfigKey)
exclusivePrefixes = labelns.ParsePrefixes(raw)
// The parent was read from the store the create writes to, so its
// exclusive namespaces are the ones that apply.
inheritedLabels, err = resolveInheritedLabels(rootCtx, parentLookupStore, labels, inheritedLabels, parentID)
if err != nil {
return HandleError("%v", err)
}
inheritedLabels = dropConflictingInheritedLabels(labels, inheritedLabels, exclusivePrefixes)
labels = mergeCreateLabels(labels, inheritedLabels)
if conflicts := labelns.Conflicts(exclusivePrefixes, labels); len(conflicts) > 0 {
c := conflicts[0]
return HandleError("namespace %q is exclusive (%s) and allows at most one label, got %s",
c.Prefix, labelns.ConfigKey, strings.Join(c.Labels, ", "))
}
if dryRun {
return renderDryRun()
@ -826,30 +821,24 @@ func buildCreateIssue(params createIssueParams) *types.Issue {
}
}
// dropConflictingInheritedLabels resolves exclusive-namespace collisions
// between explicit -l labels and labels inherited from --parent: the explicit
// label wins and the inherited one is dropped, so a child can override e.g. a
// tier: routing label without needing --no-inherit-labels (bd-7u5ki).
// Collisions among the explicit labels themselves are left for the caller to
// reject.
func dropConflictingInheritedLabels(explicit, inherited, exclusivePrefixes []string) []string {
if len(exclusivePrefixes) == 0 || len(inherited) == 0 {
return inherited
// resolveInheritedLabels settles the labels a create inherits from parentID
// against the target store's exclusive label namespaces (bd-7u5ki): an
// explicit label wins over an inherited one in its namespace, and a collision
// among the explicit or among the inherited labels is refused with an error
// saying which (see labelns.ResolveCreateLabels). bd create, bd q, and the
// create form share it so every direct front door settles a child's labels
// the same way the proxied server does. A config read error is returned, not
// read as "no namespaces": that would skip the drop and leave the store's own
// guard to refuse the create, naming labels nobody typed.
func resolveInheritedLabels(ctx context.Context, s storage.DoltStorage, explicit, inherited []string, parentID string) ([]string, error) {
if s == nil || len(explicit)+len(inherited) < 2 {
return inherited, nil
}
taken := make(map[string]bool)
for _, label := range explicit {
if prefix := labelns.Match(exclusivePrefixes, label); prefix != "" {
taken[prefix] = true
}
raw, err := s.GetConfig(ctx, labelns.ConfigKey)
if err != nil {
return nil, fmt.Errorf("failed to read %s: %w", labelns.ConfigKey, err)
}
kept := make([]string, 0, len(inherited))
for _, label := range inherited {
if prefix := labelns.Match(exclusivePrefixes, label); prefix != "" && taken[prefix] {
continue
}
kept = append(kept, label)
}
return kept
return labelns.ResolveCreateLabels(labelns.ParsePrefixes(raw), explicit, inherited, parentID)
}
func mergeCreateLabels(labels, inheritedLabels []string) []string {

View file

@ -126,6 +126,10 @@ func CreateIssueFromFormValues(ctx context.Context, s storage.DoltStorage, fv *c
externalRefPtr = &fv.ExternalRef
}
inheritedLabels, err := resolveInheritedLabels(ctx, s, fv.Labels, inheritedLabels, fv.ParentID)
if err != nil {
return nil, err
}
labels := mergeCreateLabels(fv.Labels, inheritedLabels)
issue := &types.Issue{

View file

@ -171,7 +171,12 @@ func runImportRecordsProxied(ctx context.Context, issues []*types.Issue, memorie
for _, dep := range batch.SkippedDependencies {
skippedDependencies = append(skippedDependencies, fmt.Sprintf("%s -> %s: %s", dep.IssueID, dep.DependsOnID, dep.Reason))
}
applyImportOutcome(&result, assembleImportResult(issues, staleSkippedIDs, changePlan, staleRejectedSet, skippedDependencies))
outcome := assembleImportResult(issues, staleSkippedIDs, changePlan, staleRejectedSet, skippedDependencies)
for _, conflict := range batch.ExclusiveLabelConflicts {
outcome.ExclusiveLabelConflicts = append(outcome.ExclusiveLabelConflicts,
formatExclusiveLabelConflict(conflict.IssueID, conflict.Prefix, conflict.Labels))
}
applyImportOutcome(&result, outcome)
} else {
result.Skipped += len(staleSkippedIDs)
result.StaleSkippedIDs = append(result.StaleSkippedIDs, staleSkippedIDs...)

View file

@ -200,7 +200,7 @@ func importIssuesCore(ctx context.Context, _ string, store storage.DoltStorage,
},
ExclusiveLabelConflictWarn: true,
OnExclusiveLabelConflict: func(issueID, prefix string, labels []string) {
conflict := fmt.Sprintf("%s: namespace %q has %s", issueID, prefix, strings.Join(labels, ", "))
conflict := formatExclusiveLabelConflict(issueID, prefix, labels)
if _, ok := exclusiveLabelConflictSet[conflict]; ok {
return
}
@ -228,6 +228,12 @@ func importIssuesCore(ctx context.Context, _ string, store storage.DoltStorage,
return result, nil
}
// formatExclusiveLabelConflict renders one exclusive-namespace violation the
// way both import modes report it in exclusive_label_conflicts.
func formatExclusiveLabelConflict(issueID, prefix string, labels []string) string {
return fmt.Sprintf("%s: namespace %q has %s", issueID, prefix, strings.Join(labels, ", "))
}
// assembleImportResult folds the batch write's in-transaction outcomes (stale
// rejections, skipped dependencies) into the pre-filter's classification,
// producing the report both the classic and the proxied import return. Kept

View file

@ -206,6 +206,9 @@ func applyLabelEdit(ctx context.Context, issueIDs []string, labels []string, ope
outcome.changed[i] = !before[label]
}
}
if len(exclusivePrefixes) > 0 && result.Changed {
outcome.evicted = issuePatch.Labels.Remove
}
outcomes = append(outcomes, outcome)
}
return reportLabelEdit(outcomes, operation, jsonOutput)
@ -263,11 +266,14 @@ const (
// moved. The label set is per issue rather than one shared slice because
// --prefix resolves a different set for each issue from its own current
// labels; applyLabelEdit's fixed caller-supplied set is the degenerate case
// where every outcome repeats it.
// where every outcome repeats it. evicted lists the labels `bd label add
// --replace` swapped out to make room (bd-7u5ki), taken from the same pre-edit
// read as changed.
type labelEditOutcome struct {
issueID string
labels []string
changed []bool
evicted []string
}
// labelOperationGerund returns the present-participle form of a
@ -293,6 +299,8 @@ func labelOperationGerund(operation string) string {
// as such — status "unchanged", and a line of its own — rather than as the
// operation, so a no-op cannot be read as a confirmation (GH#5988). It is
// still not an error: the exit code stays 0 so idempotent callers keep working.
// Labels --replace evicted are reported as removals, so a swap never drops a
// label without saying so.
func reportLabelEdit(outcomes []labelEditOutcome, operation string, jsonOut bool) error {
if jsonOut {
// One row per (issue, label) pair; the hint is the one-label-per-issue
@ -311,6 +319,13 @@ func reportLabelEdit(outcomes []labelEditOutcome, operation string, jsonOut bool
"label": label,
})
}
for _, label := range outcome.evicted {
results = append(results, map[string]interface{}{
"status": labelOperationRemoved,
"issue_id": outcome.issueID,
"label": label,
})
}
}
return outputJSON(results)
}
@ -331,6 +346,10 @@ func reportLabelEdit(outcomes []labelEditOutcome, operation string, jsonOut bool
fmt.Printf("%s %s %s '%s' %s %s\n", ui.RenderPass("✓"), verb,
labelNoun(moved, "label", "labels"), strings.Join(moved, "', '"), prep, outcome.issueID)
}
if len(outcome.evicted) > 0 {
fmt.Printf("%s Removed %s '%s' from %s\n", ui.RenderPass("✓"),
labelNoun(outcome.evicted, "label", "labels"), strings.Join(outcome.evicted, "', '"), outcome.issueID)
}
if len(unmoved) == 0 {
continue
}
@ -1031,7 +1050,7 @@ func reportLabelRename(oldLabel, newLabel string, renamed, merged int, jsonOut b
}
func init() {
labelAddCmd.Flags().Bool("replace", false, "In exclusive label namespaces (labels.exclusive-prefixes), swap out any existing label in the same namespace instead of failing")
labelAddCmd.Flags().Bool("replace", false, "In exclusive label namespaces (labels.exclusive-prefixes), swap out any existing label in the same namespace instead of failing; swapped-out labels are reported as removals (status \"removed\" in --json output)")
// Issue ID completions
labelAddCmd.ValidArgsFunction = issueIDCompletion

View file

@ -519,6 +519,31 @@ func TestEmbeddedLabelEditReports(t *testing.T) {
}
})
// --replace swaps a label out of an exclusive namespace (bd-7u5ki). The
// eviction is a real removal, so the report names it next to the add
// rather than letting the old label vanish unmentioned.
t.Run("label_add_replace_reports_eviction", func(t *testing.T) {
bdRunOK(t, bd, dir, "config", "set", "labels.exclusive-prefixes", "tier:")
t.Cleanup(func() { bdRunOK(t, bd, dir, "config", "unset", "labels.exclusive-prefixes") })
issue := bdCreate(t, bd, dir, "Replace tier", "--type", "task", "--label", "tier:fable", "--label", "area:x")
out := bdLabel(t, bd, dir, "add", issue.ID, "tier:opus", "--replace")
if !strings.Contains(out, "Added label 'tier:opus' to "+issue.ID) || !strings.Contains(out, "Removed label 'tier:fable' from "+issue.ID) {
t.Errorf("replace text = %s", out)
}
rows := bdLabelEditJSON(t, bd, dir, "add", issue.ID, "tier:sonnet", "--replace")
got := map[interface{}]interface{}{}
for _, r := range rows {
got[r["label"]] = r["status"]
}
if len(rows) != 2 || got["tier:sonnet"] != "added" || got["tier:opus"] != "removed" {
t.Errorf("replace JSON = %v, want tier:sonnet=added tier:opus=removed", rows)
}
if labels := bdLabelListJSON(t, bd, dir, issue.ID); strings.Join(labels, ",") != "area:x,tier:sonnet" {
t.Errorf("labels after replace = %v, want [area:x tier:sonnet]", labels)
}
})
// One label, two issues, only one of which has it: the divergence is
// BETWEEN the issues, so this pins the per-issue derivation the way
// label_edit_mixed_reports_each_label pins the per-label one. The outcome

View file

@ -5,7 +5,6 @@ package main
import (
"context"
"path/filepath"
"slices"
"strings"
"testing"
@ -222,42 +221,3 @@ func TestFindExclusiveLabelViolations(t *testing.T) {
t.Fatalf("expected nil, nil for empty prefixes, got %v, %v", none, err)
}
}
func TestExclusiveLabelEvictions(t *testing.T) {
prefixes := []string{"tier:", "review:"}
got := exclusiveLabelEvictions(prefixes, []string{"tier:fable", "area:x", "review:opus"}, []string{"tier:opus"})
if !slices.Equal(got, []string{"tier:fable"}) {
t.Fatalf("only the added label's namespace is swapped, got %v", got)
}
// A label being added is never evicted, even when the issue already has it.
got = exclusiveLabelEvictions(prefixes, []string{"tier:opus", "tier:fable"}, []string{"tier:opus"})
if !slices.Equal(got, []string{"tier:fable"}) {
t.Fatalf("re-adding a present label still evicts its siblings, got %v", got)
}
got = exclusiveLabelEvictions(prefixes, []string{"tier:fable", "review:opus"}, []string{"area:x"})
if len(got) != 0 {
t.Fatalf("a label outside every exclusive namespace evicts nothing, got %v", got)
}
got = exclusiveLabelEvictions(nil, []string{"tier:fable"}, []string{"tier:opus"})
if len(got) != 0 {
t.Fatalf("no exclusive prefixes configured: a plain add, got %v", got)
}
}
func TestDropConflictingInheritedLabels(t *testing.T) {
prefixes := []string{"tier:"}
got := dropConflictingInheritedLabels([]string{"tier:opus"}, []string{"tier:fable", "area:x"}, prefixes)
if len(got) != 1 || got[0] != "area:x" {
t.Fatalf("explicit tier: label should evict inherited one, got %v", got)
}
got = dropConflictingInheritedLabels([]string{"area:y"}, []string{"tier:fable"}, prefixes)
if len(got) != 1 || got[0] != "tier:fable" {
t.Fatalf("inherited label without explicit conflict should survive, got %v", got)
}
got = dropConflictingInheritedLabels([]string{"tier:opus"}, []string{"tier:fable"}, nil)
if len(got) != 1 || got[0] != "tier:fable" {
t.Fatalf("no exclusive prefixes: inheritance unchanged, got %v", got)
}
}

View file

@ -0,0 +1,31 @@
package main
import (
"slices"
"testing"
)
// Pure helpers for exclusive label namespaces (bd-7u5ki), kept out of the
// cgo-tagged label_exclusive_test.go so non-CGO lanes run them too.
func TestExclusiveLabelEvictions(t *testing.T) {
prefixes := []string{"tier:", "review:"}
got := exclusiveLabelEvictions(prefixes, []string{"tier:fable", "area:x", "review:opus"}, []string{"tier:opus"})
if !slices.Equal(got, []string{"tier:fable"}) {
t.Fatalf("only the added label's namespace is swapped, got %v", got)
}
// A label being added is never evicted, even when the issue already has it.
got = exclusiveLabelEvictions(prefixes, []string{"tier:opus", "tier:fable"}, []string{"tier:opus"})
if !slices.Equal(got, []string{"tier:fable"}) {
t.Fatalf("re-adding a present label still evicts its siblings, got %v", got)
}
got = exclusiveLabelEvictions(prefixes, []string{"tier:fable", "review:opus"}, []string{"area:x"})
if len(got) != 0 {
t.Fatalf("a label outside every exclusive namespace evicts nothing, got %v", got)
}
got = exclusiveLabelEvictions(nil, []string{"tier:fable"}, []string{"tier:opus"})
if len(got) != 0 {
t.Fatalf("no exclusive prefixes configured: a plain add, got %v", got)
}
}

View file

@ -443,6 +443,46 @@ func TestProxiedServerLabel(t *testing.T) {
}
})
// labels.exclusive-prefixes (bd-7u5ki) holds on this route too: the
// server-side label writes refuse what the direct route's issueops guard
// refuses.
t.Run("exclusive_namespace_guard", func(t *testing.T) {
t.Parallel()
p := newSharedProxiedProject(t, bd, "ex")
bdProxiedConfig(t, bd, p.dir, "set", "labels.exclusive-prefixes", "tier:")
issue := bdProxiedCreate(t, bd, p.dir, "Exclusive target", "-l", "tier:fable")
out := bdProxiedLabelFail(t, bd, p.dir, "add", issue.ID, "tier:opus")
if !strings.Contains(out, `namespace "tier:" is exclusive`) {
t.Errorf("expected the exclusive-namespace refusal, got:\n%s", out)
}
if got := bdProxiedLabelListJSON(t, bd, p.dir, issue.ID); len(got) != 1 || got[0] != "tier:fable" {
t.Fatalf("labels after refused add = %v, want [tier:fable]", got)
}
out = bdProxiedLabel(t, bd, p.dir, "add", issue.ID, "tier:opus", "--replace")
if !strings.Contains(out, "Removed label 'tier:fable'") {
t.Errorf("expected --replace to report the eviction, got:\n%s", out)
}
if got := bdProxiedLabelListJSON(t, bd, p.dir, issue.ID); len(got) != 1 || got[0] != "tier:opus" {
t.Fatalf("labels after --replace = %v, want [tier:opus]", got)
}
bdProxiedLabel(t, bd, p.dir, "add", issue.ID, "legacy")
out = bdProxiedLabelFail(t, bd, p.dir, "rename", "legacy", "tier:sonnet")
if !strings.Contains(out, `already has "tier:opus"`) {
t.Errorf("expected the rename refusal to name the held label, got:\n%s", out)
}
if got := bdProxiedLabelListJSON(t, bd, p.dir, issue.ID); len(got) != 2 || got[0] != "legacy" || got[1] != "tier:opus" {
t.Fatalf("labels after refused rename = %v, want [legacy tier:opus]", got)
}
child := bdProxiedCreate(t, bd, p.dir, "Child overriding tier", "--parent", issue.ID, "-l", "tier:haiku")
if got := bdProxiedLabelListJSON(t, bd, p.dir, child.ID); len(got) != 2 || got[0] != "legacy" || got[1] != "tier:haiku" {
t.Fatalf("child labels = %v, want [legacy tier:haiku] (explicit tier:haiku beats inherited tier:opus)", got)
}
})
t.Run("wisp_label_routes_to_wisp_labels", func(t *testing.T) {
t.Parallel()
p := newSharedProxiedProject(t, bd, "lw")

View file

@ -73,6 +73,10 @@ Example:
}
inheritedLabels, _ = store.GetLabels(ctx, parentID)
}
inheritedLabels, err = resolveInheritedLabels(ctx, store, labels, inheritedLabels, parentID)
if err != nil {
return HandleError("%v", err)
}
issue := &types.Issue{
Title: title,

View file

@ -350,7 +350,7 @@ Labels are free-form, but conventions like `tier:<model>` treat a prefix as sing
bd config set labels.exclusive-prefixes "tier:,review:"
```
With a namespace configured, every write path rejects a second label in it — `bd create -l`, `bd update --add-label`, `bd label add`, and `bd label propagate` — naming the existing label in the error. To swap instead of remove-then-add:
With a namespace configured, every write path rejects a second label in it — `bd create -l`, `bd update --add-label`, `bd label add`, `bd label propagate`, and `bd label rename` — naming the existing label in the error. To swap instead of remove-then-add:
```bash
bd label add bd-a1b2 tier:opus --replace # removes tier:fable, adds tier:opus
@ -359,9 +359,10 @@ bd label add bd-a1b2 tier:opus --replace # removes tier:fable, adds tier:opus
Boundary behavior:
- **Off by default.** An empty or unset key leaves all labels free-form; multi-valued prefixes like `area:` keep working unless you list them.
- **Explicit beats inherited.** A child created with `--parent` and an explicit label in an exclusive namespace drops the parent's label in that namespace instead of failing.
- **Import warns instead of failing.** `bd import` replays history that may predate the config, so violations are kept and reported, not rejected.
- **`bd doctor` reports existing violations** (server mode), so you can clean up before or after turning enforcement on.
- **Explicit beats inherited.** A child created with `--parent` and an explicit label in an exclusive namespace drops the parent's label in that namespace instead of failing. A parent that already carries two labels in one namespace fails the create with an error naming the parent: pick one with `-l`, or skip inheritance with `--no-inherit-labels`.
- **Rename refuses only new violations.** `bd label rename` fails when an issue carrying the old label already has a different label in the new label's namespace. Renaming within one namespace (`tier:fable` to `tier:opus`) or onto a label the issue already has goes through.
- **Import warns instead of failing.** `bd import` replays history that may predate the config, so violations are kept and reported (`exclusive_label_conflicts` in `--json` output), not rejected. The empty-database auto-import from `.beads/issues.jsonl` keeps them the same way.
- **`bd doctor` reports existing violations** (server mode), so you can clean up before or after turning enforcement on. It also catches the violations the write check cannot see: two concurrent writes each adding one label in the same namespace, or a Dolt merge combining both sides' labels.
### Sequential Counter IDs

View file

@ -222,6 +222,9 @@ Returns a summary object when `--json` is active:
- `tie_kept_local_ids` (string[]): Equal-`updated_at` rows where local state won
- `stale_skipped_ids` (string[]): Rows older than the local issue, skipped
- `skipped_dependencies` (string[]): Dependency edges whose target id was absent
- `exclusive_label_conflicts` (string[], optional): Imported issues carrying more
than one label in an exclusive namespace (`labels.exclusive-prefixes`), one
entry per issue and namespace; import keeps the labels as written
- `dry_run` (boolean): Whether `--dry-run` was active
### bd export --json

View file

@ -12,3 +12,25 @@ go_test(
srcs = ["labelns_test.go"],
embed = [":labelns"],
)
# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "repo_files",
srcs = glob(
["**"],
exclude = [
"**/*.db",
"**/*.exe",
"**/*.out",
"**/*.prof",
"**/*.pyc",
"**/*.test",
"**/__pycache__/**",
"**/node_modules/**",
],
),
visibility = ["//:__pkg__"],
)
# --- end repo_files ---

View file

@ -124,3 +124,47 @@ func Conflicts(prefixes, labels []string) []Conflict {
}
return conflicts
}
// ResolveCreateLabels settles exclusive-namespace collisions for a create
// that inherits labels from a parent. An explicit label wins over an
// inherited one in the same namespace: the inherited label is dropped, so a
// child can override e.g. a tier: routing label without needing
// --no-inherit-labels. It returns the inherited labels to keep, in their
// input order.
//
// Two collisions are refused instead: explicit labels that conflict among
// themselves, and inherited labels that conflict among themselves (a parent
// labeled before the namespace became exclusive, or imported with a kept
// violation). parentID only names the parent in the second error, so the
// caller learns which labels it never typed. After the drop no namespace
// holds both explicit and inherited labels, so a nil error means the merged
// label set is conflict-free.
func ResolveCreateLabels(prefixes, explicit, inherited []string, parentID string) ([]string, error) {
if len(prefixes) == 0 {
return inherited, nil
}
if conflicts := Conflicts(prefixes, explicit); len(conflicts) > 0 {
c := conflicts[0]
return nil, fmt.Errorf("namespace %q is exclusive (%s) and allows at most one label, got %s",
c.Prefix, ConfigKey, strings.Join(c.Labels, ", "))
}
taken := make(map[string]bool)
for _, label := range explicit {
if prefix := Match(prefixes, label); prefix != "" {
taken[prefix] = true
}
}
kept := make([]string, 0, len(inherited))
for _, label := range inherited {
if prefix := Match(prefixes, label); prefix != "" && taken[prefix] {
continue
}
kept = append(kept, label)
}
if conflicts := Conflicts(prefixes, kept); len(conflicts) > 0 {
c := conflicts[0]
return nil, fmt.Errorf("namespace %q is exclusive (%s) and allows at most one label, but parent %s carries %s — choose one with -l, or skip inheritance with --no-inherit-labels",
c.Prefix, ConfigKey, parentID, strings.Join(c.Labels, ", "))
}
return kept, nil
}

View file

@ -2,6 +2,7 @@ package labelns
import (
"reflect"
"strings"
"testing"
)
@ -90,3 +91,41 @@ func TestConflicts(t *testing.T) {
t.Errorf("Conflicts = %v, want %v", got, want)
}
}
func TestResolveCreateLabels(t *testing.T) {
prefixes := []string{"tier:", "review:"}
got, err := ResolveCreateLabels(prefixes, []string{"tier:opus"}, []string{"tier:fable", "area:x"}, "bd-p")
if err != nil || !reflect.DeepEqual(got, []string{"area:x"}) {
t.Fatalf("explicit tier: label should evict the inherited one, got %v, %v", got, err)
}
got, err = ResolveCreateLabels(prefixes, []string{"area:y"}, []string{"tier:fable"}, "bd-p")
if err != nil || !reflect.DeepEqual(got, []string{"tier:fable"}) {
t.Fatalf("inherited label without an explicit conflict should survive, got %v, %v", got, err)
}
got, err = ResolveCreateLabels(nil, []string{"tier:opus"}, []string{"tier:fable"}, "bd-p")
if err != nil || !reflect.DeepEqual(got, []string{"tier:fable"}) {
t.Fatalf("no exclusive prefixes: inheritance unchanged, got %v, %v", got, err)
}
// Explicit labels that collide among themselves are the caller's own
// mistake: refused, naming both.
_, err = ResolveCreateLabels(prefixes, []string{"tier:opus", "tier:fable"}, nil, "bd-p")
if err == nil || !strings.Contains(err.Error(), "tier:opus, tier:fable") || strings.Contains(err.Error(), "bd-p") {
t.Fatalf("explicit conflict should be refused without blaming the parent, got %v", err)
}
// A violating parent: the error says the labels came from the parent and
// how to get past it, instead of naming labels the caller never typed as
// if they had.
_, err = ResolveCreateLabels(prefixes, []string{"area:y"}, []string{"tier:fable", "tier:opus"}, "bd-p")
if err == nil || !strings.Contains(err.Error(), "parent bd-p carries tier:fable, tier:opus") ||
!strings.Contains(err.Error(), "--no-inherit-labels") {
t.Fatalf("inherited conflict should name the parent and the escape hatch, got %v", err)
}
// ...unless an explicit label settles that namespace, which drops both.
got, err = ResolveCreateLabels(prefixes, []string{"tier:haiku"}, []string{"tier:fable", "tier:opus"}, "bd-p")
if err != nil || len(got) != 0 {
t.Fatalf("explicit label should settle a violating parent's namespace, got %v, %v", got, err)
}
}

View file

@ -150,6 +150,9 @@ func (l *Loader) loadMolecules(ctx context.Context, molecules []*types.Issue) (i
// Molecules have their own ID namespace (mol-*) independent of project prefix.
opts := storage.BatchCreateOptions{
SkipPrefixValidation: true, // Molecules use their own prefix
// Replays catalog data: exclusive-label violations warn via bd doctor
// instead of failing the load (bd-7u5ki).
ExclusiveLabelConflictWarn: true,
}
if err := l.store.CreateIssuesWithFullOptions(ctx, newMolecules, "molecules-loader", opts); err != nil {
return 0, fmt.Errorf("batch create molecules: %w", err)

View file

@ -166,10 +166,14 @@ const statementCountToleranceDolt = 2
// Re-pinned for the batch-create round-trip work (was 7008 / 14014 / 846);
// see pinnedEmbeddedStatementCounts in internal/storage/embeddeddolt for the
// per-change breakdown. The two backends now agree to within the tolerance.
//
// Re-pinned for exclusive label namespaces (was 6396 / 12791 / 786): +1
// statement per create item, the labels.exclusive-prefixes read in
// NewBatchContext; see pinnedEmbeddedStatementCounts for the breakdown.
var pinnedDoltStatementCounts = map[string]int64{
"356 (mol 1x)": 6396,
"712 (mol 2x)": 12791,
"40 (classic)": 786,
"356 (mol 1x)": 6498,
"712 (mol 2x)": 12995,
"40 (classic)": 796,
}
// BenchmarkLargeBatchApply_Dolt is gated by setupBenchStore's own

View file

@ -27,6 +27,7 @@ go_library(
"//internal/config",
"//internal/configfile",
"//internal/idgen",
"//internal/labelns",
"//internal/storage",
"//internal/storage/dberrors",
"//internal/storage/doltutil",

View file

@ -61,6 +61,7 @@ go_test(
"dependency_usecase_metadata_test.go",
"dependency_usecase_test.go",
"events_test.go",
"exclusive_labels_test.go",
"field_length_test.go",
"is_blocked_test.go",
"issue_as_of_test.go",
@ -105,6 +106,7 @@ go_test(
data = [":go_srcs"],
embed = [":db"],
deps = [
"//internal/labelns",
"//internal/storage",
"//internal/storage/dberrors",
"//internal/storage/depid",

View file

@ -0,0 +1,179 @@
package db
import (
"github.com/steveyegge/beads/internal/labelns"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/types"
)
// TestExclusiveLabelNamespaces pins the proxied-server (uow) half of the
// labels.exclusive-prefixes contract (bd-7u5ki): every label write refuses a
// second label in an exclusive namespace, exactly as the direct route does in
// issueops.addLabelInTx. Subtests share one database, so each uses its own ids
// and labels.
func (s *testSuite) TestExclusiveLabelNamespaces() {
s.Require().NoError(NewConfigSQLRepository(s.Runner()).SetConfig(s.Ctx(), labelns.ConfigKey, "tier:"))
s.Run("InsertRejectsSecondLabel", s.exclInsertRejectsSecondLabel)
s.Run("InsertReAddOnViolatingIssuePasses", s.exclInsertReAddOnViolatingIssue)
s.Run("UpdateSwapsInOneSpec", s.exclUpdateSwapsInOneSpec)
s.Run("UpdateRemoveWinsOverAdd", s.exclUpdateRemoveWinsOverAdd)
s.Run("CreateRejectsTwoExplicitLabels", s.exclCreateRejectsTwoExplicit)
s.Run("CreateExplicitBeatsInherited", s.exclCreateExplicitBeatsInherited)
s.Run("CreateInheritedConflictNamesParent", s.exclCreateInheritedConflict)
s.Run("RenameRefusesNewViolation", s.exclRenameRefusesNewViolation)
s.Run("RenameMergeAndSameNamespacePass", s.exclRenameMergeAndSameNamespace)
}
// seedRawLabels writes label rows directly, bypassing the guard, to stage a
// violation the way an import or a Dolt merge can leave one behind.
func (s *testSuite) seedRawLabels(issueID string, labels ...string) {
for _, label := range labels {
_, err := s.Runner().ExecContext(s.Ctx(), "INSERT INTO labels (issue_id, label) VALUES (?, ?)", issueID, label)
s.Require().NoError(err)
}
}
func (s *testSuite) requireLabels(issueID string, want ...string) {
got, err := s.labelRepo().List(s.Ctx(), issueID, domain.LabelOpts{})
s.Require().NoError(err)
s.Equal(want, got)
}
func (s *testSuite) exclInsertRejectsSecondLabel() {
s.seedIssueRow("bd-excl-ins")
r := s.labelRepo()
s.Require().NoError(r.Insert(s.Ctx(), "bd-excl-ins", "tier:fable", "tester", domain.LabelOpts{}))
s.Require().NoError(r.Insert(s.Ctx(), "bd-excl-ins", "area:x", "tester", domain.LabelOpts{}))
err := r.Insert(s.Ctx(), "bd-excl-ins", "tier:opus", "tester", domain.LabelOpts{})
s.Require().Error(err)
s.Contains(err.Error(), `namespace "tier:" is exclusive`)
s.Contains(err.Error(), `already has "tier:fable"`)
s.requireLabels("bd-excl-ins", "area:x", "tier:fable")
}
func (s *testSuite) exclInsertReAddOnViolatingIssue() {
s.seedIssueRow("bd-excl-readd")
s.seedRawLabels("bd-excl-readd", "tier:fable", "tier:opus")
s.Require().NoError(s.labelRepo().Insert(s.Ctx(), "bd-excl-readd", "tier:fable", "tester", domain.LabelOpts{}),
"re-adding a label the issue already carries writes nothing and must pass")
}
func (s *testSuite) exclUpdateSwapsInOneSpec() {
s.seedOpenIssue("bd-excl-swap")
uc := s.issueUseCase()
_, err := uc.ApplyUpdate(s.Ctx(), "bd-excl-swap", domain.UpdateSpec{AddLabels: []string{"tier:fable"}}, "tester")
s.Require().NoError(err)
_, err = uc.ApplyUpdate(s.Ctx(), "bd-excl-swap", domain.UpdateSpec{
AddLabels: []string{"tier:opus"},
RemoveLabels: []string{"tier:fable"},
}, "tester")
s.Require().NoError(err, "removes must run before adds so a swap passes the guard")
s.requireLabels("bd-excl-swap", "tier:opus")
}
func (s *testSuite) exclUpdateRemoveWinsOverAdd() {
s.seedOpenIssue("bd-excl-rmwins")
uc := s.issueUseCase()
_, err := uc.ApplyUpdate(s.Ctx(), "bd-excl-rmwins", domain.UpdateSpec{AddLabels: []string{"keep"}}, "tester")
s.Require().NoError(err)
_, err = uc.ApplyUpdate(s.Ctx(), "bd-excl-rmwins", domain.UpdateSpec{
AddLabels: []string{"tier:fable"},
RemoveLabels: []string{"tier:fable"},
}, "tester")
s.Require().NoError(err)
s.requireLabels("bd-excl-rmwins", "keep")
}
func (s *testSuite) exclCreateRejectsTwoExplicit() {
s.resetMintConfig("exa", "")
_, err := s.issueUseCase().CreateIssue(s.Ctx(), domain.CreateIssueParams{
Issue: &types.Issue{Title: "two tiers", IssueType: types.TypeTask, Priority: 2},
Labels: []string{"tier:fable", "tier:opus"},
}, "tester")
s.Require().Error(err)
s.Contains(err.Error(), `namespace "tier:" is exclusive`)
}
func (s *testSuite) exclCreateExplicitBeatsInherited() {
s.resetMintConfig("exb", "")
uc := s.issueUseCase()
parent, err := uc.CreateIssue(s.Ctx(), domain.CreateIssueParams{
Issue: &types.Issue{Title: "parent", IssueType: types.TypeEpic, Priority: 2},
Labels: []string{"area:x", "tier:fable"},
}, "tester")
s.Require().NoError(err)
child, err := uc.CreateIssue(s.Ctx(), domain.CreateIssueParams{
Issue: &types.Issue{Title: "child", IssueType: types.TypeTask, Priority: 2},
ParentID: parent.Issue.ID,
InheritLabelsFromParent: true,
Labels: []string{"tier:opus"},
}, "tester")
s.Require().NoError(err)
s.Equal([]string{"area:x"}, child.InheritedLabels, "the parent's tier:fable yields to the explicit tier:opus")
s.requireLabels(child.Issue.ID, "area:x", "tier:opus")
}
func (s *testSuite) exclCreateInheritedConflict() {
s.resetMintConfig("exc", "")
uc := s.issueUseCase()
parent, err := uc.CreateIssue(s.Ctx(), domain.CreateIssueParams{
Issue: &types.Issue{Title: "violating parent", IssueType: types.TypeEpic, Priority: 2},
}, "tester")
s.Require().NoError(err)
s.seedRawLabels(parent.Issue.ID, "tier:fable", "tier:opus")
_, err = uc.CreateIssue(s.Ctx(), domain.CreateIssueParams{
Issue: &types.Issue{Title: "child", IssueType: types.TypeTask, Priority: 2},
ParentID: parent.Issue.ID,
InheritLabelsFromParent: true,
}, "tester")
s.Require().Error(err)
s.Contains(err.Error(), "parent "+parent.Issue.ID+" carries tier:fable, tier:opus")
s.Contains(err.Error(), "--no-inherit-labels")
child, err := uc.CreateIssue(s.Ctx(), domain.CreateIssueParams{
Issue: &types.Issue{Title: "child", IssueType: types.TypeTask, Priority: 2},
ParentID: parent.Issue.ID,
InheritLabelsFromParent: true,
Labels: []string{"tier:opus"},
}, "tester")
s.Require().NoError(err, "an explicit label settles the violating parent's namespace")
s.requireLabels(child.Issue.ID, "tier:opus")
}
func (s *testSuite) exclRenameRefusesNewViolation() {
s.seedIssueRow("bd-excl-rn-a")
s.seedIssueRow("bd-excl-rn-b")
r := s.labelRepo()
s.Require().NoError(r.Insert(s.Ctx(), "bd-excl-rn-a", "legacy-rn", "tester", domain.LabelOpts{}))
s.Require().NoError(r.Insert(s.Ctx(), "bd-excl-rn-b", "legacy-rn", "tester", domain.LabelOpts{}))
s.Require().NoError(r.Insert(s.Ctx(), "bd-excl-rn-b", "tier:fable", "tester", domain.LabelOpts{}))
_, _, _, err := r.RenameLabel(s.Ctx(), "legacy-rn", "tier:opus", "tester")
s.Require().Error(err)
s.Contains(err.Error(), `cannot rename label "legacy-rn" to "tier:opus"`)
s.Contains(err.Error(), `bd-excl-rn-b already has "tier:fable"`)
s.requireLabels("bd-excl-rn-a", "legacy-rn")
s.requireLabels("bd-excl-rn-b", "legacy-rn", "tier:fable")
}
func (s *testSuite) exclRenameMergeAndSameNamespace() {
s.seedIssueRow("bd-excl-rm")
r := s.labelRepo()
s.Require().NoError(r.Insert(s.Ctx(), "bd-excl-rm", "legacy-rm", "tester", domain.LabelOpts{}))
s.Require().NoError(r.Insert(s.Ctx(), "bd-excl-rm", "tier:rm-a", "tester", domain.LabelOpts{}))
renamed, merged, _, err := r.RenameLabel(s.Ctx(), "legacy-rm", "tier:rm-a", "tester")
s.Require().NoError(err, "a carrier already holding the new label merges into it")
s.Equal(1, renamed)
s.Equal(1, merged)
s.requireLabels("bd-excl-rm", "tier:rm-a")
_, _, _, err = r.RenameLabel(s.Ctx(), "tier:rm-a", "tier:rm-b", "tester")
s.Require().NoError(err, "a rename within one namespace swaps a label and never adds one")
s.requireLabels("bd-excl-rm", "tier:rm-b")
}

View file

@ -47,6 +47,13 @@ func (r *labelSQLRepositoryImpl) Insert(ctx context.Context, issueID, label, act
return err
}
table := pickLabelTable(opts.UseWispsTable)
// The same exclusive-namespace guard (labels.exclusive-prefixes) the
// direct route runs in issueops.addLabelInTx, so every proxied label write
// - label add, update --add-label, label propagate, create - refuses a
// second label in an exclusive namespace too.
if err := issueops.CheckExclusiveLabelInTx(ctx, r.runner, table, issueID, label); err != nil {
return err
}
//nolint:gosec // G201: table is one of two hardcoded constants
result, err := r.runner.ExecContext(ctx,
fmt.Sprintf("INSERT IGNORE INTO %s (issue_id, label) VALUES (?, ?)", table),

View file

@ -3,10 +3,12 @@ package domain
import (
"context"
"fmt"
"slices"
"strings"
"time"
"github.com/steveyegge/beads/internal/idgen"
"github.com/steveyegge/beads/internal/labelns"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/dberrors"
"github.com/steveyegge/beads/internal/types"
@ -772,38 +774,8 @@ func (u *issueUseCaseImpl) ApplyUpdate(ctx context.Context, id string, spec Upda
}
}
if spec.SetLabels != nil {
if useWisp {
if err := u.labelUC.SetWispLabels(ctx, id, *spec.SetLabels, actor); err != nil {
return nil, err
}
} else {
if err := u.labelUC.SetLabels(ctx, id, *spec.SetLabels, actor); err != nil {
return nil, err
}
}
}
if len(spec.AddLabels) > 0 {
if useWisp {
if err := u.labelUC.AddWispLabels(ctx, id, spec.AddLabels, actor); err != nil {
return nil, err
}
} else {
if err := u.labelUC.AddLabels(ctx, id, spec.AddLabels, actor); err != nil {
return nil, err
}
}
}
if len(spec.RemoveLabels) > 0 {
if useWisp {
if err := u.labelUC.RemoveWispLabels(ctx, id, spec.RemoveLabels, actor); err != nil {
return nil, err
}
} else {
if err := u.labelUC.RemoveLabels(ctx, id, spec.RemoveLabels, actor); err != nil {
return nil, err
}
}
if err := u.applyLabelSpec(ctx, id, spec, actor, useWisp); err != nil {
return nil, err
}
if spec.Reparent != nil {
@ -840,6 +812,48 @@ func (u *issueUseCaseImpl) ApplyUpdate(ctx context.Context, id string, spec Upda
return issue, nil
}
// applyLabelSpec applies an update's label edits: SetLabels, then
// RemoveLabels, then AddLabels minus anything also being removed. Removing
// before adding is what lets a swap inside an exclusive namespace
// (labels.exclusive-prefixes) - --remove-label tier:a --add-label tier:b, or
// bd label add --replace - pass the insert guard, the order the direct
// route's label patch uses too. Dropping removed labels from the adds keeps
// that route's answer for a label both added and removed: it ends up absent.
func (u *issueUseCaseImpl) applyLabelSpec(ctx context.Context, id string, spec UpdateSpec, actor string, useWisp bool) error {
if spec.SetLabels != nil {
set := u.labelUC.SetLabels
if useWisp {
set = u.labelUC.SetWispLabels
}
if err := set(ctx, id, *spec.SetLabels, actor); err != nil {
return err
}
}
if len(spec.RemoveLabels) > 0 {
remove := u.labelUC.RemoveLabels
if useWisp {
remove = u.labelUC.RemoveWispLabels
}
if err := remove(ctx, id, spec.RemoveLabels, actor); err != nil {
return err
}
}
adds := make([]string, 0, len(spec.AddLabels))
for _, label := range spec.AddLabels {
if !slices.Contains(spec.RemoveLabels, label) {
adds = append(adds, label)
}
}
if len(adds) == 0 {
return nil
}
add := u.labelUC.AddLabels
if useWisp {
add = u.labelUC.AddWispLabels
}
return add(ctx, id, adds, actor)
}
func (u *issueUseCaseImpl) isWispID(ctx context.Context, id string) (bool, error) {
found, err := u.issueRepo.Exists(ctx, id, IssueTableOpts{UseWispsTable: true})
if err != nil {
@ -1023,32 +1037,11 @@ func (u *issueUseCaseImpl) create(ctx context.Context, params CreateIssueParams,
result.PostCreateWrites = true
}
if params.InheritLabelsFromParent && params.ParentID != "" {
parentIsWisp, err := u.isWispID(ctx, params.ParentID)
if err != nil {
return result, fmt.Errorf("create: determine parent tier for label inheritance from %s: %w", params.ParentID, err)
}
parentLabels, err := u.labelRepo.List(ctx, params.ParentID, LabelOpts{UseWispsTable: parentIsWisp})
switch {
case dberrors.IsTableNotExist(err):
// Older schemas may lack the wisp label table; nothing to inherit.
case err != nil:
// Swallowing this silently created children missing their
// inherited labels (bd-6dnrw.44 P3); the create is transactional,
// so failing loud is safe.
return result, fmt.Errorf("create: read parent labels for inheritance from %s: %w", params.ParentID, err)
default:
existing := make(map[string]bool, len(params.Labels))
for _, l := range params.Labels {
existing[l] = true
}
for _, l := range parentLabels {
if !existing[l] {
result.InheritedLabels = append(result.InheritedLabels, l)
}
}
}
inherited, err := u.inheritedCreateLabels(ctx, params)
if err != nil {
return result, err
}
result.InheritedLabels = inherited
for _, label := range params.Labels {
if err := u.labelRepo.Insert(ctx, issue.ID, label, actor, LabelOpts{UseWispsTable: useWisp}); err != nil {
@ -1099,6 +1092,52 @@ func (u *issueUseCaseImpl) create(ctx context.Context, params CreateIssueParams,
return result, nil
}
// inheritedCreateLabels returns the parent labels a create inherits: the
// parent's labels not already among params.Labels, settled against the
// workspace's exclusive label namespaces (labels.exclusive-prefixes) the way
// the direct route's bd create front door settles them. An explicit label
// drops an inherited one in its namespace; explicit labels that collide, or
// inherited ones that do, refuse the create with an error that says which,
// before the per-label insert guard would refuse it naming only the second
// label.
func (u *issueUseCaseImpl) inheritedCreateLabels(ctx context.Context, params CreateIssueParams) ([]string, error) {
var inherited []string
if params.InheritLabelsFromParent && params.ParentID != "" {
parentIsWisp, err := u.isWispID(ctx, params.ParentID)
if err != nil {
return nil, fmt.Errorf("create: determine parent tier for label inheritance from %s: %w", params.ParentID, err)
}
parentLabels, err := u.labelRepo.List(ctx, params.ParentID, LabelOpts{UseWispsTable: parentIsWisp})
switch {
case dberrors.IsTableNotExist(err):
// Older schemas may lack the wisp label table; nothing to inherit.
case err != nil:
// Swallowing this silently created children missing their
// inherited labels (bd-6dnrw.44 P3); the create is transactional,
// so failing loud is safe.
return nil, fmt.Errorf("create: read parent labels for inheritance from %s: %w", params.ParentID, err)
default:
for _, l := range parentLabels {
if !slices.Contains(params.Labels, l) {
inherited = append(inherited, l)
}
}
}
}
if len(params.Labels)+len(inherited) < 2 {
return inherited, nil
}
raw, err := u.cfgRepo.GetConfig(ctx, labelns.ConfigKey)
if err != nil {
return nil, fmt.Errorf("create: read %s: %w", labelns.ConfigKey, err)
}
inherited, err = labelns.ResolveCreateLabels(labelns.ParsePrefixes(raw), params.Labels, inherited, params.ParentID)
if err != nil {
return nil, fmt.Errorf("create: %w", err)
}
return inherited, nil
}
func validateExplicitIDPrefix(id, prefix, allowedPrefixes string) error {
if strings.HasPrefix(id, prefix+"-") {
return nil

View file

@ -139,6 +139,7 @@ go_test(
"dualwrite_history_contract_test.go",
"edge_reader_contract_test.go",
"events_since_test.go",
"exclusive_labels_test.go",
"expected_revision_contract_test.go",
"external_dependencies_test.go",
"federation_credentials_test.go",
@ -236,6 +237,7 @@ go_test(
"//internal/debug",
"//internal/eventsjournal",
"//internal/hooks",
"//internal/labelns",
"//internal/storage",
"//internal/storage/batchbench",
"//internal/storage/batchfixtures",

View file

@ -0,0 +1,134 @@
//go:build cgo
package embeddeddolt_test
import (
"context"
"slices"
"strings"
"testing"
"github.com/steveyegge/beads/internal/labelns"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/embeddeddolt"
"github.com/steveyegge/beads/internal/types"
publicops "github.com/steveyegge/beads/issueops"
)
// TestImportJSONLData_KeepsExclusiveLabelViolations pins warn mode on the
// embedded auto-import fast path (bd-7u5ki): the exported
// labels.exclusive-prefixes config is replayed in the same transaction as the
// issues, so a historical violation must be kept for bd doctor to report
// rather than failing the whole hydration.
func TestImportJSONLData_KeepsExclusiveLabelViolations(t *testing.T) {
te := newTestEnv(t, "ij")
ctx := context.Background()
issues := []*types.Issue{{
ID: "ij-1",
Title: "carries two tier labels",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
Labels: []string{"tier:fable", "tier:opus"},
}}
imported, err := te.store.ImportJSONLData(ctx, issues, map[string]string{labelns.ConfigKey: "tier:"}, "test")
if err != nil {
t.Fatalf("ImportJSONLData must not fail on an exclusive-label violation: %v", err)
}
if imported != 1 {
t.Fatalf("imported = %d, want 1", imported)
}
labels, err := te.store.GetLabels(ctx, "ij-1")
if err != nil {
t.Fatalf("GetLabels: %v", err)
}
slices.Sort(labels)
if !slices.Equal(labels, []string{"tier:fable", "tier:opus"}) {
t.Fatalf("labels = %v, want both kept", labels)
}
raw, err := te.store.GetConfig(ctx, labelns.ConfigKey)
if err != nil || raw != "tier:" {
t.Fatalf("config %s = %q, %v; want the replayed value", labelns.ConfigKey, raw, err)
}
}
// TestExclusiveLabels_CreateAndRename pins the guarded create and rename
// paths the direct and embedded routes share (bd-7u5ki): issueops.ExecuteCreate
// lets an explicit label win over an inherited one in its exclusive namespace
// and refuses a parent's inherited conflict by name, and RenameLabelInTx
// refuses a rename that would give a carrier a second label in one.
func TestExclusiveLabels_CreateAndRename(t *testing.T) {
te := newTestEnv(t, "xl")
ctx := context.Background()
if err := te.store.SetConfig(ctx, labelns.ConfigKey, "tier:"); err != nil {
t.Fatalf("SetConfig: %v", err)
}
operations, err := embeddeddolt.NewIssueOperations(te.store)
if err != nil {
t.Fatalf("NewIssueOperations: %v", err)
}
seed := func(id string, labels ...string) {
t.Helper()
issue := &types.Issue{ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Labels: labels}
// Warn mode stages a violating parent the way an import can.
if err := te.store.CreateIssuesWithFullOptions(ctx, []*types.Issue{issue}, "seed", storage.BatchCreateOptions{
SkipPrefixValidation: true,
ExclusiveLabelConflictWarn: true,
}); err != nil {
t.Fatalf("seed %s: %v", id, err)
}
}
createChild := func(id, parentID string, labels ...string) (publicops.CreateResult, error) {
return operations.Create(ctx, publicops.CreateRequest{
Actor: "writer",
ForceIDPrefix: true,
Issue: &types.Issue{ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Labels: labels},
ParentID: parentID,
InheritLabelsFromParent: true,
})
}
requireLabels := func(id string, want ...string) {
t.Helper()
got, err := te.store.GetLabels(ctx, id)
if err != nil {
t.Fatalf("GetLabels %s: %v", id, err)
}
slices.Sort(got)
if !slices.Equal(got, want) {
t.Fatalf("labels of %s = %v, want %v", id, got, want)
}
}
t.Run("explicit label beats inherited", func(t *testing.T) {
seed("xl-parent", "area:x", "tier:fable")
result, err := createChild("xl-child", "xl-parent", "tier:opus")
if err != nil {
t.Fatalf("Create: %v", err)
}
requireLabels(result.Issue.ID, "area:x", "tier:opus")
})
t.Run("inherited conflict names the parent", func(t *testing.T) {
seed("xl-violator", "tier:fable", "tier:opus")
_, err := createChild("xl-orphan", "xl-violator")
if err == nil || !strings.Contains(err.Error(), "parent xl-violator carries tier:fable, tier:opus") ||
!strings.Contains(err.Error(), "--no-inherit-labels") {
t.Fatalf("expected the inherited conflict to name the parent, got %v", err)
}
if _, err := createChild("xl-settled", "xl-violator", "tier:opus"); err != nil {
t.Fatalf("an explicit label settles the parent's namespace: %v", err)
}
requireLabels("xl-settled", "tier:opus")
})
t.Run("rename refuses a new violation", func(t *testing.T) {
seed("xl-rn", "legacy", "tier:fable")
_, _, _, err := te.store.RenameLabel(ctx, "legacy", "tier:opus", "tester")
if err == nil || !strings.Contains(err.Error(), `xl-rn already has "tier:fable"`) {
t.Fatalf("expected rename refusal naming xl-rn, got %v", err)
}
requireLabels("xl-rn", "legacy", "tier:fable")
})
}

View file

@ -215,7 +215,7 @@ const large712ShapeName = "712 (mol 2x)"
// The 712 (mol 2x) shape alone still measures ~260-300s: it is a single
// pinned statement-count assertion over one indivisible ApplyBatchInTx
// transaction (no internal sub-cases to split further), a genuine, CPU-bound
// cost: 12790 real SQL statement round-trips through the race-instrumented
// cost: 12994 real SQL statement round-trips through the race-instrumented
// in-process Dolt engine. It is skipped under -race below, following the
// exact precedent TestLargeBatchApplyWallClock_Embedded set for its
// 1000-item shape: the cost here is race-instrumentation overhead on the
@ -224,7 +224,7 @@ const large712ShapeName = "712 (mol 2x)"
// real pass/fail assertion (the pinned Total() above), so skipping it under
// race moves this regression check to the non-race embedded variant — not a
// weakening of the assertion itself. //internal/storage/embeddeddolt:embeddeddolt_batch_apply_nonrace_test
// (the Bazel embedded tier) selects this test, so the full 12790-statement
// (the Bazel embedded tier) selects this test, so the full 12994-statement
// pinned baseline still runs, non-race.
func runLargeBatchApplyStatementCountsShape(t *testing.T, shapeName string) {
skipUnlessEmbeddedDolt(t)
@ -419,10 +419,17 @@ func TestLargeBatchApplyWallClock_Embedded(t *testing.T) {
//
// Net: 356 -613 (incl. the documented 1-statement jitter), 712 -1224,
// classic -60.
//
// Re-pinned for exclusive label namespaces (bd-7u5ki; was 6396 / 12790 /
// 786): NewBatchContext also reads labels.exclusive-prefixes, and
// ExecuteCreate builds one BatchContext per create item, so +1 statement per
// create (356: +102, 712: +204, classic: +10). Nothing else in these plans
// reads the key: no item adds a label, so addLabelInTx's guard read never
// runs here.
var pinnedEmbeddedStatementCounts = map[string]int64{
"356 (mol 1x)": 6396,
large712ShapeName: 12790,
"40 (classic)": 786,
"356 (mol 1x)": 6498,
large712ShapeName: 12994,
"40 (classic)": 796,
}
// BenchmarkLargeBatchApply_Embedded benchmarks issueops.ApplyBatchInTx on

View file

@ -1013,6 +1013,10 @@ func (s *EmbeddedDoltStore) ImportJSONLData(
// that check cannot clobber live rows — matching the server-mode
// fallback's conflict-skip behavior.
ConflictSkip: true,
// Replays existing data, and the exclusive-prefixes config above
// lands in this same transaction: exclusive-label violations warn
// via bd doctor instead of failing the hydration (bd-7u5ki).
ExclusiveLabelConflictWarn: true,
}); err != nil {
return err
}

View file

@ -6,6 +6,7 @@ import (
"fmt"
"strings"
"github.com/steveyegge/beads/internal/labelns"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
publicops "github.com/steveyegge/beads/issueops"
@ -67,11 +68,9 @@ func ExecuteCreate(ctx context.Context, tx *sql.Tx, request publicops.CreateRequ
issue.Ephemeral = true
}
if attempt.InheritLabelsFromParent && attempt.ParentID != "" {
labels, err := GetLabelsInTx(ctx, tx, "", attempt.ParentID)
if err != nil {
if err := inheritParentLabelsInTx(ctx, tx, batch.ExclusiveLabelPrefixes, issue, attempt.ParentID); err != nil {
return publicops.CreateResult{}, nil, err
}
issue.Labels = append(issue.Labels, labels...)
}
childCounterChanged := false
if issue.ID == "" && attempt.ParentID != "" {
@ -117,6 +116,24 @@ func ExecuteCreate(ctx context.Context, tx *sql.Tx, request publicops.CreateRequ
return publicops.CreateResult{Issue: hydrated}, tables, nil
}
// inheritParentLabelsInTx appends the parent's labels to a create that asked
// to inherit them. An explicit label wins over an inherited one in its
// exclusive namespace (labels.exclusive-prefixes), the rule bd create's front
// door applies before it asks for a create; refusing instead would fail every
// child that overrides its parent's tier: label.
func inheritParentLabelsInTx(ctx context.Context, tx *sql.Tx, prefixes []string, issue *types.Issue, parentID string) error {
labels, err := GetLabelsInTx(ctx, tx, "", parentID)
if err != nil {
return err
}
labels, err = labelns.ResolveCreateLabels(prefixes, issue.Labels, labels, parentID)
if err != nil {
return err
}
issue.Labels = append(issue.Labels, labels...)
return nil
}
// skippedDependency records an edge the batch engine declined to write.
type skippedDependency struct{ issueID, dependsOnID, reason string }

View file

@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"slices"
"strings"
"github.com/steveyegge/beads/internal/labelns"
@ -160,7 +161,7 @@ func addLabelInTx(ctx context.Context, tx DBTX, labelTable, eventTable, issueID,
eventTable = et
}
}
if err := checkExclusiveLabelInTx(ctx, tx, labelTable, issueID, label); err != nil {
if err := CheckExclusiveLabelInTx(ctx, tx, labelTable, issueID, label); err != nil {
return err
}
//nolint:gosec // G201: labelTable is from WispTableRouting ("labels" or "wisp_labels")
@ -195,21 +196,27 @@ func addLabelInTx(ctx context.Context, tx DBTX, labelTable, eventTable, issueID,
return RecordVersionInTx(ctx, tx, issueID, actor)
}
// checkExclusiveLabelInTx rejects the add when the label falls in a
// CheckExclusiveLabelInTx rejects the add when the label falls in a
// configured exclusive namespace (labels.exclusive-prefixes, bd-7u5ki) the
// issue already carries a different label in. It lives at the shared insert
// choke point so every interactive mutation path — bd label add, bd update
// --add-label, bd label propagate — gets the same guard. With no prefixes
// configured (the default) only the config lookup runs.
func checkExclusiveLabelInTx(ctx context.Context, tx DBTX, labelTable, issueID, label string) error {
raw, err := GetConfigInTx(ctx, tx, labelns.ConfigKey)
// issue already carries a different label in. It runs at both insert choke
// points: addLabelInTx here, which every direct and embedded mutation path
// reaches (bd label add, bd update --add-label, bd label propagate), and the
// proxied server's LabelSQLRepository.Insert. With no prefixes configured (the
// default) only the config lookup runs. Re-adding a label the issue already
// carries passes even on an issue that already violates the namespace: the
// INSERT IGNORE is a no-op there, and refusing it would only fail a write that
// changes nothing.
//
// The guard is a read-then-insert with no row lock, so two transactions adding
// different labels in one namespace to the same issue can each pass and both
// commit, and a Dolt merge can union two individually valid label sets into a
// violation. Neither is caught here; the bd doctor exclusive-label check
// (FindExclusiveLabelViolations) is the backstop that reports them.
func CheckExclusiveLabelInTx(ctx context.Context, tx DBTX, labelTable, issueID, label string) error {
prefixes, err := exclusiveLabelPrefixesInTx(ctx, tx)
if err != nil {
return fmt.Errorf("add label: %w", err)
}
prefixes := labelns.ParsePrefixes(raw)
if len(prefixes) == 0 {
return nil
}
prefix := labelns.Match(prefixes, label)
if prefix == "" {
return nil
@ -218,8 +225,11 @@ func checkExclusiveLabelInTx(ctx context.Context, tx DBTX, labelTable, issueID,
if err != nil {
return fmt.Errorf("add label: %w", err)
}
if slices.Contains(existing, label) {
return nil
}
for _, have := range existing {
if have != label && labelns.Match(prefixes, have) == prefix {
if labelns.Match(prefixes, have) == prefix {
return fmt.Errorf("cannot add label %q to %s: namespace %q is exclusive (%s) and the issue already has %q — remove it first, or swap in one step with 'bd label add --replace'",
label, issueID, prefix, labelns.ConfigKey, have)
}
@ -227,6 +237,70 @@ func checkExclusiveLabelInTx(ctx context.Context, tx DBTX, labelTable, issueID,
return nil
}
// exclusiveLabelPrefixesInTx reads and parses the workspace's exclusive label
// prefixes. A missing key reads as no prefixes, so an unconfigured workspace
// gets nil.
func exclusiveLabelPrefixesInTx(ctx context.Context, tx DBTX) ([]string, error) {
raw, err := GetConfigInTx(ctx, tx, labelns.ConfigKey)
if err != nil {
return nil, err
}
return labelns.ParsePrefixes(raw), nil
}
// checkExclusiveRenameInTx refuses a rename that would give an issue a second
// label in an exclusive namespace: newLabel falls in one, oldLabel does not,
// and a carrier of oldLabel already holds a different label in newLabel's
// namespace. A rename within one namespace swaps one label for another and
// never adds one, and a carrier already holding newLabel merges into it, so
// neither can create a violation and both pass. Carriers are checked in id
// order, so the error names the same offender on every run.
func checkExclusiveRenameInTx(ctx context.Context, tx DBTX, oldLabel, newLabel string) error {
prefixes, err := exclusiveLabelPrefixesInTx(ctx, tx)
if err != nil {
return fmt.Errorf("rename label: %w", err)
}
prefix := labelns.Match(prefixes, newLabel)
if prefix == "" || labelns.Match(prefixes, oldLabel) == prefix {
return nil
}
for _, plane := range renameLabelPlanes {
carriers, err := issueIDsWithLabelInTx(ctx, tx, plane.labelTable, oldLabel)
if err != nil {
return fmt.Errorf("rename label: query issues carrying %q: %w", oldLabel, err)
}
if len(carriers) == 0 {
continue
}
slices.Sort(carriers)
labelsByID, err := GetLabelsForIssuesFromTableInTx(ctx, tx, plane.labelTable, carriers)
if err != nil {
return fmt.Errorf("rename label: %w", err)
}
for _, id := range carriers {
if have := exclusiveRenameBlocker(prefixes, prefix, newLabel, labelsByID[id]); have != "" {
return fmt.Errorf("cannot rename label %q to %q: namespace %q is exclusive (%s) and %s already has %q — remove it first",
oldLabel, newLabel, prefix, labelns.ConfigKey, id, have)
}
}
}
return nil
}
// exclusiveRenameBlocker returns the label in prefix's namespace that keeps a
// carrier from taking newLabel, or "" when the rename is safe for it.
func exclusiveRenameBlocker(prefixes []string, prefix, newLabel string, labels []string) string {
if slices.Contains(labels, newLabel) {
return ""
}
for _, have := range labels {
if labelns.Match(prefixes, have) == prefix {
return have
}
}
return ""
}
// ExclusiveLabelViolation reports an issue carrying more than one label in a
// configured exclusive namespace.
type ExclusiveLabelViolation struct {
@ -361,7 +435,10 @@ var ErrRenameLabelSameName = errors.New("rename label: old and new label are the
// 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.
// proceeding would wipe the label instead of leaving it alone. A rename that
// would give a carrier a second label in an exclusive namespace
// (labels.exclusive-prefixes) is refused before any write; see
// checkExclusiveRenameInTx.
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
@ -369,6 +446,9 @@ func RenameLabelInTx(ctx context.Context, tx DBTX, oldLabel, newLabel, actor str
if err := types.CheckFieldLen("label", newLabel); err != nil {
return 0, 0, nil, err
}
if err := checkExclusiveRenameInTx(ctx, tx, oldLabel, 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 {

View file

@ -178,6 +178,7 @@ go_test(
"//internal/configfile",
"//internal/doltserver",
"//internal/hooks",
"//internal/labelns",
"//internal/procid",
"//internal/storage",
"//internal/storage/dberrors",

View file

@ -3,6 +3,8 @@ package uow
import (
"context"
"fmt"
"slices"
"strings"
"github.com/steveyegge/beads/internal/storage"
storageissueops "github.com/steveyegge/beads/internal/storage/issueops"
@ -89,6 +91,7 @@ func (o *importer) ImportBatch(ctx context.Context, request publicops.ImportBatc
}
staleRejected := make(map[string]struct{})
skippedSeen := make(map[string]struct{})
conflictSeen := make(map[string]struct{})
opts := storage.BatchCreateOptions{
SkipPrefixValidation: request.SkipPrefixValidation,
RejectStaleUpserts: !request.AllowStale,
@ -96,6 +99,18 @@ func (o *importer) ImportBatch(ctx context.Context, request publicops.ImportBatc
// Replays existing data: exclusive-label violations warn via bd
// doctor instead of failing the replay (bd-7u5ki).
ExclusiveLabelConflictWarn: true,
OnExclusiveLabelConflict: func(issueID, prefix string, labels []string) {
key := issueID + "\x00" + prefix + "\x00" + strings.Join(labels, "\x00")
if _, ok := conflictSeen[key]; ok {
return
}
conflictSeen[key] = struct{}{}
result.ExclusiveLabelConflicts = append(result.ExclusiveLabelConflicts, publicops.ExclusiveLabelConflict{
IssueID: issueID,
Prefix: prefix,
Labels: slices.Clone(labels),
})
},
OnSkippedDependency: func(issueID, dependsOnID, reason string) {
key := issueID + "\x00" + dependsOnID + "\x00" + reason
if _, ok := skippedSeen[key]; ok {

View file

@ -2,10 +2,12 @@ package uow
import (
"context"
"reflect"
"strings"
"testing"
"time"
"github.com/steveyegge/beads/internal/labelns"
"github.com/steveyegge/beads/internal/types"
publicops "github.com/steveyegge/beads/issueops"
)
@ -383,6 +385,43 @@ func TestImporterUOW(t *testing.T) {
}
})
t.Run("ExclusiveLabelViolationsWarnAndKeepLabels", func(t *testing.T) {
// Import replays history that may predate labels.exclusive-prefixes
// (bd-7u5ki): a violation lands as written and is reported in the
// result, the proxied twin of the classic import's callback.
if err := kit.SetConfig(ctx, labelns.ConfigKey, "tier:"); err != nil {
t.Fatalf("set %s: %v", labelns.ConfigKey, err)
}
t.Cleanup(func() {
if err := kit.SetConfig(ctx, labelns.ConfigKey, ""); err != nil {
t.Errorf("clear %s: %v", labelns.ConfigKey, err)
}
})
when := time.Date(2026, 8, 3, 12, 0, 0, 0, time.UTC)
result, err := imp.ImportBatch(ctx, publicops.ImportBatchRequest{
Actor: "importer-test",
Issues: []*types.Issue{{
ID: "imp-excl", Title: "Carries two tiers", Status: types.StatusOpen,
IssueType: types.TypeTask, Priority: 2,
Labels: []string{"tier:fable", "tier:opus"},
CreatedAt: when, UpdatedAt: when,
}},
SkipPrefixValidation: true,
Source: "exclusive.jsonl",
})
if err != nil {
t.Fatalf("ImportBatch must warn, not fail, on an exclusive-label violation: %v", err)
}
want := []publicops.ExclusiveLabelConflict{{IssueID: "imp-excl", Prefix: "tier:", Labels: []string{"tier:fable", "tier:opus"}}}
if !reflect.DeepEqual(result.ExclusiveLabelConflicts, want) {
t.Fatalf("ExclusiveLabelConflicts = %#v, want %#v", result.ExclusiveLabelConflicts, want)
}
if got := queryInt(t, "SELECT COUNT(*) FROM labels WHERE issue_id = ?", "imp-excl"); got != 2 {
t.Fatalf("labels kept = %d, want 2", got)
}
})
t.Run("EmptyActorIsRefused", func(t *testing.T) {
if _, err := imp.ImportBatch(ctx, publicops.ImportBatchRequest{Source: "noactor.jsonl"}); err == nil {
t.Fatal("ImportBatch with empty actor should be refused")

View file

@ -55,6 +55,16 @@ type SkippedDependency struct {
Reason string
}
// ExclusiveLabelConflict reports one imported issue that carries more than
// one label in an exclusive namespace (labels.exclusive-prefixes). Import
// replays history, so the batch keeps the labels as written; bd doctor
// reports them for cleanup.
type ExclusiveLabelConflict struct {
IssueID string
Prefix string
Labels []string
}
// ImportBatchResult reports what one import batch landed.
type ImportBatchResult struct {
// Created counts the rows the batch wrote — inserts and rewrites alike —
@ -67,6 +77,9 @@ type ImportBatchResult struct {
StaleRejectedIDs []string
// SkippedDependencies lists the edges dropped by the batch, deduplicated.
SkippedDependencies []SkippedDependency
// ExclusiveLabelConflicts lists the batch's exclusive-namespace
// violations, deduplicated. Their labels landed as written.
ExclusiveLabelConflicts []ExclusiveLabelConflict
// PrefixSynced reports that the batch wrote the stored issue_prefix to
// SyncIssuePrefix — either seeding it, when the config table carried no
// prefix at all, or rewriting a stored value that disagreed.

View file

@ -204,6 +204,7 @@ release_cross_build(
"//internal/httpclient:httpclient",
"//internal/idgen:idgen",
"//internal/jira:jira",
"//internal/labelns:labelns",
"//internal/linear:linear",
"//internal/lockfile:lockfile",
"//internal/memoryapi:memoryapi",